text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { useState, useCallback } from 'react';
import { useImmer } from 'use-immer';
import { ShapePanelEnum } from '@/enum';
import { uuid, getCenterXY } from '@/utils/util';
import { useModel } from 'umi';
import type { DataModel, DatModelItem } from '@/typing';
import _ from 'lodash';
import canvasModel from './canvasModel';
export type CanvasModel = {
width: number;
height: number;
nodes: DataModel;
};
const initData: DataModel = [
{
id: 'bg',
type: 'color',
color: '#F5EDDF',
},
{
name: 'node',
draggable: true,
x: 436,
y: 49.772379680409145,
id: '28608db7-7f68-4fb4-bfc9-54522364c617',
fontSize: 60,
type: 'text-input',
text: '节点框选功能',
fill: '#000',
width: 360.0000000000001,
isSelected: true,
lineHeight: 1,
rotation: 0,
scaleX: 1,
scaleY: 1,
offsetX: 0,
offsetY: 0,
skewX: 0,
skewY: 0,
visible: true,
height: 60.99999999999992,
},
// {
// name: 'node',
// draggable: true,
// id: '3f0dfc51-5481-49d0-8f3a-8a93dd3e3bfa',
// type: 'image',
// x: 142.42857142857156,
// y: 532.0390814535209,
// isSelected: false,
// width: 174.80503425244814,
// height: 132.10377568933617,
// url: '/image2/1.jpg',
// rotation: 0,
// scaleX: 1,
// scaleY: 1,
// offsetX: 0,
// offsetY: 0,
// skewX: 0,
// skewY: 0,
// },
{
name: 'group',
draggable: true,
id: 'b366673e-a7cf-445e-8e52-65ce3ecb7b81',
type: 'group',
x: 0,
y: 0,
children: [
{
name: 'node',
draggable: false,
id: '1',
type: 'image',
url: '/image2/1.jpg',
x: 142.42857142857156,
y: 357.7714218418357,
isSelected: false,
width: 162.8722198534792,
height: 123.15416489010939,
rotation: 0,
scaleX: 1,
scaleY: 1,
offsetX: 0,
offsetY: 0,
skewX: 0,
skewY: 0,
},
{
name: 'node',
draggable: false,
id: '2',
type: 'image',
url: '/image2/14.jpeg',
x: 142.42857142857156,
y: 81.90962940621816,
isSelected: false,
width: 193.94019696803468,
height: 146.45514772602604,
rotation: 0,
scaleX: 1,
scaleY: 1,
offsetX: 0,
offsetY: 0,
skewX: 0,
skewY: 0,
},
],
},
// {
// draggable: true,
// id: '1789615c-ef9a-4378-99cf-292c7e5d47b2',
// type: 'image',
// url: '/image2/1.jpg',
// x: 936.2857142857144,
// y: 176.19534369193246,
// isSelected: true,
// width: 240.7681041998711,
// height: 181.57607814990322,
// rotation: 0,
// scaleX: 1,
// scaleY: 1,
// skewX: 0,
// skewY: 0,
// offsetX: 0,
// offsetY: 0,
// },
];
const newData = [
{
id: 'bg',
type: 'color',
fill: '#F5EDDF',
},
{
name: 'node',
draggable: true,
x: 436,
y: 49.772379680409145,
id: '28608db7-7f68-4fb4-bfc9-54522364c617',
fontSize: 60,
type: 'text-input',
text: '节点框选案例',
fill: '#000',
width: 360.0000000000001,
isSelected: true,
lineHeight: 1,
rotation: 0,
scaleX: 1,
scaleY: 1,
offsetX: 0,
offsetY: 0,
skewX: 0,
skewY: 0,
visible: true,
// height: 60.99999999999992,
},
{
width: 162.8722198534792,
height: 123.15416489010939,
name: 'node',
draggable: true,
id: '1',
type: 'image',
x: 142.42857142857156,
y: 357.7714218418357,
isSelected: false,
rotation: 0,
scaleX: 1,
scaleY: 1,
offsetX: 0,
offsetY: 0,
skewX: 0,
skewY: 0,
// "child": true,
url: '/image2/1.jpg',
},
{
width: 193.94019696803468,
height: 146.45514772602604,
name: 'node',
draggable: true,
id: '2',
type: 'image',
x: 142.42857142857156,
y: 81.90962940621816,
isSelected: false,
rotation: 0,
scaleX: 1,
scaleY: 1,
offsetX: 0,
offsetY: 0,
skewX: 0,
skewY: 0,
// "child": true,
url: '/image2/14.jpeg',
},
{
width: 193.94019696803468,
height: 146.45514772602604,
name: 'node',
draggable: true,
id: '3',
type: 'image',
x: 342.42857142857156,
y: 181.90962940621816,
isSelected: false,
rotation: 0,
scaleX: 1,
scaleY: 1,
offsetX: 0,
offsetY: 0,
skewX: 0,
skewY: 0,
// "child": true,
url: '/image2/14.jpeg',
},
// {
// "draggable": true,
// "name": "group",
// "id": "b366673e-a7cf-445e-8e52-65ce3ecb7b81",
// "type": "group",
// "x": -142.61460101867573,
// "y": 29.278321955451514,
// "isSelected": true,
// "rotation": 0,
// "scaleX": 1,
// "scaleY": 1,
// "offsetX": 0,
// "offsetY": 0,
// "skewX": 0,
// "skewY": 0,
// "children": [
// ]
// }
];
const recordPush = (nodes: any, undoRedoData: any, updateUndoRedoData: any) => {
// const currNodes = undoRedoData.activeSnapshot || nodes;
const newNodes = undoRedoData.activeSnapshot || nodes;
updateUndoRedoData({ type: 'push', data: newNodes });
return newNodes;
};
const canvasDataModel = ({ get, set }: any) => ({
width: 1200,
height: 700,
nodes: newData || initData,
changeCanvasModel: (currCanvasModel: any) => {
set(currCanvasModel);
},
changeCanvasModelDataItem: (currDataModelItem: DatModelItem) => {
const { nodes } = get();
// window.nodes = nodes;
const { changeCanvas, updateUndoRedoData, undoRedoData } = get(canvasModel);
changeCanvas({
selectNode: currDataModelItem,
});
const currNodes = undoRedoData.activeSnapshot || nodes;
updateUndoRedoData({ type: 'push', data: currNodes });
set((state: any) => {
let index = currNodes.findIndex(
(item: DatModelItem) => item.id === currDataModelItem.id,
);
currNodes[index] = currDataModelItem;
// console.log('currNodescurrNodescurrNodescurrNodescurrNodes=>', currNodes)
return {
nodes: [...currNodes],
};
});
},
addGroup: (groupKey: string, group: Array<DatModelItem>) => {
const { changeCanvas, updateUndoRedoData, undoRedoData } = get(canvasModel);
set((state: any) => {
console.log('group=>', group);
_.remove(state.nodes, (n) => {
const index = group.findIndex((f) => f.id === n.id);
console.log('index=>', index);
return index != -1;
});
console.log('nodes=>', state.nodes);
const index = state.nodes.findIndex(
(f: DatModelItem) => f.id === groupKey,
);
let currNode = null;
if (index !== -1) {
currNode = { ...state.nodes[index], children: group };
state.nodes[index] = currNode;
// currGroup.children = group;
// state.nodes.push(currGroup);
} else {
currNode = {
id: groupKey,
type: 'group',
draggable: true,
children: group,
};
state.nodes.push(currNode);
}
changeCanvas({
selectNode: currNode,
});
return {
nodes: [...state.nodes],
};
});
},
removeGroup: (groupKey: string) => {
set((state: any) => {
const index = state.nodes.findIndex(
(f: DatModelItem) => f.id === groupKey,
);
const currGroup = state.nodes?.[index];
if (!currGroup) {
return;
}
console.log('remove-group,', currGroup);
currGroup.children?.forEach((item: any) => {
item.child = undefined;
item.draggable = true;
item.x = item.x + currGroup.x;
item.y = item.y + currGroup.y;
item.offsetX = item.width / 2;
item.offsetY = item.height / 2;
item.rotation = currGroup.rotation;
item.skewX = item.skewX + currGroup.skewX;
item.scaleX = currGroup.scaleX;
item.skewY = currGroup.skewY;
item.scaleY = currGroup.scaleY;
state.nodes.push(item);
});
_.remove(state.nodes, (n) => {
return n.id == groupKey;
});
return {
nodes: [...state.nodes],
};
});
},
addNode: (node: DatModelItem, nodeWidth: number, nodeHeight: number) => {
const { width, height, nodes } = get();
const { changeCanvas, undoRedoData, updateUndoRedoData } = get(canvasModel);
const [x, y] = getCenterXY(width, height, nodeWidth, nodeHeight);
node.x = x;
node.y = y;
// debugger;
const newNodes = recordPush(nodes, undoRedoData, updateUndoRedoData);
set((state: any) => {
return {
nodes: [...newNodes, node],
};
});
changeCanvas({
selectNode: node,
});
},
addText: () => {
const { addNode } = get();
const textWidth = 360;
const textHeight = 60;
const currTextDateItem: DatModelItem = {
x: 0,
y: 0,
id: uuid(),
fontSize: 60,
type: 'text-input',
text: '双击编辑文字',
fill: '#000',
width: textWidth,
};
addNode(currTextDateItem, textWidth, textHeight);
},
addImage: (url: string) => {
const { addNode } = get();
const textWidth = 400;
const textHeight = 200;
const currTextDateItem: DatModelItem = {
id: uuid(),
// x: 0,
// y: 0,
type: 'image',
url,
};
addNode(currTextDateItem, textWidth, textHeight);
},
removeNode: (id: string) => {
const { nodes } = get();
const { undoRedoData, updateUndoRedoData } = get(canvasModel);
const currNodes = recordPush(nodes, undoRedoData, updateUndoRedoData);
set((state: any) => {
let newNodes = currNodes.filter((item: DatModelItem) => item.id !== id);
return {
nodes: [...newNodes],
};
});
},
copyNode: (item: DatModelItem) => {
const { nodes } = get();
const { changeCanvas, undoRedoData, updateUndoRedoData } = get(canvasModel);
item.id = uuid();
item.x += 20;
item.y += 20;
const newNodes = recordPush(nodes, undoRedoData, updateUndoRedoData);
set((state: any) => {
return {
nodes: [...newNodes, item],
};
});
changeCanvas({
selectNode: item,
});
},
setTemplate: (data: any) => {
const { setTemplate } = get(canvasModel);
set((state: any) => {
setTemplate(data);
return {
width: data.width,
height: data.height,
nodes: data.nodes,
};
});
},
});
export default canvasDataModel; | the_stack |
import * as geom from "../format/geom";
import * as dbft from "../format/dragonBonesFormat";
import * as spft from "../format/spineFormat";
type Map<T> = {
[key: string]: T;
};
type Input = {
name: string;
data: spft.Spine;
textureAtlas: string;
};
/**
* Convert Spine format to DragonBones format.
*/
export default function (data: Input, forPro: boolean = false): dbft.DragonBones {
let textureAtlasScale = -1.0;
const result: dbft.DragonBones = new dbft.DragonBones();
{ // Convert texture atlas.
const lines = data.textureAtlas.split(/\r\n|\r|\n/);
const tuple = new Array<string>(4);
let textureAtlas: dbft.TextureAtlas | null = null;
while (true) {
const line = lines.shift();
if (line === null || line === undefined) {
break;
}
if (line.length === 0) {
textureAtlas = null;
}
else if (!textureAtlas) {
textureAtlas = new dbft.TextureAtlas();
textureAtlas.name = data.name;
textureAtlas.imagePath = line;
if (readTuple(tuple, lines.shift()) === 2) {
textureAtlas.width = parseInt(tuple[0]);
textureAtlas.height = parseInt(tuple[1]);
readTuple(tuple, lines.shift());
}
readTuple(tuple, lines.shift());
readValue(lines.shift());
result.textureAtlas.push(textureAtlas);
}
else {
const texture = new dbft.Texture();
texture.name = line;
texture.rotated = readValue(lines.shift()) === "true" ? (forPro ? 1 as any : true) : false;
readTuple(tuple, lines.shift());
texture.x = parseInt(tuple[0]);
texture.y = parseInt(tuple[1]);
readTuple(tuple, lines.shift());
if (texture.rotated) {
texture.height = parseInt(tuple[0]);
texture.width = parseInt(tuple[1]);
}
else {
texture.width = parseInt(tuple[0]);
texture.height = parseInt(tuple[1]);
}
if (readTuple(tuple, lines.shift()) === 4) {
if (readTuple(tuple, lines.shift()) === 4) {
readTuple(tuple, lines.shift());
}
}
texture.frameWidth = parseInt(tuple[0]);
texture.frameHeight = parseInt(tuple[1]);
readTuple(tuple, lines.shift());
texture.frameX = -parseInt(tuple[0]);
texture.frameY = -(texture.frameHeight - (texture.rotated ? texture.width : texture.height) - parseInt(tuple[1]));
readTuple(tuple, lines.shift());
textureAtlas.SubTexture.push(texture);
}
}
}
const armature = new dbft.Armature();
armature.name = data.name;
result.frameRate = data.data.skeleton.fps;
result.name = data.name;
result.version = dbft.DATA_VERSION_5_5;
result.compatibleVersion = dbft.DATA_VERSION_5_5;
result.armature.push(armature);
for (const sfBone of data.data.bones) {
const bone = new dbft.Bone();
bone.length = sfBone.length;
bone.transform.x = sfBone.x;
bone.transform.y = -sfBone.y;
bone.transform.skY = -(sfBone.rotation + sfBone.shearX);
bone.transform.skX = bone.transform.skY - sfBone.shearY;
bone.transform.scX = sfBone.scaleX;
bone.transform.scY = sfBone.scaleY;
bone.name = sfBone.name;
bone.parent = sfBone.parent;
switch (sfBone.transform) {
case "onlyTranslation":
bone.inheritRotation = false;
bone.inheritScale = false;
bone.inheritReflection = false;
break;
case "noRotationOrReflection":
bone.inheritRotation = false;
bone.inheritScale = true;
bone.inheritReflection = false;
break;
case "noScaleOrReflection":
bone.inheritRotation = true;
bone.inheritScale = false;
bone.inheritReflection = false;
break;
case "noScale":
bone.inheritRotation = true;
bone.inheritScale = false;
bone.inheritReflection = true;
break;
case "normal":
default:
bone.inheritRotation = sfBone.inheritRotation;
bone.inheritScale = sfBone.inheritScale;
bone.inheritReflection = true;
break;
}
armature.bone.push(bone);
}
armature.sortBones();
armature.localToGlobal();
const slotDisplays: Map<string[]> = {}; // Create attachments sort.
const addDisplayToSlot = (rawDisplays: string[], display: dbft.Display, displays: (dbft.Display | null)[]) => {
// tslint:disable-next-line:no-unused-expression
rawDisplays;
// const index = rawDisplays.indexOf(display.name); TODO
// while (displays.length < index) {
// displays.push(null);
// }
displays.push(display);
};
for (const skinName in data.data.skins) {
const spSkin = data.data.skins[skinName];
const skin = new dbft.Skin();
skin.name = skinName;
for (const slotName in spSkin) {
const spSlot = spSkin[slotName];
const slot = new dbft.SkinSlot();
const displays = slotDisplays[slotName] = slotDisplays[slotName] || [];
slot.name = slotName;
for (const attachmentName in spSlot) {
const attachment = spSlot[attachmentName];
if (displays.indexOf(attachmentName) < 0) {
displays.push(attachmentName);
}
if (attachment instanceof spft.RegionAttachment) {
const display = new dbft.ImageDisplay();
display.name = attachmentName;
display.path = attachment.path || attachment.name;
display.transform.x = attachment.x;
display.transform.y = -attachment.y;
display.transform.skX = -attachment.rotation;
display.transform.skY = -attachment.rotation;
display.transform.scX = attachment.scaleX;
display.transform.scY = attachment.scaleY;
addDisplayToSlot(displays, display, slot.display);
if (textureAtlasScale < 0.0) {
textureAtlasScale = modifyTextureAtlasScale(display.path || display.name, attachment, result.textureAtlas);
}
}
else if (attachment instanceof spft.MeshAttachment) {
const display = new dbft.MeshDisplay();
display.name = attachmentName;
display.width = attachment.width;
display.height = attachment.height;
display.path = attachment.path || attachment.name;
for (const v of attachment.uvs) {
display.uvs.push(v);
}
for (const v of attachment.triangles) {
display.triangles.push(v);
}
if (attachment.uvs.length === attachment.vertices.length) {
for (let i = 0; i < attachment.vertices.length; ++i) {
const v = attachment.vertices[i];
if (i % 2) {
display.vertices[i] = -v;
}
else {
display.vertices[i] = v;
}
}
}
else {
const bones = new Array<number>();
for (
let i = 0, iW = 0;
i < attachment.uvs.length / 2;
++i
) {
const boneCount = attachment.vertices[iW++];
let xG = 0.0;
let yG = 0.0;
display.weights.push(boneCount);
for (let j = 0; j < boneCount; j++) {
const boneIndex = attachment.vertices[iW++];
const xL = attachment.vertices[iW++];
const yL = -attachment.vertices[iW++];
const weight = attachment.vertices[iW++];
const bone = armature.getBone(data.data.bones[boneIndex].name);
if (bone && bone._global) {
const boneIndex = armature.bone.indexOf(bone);
bone._global.toMatrix(geom.helpMatrixA);
geom.helpMatrixA.transformPoint(xL, yL, geom.helpPointA);
xG += geom.helpPointA.x * weight;
yG += geom.helpPointA.y * weight;
display.weights.push(boneIndex, weight);
if (bones.indexOf(boneIndex) < 0) {
bones.push(boneIndex);
display.bonePose.push(boneIndex, geom.helpMatrixA.a, geom.helpMatrixA.b, geom.helpMatrixA.c, geom.helpMatrixA.d, geom.helpMatrixA.tx, geom.helpMatrixA.ty);
}
}
}
display.vertices.push(xG, yG);
}
display.slotPose.push(1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
}
const edges = dbft.getEdgeFormTriangles(display.triangles);
display.edges.length = edges.length;
for (const value of edges) {
display.edges.push(value);
}
if (attachment.edges.length !== attachment.hull * 2) {
for (let i = attachment.hull * 2; i < attachment.edges.length; ++i) {
display.userEdges.push(attachment.edges[i] / 2);
}
}
addDisplayToSlot(displays, display, slot.display);
if (textureAtlasScale < 0.0) {
textureAtlasScale = modifyTextureAtlasScale(display.path || display.name, attachment, result.textureAtlas);
}
}
else if (attachment instanceof spft.LinkedMeshAttachment) {
const display = new dbft.SharedMeshDisplay();
display.inheritDeform = attachment.deform;
display.name = attachmentName;
display.share = attachment.parent;
display.skin = attachment.skin;
display.path = attachment.path || attachment.name;
addDisplayToSlot(displays, display, slot.display);
if (textureAtlasScale < 0.0) {
textureAtlasScale = modifyTextureAtlasScale(display.path || display.name, attachment, result.textureAtlas);
}
}
else if (attachment instanceof spft.PathAttachment) {
const display = new dbft.PathDisplay();
display.name = attachment.name || attachmentName;
display.closed = attachment.closed;
display.constantSpeed = attachment.constantSpeed;
display.vertexCount = attachment.vertexCount;
display.lengths.length = attachment.lengths.length;
for (let i = 0, l = attachment.lengths.length; i < l; i++) {
display.lengths[i] = attachment.lengths[i];
}
//
// const bones = new Array<number>();
// // weight
// for (let iW = 0; iW < attachment.vertices.length;) {
// const boneCount = attachment.vertices[iW++];
// display.weights.push(boneCount);
// let xG: number = 0.0;
// let yG: number = 0.0;
// for (let j = 0; j < boneCount; j++) {
// const boneIndex = attachment.vertices[iW++];
// const xL = attachment.vertices[iW++];
// const yL = -attachment.vertices[iW++];
// const weight = attachment.vertices[iW++];
// const bone = armature.getBone(data.data.bones[boneIndex].name);
// if (bone && bone._global) {
// const boneIndex = armature.bone.indexOf(bone);
// bone._global.toMatrix(geom.helpMatrixA);
// geom.helpMatrixA.transformPoint(xL, yL, geom.helpPointA);
// xG += geom.helpPointA.x * weight;
// yG += geom.helpPointA.y * weight;
// display.weights.push(boneIndex);
// display.weights.push(weight);
// if (bones.indexOf(boneIndex) < 0) {
// bones.push(boneIndex);
// display.bonePose.push(boneIndex, geom.helpMatrixA.a, geom.helpMatrixA.b, geom.helpMatrixA.c, geom.helpMatrixA.d, geom.helpMatrixA.tx, geom.helpMatrixA.ty);
// }
// }
// }
// display.vertices.push(xG, yG);
// }
// display.slotPose.push(1.0, 0.0, 0.0, 1.0, 0.0, 0.0);
//没有权重数据,这么这些就是曲线顶点数据
if (attachment.vertexCount * 2 === attachment.vertices.length) {
display.vertices.length = attachment.vertices.length;
for (let i = 0, l = attachment.vertices.length; i < l; i++) {
display.vertices[i] = attachment.vertices[i];
}
}
else {//有权重数据(boneCount:boneIndex:boneX:boneY:weight...)
for (let iW = 0; iW < attachment.vertices.length;) {
const boneCount = attachment.vertices[iW++];
display.weights.push(boneCount);
for (let j = 0; j < boneCount; j++) {
const boneIndex = attachment.vertices[iW++];
const xL = attachment.vertices[iW++];
const yL = -attachment.vertices[iW++];
const weight = attachment.vertices[iW++];
display.weights.push(boneIndex);
display.weights.push(weight);
display.vertices.push(xL, yL);
if (display.bones.indexOf(boneIndex) < 0) {
display.bones.push(boneIndex);
}
}
}
}
slot.display.push(display);
}
else if (attachment instanceof spft.BoundingBoxAttachment) {
const display = new dbft.PolygonBoundingBoxDisplay();
display.name = attachmentName;
if (attachment.vertexCount < attachment.vertices.length / 2) { // Check
for (
let i = 0, iW = 0;
i < attachment.vertexCount;
++i
) {
const boneCount = attachment.vertices[iW++];
let xG = 0.0;
let yG = 0.0;
for (let j = 0; j < boneCount; j++) {
const boneIndex = attachment.vertices[iW++];
const xL = attachment.vertices[iW++];
const yL = -attachment.vertices[iW++];
const weight = attachment.vertices[iW++];
const bone = armature.getBone(data.data.bones[boneIndex].name);
if (bone && bone._global) {
bone._global.toMatrix(geom.helpMatrixA);
geom.helpMatrixA.transformPoint(xL, yL, geom.helpPointA);
xG += geom.helpPointA.x * weight;
yG += geom.helpPointA.y * weight;
}
}
display.vertices.push(xG, yG);
}
}
else {
for (let i = 0; i < attachment.vertices.length; ++i) {
const v = attachment.vertices[i];
if (i % 2) {
display.vertices[i] = -v;
}
else {
display.vertices[i] = v;
}
}
}
addDisplayToSlot(displays, display, slot.display);
}
else {
const display = new dbft.ImageDisplay();
addDisplayToSlot(displays, display, slot.display);
}
}
skin.slot.push(slot);
}
armature.skin.push(skin);
}
// for (const skin of armature.skin) { TODO
// for (const slot of skin.slot) {
// const displays = slotDisplays[slot.name];
// while (slot.display.length !== displays.length) {
// slot.display.push(null);
// }
// }
// }
for (const spSlot of data.data.slots) {
const slot = new dbft.Slot();
slot.name = spSlot.name;
slot.parent = spSlot.bone;
const displays = slotDisplays[slot.name];
slot.displayIndex = displays ? displays.indexOf(spSlot.attachment) : -1;
slot.color.copyFromRGBA(Number("0x" + spSlot.color));
switch (spSlot.blend) {
case "normal":
slot.blendMode = dbft.BlendMode[dbft.BlendMode.Normal].toLowerCase();
break;
case "additive":
slot.blendMode = dbft.BlendMode[dbft.BlendMode.Add].toLowerCase();
break;
case "multiply":
// slot.blendMode = dbft.BlendMode[dbft.BlendMode.Multiply].toLowerCase();
break;
case "screen":
// slot.blendMode = dbft.BlendMode[dbft.BlendMode.Screen].toLowerCase();
break;
}
armature.slot.push(slot);
}
for (const spIK of data.data.ik) {
const ik = new dbft.IKConstraint();
ik.bendPositive = !spIK.bendPositive;
ik.chain = spIK.bones.length > 1 ? 1 : 0;
ik.weight = spIK.mix;
ik.name = spIK.name;
ik.bone = spIK.bones[spIK.bones.length - 1];
ik.target = spIK.target;
armature.ik.push(ik);
}
for (const spPath of data.data.path) {
const path = new dbft.PathConstraint();
path.name = spPath.name;
path.positionMode = spPath.positionMode;
path.spacingMode = spPath.spacingMode;
path.rotateMode = spPath.rotateMode;
path.position = spPath.position;
path.spacing = spPath.spacing;
path.rotateOffset = spPath.rotation;
path.rotateMix = spPath.rotateMix;
path.translateMix = spPath.translateMix;
path.target = spPath.target;
path.bones = spPath.bones;
armature.path.push(path);
}
for (const animationName in data.data.animations) {
const spAnimation = data.data.animations[animationName];
const animation = new dbft.Animation();
let lastFramePosition = 0;
let iF = 0;
animation.playTimes = 0;
animation.name = animationName;
for (const timelineName in spAnimation.bones) {
const spTimeline = spAnimation.bones[timelineName];
const timeline = new dbft.BoneTimeline();
timeline.name = timelineName;
iF = 0;
for (const spFrame of spTimeline.translate) {
const frame = new dbft.DoubleValueFrame0();
frame._position = Math.floor(spFrame.time * result.frameRate);
frame.x = spFrame.x;
frame.y = -spFrame.y;
setTweenFormSP(frame, spFrame, iF++ === spTimeline.translate.length - 1);
timeline.translateFrame.push(frame);
lastFramePosition = Math.max(frame._position, lastFramePosition);
}
iF = 0;
for (const spFrame of spTimeline.rotate) {
const frame = new dbft.BoneRotateFrame();
frame._position = Math.floor(spFrame.time * result.frameRate);
frame.rotate = -spFrame.angle;
setTweenFormSP(frame, spFrame, iF++ === spTimeline.rotate.length - 1);
timeline.rotateFrame.push(frame);
lastFramePosition = Math.max(frame._position, lastFramePosition);
}
iF = 0;
for (const spFrame of spTimeline.shear) {
const position = Math.floor(spFrame.time * result.frameRate);
const index = timeline.insertFrame(timeline.rotateFrame, position);
if (index < 0) {
continue;
}
const frame = timeline.rotateFrame[index];
frame.rotate += -spFrame.x;
frame.skew = spFrame.x - spFrame.y;
lastFramePosition = Math.max(position, lastFramePosition);
}
iF = 0;
for (const spFrame of spTimeline.scale) {
const frame = new dbft.DoubleValueFrame1();
frame._position = Math.floor(spFrame.time * result.frameRate);
frame.x = spFrame.x;
frame.y = spFrame.y;
setTweenFormSP(frame, spFrame, iF++ === spTimeline.scale.length - 1);
timeline.scaleFrame.push(frame);
lastFramePosition = Math.max(frame._position, lastFramePosition);
}
modifyFrames(timeline.translateFrame);
modifyFrames(timeline.rotateFrame);
modifyFrames(timeline.scaleFrame);
animation.bone.push(timeline);
}
for (const timelineName in spAnimation.slots) {
const spTimeline = spAnimation.slots[timelineName];
const timeline = new dbft.SlotTimeline();
timeline.name = timelineName;
for (const spFrame of spTimeline.attachment) {
const frame = new dbft.SlotDisplayFrame();
const displays = slotDisplays[timelineName];
frame._position = Math.floor(spFrame.time * result.frameRate);
frame.value = displays ? displays.indexOf(spFrame.name) : -1;
timeline.displayFrame.push(frame);
lastFramePosition = Math.max(frame._position, lastFramePosition);
}
iF = 0;
for (const spFrame of spTimeline.color) {
const frame = new dbft.SlotColorFrame();
frame._position = Math.floor(spFrame.time * result.frameRate);
frame.value.copyFromRGBA(Number("0x" + spFrame.color));
setTweenFormSP(frame, spFrame, iF++ === spTimeline.color.length - 1);
timeline.colorFrame.push(frame);
lastFramePosition = Math.max(frame._position, lastFramePosition);
}
modifyFrames(timeline.displayFrame);
modifyFrames(timeline.colorFrame);
animation.slot.push(timeline);
}
let deformKey = "";
for (deformKey in spAnimation.deform) {
break;
}
const spTimelines = deformKey ? spAnimation.deform : spAnimation.ffd;
for (const skinName in spTimelines) {
const slots = spTimelines[skinName];
for (const slotName in slots) {
const timelines = slots[slotName];
for (const timelineName in timelines) {
const meshName = timelineName;
const meshDisplay = armature.getDisplay(skinName, slotName, meshName) as dbft.MeshDisplay | null;
if (!meshDisplay) {
continue;
}
const timeline = new dbft.SlotDeformTimeline();
const spFrames = timelines[timelineName];
timeline.name = meshName;
timeline.skin = skinName;
timeline.slot = slotName;
iF = 0;
for (const spFrame of spFrames) {
const frame = new dbft.MutilpleValueFrame();
frame._position = Math.floor(spFrame.time * result.frameRate);
setTweenFormSP(frame, spFrame, iF++ === spFrames.length - 1);
timeline.frame.push(frame);
if (meshDisplay.weights.length > 0) {
for (let i = 0; i < spFrame.offset; ++i) {
spFrame.vertices.unshift(0.0);
}
for (
let i = 0, iW = 0, iV = 0;
i < meshDisplay.vertices.length;
i += 2
) {
const boneCount = meshDisplay.weights[iW++];
let xG = 0.0;
let yG = 0.0;
for (let j = 0; j < boneCount; j++) {
const boneIndex = meshDisplay.weights[iW++];
const weight = meshDisplay.weights[iW++];
const bone = armature.bone[boneIndex];
if (bone && bone._global) {
const xL = spFrame.vertices[iV++] || 0.0;
const yL = -spFrame.vertices[iV++] || 0.0;
bone._global.toMatrix(geom.helpMatrixA);
geom.helpMatrixA.transformPoint(xL, yL, geom.helpPointA, true);
if (xL !== 0.0) {
xG += geom.helpPointA.x * weight;
}
if (yL !== 0.0) {
yG += geom.helpPointA.y * weight;
}
}
}
frame.vertices[i] = xG;
frame.vertices[i + 1] = yG;
}
}
else {
frame.offset = spFrame.offset;
for (let i = 0, l = spFrame.vertices.length; i < l; ++i) {
if ((frame.offset + i) % 2) {
frame.vertices.push(-spFrame.vertices[i]);
}
else {
frame.vertices.push(spFrame.vertices[i]);
}
}
}
lastFramePosition = Math.max(frame._position, lastFramePosition);
}
modifyFrames(timeline.frame);
animation.ffd.push(timeline);
}
}
}
for (const ikConstraintName in spAnimation.ik) {
const spFrames = spAnimation.ik[ikConstraintName];
const timeline = new dbft.IKConstraintTimeline();
timeline.name = ikConstraintName;
iF = 0;
for (const spFrame of spFrames) {
const frame = new dbft.IKConstraintFrame();
frame._position = Math.floor(spFrame.time * result.frameRate);
frame.bendPositive = !spFrame.bendPositive;
frame.weight = spFrame.mix;
setTweenFormSP(frame, spFrame, iF++ === spFrames.length - 1);
timeline.frame.push(frame);
lastFramePosition = Math.max(frame._position, lastFramePosition);
}
modifyFrames(timeline.frame);
}
if (spAnimation.events.length > 0) {
spAnimation.events.sort((a, b) => {
return a.time > b.time ? 1 : -1;
});
let prevFrame: dbft.Frame | null = null;
for (const spFrame of spAnimation.events) {
const position = Math.floor(spFrame.time * result.frameRate);
let frame: dbft.ActionFrame;
if (prevFrame && prevFrame._position === position) {
frame = prevFrame as any;
}
else {
frame = new dbft.ActionFrame();
frame._position = position;
animation.frame.push(frame);
prevFrame = frame;
}
const spEvent = data.data.events[spFrame.name];
const action = new dbft.Action();
action.type = dbft.ActionType.Frame;
action.name = spFrame.name;
if (spFrame.int || spEvent.int) {
action.ints.push(spFrame.int || spEvent.int);
}
if (spFrame.float || spEvent.float) {
action.floats.push(spFrame.float || spEvent.float);
}
if (spFrame.string || spEvent.string) {
action.strings.push(spFrame.string || spEvent.string);
}
frame.actions.push(action);
lastFramePosition = Math.max(frame._position, lastFramePosition);
}
modifyFrames(animation.frame);
}
if (spAnimation.drawOrder.length > 0) {
animation.zOrder = new dbft.ZOrderTimeline();
for (const spFrame of spAnimation.drawOrder) {
const frame = new dbft.MutilpleValueFrame();
frame._position = Math.floor(spFrame.time * result.frameRate);
for (const v of spFrame.offsets) {
const slot = armature.getSlot(v.slot);
frame.zOrder.push(slot ? armature.slot.indexOf(slot) : -1, v.offset);
}
animation.zOrder.frame.push(frame);
lastFramePosition = Math.max(frame._position, lastFramePosition);
}
modifyFrames(animation.zOrder.frame);
}
animation.duration = lastFramePosition + 1;
armature.animation.push(animation);
}
if (textureAtlasScale > 0.0) {
for (const textureAtlas of result.textureAtlas) {
textureAtlas.scale = textureAtlasScale;
}
}
return result;
}
function modifyTextureAtlasScale(textureName: string, attachment: { width: number, height: number }, textureAtlases: dbft.TextureAtlas[]): number {
const texture = dbft.getTextureFormTextureAtlases(textureName, textureAtlases);
if (texture) {
if (texture.frameWidth) {
return texture.frameWidth / attachment.width;
}
if (texture.rotated) {
return texture.width / attachment.height;
}
return texture.width / attachment.width;
}
return -1;
}
function setTweenFormSP(dbFrame: dbft.TweenFrame, spFrame: spft.TweenFrame, isLastFrame: boolean): void {
if (isLastFrame) {
return;
}
if (spFrame.curve instanceof Array) {
dbFrame.curve = spFrame.curve;
}
else if (spFrame.curve === "linear") {
dbFrame.tweenEasing = 0.0;
}
else {
dbFrame.tweenEasing = NaN;
}
}
function modifyFrames(frames: dbft.Frame[]): void {
if (frames.length === 0) {
return;
}
if (frames[0]._position !== 0) {
const frame = new (frames[0] as any).constructor() as dbft.Frame;
if (frame instanceof dbft.TweenFrame) {
frame.tweenEasing = 0.0;
}
frames.unshift(frame);
}
for (let i = 0, l = frames.length; i < l; ++i) {
const frame = frames[i];
if (i < l - 1) {
frame.duration = frames[i + 1]._position - frame._position;
}
}
}
function readValue(line: string | undefined): string {
if (line === undefined || line === null) {
throw new Error("Invalid line: " + line);
}
let colon = line.indexOf(":");
if (colon === -1)
throw new Error("Invalid line: " + line);
return line.substring(colon + 1).trim();
}
function readTuple(tuple: Array<string>, line: string | undefined): number {
if (line === undefined || line === null) {
throw new Error("Invalid line: " + line);
}
let colon = line.indexOf(":");
if (colon === -1)
throw new Error("Invalid line: " + line);
let i = 0, lastMatch = colon + 1;
for (; i < 3; i++) {
let comma = line.indexOf(",", lastMatch);
if (comma === -1) break;
tuple[i] = line.substr(lastMatch, comma - lastMatch).trim();
lastMatch = comma + 1;
}
tuple[i] = line.substring(lastMatch).trim();
return i + 1;
} | the_stack |
import { CellModel, ColumnModel, getCell, SheetModel } from './../base/index';
import { getCellAddress, getRangeIndexes } from './address';
/**
* Check whether the text is formula or not.
*
* @param {string} text - Specify the text.
* @returns {boolean} - Check whether the text is formula or not.
*/
export function checkIsFormula(text: string, isEditing?: boolean): boolean {
return text && text[0] === '=' && (text.length > 1 || isEditing);
}
/**
* Check whether the value is cell reference or not.
*
* @param {string} value - Specify the value to check.
* @returns {boolean} - Returns boolean value
*/
export function isCellReference(value: string): boolean {
let range: string = value;
range = range.split('$').join('');
if (range.indexOf(':') > -1) {
const rangeSplit: string[] = range.split(':');
if (isValidCellReference(rangeSplit[0]) && isValidCellReference(rangeSplit[1])) {
return true;
}
} else if (range.indexOf(':') < 0) {
if (isValidCellReference(range)) {
return true;
}
}
return false;
}
/**
* Check whether the value is character or not.
*
* @param {string} value - Specify the value to check.
* @returns {boolean} - Returns boolean value
*/
export function isChar(value: string): boolean {
if ((value.charCodeAt(0) >= 65 && value.charCodeAt(0) <= 90) || (value.charCodeAt(0) >= 97 && value.charCodeAt(0) <= 122)) {
return true;
}
return false;
}
/**
* @param {number[]} range - Specify the range
* @param {number} rowIdx - Specify the row index
* @param {number} colIdx - Specify the col index
* @returns {boolean} - Returns boolean value
*/
export function inRange(range: number[], rowIdx: number, colIdx: number) : boolean {
return range && (rowIdx >= range[0] && rowIdx <= range[2] && colIdx >= range[1] && colIdx <= range[3]);
}
/** @hidden
* @param {number[]} range - Specify the range
* @param {number[]} testRange - Specify the test range
* @param {boolean} isModify - Specify the boolean value
* @returns {boolean} - Returns boolean value
*/
export function isInRange(range: number[], testRange: number[], isModify?: boolean) : boolean {
let inRange: boolean = range[0] <= testRange[0] && range[2] >= testRange[2] && range[1] <= testRange[1] && range[3] >= testRange[3];
if (inRange) { return true; }
if (isModify) {
if (testRange[0] < range[0] && testRange[2] < range[0] || testRange[0] > range[2] && testRange[2] > range[2]) {
return false;
} else {
if (testRange[0] < range[0] && testRange[2] > range[0]) {
testRange[0] = range[0];
inRange = true;
}
if (testRange[2] > range[2]) {
testRange[2] = range[2];
inRange = true;
}
}
if (testRange[1] < range[1] && testRange[3] < range[1] || testRange[1] > range[3] && testRange[3] > range[3]) {
return false;
} else {
if (testRange[1] < range[1] && testRange[3] > range[1]) {
testRange[1] = range[1];
inRange = true;
}
if (testRange[3] > range[3]) {
testRange[3] = range[3];
inRange = true;
}
}
}
return inRange;
}
/**
* Check whether the cell is locked or not
*
* @param {CellModel} cell - Specify the cell.
* @param {ColumnModel} column - Specify the column.
* @returns {boolean} - Returns boolean value
* @hidden
*/
export function isLocked(cell: CellModel, column: ColumnModel): boolean {
if (!cell) {
cell = {};
}
if (cell.isLocked) {
return true;
} else if (cell.isLocked === false) {
return false;
} else if (column && column.isLocked) {
return true;
} else if (!cell.isLocked && (column && column.isLocked !== false)) {
return true;
}
return false;
}
/**
* Check whether the value is cell reference or not.
*
* @param {string} value - Specify the value to check.
* @returns {boolean} - Returns boolean value
* @hidden
*/
export function isValidCellReference(value: string): boolean {
const text: string = value;
const startNum: number = 0;
let endNum: number = 0;
let j: number = 0;
const numArr: number[] = [89, 71, 69];
// XFD is the last column, for that we are using ascii values of Z, G, E (89, 71, 69) to restrict the flow.
let cellText: string = '';
const textLength: number = text.length;
for (let i: number = 0; i < textLength; i++) {
if (isChar(text[i])) {
endNum++;
}
}
cellText = text.substring(startNum, endNum);
const cellTextLength: number = cellText.length;
if (cellTextLength !== textLength) {
if (cellTextLength < 4) {
if (textLength !== 1 && (isNaN(parseInt(text, 10)))) {
while (j < cellTextLength) {
if ((cellText[j]) && cellText[j].charCodeAt(0) < numArr[j]) {
j++;
continue;
} else if (!(cellText[j]) && j > 0) {
break;
} else {
return false;
}
}
const cellNumber: number = parseFloat(text.substring(endNum, textLength));
if (cellNumber > 0 && cellNumber < 1048577) { // 1048576 - Maximum number of rows in excel.
return true;
}
}
}
}
return false;
}
/**
* @param {number[]} currIndexes - current indexes in which formula get updated
* @param {number[]} prevIndexes - copied indexes
* @param {SheetModel} sheet - sheet model
* @param {CellModel} prevCell - copied or prev cell
* @returns {string} - retruns updated formula
* @hidden
*/
export function getUpdatedFormula(currIndexes: number[], prevIndexes: number[], sheet: SheetModel, prevCell?: CellModel): string {
let cIdxValue: string; let cell: CellModel;
if (prevIndexes) {
cell = prevCell || getCell(prevIndexes[0], prevIndexes[1], sheet, false, true);
cIdxValue = cell.formula ? cell.formula.toUpperCase() : '';
}
if (cIdxValue) {
if (cIdxValue.indexOf('=') === 0) {
cIdxValue = cIdxValue.slice(1);
}
cIdxValue = cIdxValue.split('(').join(',').split(')').join(',');
const formulaOperators: string[] = ['+', '-', '*', '/', '>=', '<=', '<>', '>', '<', '=', '%']; let splitArray: string[];
let value: string = cIdxValue;
for (let i: number = 0; i < formulaOperators.length; i++) {
splitArray = value.split(formulaOperators[i]);
value = splitArray.join(',');
}
splitArray = value.split(',');
const newAddress: { [key: string]: string }[] = []; let newRef: string; let refObj: { [key: string]: string };
for (let j: number = 0; j < splitArray.length; j++) {
if (isCellReference(splitArray[j])) {
const range: number[] = getRangeIndexes(splitArray[j]);
const newRange: number[] = [currIndexes[0] - (prevIndexes[0] - range[0]), currIndexes[1] - (prevIndexes[1] - range[1]),
currIndexes[0] - (prevIndexes[0] - range[2]), currIndexes[1] - (prevIndexes[1] - range[3])];
if (newRange[0] < 0 || newRange[1] < 0 || newRange[2] < 0 || newRange[3] < 0) {
newRef = '#REF!';
} else {
newRef = getCellAddress(newRange[0], newRange[1]);
if (splitArray[j].includes(':')) {
newRef += (':' + getCellAddress(newRange[2], newRange[3]));
}
newRef = isCellReference(newRef) ? newRef : '#REF!';
}
refObj = {}; refObj[splitArray[j]] = newRef;
if (splitArray[j].includes(':')) {
newAddress.splice(0, 0, refObj);
} else {
newAddress.push(refObj);
}
}
}
let objKey: string; cIdxValue = cell.formula;
for (let j: number = 0; j < newAddress.length; j++) {
objKey = Object.keys(newAddress[j])[0];
cIdxValue = cIdxValue.replace(new RegExp(objKey, 'gi'), newAddress[j][objKey].toUpperCase());
}
return cIdxValue;
} else {
return null;
}
}
/**
* @param {number} rowIdx - row index
* @param {number} colIdx - column index
* @param {SheetModel} sheet - sheet model
* @returns {number[]} - retruns data range
* @hidden
*/
export function getDataRange(rowIdx: number, colIdx: number, sheet: SheetModel): number[] {
let topIdx: number = rowIdx; let btmIdx: number = rowIdx;
let leftIdx: number = colIdx; let prevleftIdx: number;
let rightIdx: number = colIdx; let prevrightIdx: number;
let topReached: boolean; let btmReached: boolean;
let leftReached: boolean; let rightReached: boolean;
for (let i: number = 1; ; i++) {
if (!btmReached && getCell(rowIdx + i, colIdx, sheet, null, true).value) {
btmIdx = rowIdx + i;
} else {
btmReached = true;
}
if (!topReached && getCell(rowIdx - i, colIdx, sheet, null, true).value) {
topIdx = rowIdx - i;
} else {
topReached = true;
}
if (topReached && btmReached) {
break;
}
}
for (let j: number = 1; ; j++) {
prevleftIdx = leftIdx;
prevrightIdx = rightIdx;
for (let i: number = topIdx; i <= btmIdx; i++) {
if (!leftReached && getCell(i, leftIdx - 1, sheet, null, true).value) {
leftIdx = prevleftIdx - 1;
}
if (!rightReached && getCell(i, rightIdx + 1, sheet, null, true).value) {
rightIdx = prevrightIdx + 1;
}
if (i === btmIdx) {
if (leftIdx === prevleftIdx) {
leftReached = true;
}
if (rightIdx === prevrightIdx) {
rightReached = true;
}
}
if (rightReached && leftReached) {
return [topIdx, leftIdx, btmIdx, rightIdx];
}
}
}
} | the_stack |
import { workspace } from 'vscode';
import { CliCommand, createCliCommand } from './cli';
export function newTknCommand(...tknArguments: string[]): CliCommand {
return createCliCommand('tkn', ...tknArguments);
}
export function newK8sCommand(...k8sArguments: string[]): CliCommand {
return createCliCommand('kubectl', ...k8sArguments);
}
export function newOcCommand(...OcArguments: string[]): CliCommand {
return createCliCommand('oc', ...OcArguments);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function verbose(_target: unknown, key: string, descriptor: any): void {
let fnKey: string | undefined;
// eslint-disable-next-line @typescript-eslint/ban-types
let fn: Function;
if (typeof descriptor.value === 'function') {
fnKey = 'value';
fn = descriptor.value;
} else {
throw new Error('not supported');
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
descriptor[fnKey] = function (...args: any[]) {
const v: number = workspace.getConfiguration('vs-tekton').get('outputVerbosityLevel');
const command: CliCommand = fn.apply(this, args);
if (v > 0) {
command.cliArguments.push('-v', v.toString());
}
return command;
};
}
export class Command {
static printOcVersionJson(): CliCommand {
return newOcCommand('version', '-o', 'json');
}
static kubectlVersion(): CliCommand {
return newK8sCommand('version', '-o', 'json');
}
static listTaskRunsForTasks(task: string): CliCommand {
return newK8sCommand('get', 'taskrun', '-l', `tekton.dev/task=${task}`, '-o', 'json');
}
static listTaskRunsForClusterTasks(clusterTask: string): CliCommand {
return newK8sCommand('get', 'taskrun', '-l', `tekton.dev/clusterTask=${clusterTask}`, '-o', 'json');
}
static resourceList(resource: string): CliCommand {
return newK8sCommand('get', resource, '-o', 'json');
}
static getTaskRun(taskRunName: string): CliCommand {
return newK8sCommand('get', 'taskrun', taskRunName, '-o', 'json');
}
@verbose
static listTaskRunsForTasksInTerminal(task: string): CliCommand {
return newTknCommand('taskrun', 'list', task);
}
static restartPipeline(name: string): CliCommand {
return newTknCommand('pipeline', 'start', name, '--last', '-s', 'pipeline');
}
static deletePipeline(name: string): CliCommand {
return newK8sCommand('delete', 'Pipeline', name);
}
static listPipelineResources(): CliCommand {
return newK8sCommand('get', 'pipelineresources', '-o', 'json');
}
static listTriggerTemplates(): CliCommand {
return newK8sCommand('get', 'triggertemplates', '-o', 'json');
}
static listTriggerBinding(): CliCommand {
return newK8sCommand('get', 'triggerbinding', '-o', 'json');
}
static listClusterTriggerBinding(): CliCommand {
return newK8sCommand('get', 'clustertriggerbinding', '-o', 'json');
}
static deleteClusterTriggerBinding(name: string): CliCommand {
return newK8sCommand('delete', 'ClusterTriggerBinding', name);
}
static listEventListener(): CliCommand {
return newK8sCommand('get', 'eventlistener', '-o', 'json');
}
static featureFlags(): CliCommand {
return newK8sCommand('get', '-n', 'tekton-pipelines', 'configmap', 'feature-flags', '-o', 'json');
}
static deleteTriggerTemplate(name: string): CliCommand {
return newK8sCommand('delete', 'TriggerTemplate', name);
}
static deleteTriggerBinding(name: string): CliCommand {
return newK8sCommand('delete', 'TriggerBinding', name);
}
static deleteCondition(name: string): CliCommand {
return newK8sCommand('delete', 'Condition', name);
}
static deleteEventListeners(name: string): CliCommand {
return newK8sCommand('delete', 'EventListener', name);
}
@verbose
static describePipelineResource(name: string): CliCommand {
return newTknCommand('resource', 'describe', name);
}
static deletePipelineResource(name: string): CliCommand {
return newK8sCommand('delete', 'PipelineResource', name);
}
static listPipelines(): CliCommand {
return newK8sCommand('get', 'pipeline', '-o', 'json');
}
@verbose
static describePipelines(name: string): CliCommand {
return newTknCommand('pipeline', 'describe', name);
}
@verbose
static listPipelineRuns(name: string): CliCommand {
return newK8sCommand('get', 'pipelinerun', '-l', `tekton.dev/pipeline=${name}`, '-o', 'json');
}
@verbose
static describePipelineRuns(name: string): CliCommand {
return newTknCommand('pipelinerun', 'describe', name);
}
@verbose
static cancelPipelineRun(name: string): CliCommand {
return newTknCommand('pipelinerun', 'cancel', name);
}
@verbose
static deletePipelineRun(name: string): CliCommand {
return newK8sCommand('delete', 'PipelineRun', name);
}
@verbose
static showPipelineRunLogs(name: string): CliCommand {
return newTknCommand('pipelinerun', 'logs', name);
}
static showDiagnosticData(name: string): CliCommand {
return newK8sCommand('get', 'pods', name, '-o', 'jsonpath=\'{range .status.conditions[?(.reason)]}{"reason: "}{.reason}{"\\n"}{"message: "}{.message}{"\\n"}{end}\'');
}
static getPipelineRunAndTaskRunData(resource: string, name: string): CliCommand {
return newK8sCommand('get', resource, name, '-o', 'json');
}
@verbose
static listTasks(namespace?: string): CliCommand {
return newK8sCommand('get', 'task.tekton', ...(namespace ? ['-n', namespace] : ''), '-o', 'json');
}
static listTaskRunsForPipelineRun(pipelineRunName: string): CliCommand {
return newK8sCommand('get', 'taskrun', '-l', `tekton.dev/pipelineRun=${pipelineRunName}`, '-o', 'json');
}
static listTaskRunsForPipelineRunInTerminal(pipelineRunName: string): CliCommand {
return newK8sCommand('get', 'taskrun', '-l', `tekton.dev/pipelineRun=${pipelineRunName}`);
}
static getTask(name: string, type: 'clustertask' | 'task.tekton'): CliCommand {
return newK8sCommand('get', type, name, '-o', 'json');
}
@verbose
static deleteTask(name: string): CliCommand {
return newK8sCommand('delete', 'Task', name);
}
@verbose
static listClusterTasks(namespace?: string): CliCommand {
return newK8sCommand('get', 'clustertask', ...(namespace ? ['-n', namespace] : ''), '-o', 'json');
}
@verbose
static deleteClusterTask(name: string): CliCommand {
return newK8sCommand('delete', 'ClusterTask', name);
}
@verbose
static showTaskRunLogs(name: string): CliCommand {
return newTknCommand('taskrun', 'logs', name);
}
@verbose
static deleteTaskRun(name: string): CliCommand {
return newK8sCommand('delete', 'TaskRun', name);
}
@verbose
static printTknVersion(): CliCommand {
return newTknCommand('version');
}
static showPipelineRunFollowLogs(name: string): CliCommand {
return newTknCommand('pipelinerun', 'logs', name, '-f');
}
static showTaskRunFollowLogs(name: string): CliCommand {
return newTknCommand('taskrun', 'logs', name, '-f');
}
static checkTekton(): CliCommand {
return newK8sCommand('auth', 'can-i', 'create', 'pipeline.tekton.dev', '&&', 'kubectl', 'get', 'pipeline.tekton.dev');
}
static updateYaml(fsPath: string): CliCommand {
return newK8sCommand('apply', '-f', fsPath);
}
static hubInstall(name: string, version: string): CliCommand {
return newTknCommand('hub', 'install', 'task', name, '--version', version);
}
static hubTaskUpgrade(name: string, version: string): CliCommand {
return newTknCommand('hub', 'upgrade', 'task', name, '--to', version);
}
static hubTaskDowngrade(name: string, version: string): CliCommand {
return newTknCommand('hub', 'downgrade', 'task', name, '--to', version);
}
static hubTaskReinstall(name: string, version: string): CliCommand {
return newTknCommand('hub', 'reinstall', 'task', name, '--version', version);
}
static listTaskRun(): CliCommand {
return newK8sCommand('get', 'taskrun', '-o', 'json');
}
static listConditions(): CliCommand {
return newK8sCommand('get', 'conditions', '-o', 'json');
}
static listPipelineRun(): CliCommand {
return newK8sCommand('get', 'pipelinerun', '-o', 'json');
}
static watchResources(resourceName: string, name: string): CliCommand {
return newK8sCommand('get', resourceName, name, '-w', '-o', 'json');
}
static loginToContainer(container: string, podName: string, namespace: string): CliCommand {
return newK8sCommand('exec', '-it', '-n', namespace, '-c', container, podName, '--', 'bash');
}
static isContainerStoppedOnDebug(container: string, podName: string, namespace: string): CliCommand {
return newK8sCommand('exec', '-it', '-n', namespace, '-c', container, podName, '--', 'awk \'END{print NR}\' tekton/termination');
}
static debugContinue(container: string, podName: string, namespace: string): CliCommand {
return newK8sCommand('exec', '-it', '-n', namespace, '-c', container, podName, '--', '/tekton/debug/scripts/debug-continue');
}
static debugFailContinue(container: string, podName: string, namespace: string): CliCommand {
return newK8sCommand('exec', '-it', '-n', namespace, '-c', container, podName, '--', '/tekton/debug/scripts/debug-fail-continue');
}
static cancelTaskRun(name: string): CliCommand {
return newTknCommand('taskrun', 'cancel', name);
}
static workspace(name: string): CliCommand {
return newK8sCommand('get', name, '-o', 'json');
}
static getPipelineResource(): CliCommand {
return newK8sCommand('get', 'pipelineresources', '-o', 'json');
}
static getPipelineRun(name: string): CliCommand {
return newK8sCommand('get', 'pipelinerun', name, '-o', 'json');
}
static getPipeline(name: string): CliCommand {
return newK8sCommand('get', 'pipeline', name, '-o', 'json');
}
static getEventListener(name: string): CliCommand {
return newK8sCommand('get', 'el', name, '-o', 'json');
}
static getService(name: string): CliCommand {
return newK8sCommand('get', 'Service', name, '-o', 'json');
}
static create(file: string): CliCommand {
return newK8sCommand('create', '--save-config', '-f', file);
}
static apply(file: string): CliCommand {
return newK8sCommand('apply', '-f', file);
}
static getRoute(name: string): CliCommand {
return newK8sCommand('get', 'route', name, '-o', 'json');
}
static getTrigger(name: string): CliCommand {
return newK8sCommand('get', 'trigger', name, '-o', 'json');
}
} | the_stack |
import { GraphQLSchemaPlugin } from "@webiny/handler-graphql/plugins";
import { ErrorResponse, ListResponse } from "@webiny/handler-graphql";
import {
ApwContentReviewStep,
ApwContentReviewStepStatus,
ApwContext,
ApwContentReviewListParams,
ApwContentReviewContent
} from "~/types";
import resolve from "~/utils/resolve";
const contentReviewSchema = new GraphQLSchemaPlugin<ApwContext>({
typeDefs: /* GraphQL */ `
type ApwContentReviewListItem {
# System generated fields
id: ID
savedOn: DateTime
createdOn: DateTime
createdBy: ApwCreatedBy
# ContentReview specific fields
title: String
steps: [ApwContentReviewStep]
content: ApwContentReviewContent
status: ApwContentReviewStatus
activeStep: ApwContentReviewStep
totalComments: Int
latestCommentId: String
reviewers: [ID!]!
}
type ApwListContentReviewsResponse {
data: [ApwContentReviewListItem]
error: ApwError
meta: ApwMeta
}
type ApwContentReviewReviewer {
id: ID
displayName: String
}
type ApwContentReviewComment {
body: JSON
author: String
}
type ApwContentReviewChangeRequested {
title: String
body: JSON
media: JSON
step: String
resolved: Boolean
comments: [ApwContentReviewComment]
}
enum ApwContentReviewStepStatus {
done
active
inactive
}
enum ApwContentReviewStatus {
underReview
readyToBePublished
published
requiresMyAttention
}
type ApwContentReviewStep {
status: ApwContentReviewStepStatus
id: String
title: String
pendingChangeRequests: Int
signOffProvidedOn: DateTime
signOffProvidedBy: ApwCreatedBy
}
type ApwContentReview {
# System generated fields
id: ID
savedOn: DateTime
createdOn: DateTime
createdBy: ApwCreatedBy
# ContentReview specific fields
title: String
steps: [ApwContentReviewStep]
content: ApwContentReviewContent
workflow: ID
status: ApwContentReviewStatus
}
type ApwContentReviewResponse {
data: ApwContentReview
error: ApwError
}
type ApwDeleteContentReviewResponse {
data: Boolean
error: ApwError
}
enum ApwListContentReviewsSort {
id_ASC
id_DESC
savedOn_ASC
savedOn_DESC
createdOn_ASC
createdOn_DESC
title_ASC
title_DESC
}
input ApwContentReviewReviewerInput {
id: ID
}
input ApwContentReviewScopeInput {
type: String
options: JSON
}
input ApwContentReviewCommentInput {
body: JSON
author: String
}
input ApwContentReviewChangeRequestedInput {
title: String
body: JSON
media: JSON
step: String
resolved: Boolean
comments: [ApwContentReviewCommentInput]
}
enum ApwContentReviewContentTypes {
page
cms_entry
}
type ApwContentReviewContentSettings {
modelId: String
}
input ApwContentReviewContentSettingsInput {
modelId: String
}
type ApwContentReviewContent {
id: ID!
type: ApwContentReviewContentTypes!
version: Int!
settings: ApwContentReviewContentSettings
publishedOn: String
publishedBy: ApwCreatedBy
scheduledOn: DateTime
scheduledBy: ApwCreatedBy
}
input ApwContentReviewContentInput {
id: ID!
type: ApwContentReviewContentTypes!
settings: ApwContentReviewContentSettingsInput
}
input ApwCreateContentReviewInput {
content: ApwContentReviewContentInput!
}
input ApwListContentReviewsWhereInput {
id: ID
status: ApwContentReviewStatus
title: String
title_contains: String
}
type ApwProvideSignOffResponse {
data: Boolean
error: ApwError
}
type ApwIsReviewRequiredData {
isReviewRequired: Boolean
contentReviewId: ID
}
type ApwIsReviewRequiredResponse {
data: ApwIsReviewRequiredData
error: ApwError
}
type ApwPublishContentResponse {
data: Boolean
error: ApwError
}
enum ApwContentActions {
publish
unpublish
}
type ApwScheduleActionResponse {
data: Boolean
error: ApwError
}
input ApwScheduleActionInput {
action: ApwContentActions!
datetime: String!
type: ApwContentReviewContentTypes!
entryId: ID!
}
extend type ApwQuery {
getContentReview(id: ID!): ApwContentReviewResponse
listContentReviews(
where: ApwListContentReviewsWhereInput
limit: Int
after: String
sort: [ApwListContentReviewsSort!]
): ApwListContentReviewsResponse
isReviewRequired(data: ApwContentReviewContentInput!): ApwIsReviewRequiredResponse
}
extend type ApwMutation {
createContentReview(data: ApwCreateContentReviewInput!): ApwContentReviewResponse
deleteContentReview(id: ID!): ApwDeleteContentReviewResponse
provideSignOff(id: ID!, step: String!): ApwProvideSignOffResponse
retractSignOff(id: ID!, step: String!): ApwProvideSignOffResponse
publishContent(id: ID!, datetime: String): ApwPublishContentResponse
unpublishContent(id: ID!, datetime: String): ApwPublishContentResponse
scheduleAction(data: ApwScheduleActionInput!): ApwScheduleActionResponse
deleteScheduledAction(id: ID!): ApwScheduleActionResponse
}
`,
resolvers: {
ApwContentReviewContent: {
version: async (parent: ApwContentReviewContent, _, context: ApwContext) => {
const getContent = context.apw.getContentGetter(parent.type);
const content = await getContent(parent.id, parent.settings);
if (!content) {
return null;
}
return content.version;
},
publishedOn: async (parent: ApwContentReviewContent, _, context: ApwContext) => {
const getContent = context.apw.getContentGetter(parent.type);
const content = await getContent(parent.id, parent.settings);
if (!content) {
return null;
}
return content.publishedOn;
},
publishedBy: async (parent: ApwContentReviewContent, _, context: ApwContext) => {
const id = parent.publishedBy;
if (id) {
const [[reviewer]] = await context.apw.reviewer.list({
where: { identityId: id }
});
return reviewer;
}
return null;
},
scheduledBy: async (parent: ApwContentReviewContent, _, context: ApwContext) => {
const id = parent.scheduledBy;
if (id) {
const [[reviewer]] = await context.apw.reviewer.list({
where: { identityId: id }
});
return reviewer;
}
return null;
}
},
ApwContentReviewListItem: {
activeStep: async parent => {
const steps: ApwContentReviewStep[] = parent.steps;
return steps.find(step => step.status === ApwContentReviewStepStatus.ACTIVE);
},
totalComments: async parent => {
const steps: ApwContentReviewStep[] = parent.steps;
return steps.reduce((count, step) => {
/**
* Aggregate totalComments from each step.
*/
if (!isNaN(step.totalComments)) {
count += step.totalComments;
}
return count;
}, 0);
},
reviewers: async parent => {
const steps: ApwContentReviewStep[] = parent.steps;
const reviewerIds: string[] = [];
for (const step of steps) {
for (const reviewer of step.reviewers) {
if (!reviewerIds.includes(reviewer.id)) {
reviewerIds.push(reviewer.id);
}
}
}
return reviewerIds;
}
},
ApwQuery: {
getContentReview: async (_, args: any, context) => {
return resolve(() => context.apw.contentReview.get(args.id));
},
listContentReviews: async (_, args: any, context) => {
try {
/**
* We know that args is ApwContentReviewListParams.
*/
const [entries, meta] = await context.apw.contentReview.list(
args as unknown as ApwContentReviewListParams
);
return new ListResponse(entries, meta);
} catch (e) {
return new ErrorResponse(e);
}
},
isReviewRequired: async (_, args: any, context) => {
return resolve(() => context.apw.contentReview.isReviewRequired(args.data));
}
},
ApwMutation: {
createContentReview: async (_, args: any, context) => {
return resolve(() => context.apw.contentReview.create(args.data));
},
deleteContentReview: async (_, args: any, context) => {
return resolve(() => context.apw.contentReview.delete(args.id));
},
provideSignOff: async (_, args: any, context) => {
return resolve(() => context.apw.contentReview.provideSignOff(args.id, args.step));
},
retractSignOff: async (_, args: any, context) => {
return resolve(() => context.apw.contentReview.retractSignOff(args.id, args.step));
},
publishContent: async (_, args: any, context) => {
return resolve(() =>
context.apw.contentReview.publishContent(args.id, args.datetime)
);
},
unpublishContent: async (_, args: any, context) => {
return resolve(() =>
context.apw.contentReview.unpublishContent(args.id, args.datetime)
);
},
deleteScheduledAction: async (_, args: any, context) => {
return resolve(() => context.apw.contentReview.deleteScheduledAction(args.id));
}
}
}
});
export default contentReviewSchema; | the_stack |
import uuid from 'uuid/v4';
import {
EventOrdersUpdate,
EventPositionsUpdate,
EventTradesUpdate,
EventWSAuthResult,
EventWSData
} from './constants';
import { loadTradeCredentials } from '../util/credentials';
import { ProtobufBroker, ProtobufStream } from './modules/proto';
import SessionTracker from './SessionTracker';
import { TradeOpts } from './types/client';
import {
BrokerRequest,
CancelOrderOpts,
// ExchangeBalances,
PlaceOrderOpt,
PrivateOrder,
PrivatePosition,
PrivateTrade
} from './types/trading';
import { getNumber } from '../util/helpers';
import logger from '../util/logger';
import proto from './proto';
import WebSocketClient from './WebSocketClient';
import { errNotInitialized, errPlaceOrderBadResponse, errCancelOrderBadResponse } from './errors';
// The number of recent trades kept locally in cache
const tradeCacheLimit = 1000;
// Requests to the trade service time out after 5s
const requestTimeout = 5000;
export class TradeClient extends WebSocketClient {
// Mapping of market id to private orderUpdates
public orders: {
[key: number]: PrivateOrder[];
};
// Mapping of market ids to private trades
public trades: {
[key: number]: PrivateTrade[];
};
// Mapping of market ids to private positions
public positions: {
[key: number]: PrivatePosition[];
};
// List of balances for each exchange with an active session
// public balances: ExchangeBalances[];
private session: SessionTracker;
constructor(opts: Partial<TradeOpts>) {
logger.setLevel(opts.logLevel);
const tradeOpts = loadTradeCredentials(opts);
super(tradeOpts);
if (
!(tradeOpts.tradeSubscriptions instanceof Array) ||
tradeOpts.tradeSubscriptions.length === 0
) {
throw new Error('Missing parameter: tradeSubscriptions');
}
// Keep track of subscriptions for reconnecting
tradeOpts.tradeSubscriptions.forEach((ts) => {
this.subscriptions[ts.marketID] = proto.tradeSubscriptionToProto(ts);
});
this.session = new SessionTracker(tradeOpts.tradeSubscriptions);
this.onDisconnect(() => {
logger.debug('disconnected: resetting session');
this.session.reset();
});
this.on(EventWSData, (data: Buffer) => {
let dataDecoded: ProtobufBroker.BrokerUpdateMessage | null = null;
try {
dataDecoded = ProtobufBroker.BrokerUpdateMessage.decode(data);
} catch (e) {
this.error('Failed to deserialize ProtobufBroker message');
return;
}
this.brokerMessageHandler(dataDecoded);
});
this.orders = {};
this.trades = {};
this.positions = {};
// this.balances = [];
}
public onReady(fn: () => void): void {
this.session.on('ready', () => {
fn();
});
}
public onOrdersUpdate(fn: (o: PrivateOrder[]) => void): void {
this.on(EventOrdersUpdate, (orders) => {
fn(orders);
});
}
public onTradesUpdate(fn: (t: PrivateTrade[]) => void): void {
this.on(EventTradesUpdate, (trades) => {
fn(trades);
});
}
public onPositionsUpdate(fn: (p: PrivatePosition[]) => void): void {
this.on(EventPositionsUpdate, (positions) => {
fn(positions);
});
}
public async placeOrder(opts: Partial<PlaceOrderOpt>): Promise<PrivateOrder> {
if (!this.session.isReady()) {
throw errNotInitialized;
}
if (opts.marketID == null) {
throw new Error('place order opts missing market id');
}
logger.debug('place order request %o', JSON.stringify(opts));
const startTime = new Date();
const response = await this.makeRequest(
opts.marketID,
ProtobufBroker.PlaceOrderRequest.create({
order: proto.placeOrderOptToProto(opts)
}),
opts.requestID
);
if (!response.placeOrderResult || !response.placeOrderResult.order) {
throw errPlaceOrderBadResponse;
}
const po = proto.privateOrderFromProto(response.placeOrderResult.order);
if (!po) {
logger.debug('failed to serialize order result %o', response.placeOrderResult.order);
throw errPlaceOrderBadResponse;
}
logger.debug('order placed', `${new Date().getTime() - startTime.getTime()}s`);
return po;
}
public async cancelOrder(opts: CancelOrderOpts): Promise<void> {
if (typeof opts.orderID !== 'string' || opts.orderID === '') {
throw new Error(`invalid order id: ${opts.orderID}`);
}
logger.debug('sending cancel order request');
const response = await this.makeRequest(
opts.marketID,
ProtobufBroker.CancelOrderRequest.create({
orderId: opts.orderID
}),
opts.requestID
);
logger.debug('order resolution %o', response);
if (!response.cancelOrderResult || response.cancelOrderResult.orderId === null) {
throw errCancelOrderBadResponse;
}
}
private makeRequest(
marketID: number,
request: BrokerRequest,
requestID?: string
): Promise<ProtobufBroker.RequestResolutionUpdate> {
const reqID = requestID || uuid();
let brokerRequest: ProtobufBroker.BrokerRequest;
if (request instanceof ProtobufBroker.PlaceOrderRequest) {
brokerRequest = ProtobufBroker.BrokerRequest.create({
id: reqID,
marketId: Number(marketID),
placeOrderRequest: request
});
} else if (request instanceof ProtobufBroker.CancelOrderRequest) {
brokerRequest = ProtobufBroker.BrokerRequest.create({
id: reqID,
marketId: Number(marketID),
cancelOrderRequest: request
});
} else {
throw new Error('internal error: invalid request');
}
this.send(ProtobufBroker.BrokerRequest.encode(brokerRequest).finish());
return new Promise((resolve, reject): void => {
const timeoutTimer = setTimeout(() => {
reject();
}, requestTimeout);
// TODO (wells) look into how "once" works; could this be a memory leak?
this.once(reqID, (response) => {
clearTimeout(timeoutTimer);
if (response.error !== 0) {
reject(`error: ${response.message}`);
} else {
resolve(response);
}
});
});
}
private brokerMessageHandler(message: ProtobufBroker.BrokerUpdateMessage): void {
const marketID = getNumber(message.marketId);
switch (message.Update) {
case 'authenticationResult':
this.emit(EventWSAuthResult, message.authenticationResult);
break;
case 'ordersUpdate':
logger.debug('call orders update handler %o', message);
if (message.ordersUpdate) {
this.ordersUpdateHandler(marketID, message.ordersUpdate);
}
break;
case 'tradesUpdate':
if (message.tradesUpdate) {
this.tradesUpdateHandler(marketID, message.tradesUpdate);
}
break;
case 'balancesUpdate':
// logger.debug("balance update %o", JSON.stringify(message));
// if (message.balancesUpdate) {
// this.balancesUpdateHandler(marketID, message.balancesUpdate);
// }
break;
case 'positionsUpdate':
if (message.positionsUpdate) {
this.positionsUpdateHandler(marketID, message.positionsUpdate);
}
break;
case 'subscriptionResult':
if (message.subscriptionResult) {
this.subscriptionResultHandler(message.subscriptionResult);
}
break;
case 'sessionStatusUpdate':
if (message.sessionStatusUpdate && !this.session.isModuleReady(marketID, 'initialize')) {
this.sessionStatusUpdateHandler(marketID, message.sessionStatusUpdate);
}
break;
case 'requestResolutionUpdate':
if (message.requestResolutionUpdate) {
this.requestResolutionUpdateHandler(message.requestResolutionUpdate);
}
break;
default:
// unsupported type; no-op
}
}
private ordersUpdateHandler(marketID: number, ordersUpdate: ProtobufBroker.IOrdersUpdate): void {
if (ordersUpdate.orders === null || ordersUpdate.orders === undefined) {
logger.debug('received empty orders update');
return;
}
const newOrders: PrivateOrder[] = [];
ordersUpdate.orders.forEach((o) => {
const order = proto.privateOrderFromProto(o);
if (order != null) {
newOrders.push(order);
}
});
this.orders[marketID] = newOrders;
logger.debug('orders update %o', newOrders);
this.emit(EventOrdersUpdate, newOrders);
this.session.setModuleReady(marketID, 'orderUpdates');
}
private tradesUpdateHandler(marketID: number, tradesUpdate: ProtobufBroker.ITradesUpdate): void {
if (tradesUpdate.trades === null || tradesUpdate.trades === undefined) {
return;
}
const newTrades: PrivateTrade[] = [];
tradesUpdate.trades.forEach((tradeProto) => {
const trade = proto.privateTradeFromProto(tradeProto);
if (trade) {
newTrades.push(trade);
}
});
if (!this.trades[marketID]) {
this.trades[marketID] = [];
}
// Add new trades to old trades
this.trades[marketID] = this.trades[marketID].concat(newTrades);
// Trim cache if it's over the limit
if (this.trades[marketID].length > tradeCacheLimit) {
this.trades[marketID] = this.trades[marketID].slice(0, tradeCacheLimit);
}
logger.debug('trades update %o', newTrades);
this.emit(EventTradesUpdate, newTrades);
this.session.setModuleReady(marketID, 'tradeUpdates');
}
// private balancesUpdateHandler(
// marketID: string,
// balancesUpdate: ProtobufBroker.IBalancesUpdate
// ) {
// if (!balancesUpdate.balances) {
// return;
// }
// // Each balance can apply to multiple markets, so we find the balances index first
// let balancesIndex = -1;
// for (let i = 0; i < this.balances.length; i++) {
// for (const j of this.balances[i].marketIDs) {
// if (j === marketID) {
// balancesIndex = i;
// break;
// }
// }
// if (balancesIndex > -1) {
// break;
// }
// }
// if (balancesIndex === -1) {
// const exchangeBalances: ExchangeBalances = {
// marketIDs: [marketID],
// spot: [],
// margin: []
// };
// }
// balancesUpdate.balances.forEach(balancesProto => {
// const balance = proto.balancesFromProto(balancesProto);
// if (!balance) {
// return;
// }
// });
// this.session.setModuleReady(marketID, "balances");
// logger.debug("balances update");
// // TODO update balances cache
// // TODO emit exchange balances
// // this.emit(EventBalancesUpdate, exchangeBalances);
// }
private positionsUpdateHandler(
marketID: number,
positionsUpdate: ProtobufBroker.IPositionsUpdate
): void {
if (positionsUpdate.positions === null || positionsUpdate.positions === undefined) {
return;
}
const newPositions: PrivatePosition[] = [];
positionsUpdate.positions.forEach((positionProto) => {
const position = proto.privatePositionFromProto(positionProto);
if (!position) {
return;
}
newPositions.push(position);
});
this.positions[marketID] = newPositions;
logger.debug('positions update %o', newPositions);
this.emit(EventPositionsUpdate, newPositions);
this.session.setModuleReady(marketID, 'positionUpdates');
}
private subscriptionResultHandler(subResult: ProtobufStream.ISubscriptionResult): void {
if (subResult.failed instanceof Array) {
subResult.failed.forEach((e) => {
let keyStr = '';
if (e.key) {
keyStr = ` for "${e.key}"`;
}
this.error(`trading session failed${keyStr}: ${e.error}`);
});
}
}
private sessionStatusUpdateHandler(
marketID: number,
sessionStatusUpdate: ProtobufBroker.ISessionStatusUpdate
): void {
if (sessionStatusUpdate.initialized === true) {
logger.debug('session initialized');
this.session.setModuleReady(marketID, 'initialize');
}
}
private requestResolutionUpdateHandler(
requestResolution: ProtobufBroker.IRequestResolutionUpdate
): void {
logger.debug('request resolution %o', requestResolution);
if (requestResolution.id != null) {
this.emit(requestResolution.id, requestResolution);
}
}
} | the_stack |
import React, { useCallback, useMemo, useState } from "react";
import {
GestureResponderEvent,
NativeSyntheticEvent,
StyleProp,
StyleSheet,
TargetedEvent,
TextStyle,
View,
ViewStyle,
} from "react-native";
import Surface, { SurfaceProps } from "./Surface";
import Text from "./Text";
import ActivityIndicator from "./ActivityIndicator";
import Pressable, { PressableProps } from "./Pressable";
import { Color, usePaletteColor } from "./hooks/use-palette-color";
import { useSurfaceScale } from "./hooks/use-surface-scale";
import { useStyles } from "./hooks/use-styles";
import { useAnimatedElevation } from "./hooks/use-animated-elevation";
export interface ButtonProps extends Omit<SurfaceProps, "hitSlop">, Omit<PressableProps, "style" | "children"> {
/**
* The text content of the button.
*/
title: string | React.ReactNode | ((props: { color: string }) => React.ReactNode | null) | null;
/**
* The element placed before the `title`.
*/
leading?: React.ReactNode | ((props: { color: string; size: number }) => React.ReactNode | null) | null;
/**
* The element placed after the `title`.
*/
trailing?: React.ReactNode | ((props: { color: string; size: number }) => React.ReactNode | null) | null;
/**
* The style of the button.
* - `text`: Text buttons are typically used for less important actions (low emphasis).
* - `outlined`: Outlined buttons are used for more emphasis than text buttons due to the stroke (medium emphasis).
* - `contained`: Contained buttons have more emphasis, as they use a color fill and shadow (high emphasis).
*
* @default "contained"
*/
variant?: "text" | "outlined" | "contained";
/**
* The main color of the button.
* for `contained` buttons, this is the background color.
* for `outlined` and `text` buttons, this is the color of the content (text, icons, etc.).
*
* @default "primary"
*/
color?: Color;
/**
* The color of the `contained` buttons content (text, icons, etc.). No effect on `outlined` and `text` buttons.
*/
tintColor?: Color;
/**
* Smaller horizontal padding, useful for `text` buttons in a row.
*
* @default false
*/
compact?: boolean;
/**
* If `true`, no shadow is used. No effect on `outlined` and `text` buttons.
*
* @default false
*/
disableElevation?: boolean;
/**
* If `false`, the button title is not rendered in upper case. No effect if you pass a React.Node as the `title` prop.
*
* @default true
*/
uppercase?: boolean;
/**
* Whether to show a loading indicator.
*
* @default false
*/
loading?: boolean;
/**
* The place where the loading indicator should appear.
* - `leading`: The indicator will replace the `leading` element.
* - `trailing`: The indicator will replace the `trailing` element.
* - `overlay`: The indicator will be added as an overlay over the button.
*
* @default "leading"
*/
loadingIndicatorPosition?: "leading" | "trailing" | "overlay";
/**
* A React.Node to replace the default loading indicator. Also, you can pass a string to show a text (e.g. "Loading...").
*/
loadingIndicator?: string | React.ReactNode | ((props: { color: string }) => React.ReactNode | null) | null;
/**
* The style of the button's pressable component container.
*/
pressableContainerStyle?: StyleProp<ViewStyle>;
/**
* The style of the button's container.
*/
contentContainerStyle?: PressableProps["style"];
/**
* The style of the button's text. No effect if you pass a React.Node as the `title` prop.
*/
titleStyle?: StyleProp<TextStyle>;
/**
* The style of the button's leading element container.
*/
leadingContainerStyle?: StyleProp<ViewStyle>;
/**
* The style of the button's trailing element container.
*/
trailingContainerStyle?: StyleProp<ViewStyle>;
/**
* The style of the button's loading indicator overlay view. No effect if `loadingIndicatorPosition` is not `overlay`.
*/
loadingOverlayContainerStyle?: StyleProp<ViewStyle>;
}
const Button: React.FC<ButtonProps> = ({
title,
leading,
trailing,
variant = "contained",
color = "primary",
tintColor,
compact = false,
disableElevation = false,
uppercase = true,
loading = false,
loadingIndicatorPosition = "leading",
loadingIndicator,
style,
pressableContainerStyle,
contentContainerStyle,
titleStyle,
leadingContainerStyle,
trailingContainerStyle,
loadingOverlayContainerStyle,
pressEffect,
pressEffectColor,
onPress,
onPressIn,
onPressOut,
onLongPress,
onBlur,
onFocus,
onMouseEnter,
onMouseLeave,
delayLongPress,
disabled,
hitSlop,
pressRetentionOffset,
android_disableSound,
android_ripple,
testOnly_pressed,
...rest
}) => {
const surfaceScale = useSurfaceScale();
const p = usePaletteColor(
disabled ? surfaceScale(0.12).hex() : color,
disabled ? surfaceScale(0.35).hex() : tintColor,
);
const contentColor = useMemo(
() => (variant === "contained" ? p.on : disabled ? p.on : p.main),
[variant, p, disabled],
);
const hasLeading = useMemo(
() => !!leading || (loading && loadingIndicatorPosition === "leading"),
[leading, loading, loadingIndicatorPosition],
);
const hasTrailing = useMemo(
() => !!trailing || (loading && loadingIndicatorPosition === "trailing"),
[trailing, loading, loadingIndicatorPosition],
);
const styles = useStyles(
({ palette, shapes }) => ({
container: {
backgroundColor: variant === "contained" ? p.main : "transparent",
},
outline: {
...shapes.small,
borderWidth: 1,
borderColor: surfaceScale(0.12).hex(),
},
pressableContainer: {
...shapes.small,
overflow: "hidden",
},
pressable: {
minWidth: 64,
height: 36,
flexDirection: "row",
justifyContent: "center",
alignItems: "center",
paddingStart: hasLeading ? (compact ? 6 : 12) : compact ? 8 : 16,
paddingEnd: hasTrailing ? (compact ? 6 : 12) : compact ? 8 : 16,
},
titleStyle: {
textTransform: uppercase ? "uppercase" : "none",
opacity: loading && loadingIndicatorPosition === "overlay" ? 0 : 1,
},
leadingContainer: {
marginEnd: compact ? 6 : 8,
opacity: loading && loadingIndicatorPosition === "overlay" ? 0 : 1,
},
trailingContainer: {
marginStart: compact ? 6 : 8,
opacity: loading && loadingIndicatorPosition === "overlay" ? 0 : 1,
},
loadingOverlayContainer: {
...StyleSheet.absoluteFillObject,
justifyContent: "center",
alignItems: "center",
},
}),
[variant, uppercase, compact, loading, loadingIndicatorPosition, p, hasLeading, hasTrailing, surfaceScale],
);
const getTitle = () => {
switch (typeof title) {
case "string":
return (
<Text variant="button" selectable={false} style={[{ color: contentColor }, styles.titleStyle, titleStyle]}>
{title}
</Text>
);
case "function":
return title({ color: contentColor });
default:
return title;
}
};
const getLoadingIndicator = () => {
if (!loadingIndicator) return <ActivityIndicator color={contentColor} />;
switch (typeof loadingIndicator) {
case "string":
return (
<Text variant="button" style={{ color: contentColor }}>
{loadingIndicator}
</Text>
);
case "function":
return loadingIndicator({ color: contentColor });
default:
return loadingIndicator;
}
};
const getLeading = () => {
if (loading && loadingIndicatorPosition === "leading") return getLoadingIndicator();
return typeof leading === "function" ? leading({ color: contentColor, size: 18 }) : leading;
};
const getTrailing = () => {
if (loading && loadingIndicatorPosition === "trailing") return getLoadingIndicator();
return typeof trailing === "function" ? trailing({ color: contentColor, size: 18 }) : trailing;
};
const [hovered, setHovered] = useState(false);
const handleMouseEnter = useCallback((event: NativeSyntheticEvent<TargetedEvent>) => {
onMouseEnter?.(event);
setHovered(true);
}, [onMouseEnter]);
const handleMouseLeave = useCallback((event: NativeSyntheticEvent<TargetedEvent>) => {
onMouseLeave?.(event);
setHovered(false);
}, [onMouseLeave]);
const [pressed, setPressed] = useState(false);
const handlePressIn = useCallback((event: GestureResponderEvent) => {
onPressIn?.(event);
setPressed(true);
}, [onPressIn])
const handlePressOut = useCallback((event: GestureResponderEvent) => {
onPressOut?.(event);
setPressed(false);
}, [onPressOut])
const animatedElevation = useAnimatedElevation(variant === "contained" && !disableElevation && !disabled ? pressed ? 8 : hovered ? 4 : 2 : 0)
return (
<Surface category="small" style={[animatedElevation, styles.container, style]} {...rest}>
<View style={[styles.pressableContainer, pressableContainerStyle]}>
<Pressable
style={[styles.pressable, contentContainerStyle]}
pressEffect={pressEffect}
pressEffectColor={pressEffectColor ?? contentColor}
onPress={onPress}
onPressIn={handlePressIn}
onPressOut={handlePressOut}
onLongPress={onLongPress}
onBlur={onBlur}
onFocus={onFocus}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
delayLongPress={delayLongPress}
disabled={disabled}
hitSlop={hitSlop}
pressRetentionOffset={pressRetentionOffset}
android_disableSound={android_disableSound}
android_ripple={android_ripple}
testOnly_pressed={testOnly_pressed}
>
{hasLeading && <View style={[styles.leadingContainer, leadingContainerStyle]}>{getLeading()}</View>}
{getTitle()}
{hasTrailing && <View style={[styles.trailingContainer, trailingContainerStyle]}>{getTrailing()}</View>}
{loading && loadingIndicatorPosition === "overlay" && (
<View style={[styles.loadingOverlayContainer, loadingOverlayContainerStyle]}>{getLoadingIndicator()}</View>
)}
</Pressable>
</View>
{variant === 'outlined' && <View style={[StyleSheet.absoluteFill, styles.outline]} pointerEvents="none" />}
</Surface>
);
};
export default Button; | the_stack |
import * as ethers from 'ethers'
import * as fs from 'fs'
import {
maciContractAbi,
formatProofForVerifierContract,
} from 'maci-contracts'
import {
genBatchUstProofAndPublicSignals,
verifyBatchUstProof,
getSignalByNameViaSym,
} from 'maci-circuits'
import {
PubKey,
PrivKey,
Keypair,
StateLeaf,
} from 'maci-domainobjs'
import {
delay,
promptPwd,
validateEthSk,
validateEthAddress,
contractExists,
genMaciStateFromContract,
checkDeployerProviderConnection,
readJSONFile,
} from './utils'
import {contractFilepath} from './config'
import {
DEFAULT_ETH_PROVIDER,
DEFAULT_ETH_SK,
} from './defaults'
const configureSubparser = (subparsers: any) => {
const parser = subparsers.addParser(
'proveOnChain',
{ addHelp: true },
)
parser.addArgument(
['-e', '--eth-provider'],
{
action: 'store',
type: 'string',
help: `A connection string to an Ethereum provider. Default: ${DEFAULT_ETH_PROVIDER}`,
}
)
const maciPrivkeyGroup = parser.addMutuallyExclusiveGroup({ required: true })
maciPrivkeyGroup.addArgument(
['-dsk', '--prompt-for-maci-privkey'],
{
action: 'storeTrue',
help: 'Whether to prompt for your serialized MACI private key',
}
)
maciPrivkeyGroup.addArgument(
['-sk', '--privkey'],
{
action: 'store',
type: 'string',
help: 'Your serialized MACI private key',
}
)
const ethPrivkeyGroup = parser.addMutuallyExclusiveGroup({ required: false })
ethPrivkeyGroup.addArgument(
['-dp', '--prompt-for-eth-privkey'],
{
action: 'storeTrue',
help: 'Whether to prompt for the user\'s Ethereum private key and ignore -d / --eth-privkey',
}
)
ethPrivkeyGroup.addArgument(
['-d', '--eth-privkey'],
{
action: 'store',
type: 'string',
help: 'The deployer\'s Ethereum private key',
}
)
parser.addArgument(
['-x', '--contract'],
{
type: 'string',
help: 'The MACI contract address',
}
)
parser.addArgument(
['-o', '--proof-file'],
{
required: true,
type: 'string',
help: 'The proof output file from the genProofs subcommand',
}
)
}
const proveOnChain = async (args: any) => {
let contractAddrs = readJSONFile(contractFilepath)
if ((!contractAddrs||!contractAddrs["MACI"]) && !args.contract) {
console.error('Error: MACI contract address is empty')
return
}
const maciAddress = args.contract ? args.contract: contractAddrs["MACI"]
// MACI contract
if (!validateEthAddress(maciAddress)) {
console.error('Error: invalid MACI contract address')
return
}
let ethSk
// The coordinator's Ethereum private key
// The user may either enter it as a command-line option or via the
// standard input
if (args.prompt_for_eth_privkey) {
ethSk = await promptPwd('Your Ethereum private key')
} else {
ethSk = args.eth_privkey?args.eth_privkey:DEFAULT_ETH_SK
}
if (ethSk.startsWith('0x')) {
ethSk = ethSk.slice(2)
}
if (!validateEthSk(ethSk)) {
console.error('Error: invalid Ethereum private key')
return
}
// Ethereum provider
const ethProvider = args.eth_provider ? args.eth_provider : DEFAULT_ETH_PROVIDER
if (! (await checkDeployerProviderConnection(ethSk, ethProvider))) {
console.error('Error: unable to connect to the Ethereum provider at', ethProvider)
return
}
const provider = new ethers.providers.JsonRpcProvider(ethProvider)
const wallet = new ethers.Wallet(ethSk, provider)
if (! (await contractExists(provider, maciAddress))) {
console.error('Error: there is no contract deployed at the specified address')
return
}
// The coordinator's MACI private key
// They may either enter it as a command-line option or via the
// standard input
let coordinatorPrivkey
if (args.prompt_for_maci_privkey) {
coordinatorPrivkey = await promptPwd('Coordinator\'s MACI private key')
} else {
coordinatorPrivkey = args.privkey
}
if (!PrivKey.isValidSerializedPrivKey(coordinatorPrivkey)) {
console.error('Error: invalid MACI private key')
return
}
const maciContract = new ethers.Contract(
maciAddress,
maciContractAbi,
wallet,
)
// Check that the contract is ready to accept proofs
const currentMessageBatchIndex = Number(await maciContract.currentMessageBatchIndex())
const numMessages = Number(await maciContract.numMessages())
const messageBatchSize = Number(await maciContract.messageBatchSize())
const numSignUps = Number(await maciContract.numSignUps())
const tallyBatchSize = Number(await maciContract.tallyBatchSize())
const expectedIndex = Math.floor(numMessages / messageBatchSize) * messageBatchSize
if (currentMessageBatchIndex > expectedIndex) {
console.error('Error: unexpected current message batch index. Is the contract address correct?')
return
}
// Read the proof file
let data
if (typeof args.proof_file === 'object' && args.proof_file !== null) {
// Argument is a javascript object
data = args.proof_file
} else {
// Argument is a filename
try {
data = JSON.parse(fs.readFileSync(args.proof_file).toString())
if (data.processProofs == undefined || data.tallyProofs == undefined) {
throw new Error()
}
} catch {
console.error('Error: could not parse the proof file')
return
}
}
// Check that the proof file is complete
const expectedNumProcessProofs =
numMessages % messageBatchSize === 0 ?
numMessages / messageBatchSize
:
1 + Math.floor(numMessages / messageBatchSize)
const expectedNumTallyProofs = (1 + numSignUps) % tallyBatchSize === 0 ?
(1 + numSignUps) / tallyBatchSize
:
1 + Math.floor((1 + numSignUps) / tallyBatchSize)
if (expectedNumProcessProofs !== data.processProofs.length) {
console.error('Error: the message processing proofs in', args.proof_file, 'are incomplete')
return
}
if (expectedNumTallyProofs !== data.tallyProofs.length) {
console.error('Error: the vote tallying proofs in', args.proof_file, 'are incomplete')
return
}
// ------------------------------------------------------------------------
// Message processing proofs
console.log('\nSubmitting proofs of message processing...')
// Get the maximum message batch index
const maxMessageBatchIndex = numMessages % messageBatchSize === 0 ?
(numMessages / messageBatchSize - 1) * messageBatchSize
:
Math.floor(numMessages / messageBatchSize) * messageBatchSize
// Get the number of processed message batches
let numProcessedMessageBatches
if (! (await maciContract.hasUnprocessedMessages())) {
numProcessedMessageBatches = data.processProofs.length
} else {
numProcessedMessageBatches = (
maxMessageBatchIndex - currentMessageBatchIndex
) / messageBatchSize
}
for (let i = numProcessedMessageBatches; i < data.processProofs.length; i ++) {
console.log(`\nProgress: ${i+1}/${data.processProofs.length}`)
const p = data.processProofs[i]
//const circuitInputs = p.circuitInputs
const stateRootAfter = BigInt(p.stateRootAfter)
const proof = p.proof
const ecdhPubKeys = p.ecdhPubKeys.map((x) => PubKey.unserialize(x))
const formattedProof = formatProofForVerifierContract(proof)
const txErr = 'Error: batchProcessMessage() failed'
let tx
try {
tx = await maciContract.batchProcessMessage(
'0x' + stateRootAfter.toString(16),
ecdhPubKeys.map((x) => x.asContractParam()),
formattedProof,
{ gasLimit: 2000000 },
)
} catch (e) {
console.error(txErr)
console.error(e)
break
}
const receipt = await tx.wait()
if (receipt.status !== 1) {
console.error(txErr)
break
}
console.log(`Transaction hash: ${tx.hash}`)
}
// ------------------------------------------------------------------------
// Vote tallying proofs
console.log('Submitting proofs of vote tallying...')
// Get the maximum tally batch index
const maxTallyBatchIndex = (1 + numSignUps) % tallyBatchSize === 0 ?
(1 + numSignUps) / tallyBatchSize
:
1 + Math.floor((1 + numSignUps) / tallyBatchSize)
// Get the number of processed message batches
const currentQvtBatchNum = Number(await maciContract.currentQvtBatchNum())
for (let i = currentQvtBatchNum; i < maxTallyBatchIndex; i ++) {
console.log(`\nProgress: ${i+1}/${maxTallyBatchIndex}`)
const p = data.tallyProofs[i]
const proof = p.proof
const circuitInputs = p.circuitInputs
const newResultsCommitment = p.newResultsCommitment
const newSpentVoiceCreditsCommitment = p.newSpentVoiceCreditsCommitment
const newPerVOSpentVoiceCreditsCommitment = p.newPerVOSpentVoiceCreditsCommitment
const totalVotes = p.totalVotes
const totalVotesPublicInput = BigInt(circuitInputs.isLastBatch) === BigInt(1) ? totalVotes.toString() : 0
let tx
const txErr = 'Error: proveVoteTallyBatch() failed'
const formattedProof = formatProofForVerifierContract(proof)
try {
tx = await maciContract.proveVoteTallyBatch(
circuitInputs.intermediateStateRoot.toString(),
newResultsCommitment.toString(),
newSpentVoiceCreditsCommitment.toString(),
newPerVOSpentVoiceCreditsCommitment.toString(),
totalVotesPublicInput.toString(),
formattedProof,
{ gasLimit: 2000000 },
)
} catch (e) {
console.error('Error: proveVoteTallyBatch() failed')
console.error(txErr)
console.error(e)
break
}
const receipt = await tx.wait()
if (receipt.status !== 1) {
console.error(txErr)
break
}
console.log(`Transaction hash: ${tx.hash}`)
}
console.log('OK')
}
export {
proveOnChain,
configureSubparser,
} | the_stack |
export interface RPCHandler {
(...args: any[]): any;
}
export interface RPCError {
code: number;
message: string;
data: any;
}
export interface RPCEvent {
emit(event: string, ...args: any[]): void;
on(event: string, fn: RPCHandler): void;
off(event: string, fn?: RPCHandler): void;
onerror: null | ((error: RPCError) => void);
destroy?: () => void;
}
export interface RPCMessageDataFormat {
event: string;
args: any[];
}
export interface RPCPostMessageConfig extends WindowPostMessageOptions {}
export interface AbstractMessageSendEndpoint {
// BroadcastChannel
// postMessage(message: any): void;
// Wroker && ServiceWorker && MessagePort
// postMessage(message: any, transfer: Transferable[]): void;
// postMessage(message: any, options?: StructuredSerializeOptions): void;
// window
// postMessage(message: any, targetOrigin: string, transfer?: Transferable[]): void;
postMessage(message: any, options?: WindowPostMessageOptions): void;
}
export interface AbstractMessageReceiveEndpoint extends AbstractMessageSendEndpoint {
onmessage?: ((this: any, ev: MessageEvent) => any) | null;
onmessageerror?: ((this: any, ev: MessageEvent) => any) | null;
/** Disconnects the port, so that it is no longer active. */
close?: () => void;
/** Begins dispatching messages received on the port. */
start?: () => void;
addEventListener<K extends keyof MessagePortEventMap>(
type: K,
listener: (this: any, ev: MessagePortEventMap[K]) => any,
options?: boolean | AddEventListenerOptions
): void;
addEventListener(
type: string,
listener: EventListenerOrEventListenerObject,
options?: boolean | AddEventListenerOptions
): void;
removeEventListener<K extends keyof MessagePortEventMap>(
type: K,
listener: (this: any, ev: MessagePortEventMap[K]) => any,
options?: boolean | EventListenerOptions
): void;
removeEventListener(
type: string,
listener: EventListenerOrEventListenerObject,
options?: boolean | EventListenerOptions
): void;
}
export interface RPCMessageReceiveEndpoint extends AbstractMessageReceiveEndpoint {}
export interface RPCMessageSendEndpoint extends AbstractMessageSendEndpoint {}
export interface RPCMessageEventOptions {
currentEndpoint: RPCMessageReceiveEndpoint;
targetEndpoint: RPCMessageSendEndpoint;
config?:
| ((data: any, context: RPCMessageSendEndpoint) => RPCPostMessageConfig)
| RPCPostMessageConfig;
sendAdapter?: (
data: RPCMessageDataFormat | any,
context: RPCMessageSendEndpoint
) => {
data: RPCMessageDataFormat;
transfer?: Transferable[];
};
receiveAdapter?: (event: MessageEvent) => RPCMessageDataFormat;
}
export const RPCCodes: Record<string, Pick<RPCError, 'code' | 'message'>> = {
CONNECT_TIMEOUT: {
code: -32300,
message: 'Connect timeout',
},
APPLICATION_ERROR: {
code: -32500,
message: 'Application error',
},
METHOD_NOT_FOUND: {
code: -32601,
message: `Method not found`,
},
};
export class RPCMessageEvent implements RPCEvent {
private _currentEndpoint: RPCMessageEventOptions['currentEndpoint'];
private _targetEndpoint: RPCMessageEventOptions['targetEndpoint'];
private _events: Record<string, Array<RPCHandler>>;
private _originOnmessage: ((event: MessageEvent) => void) | null;
private _receiveMessage: (event: MessageEvent) => void;
onerror: null | ((error: RPCError) => void) = null;
config?: RPCMessageEventOptions['config'];
sendAdapter?: RPCMessageEventOptions['sendAdapter'];
receiveAdapter?: RPCMessageEventOptions['receiveAdapter'];
constructor(options: RPCMessageEventOptions) {
this._events = {};
this._currentEndpoint = options.currentEndpoint;
this._targetEndpoint = options.targetEndpoint;
this._originOnmessage = null;
// hooks
this.config = options.config;
this.receiveAdapter = options.receiveAdapter;
this.sendAdapter = options.sendAdapter;
const receiveMessage = (event: MessageEvent) => {
const receiveData = this.receiveAdapter
? this.receiveAdapter(event)
: (event.data as RPCMessageDataFormat);
if (receiveData && typeof receiveData.event === 'string') {
const eventHandlers = this._events[receiveData.event] || [];
if (eventHandlers.length) {
eventHandlers.forEach((handler) => {
handler(...(receiveData.args || []));
});
return;
}
// method not found
if (this.onerror) {
this.onerror({
...RPCCodes.METHOD_NOT_FOUND,
data: receiveData,
});
}
}
};
if (this._currentEndpoint.addEventListener) {
if ('start' in this._currentEndpoint && this._currentEndpoint.start) {
this._currentEndpoint.start();
}
this._currentEndpoint.addEventListener(
'message',
receiveMessage as EventListenerOrEventListenerObject,
false
);
this._receiveMessage = receiveMessage;
return;
}
// some plugine env don't support addEventListener(like figma.ui)
// @ts-ignore
this._originOnmessage = this._currentEndpoint.onmessage;
// @ts-ignore
this._currentEndpoint.onmessage = (event: MessageEvent) => {
if (this._originOnmessage) {
this._originOnmessage(event);
}
receiveMessage(event);
};
// @ts-ignore
this._receiveMessage = this._currentEndpoint.onmessage;
}
emit(event: string, ...args: any[]): void {
const data: RPCMessageDataFormat = {
event,
args,
};
const result = this.sendAdapter ? this.sendAdapter(data, this._targetEndpoint) : { data };
const sendData = result.data || data;
const postMessageConfig = this.config
? typeof this.config === 'function'
? this.config(sendData, this._targetEndpoint) || {}
: this.config || {}
: {};
if (Array.isArray(result.transfer) && result.transfer.length) {
postMessageConfig.transfer = result.transfer;
}
this._targetEndpoint.postMessage(sendData, postMessageConfig);
}
on(event: string, fn: RPCHandler): void {
if (!this._events[event]) {
this._events[event] = [];
}
this._events[event].push(fn);
}
off(event: string, fn?: RPCHandler): void {
if (!this._events[event]) return;
if (!fn) {
this._events[event] = [];
return;
}
const handlers = this._events[event] || [];
this._events[event] = handlers.filter((handler) => handler !== fn);
}
destroy(): void {
if (this._currentEndpoint.removeEventListener) {
this._currentEndpoint.removeEventListener(
'message',
this._receiveMessage as EventListenerOrEventListenerObject,
false
);
return;
}
try {
// @ts-ignore
this._currentEndpoint.onmessage = this._originOnmessage;
} catch (error) {
console.warn(error);
}
}
}
export interface RPCInitOptions {
event: RPCEvent;
methods?: Record<string, RPCHandler>;
timeout?: number;
}
export interface RPCSYNEvent {
jsonrpc: '2.0';
method: string;
params: any[];
id?: string;
}
export interface RPCSACKEvent {
jsonrpc: '2.0';
result?: any;
error?: RPCError;
id?: string;
}
export interface RPCInvokeOptions {
isNotify?: boolean;
timeout?: number;
}
export class RPC {
private _event: RPCEvent;
private _methods: Record<string, RPCHandler> = {};
private _timeout: number = 0;
private _$connect: Promise<void> | null = null;
static CODES = RPCCodes;
static EVENT = {
SYN_SIGN: 'syn:',
ACK_SIGN: 'ack:',
CONNECT: '__rpc_connect_event',
SYNC_METHODS: '__rpc_sync_methods_event',
};
static uuid(): string {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = (Math.random() * 16) | 0;
const v = c == 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
constructor(options: RPCInitOptions) {
this._event = options.event;
this._timeout = options.timeout || 0;
if (options.methods) {
Object.entries(options.methods).forEach(([method, handler]) => {
this.registerMethod(method, handler);
});
}
this._event.onerror = (error) => {
const { code, message, data } = error;
if (data.event && Array.isArray(data.args) && data.args.length) {
const synEventData = data.args[0] as RPCSYNEvent;
const ackEventName = this._getAckEventName(synEventData.method);
const ackEventData: RPCSACKEvent = {
jsonrpc: '2.0',
id: synEventData?.id,
error: {
code,
message,
data: synEventData,
},
};
this._event.emit(ackEventName, ackEventData);
} else {
console.error(error);
}
};
this.connect();
}
_getSynEventName(method: string): string {
return `${RPC.EVENT.SYN_SIGN}${method}`;
}
_getAckEventName(method: string): string {
return `${RPC.EVENT.ACK_SIGN}${method}`;
}
// check connect
connect(timeout?: number): Promise<void> {
if (this._$connect) {
return this._$connect;
}
this._$connect = new Promise((resolve, reject) => {
const connectTimeout = timeout || this._timeout;
let connectTimer: ReturnType<typeof setTimeout>;
if (connectTimeout) {
connectTimer = setTimeout(() => {
const error: RPCError = {
...RPCCodes.TIMEOUT,
data: { timeout: connectTimeout },
};
reject(error);
}, connectTimeout);
}
const connectEventName = RPC.EVENT.CONNECT;
const connectAckEventName = this._getAckEventName(connectEventName);
const connectSynEventName = this._getSynEventName(connectEventName);
const resolveConnectEvent = () => {
clearTimeout(connectTimer);
resolve();
};
// listen connect ask event && resolve
this._event.on(connectAckEventName, resolveConnectEvent);
const connectSynEventHandler = () => {
// send ack
this._event.emit(connectAckEventName);
resolveConnectEvent();
};
// listen connect syn event && resolve
this._event.on(connectSynEventName, connectSynEventHandler);
// send syn
this._event.emit(connectSynEventName);
});
return this._$connect;
}
registerMethod(method: string, handler: RPCHandler) {
if (this._methods[method]) {
throw new Error(`${method} already registered`);
}
this._methods[method] = handler;
const synEventName = this._getSynEventName(method);
const synEventHandler = (synEventData: RPCSYNEvent) => {
const ackEventName = this._getAckEventName(method);
// notify not need ack
if (!synEventData.id) {
handler(...synEventData.params);
return;
}
Promise.resolve(handler(...synEventData.params))
.then((result) => {
const ackEventData: RPCSACKEvent = {
jsonrpc: '2.0',
result,
id: synEventData.id,
};
this._event.emit(ackEventName, ackEventData);
})
.catch((error) => {
const ackEventData: RPCSACKEvent = {
jsonrpc: '2.0',
id: synEventData.id,
error: {
code: error?.code || RPCCodes.APPLICATION_ERROR.code,
message: error?.message || RPCCodes.APPLICATION_ERROR.message,
data: null,
},
};
this._event.emit(ackEventName, ackEventData);
});
};
this._event.on(synEventName, synEventHandler);
}
removeMethod(method: string) {
if (!this._methods[method]) {
delete this._methods[method];
}
const synEventName = this._getSynEventName(method);
this._event.off(synEventName);
}
invoke(method: string, ...args: any[] | [...any[], RPCInvokeOptions]): Promise<any> {
return new Promise((resolve, reject) => {
const lastArg = args[args.length - 1];
const hasInvokeOptions =
lastArg &&
typeof lastArg === 'object' &&
(Reflect.has(lastArg, 'isNotify') || Reflect.has(lastArg, 'timeout'));
const options: RPCInvokeOptions = hasInvokeOptions
? lastArg
: { isNotify: false, timeout: 0 };
const params = hasInvokeOptions ? args.slice(0, -1) : args;
const synEventName = this._getSynEventName(method);
const synEventId = RPC.uuid();
const synEventData: RPCSYNEvent = {
jsonrpc: '2.0',
method,
params,
id: synEventId,
};
this._event.emit(synEventName, synEventData);
if (!options.isNotify) {
const ackEventName = this._getAckEventName(method);
const timeout = options.timeout || this._timeout;
let timer: ReturnType<typeof setTimeout>;
if (timeout) {
timer = setTimeout(() => {
const error: RPCError = {
...RPCCodes.CONNECT_TIMEOUT,
data: { timeout },
};
reject(error);
}, timeout);
}
const ackEventHandler = (ackEventData: RPCSACKEvent) => {
if (ackEventData.id === synEventId) {
clearTimeout(timer);
this._event.off(ackEventName, ackEventHandler);
if (!ackEventData.error) {
resolve(ackEventData.result);
} else {
reject(ackEventData.error);
}
}
};
this._event.on(ackEventName, ackEventHandler);
} else {
// notify is not need ack
resolve(undefined);
}
});
}
destroy(): void {
Object.entries(this._methods).forEach(([method]) => {
const synEventName = this._getSynEventName(method);
this._event.off(synEventName);
});
const connectAckEventName = this._getAckEventName(RPC.EVENT.CONNECT);
const connectSynEventName = this._getSynEventName(RPC.EVENT.CONNECT);
this._event.off(connectSynEventName);
this._event.off(connectAckEventName);
if (this._event.destroy) {
this._event.destroy();
}
}
} | the_stack |
import { get } from '@microsoft/sp-lodash-subset';
import { ISiteScriptAction } from '../../models/ISiteScript';
import DefaultSchema from '../../schema/schema';
import { ServiceScope, ServiceKey } from '@microsoft/sp-core-library';
import { HttpClient, SPHttpClient } from '@microsoft/sp-http';
export interface ISiteScriptSchemaService {
configure(schemaJSONorURL?: string, forceReconfigure?: boolean): Promise<any>;
getNewSiteScript(): any;
getSiteScriptSchema(): any;
getActionSchema(action: ISiteScriptAction): any;
getActionTitle(action: ISiteScriptAction, parentAction?: ISiteScriptAction): string;
getActionTitleByVerb(actionVerb: string, parentActionVerb?: string): string;
getActionDescription(action: ISiteScriptAction, parentAction?: ISiteScriptAction): string;
getActionDescriptionByVerb(actionVerb: string, parentActionVerb?: string): string;
getSubActionSchemaByVerbs(parentActionVerb: string, subActionVerb: string): any;
getSubActionSchema(parentAction: ISiteScriptAction, subAction: ISiteScriptAction): any;
getAvailableActions(): string[];
getAvailableSubActions(parentAction: ISiteScriptAction): string[];
}
export class SiteScriptSchemaService implements ISiteScriptSchemaService {
private schema: any = null;
private isConfigured: boolean = false;
private availableActions: string[] = null;
private availableSubActionByVerb: {} = null;
private availableActionSchemas = null;
private availableSubActionSchemasByVerb = null;
constructor(private serviceScope: ServiceScope) {}
private _getElementSchema(object: any, property: string = null): any {
let value = !property ? object : object[property];
if (value['$ref']) {
let path = value['$ref'];
return this._getPropertyFromPath(this.schema, path);
}
return value;
}
private _getPropertyFromPath(object: any, path: string, separator: string = '/'): any {
path = path.replace('#/', '').replace('#', '').replace(new RegExp(separator, 'g'), '.');
return get(object, path);
}
private _getVerbFromActionSchema(actionDefinition: any): string {
if (
!actionDefinition.properties ||
!actionDefinition.properties.verb ||
!actionDefinition.properties.verb.enum ||
!actionDefinition.properties.verb.enum.length
) {
throw new Error('Invalid Action schema');
}
return actionDefinition.properties.verb.enum[0];
}
private _getSubActionsSchemaFromParentActionSchema(parentActionDefinition: any): any[] {
if (!parentActionDefinition.properties) {
throw new Error('Invalid Action schema');
}
if (!parentActionDefinition.properties.subactions) {
return null;
}
if (
parentActionDefinition.properties.subactions.type != 'array' ||
!parentActionDefinition.properties.subactions.items ||
!parentActionDefinition.properties.subactions.items.anyOf
) {
throw new Error('Invalid Action schema');
}
return parentActionDefinition.properties.subactions.items.anyOf.map((subActionSchema) =>
this._getElementSchema(subActionSchema)
);
}
public configure(schemaJSONorURL?: string, forceReconfigure: boolean = false): Promise<void> {
return new Promise((resolve, reject) => {
if (this.isConfigured && !forceReconfigure) {
resolve();
return;
}
this._loadSchema(schemaJSONorURL)
.then((schema) => {
if (!schema) {
reject('Schema cannot be found');
return;
}
this.schema = schema;
try {
// Get available action schemas
let actionsArraySchema = this.schema.properties.actions;
if (!actionsArraySchema.type || actionsArraySchema.type != 'array') {
throw new Error('Invalid Actions schema');
}
if (!actionsArraySchema.items || !actionsArraySchema.items.anyOf) {
throw new Error('Invalid Actions schema');
}
let actionsArraySchemaItems = actionsArraySchema.items;
// Get Main Actions schema
let availableActionSchemasAsArray: any[] = actionsArraySchemaItems.anyOf.map((action) =>
this._getElementSchema(action)
);
this.availableActionSchemas = {};
availableActionSchemasAsArray.forEach((actionSchema) => {
// Keep the current action schema
let actionVerb = this._getVerbFromActionSchema(actionSchema);
this.availableActionSchemas[actionVerb] = actionSchema;
// Check if the current action has subactions
let subActionSchemas = this._getSubActionsSchemaFromParentActionSchema(actionSchema);
if (subActionSchemas) {
// If yes, keep the sub actions schema and verbs
// Keep the list of subactions verbs
if (!this.availableSubActionByVerb) {
this.availableSubActionByVerb = {};
}
this.availableSubActionByVerb[actionVerb] = subActionSchemas.map((sa) =>
this._getVerbFromActionSchema(sa)
);
// Keep the list of subactions schemas
if (!this.availableSubActionSchemasByVerb) {
this.availableSubActionSchemasByVerb = {};
}
this.availableSubActionSchemasByVerb[actionVerb] = {};
subActionSchemas.forEach((sas) => {
let subActionVerb = this._getVerbFromActionSchema(sas);
this.availableSubActionSchemasByVerb[actionVerb][subActionVerb] = sas;
});
}
});
this.availableActions = availableActionSchemasAsArray.map((a) =>
this._getVerbFromActionSchema(a)
);
this.isConfigured = true;
resolve();
} catch (error) {
reject(error);
}
})
.catch((error) => reject(error));
});
}
public getNewSiteScript(): any {
return {
$schema: 'schema.json',
actions: [],
bindata: {},
version: 1
};
}
public getSiteScriptSchema(): any {
return this.schema;
}
public getActionSchema(action: ISiteScriptAction): any {
return this._getActionSchemaByVerb(action.verb);
}
private _getActionSchemaByVerb(actionVerb: string): any {
if (!this.isConfigured) {
throw new Error(
'The Schema Service is not properly configured. Make sure the configure() method has been called.'
);
}
let directResolvedSchema = this.availableActionSchemas[actionVerb];
if (directResolvedSchema) {
return directResolvedSchema;
}
// Try to find the schema by case insensitive key
let availableActionKeys = Object.keys(this.availableActionSchemas);
let foundKeys = availableActionKeys.filter((k) => k.toUpperCase() == actionVerb.toUpperCase());
let actionSchemaKey = foundKeys.length == 1 ? foundKeys[0] : null;
return this.availableActionSchemas[actionSchemaKey];
}
public getActionTitle(action: ISiteScriptAction, parentAction: ISiteScriptAction): string {
return this.getActionTitleByVerb(action.verb, parentAction && parentAction.verb);
}
public getActionTitleByVerb(actionVerb: string, parentActionVerb: string): string {
let actionSchema = parentActionVerb
? this.getSubActionSchemaByVerbs(parentActionVerb, actionVerb)
: this._getActionSchemaByVerb(actionVerb);
return actionSchema.title;
}
public getActionDescription(action: ISiteScriptAction, parentAction: ISiteScriptAction): string {
return this.getActionDescriptionByVerb(action.verb, parentAction && parentAction.verb);
}
public getActionDescriptionByVerb(actionVerb: string, parentActionVerb: string): string {
let actionSchema = parentActionVerb
? this.getSubActionSchemaByVerbs(parentActionVerb, actionVerb)
: this._getActionSchemaByVerb(actionVerb);
return actionSchema.description;
}
public getSubActionSchemaByVerbs(parentActionVerb: string, subActionVerb: string): any {
if (!this.isConfigured) {
throw new Error(
'The Schema Service is not properly configured. Make sure the configure() method has been called.'
);
}
let availableSubActionSchemas = this.availableSubActionSchemasByVerb[parentActionVerb];
let directResolvedSchema = availableSubActionSchemas[subActionVerb];
if (directResolvedSchema) {
return directResolvedSchema;
}
// Try to find the schema by case insensitive key
let availableSubActionKeys = Object.keys(availableSubActionSchemas);
let foundKeys = availableSubActionKeys.filter((k) => k.toUpperCase() == subActionVerb.toUpperCase());
let subActionSchemaKey = foundKeys.length == 1 ? foundKeys[0] : null;
return availableSubActionSchemas[subActionSchemaKey];
}
public getSubActionSchema(parentAction: ISiteScriptAction, subAction: ISiteScriptAction): any {
return this.getSubActionSchemaByVerbs(parentAction.verb, subAction.verb);
}
public getAvailableActions(): string[] {
if (!this.isConfigured) {
throw new Error(
'The Schema Service is not properly configured. Make sure the configure() method has been called.'
);
}
return this.availableActions;
}
public getAvailableSubActions(parentAction: ISiteScriptAction): string[] {
if (!this.isConfigured) {
throw new Error(
'The Schema Service is not properly configured. Make sure the configure() method has been called.'
);
}
return this.availableSubActionByVerb[parentAction.verb];
}
private _loadSchema(schemaJSONorURL: string): Promise<any> {
return new Promise((resolve, reject) => {
// If argument is not set, use the embedded default schema
if (!schemaJSONorURL) {
resolve(DefaultSchema);
return;
}
if (
schemaJSONorURL.indexOf('/') == 0 ||
schemaJSONorURL.indexOf('http://') == 0 ||
schemaJSONorURL.indexOf('https://') == 0
) {
// The argument is a URL
// Fetch the schema at the specified URL
this._getSchemaFromUrl(schemaJSONorURL).then((schema) => resolve(schema)).catch((error) => {
console.error('An error occured while trying to fetch schema from URL', error);
reject(error);
});
} else {
// The argument is supposed to be JSON stringified
try {
let schema = JSON.parse(schemaJSONorURL);
resolve(schema);
} catch (error) {
console.error('An error occured while parsing JSON string', error);
reject(error);
}
}
});
}
private _getSchemaFromUrl(url: string): Promise<any> {
// Use spHttpClient if it is a SPO URL, use regular httpClient otherwise
if (url.indexOf('.sharepoint.com') > -1) {
let spHttpClient: SPHttpClient = this.serviceScope.consume(SPHttpClient.serviceKey);
return spHttpClient.get(url, SPHttpClient.configurations.v1).then((v) => v.json());
} else {
let httpClient: HttpClient = this.serviceScope.consume(HttpClient.serviceKey);
return httpClient.get(url, HttpClient.configurations.v1).then((v) => v.json());
}
}
}
export const SiteScriptSchemaServiceKey = ServiceKey.create<ISiteScriptSchemaService>(
'YPCODE:SiteScriptSchemaService',
SiteScriptSchemaService
); | the_stack |
import {
EVENT_ACTION,
PRESENCE_ACTION,
RECORD_ACTION,
RPC_ACTION,
TOPIC,
MONITORING_ACTION,
Message,
BulkSubscriptionMessage,
STATE_REGISTRY_TOPIC
} from '../../constants'
import { SocketWrapper, DeepstreamConfig, DeepstreamServices, SubscriptionListener, StateRegistry, SubscriptionRegistry, LOG_LEVEL, EVENT, NamespacedLogger } from '@deepstream/types'
interface SubscriptionActions {
MULTIPLE_SUBSCRIPTIONS: RECORD_ACTION.MULTIPLE_SUBSCRIPTIONS | EVENT_ACTION.MULTIPLE_SUBSCRIPTIONS | RPC_ACTION.MULTIPLE_PROVIDERS | PRESENCE_ACTION.MULTIPLE_SUBSCRIPTIONS
NOT_SUBSCRIBED: RECORD_ACTION.NOT_SUBSCRIBED | EVENT_ACTION.NOT_SUBSCRIBED | RPC_ACTION.NOT_PROVIDED | PRESENCE_ACTION.NOT_SUBSCRIBED
SUBSCRIBE: RECORD_ACTION.SUBSCRIBE | EVENT_ACTION.SUBSCRIBE | RPC_ACTION.PROVIDE | PRESENCE_ACTION.SUBSCRIBE
UNSUBSCRIBE: RECORD_ACTION.UNSUBSCRIBE | EVENT_ACTION.UNSUBSCRIBE | RPC_ACTION.UNPROVIDE | PRESENCE_ACTION.UNSUBSCRIBE
}
interface Subscription {
name: string
sockets: Set<SocketWrapper>
}
export class DefaultSubscriptionRegistry implements SubscriptionRegistry {
private sockets = new Map<SocketWrapper, Set<Subscription>>()
private subscriptions = new Map<string, Subscription>()
private subscriptionListener: SubscriptionListener | null = null
private constants: SubscriptionActions
private clusterSubscriptions: StateRegistry
private actions: any
private logger: NamespacedLogger = this.services.logger.getNameSpace('SUBSCRIPTION_REGISTRY')
private invalidSockets = new Set<SocketWrapper>()
/**
* A generic mechanism to handle subscriptions from sockets to topics.
* A bit like an event-hub, only that it registers SocketWrappers rather
* than functions
*/
constructor (private pluginConfig: any, private services: Readonly<DeepstreamServices>, private config: Readonly<DeepstreamConfig>, private topic: TOPIC | STATE_REGISTRY_TOPIC, clusterTopic: TOPIC) {
switch (topic) {
case TOPIC.RECORD:
case STATE_REGISTRY_TOPIC.RECORD_LISTEN_PATTERNS:
this.actions = RECORD_ACTION
break
case TOPIC.EVENT:
case STATE_REGISTRY_TOPIC.EVENT_LISTEN_PATTERNS:
this.actions = EVENT_ACTION
break
case TOPIC.RPC:
this.actions = RPC_ACTION
break
case TOPIC.PRESENCE:
this.actions = PRESENCE_ACTION
break
case TOPIC.MONITORING:
this.actions = MONITORING_ACTION
break
}
this.constants = {
MULTIPLE_SUBSCRIPTIONS: this.actions.MULTIPLE_SUBSCRIPTIONS,
NOT_SUBSCRIBED: this.actions.NOT_SUBSCRIBED,
SUBSCRIBE: this.actions.SUBSCRIBE,
UNSUBSCRIBE: this.actions.UNSUBSCRIBE,
}
this.onSocketClose = this.onSocketClose.bind(this)
this.clusterSubscriptions = this.services.clusterStates.getStateRegistry(clusterTopic)
if (this.pluginConfig.subscriptionsSanityTimer > 0) {
setInterval(this.illegalCleanup.bind(this), this.pluginConfig.subscriptionsSanityTimer)
setInterval(() => this.invalidSockets.clear(), this.pluginConfig.subscriptionsSanityTimer * 100)
}
}
public async whenReady () {
await this.clusterSubscriptions.whenReady()
}
public async close () {
await this.clusterSubscriptions.whenReady()
}
/**
* Return all the servers that have this subscription.
*/
public getAllServers (subscriptionName: string): string[] {
return this.clusterSubscriptions.getAllServers(subscriptionName)
}
/**
* Return all the servers that have this subscription excluding the current
* server name
*/
public getAllRemoteServers (subscriptionName: string): string[] {
const serverNames = this.clusterSubscriptions.getAllServers(subscriptionName)
const localServerIndex = serverNames.indexOf(this.config.serverName)
if (localServerIndex > -1) {
serverNames.splice(serverNames.indexOf(this.config.serverName), 1)
}
return serverNames
}
/**
* Returns a list of all the topic this registry
* currently has subscribers for
*/
public getNames (): string[] {
return this.clusterSubscriptions.getAll()
}
/**
* Returns true if the subscription exists somewhere
* in the cluster
*/
public hasName (subscriptionName: string): boolean {
return this.clusterSubscriptions.has(subscriptionName)
}
/**
* This method allows you to customise the SubscriptionRegistry so that it can send
* custom events and ack messages back.
* For example, when using the ACTIONS.LISTEN, you would override SUBSCRIBE with
* ACTIONS.SUBSCRIBE and UNSUBSCRIBE with UNSUBSCRIBE
*/
public setAction (name: string, value: EVENT_ACTION | RECORD_ACTION | RPC_ACTION): void {
(this.constants as any)[name.toUpperCase()] = value
}
/**
* Enqueues a message string to be broadcast to all subscribers. Broadcasts will potentially
* be reordered in relation to *other* subscription names, but never in relation to the same
* subscription name.
*/
public sendToSubscribers (name: string, message: Message, noDelay: boolean, senderSocket: SocketWrapper | null, suppressRemote: boolean = false): void {
// If the senderSocket is null it means it was received via the message bus
if (senderSocket !== null && suppressRemote === false) {
this.services.clusterNode.send(message)
}
const subscription = this.subscriptions.get(name)
if (!subscription) {
return
}
const subscribers = subscription.sockets
this.services.monitoring.onBroadcast(message, subscribers.size)
const serializedMessages: { [index: string]: any } = {}
for (const socket of subscribers) {
if (socket === senderSocket) {
continue
}
if (!serializedMessages[socket.socketType]) {
if (message.parsedData) {
delete message.data
}
this.logger.debug('SEND_TO_SUBSCRIBERS', `encoding ${name} with protocol ${socket.socketType} with data ${JSON.stringify(message)}`)
serializedMessages[socket.socketType] = socket.getMessage(message)
}
this.logger.debug('SEND_TO_SUBSCRIBERS', `sending ${socket.socketType} payload of ${serializedMessages[socket.socketType]}`)
socket.sendBuiltMessage!(serializedMessages[socket.socketType], !noDelay)
}
}
/**
* Adds a SocketWrapper as a subscriber to a topic
*/
public subscribeBulk (message: BulkSubscriptionMessage, socket: SocketWrapper, silent?: boolean): void {
const length = message.names.length
for (let i = 0; i < length; i++) {
this.subscribe(message.names[i], message, socket, true)
}
if (!silent) {
socket.sendAckMessage({
topic: message.topic,
action: message.action,
correlationId: message.correlationId
})
}
}
/**
* Adds a SocketWrapper as a subscriber to a topic
*/
public unsubscribeBulk (message: BulkSubscriptionMessage, socket: SocketWrapper, silent?: boolean): void {
message.names!.forEach((name) => {
this.unsubscribe(name, message, socket, true)
})
if (!silent) {
socket.sendAckMessage({
topic: message.topic,
action: message.action,
correlationId: message.correlationId
})
}
}
/**
* Adds a SocketWrapper as a subscriber to a topic
*/
public subscribe (name: string, message: Message, socket: SocketWrapper, silent?: boolean): void {
const subscription = this.subscriptions.get(name) || {
name,
sockets: new Set()
}
if (subscription.sockets.size === 0) {
this.subscriptions.set(name, subscription)
} else if (subscription.sockets.has(socket)) {
if (this.logger.shouldLog(LOG_LEVEL.WARN)) {
const msg = `repeat subscription to "${name}" by ${socket.userId}`
this.logger.warn(EVENT_ACTION[this.constants.MULTIPLE_SUBSCRIPTIONS], msg, { message, socketWrapper: socket })
}
socket.sendMessage({
topic: this.topic,
action: this.constants.MULTIPLE_SUBSCRIPTIONS,
originalAction: message.action,
name
})
return
}
subscription.sockets.add(socket)
this.addSocket(subscription, socket)
if (!silent) {
if (this.logger.shouldLog(LOG_LEVEL.DEBUG)) {
const logMsg = `for ${TOPIC[this.topic] || STATE_REGISTRY_TOPIC[this.topic]}:${name} by ${socket.userId}`
this.logger.debug(this.actions[this.constants.SUBSCRIBE], logMsg)
}
socket.sendAckMessage(message)
}
}
/**
* Removes a SocketWrapper from the list of subscriptions for a topic
*/
public unsubscribe (name: string, message: Message, socket: SocketWrapper, silent?: boolean): void {
const subscription = this.subscriptions.get(name)
if (!subscription || !subscription.sockets.delete(socket)) {
if (!silent) {
if (this.logger.shouldLog(LOG_LEVEL.WARN)) {
const msg = `${socket.userId} is not subscribed to ${name}`
this.logger.warn(this.actions[this.constants.NOT_SUBSCRIBED], msg, { socketWrapper: socket, message})
}
if (STATE_REGISTRY_TOPIC[this.topic]) {
// This isn't supported for STATE_REGISTRY_TOPIC/s
return
}
socket.sendMessage({
topic: this.topic,
action: this.constants.NOT_SUBSCRIBED,
originalAction: message.action,
name
})
}
return
}
this.removeSocket(subscription, socket)
if (!silent) {
if (this.logger.shouldLog(LOG_LEVEL.DEBUG)) {
const logMsg = `for ${this.topic}:${name} by ${socket.userId}`
this.logger.debug(this.actions[this.constants.UNSUBSCRIBE], logMsg)
}
socket.sendAckMessage(message)
}
}
/**
* Returns an array of SocketWrappers that are subscribed
* to <name> or null if there are no subscribers
*/
public getLocalSubscribers (name: string): Set<SocketWrapper> {
const subscription = this.subscriptions.get(name)
return subscription ? subscription.sockets : new Set()
}
/**
* Returns true if there are SocketWrappers that
* are subscribed to <name> or false if there
* aren't any subscribers
*/
public hasLocalSubscribers (name: string): boolean {
return this.subscriptions.has(name)
}
/**
* Allows to set a subscriptionListener after the class had been instantiated
*/
public setSubscriptionListener (listener: SubscriptionListener): void {
this.subscriptionListener = listener
this.clusterSubscriptions.onAdd(listener.onFirstSubscriptionMade.bind(listener))
this.clusterSubscriptions.onRemove(listener.onLastSubscriptionRemoved.bind(listener))
}
private addSocket (subscription: Subscription, socket: SocketWrapper): void {
const subscriptions = this.sockets.get(socket) || new Set()
if (subscriptions.size === 0) {
this.sockets.set(socket, subscriptions)
socket.onClose(this.onSocketClose)
}
subscriptions.add(subscription)
this.clusterSubscriptions!.add(subscription.name)
if (this.subscriptionListener) {
this.subscriptionListener.onSubscriptionMade(subscription.name, socket)
}
}
private removeSocket (subscription: Subscription, socket: SocketWrapper): void {
if (subscription.sockets.size === 0) {
this.subscriptions.delete(subscription.name)
}
if (this.subscriptionListener) {
this.subscriptionListener.onSubscriptionRemoved(subscription.name, socket)
}
this.clusterSubscriptions!.remove(subscription.name)
const subscriptions = this.sockets.get(socket)
if (subscriptions) {
subscriptions.delete(subscription)
if (subscriptions.size === 0) {
this.sockets.delete(socket)
socket.removeOnClose(this.onSocketClose)
}
} else {
this.logger.error(EVENT.ERROR, 'Attempting to delete a subscription that doesn\'t exist')
}
}
/**
* Called whenever a socket closes to remove all of its subscriptions
*/
private onSocketClose (socket: SocketWrapper): void {
const subscriptions = this.sockets.get(socket)
if (!subscriptions) {
this.logger.error(
EVENT_ACTION[this.constants.NOT_SUBSCRIBED],
'A socket has an illegal registered close callback',
{ socketWrapper: socket }
)
return
}
for (const subscription of subscriptions) {
subscription.sockets.delete(socket)
this.removeSocket(subscription, socket)
}
this.sockets.delete(socket)
}
private illegalCleanup () {
this.sockets.forEach((subscriptions, socket) => {
if (socket.isClosed) {
if (!this.invalidSockets.has(socket)) {
this.logger.error(
EVENT.CLOSED_SOCKET,
`Socket ${socket.uuid} is closed but still in registry. Currently there are ${this.invalidSockets.size} sockets. If you see this please raise a github issue!`
)
this.invalidSockets.add(socket)
}
}
})
}
} | the_stack |
import * as React from "react";
import IGraphBotProps from "./IGraphBotProps";
import { ActionButton } from "office-ui-fabric-react/lib/Button";
import { Panel, PanelType } from "office-ui-fabric-react/lib/Panel";
import { Spinner, SpinnerSize} from "office-ui-fabric-react/lib/spinner";
import { Overlay } from "office-ui-fabric-react/lib/overlay";
import { Chat, DirectLine, ConnectionStatus } from 'botframework-webchat';
import IGraphBotState from "./IGraphBotState";
require("botframework-webchat/botchat.css");
import { Text } from "@microsoft/sp-core-library";
import styles from "./GraphBot.module.scss";
import IGraphBotSettings from "./IGraphBotSettings";
import * as strings from "GraphBotApplicationCustomizerStrings";
import { PnPClientStorage } from "@pnp/common";
import { Util } from "@pnp/common";
import { Logger } from "@pnp/logging";
import { UserAgentApplication } from "msal";
// Add your scopes according the graph queries you want to perfrom
// Use the Microsoft Graph explorer/documentation to see required permissions by queries
// (https://developer.microsoft.com/en-us/graph/graph-explorer)
const scopes = ["Directory.Read.All","User.Read"];
class GraphBot extends React.Component<IGraphBotProps, IGraphBotState> {
private _botConnection: DirectLine;
private _clientApplication: UserAgentApplication;
private _botId: string;
private _directLineSecret: string;
private _storage: PnPClientStorage;
// Local storage keys
private readonly ENTITYKEY_CLIENTID = "PnP_MSAL_GraphBot_ClientId";
private readonly ENTITYKEY_BOTID = "PnP_MSAL_GraphBot_BotId";
private readonly ENTITYKEY_DIRECTLINESECRET = "PnP_MSAL_GraphBot_BotDirectLineSecret";
private readonly ENTITYKEY_TENANTID = "PnP_MSAL_GraphBot_TenantId";
private readonly CONVERSATION_ID_KEY = "PnP_MSAL_GraphBot_ConversationId";
constructor(props: IGraphBotProps) {
super(props);
this._login = this._login.bind(this);
this._getAccessToken = this._getAccessToken.bind(this);
this._sendAccessTokenToBot = this._sendAccessTokenToBot.bind(this);
this.state = {
showPanel: false,
isBotInitializing: false
};
// Enable sp-pnp-js session storage wrapper
this._storage = new PnPClientStorage();
this._storage.local.enabled = true;
}
public render() {
// Be careful, the user Id is mandatory to be able to use the bot state service (i.e privateConversationData)
return (
<div className={ styles.banner }>
<ActionButton onClick= { this._login } checked={ true } iconProps={ { iconName: "Robot", className: styles.banner__chatButtonIcon } } className={ styles.banner__chatButton}>
{ strings.GraphBotButtonLabel }
</ActionButton>
<Panel
isOpen={ this.state.showPanel }
type={ PanelType.medium}
isLightDismiss={ true }
onDismiss={ () => this.setState({ showPanel: false }) }
>
{ this.state.isBotInitializing ?
<Overlay className={ styles.overlayList } >
<Spinner size={ SpinnerSize.large } label={ strings.GraphBotInitializationMessage }/>
</Overlay>
:
<Chat
botConnection={ this._botConnection }
adaptiveCardsHostConfig= { {} }
bot={
{
id: this._botId,
}
}
showUploadButton= { false }
user={
{
// IMPORTANT (2 of 2): USE THE SAME USER ID FOR BOT STATE TO BE ABLE TO GET USER SPECIFIC DATA
id: this.props.context.pageContext.user.email,
name: this.props.context.pageContext.user.displayName,
}
}
locale={ this.props.context.pageContext.cultureInfo.currentCultureName }
formatOptions={
{
showHeader: false,
}
}
/>
}
</Panel>
</div>
);
}
public async componentDidMount() {
// Delete expired local storage items (conversation id, etc.)
this._storage.local.deleteExpired();
// Read the bot settings from the tenant property bag or local storage if available
const settings = await this._getGraphBotSettings(this.props);
// Initiliaze the MSAL User Agent Application
this._initMsalUserAgentApplication(settings.ClientId, settings.TenantId);
// Note: no need to store these informations in state because they are never updated after that
this._botId = settings.BotId;
this._directLineSecret = settings.DirectLineSecret;
}
/**
* Initialize the chat bot by sending the access token of the current user
* @param token The access token of the current user
*/
private _sendAccessTokenToBot(token: string): void {
// Using the backchannel to pass the auth token retrieved from OAuth2 implicit grant flow
this._botConnection.postActivity({
type: "event",
value: {
accessToken: token,
userDisplayName: this.props.context.pageContext.user.displayName // For the welcome message
},
from: {
// IMPORTANT (1 of 2): USE THE SAME USER ID FOR BOT STATE TO BE ABLE TO GET USER SPECIFIC DATA
id: this.props.context.pageContext.user.email
},
name: "userAuthenticated" // Custom name to identify this event in the bot
})
.subscribe(
id => {
// Show the panel only if the event has been well received by the bot (RxJs format)
this.setState({
isBotInitializing :false
});
},
error => {
Logger.write(Text.format("[GraphBot_sendAccessTokenToBot]: Error: {0}", error));
}
);
}
/**
* Login the current user
*/
private async _login() {
this.setState({
isBotInitializing :true,
showPanel: true,
});
// Get the conversation id if there is one. Otherwise, a new one will be created
const conversationId = this._storage.local.get(this.CONVERSATION_ID_KEY);
// Initialize the bot connection direct line
this._botConnection = new DirectLine({
secret: this._directLineSecret,
webSocket: false, // Needed to be able to retrieve history
conversationId: conversationId ? conversationId : null,
});
this._botConnection.connectionStatus$
.subscribe((connectionStatus) => {
switch (connectionStatus) {
// Successfully connected to the converstaion.
case ConnectionStatus.Online :
if (!conversationId) {
// Store the current conversation id in the browser session storage
// with 15 minutes expiration
this._storage.local.put(
this.CONVERSATION_ID_KEY, this._botConnection["conversationId"],
Util.dateAdd(new Date(), "minute", 15)
);
}
break;
}
});
// Login the user
if (this._clientApplication.getUser()) {
const token = await this._getAccessToken();
// The acces token is sent every time to the bot because we don't want to store it directly in the bot state per user and handle expiration/refresh behavior
// This responsibility is delegated to the Web Part itself since it handles the OAuth2 flow.
// If the token expired, a new one will be generated by reprompting the user
this._sendAccessTokenToBot(token);
} else {
// Be careful here, the loginPopup actuall returns an id_token, not an access_token
// You can validate the JWT token by your own if you want (not mandatory)
const idToken = await this._clientApplication.loginPopup(scopes);
const accessToken = await this._getAccessToken();
this._sendAccessTokenToBot(accessToken);
}
}
/**
* Retrieve a valid accessToken for the current user
*/
private async _getAccessToken() {
try {
// Try to get a token silently, if the user is already signed in
const token = await this._clientApplication.acquireTokenSilent(scopes);
return token;
} catch (error) {
try {
const token = await this._clientApplication.acquireTokenPopup(scopes);
return token;
} catch (error) {
Logger.write(Text.format("[GraphBot_getAccessToken]: Error: {0}", error));
}
}
}
/**
* Read the bot settings in the tenant property bag or local storage
* @param props the component properties
*/
private async _getGraphBotSettings(props: IGraphBotProps): Promise<IGraphBotSettings> {
// Read these values from the local storage first
let clientId = this._storage.local.get(this.ENTITYKEY_CLIENTID);
let botId = this._storage.local.get(this.ENTITYKEY_BOTID);
let directLineSecret = this._storage.local.get(this.ENTITYKEY_DIRECTLINESECRET);
let tenantId = this._storage.local.get(this.ENTITYKEY_TENANTID);
const expiration = Util.dateAdd(new Date(), "day", 1);
try {
if (!clientId) {
clientId = await props.tenantDataProvider.getTenantPropertyValue(this.ENTITYKEY_CLIENTID);
this._storage.local.put(this.ENTITYKEY_CLIENTID, clientId, expiration);
}
if (!botId) {
botId = await props.tenantDataProvider.getTenantPropertyValue(this.ENTITYKEY_BOTID);
this._storage.local.put(this.ENTITYKEY_BOTID, botId, expiration);
}
if (!directLineSecret) {
directLineSecret = await props.tenantDataProvider.getTenantPropertyValue(this.ENTITYKEY_DIRECTLINESECRET);
this._storage.local.put(this.ENTITYKEY_DIRECTLINESECRET, directLineSecret, expiration);
}
if (!tenantId) {
tenantId = await props.tenantDataProvider.getTenantPropertyValue(this.ENTITYKEY_TENANTID);
this._storage.local.put(this.ENTITYKEY_TENANTID, tenantId, expiration);
}
return {
BotId: botId,
ClientId: clientId,
DirectLineSecret: directLineSecret,
TenantId: tenantId,
} as IGraphBotSettings;
} catch (error) {
Logger.write(Text.format("[GraphBot_getGraphBotSettings]: Error: {0}", error));
}
}
/**
* Initialize the MSAL user agent
* @param clientId The client id
* @param tenantId The tenant id
*/
private _initMsalUserAgentApplication(clientId: string, tenantId: string) {
if (!this._clientApplication) {
const authorityUrl = Text.format("https://login.microsoftonline.com/{0}", tenantId);
this._clientApplication = new UserAgentApplication(clientId, authorityUrl, null, {
// This URL should be the same as the AAD app registered in registration portal
// This is this parameter getting login popup window to close
redirectUri: this.props.context.pageContext.site.absoluteUrl,
});
}
}
}
export default GraphBot; | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* Manages a Dataset inside an Azure Data Factory. This is a generic resource that supports all different Dataset Types.
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as azure from "@pulumi/azure";
*
* const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"});
* const exampleFactory = new azure.datafactory.Factory("exampleFactory", {
* location: exampleResourceGroup.location,
* resourceGroupName: exampleResourceGroup.name,
* identity: {
* type: "SystemAssigned",
* },
* });
* const exampleAccount = new azure.storage.Account("exampleAccount", {
* resourceGroupName: exampleResourceGroup.name,
* location: exampleResourceGroup.location,
* accountKind: "BlobStorage",
* accountTier: "Standard",
* accountReplicationType: "LRS",
* });
* const exampleLinkedCustomService = new azure.datafactory.LinkedCustomService("exampleLinkedCustomService", {
* dataFactoryId: exampleFactory.id,
* type: "AzureBlobStorage",
* typePropertiesJson: `{
* "connectionString":"${azurerm_storage_account.test.primary_connection_string}"
* }
* `,
* });
* const exampleCustomDataset = new azure.datafactory.CustomDataset("exampleCustomDataset", {
* dataFactoryId: exampleFactory.id,
* type: "Json",
* linkedService: {
* name: azurerm_data_factory_linked_custom_service.test.name,
* parameters: {
* key1: "value1",
* },
* },
* typePropertiesJson: `{
* "location": {
* "container":"${azurerm_storage_container.test.name}",
* "fileName":"foo.txt",
* "folderPath": "foo/bar/",
* "type":"AzureBlobStorageLocation"
* },
* "encodingName":"UTF-8"
* }
* `,
* description: "test description",
* annotations: [
* "test1",
* "test2",
* "test3",
* ],
* folder: "testFolder",
* parameters: {
* foo: "test1",
* Bar: "Test2",
* },
* additionalProperties: {
* foo: "test1",
* bar: "test2",
* },
* schemaJson: `{
* "type": "object",
* "properties": {
* "name": {
* "type": "object",
* "properties": {
* "firstName": {
* "type": "string"
* },
* "lastName": {
* "type": "string"
* }
* }
* },
* "age": {
* "type": "integer"
* }
* }
* }
* `,
* });
* ```
*
* ## Import
*
* Data Factory Datasets can be imported using the `resource id`, e.g.
*
* ```sh
* $ pulumi import azure:datafactory/customDataset:CustomDataset example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example/providers/Microsoft.DataFactory/factories/example/datasets/example
* ```
*/
export class CustomDataset extends pulumi.CustomResource {
/**
* Get an existing CustomDataset resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param state Any extra arguments used during the lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: CustomDatasetState, opts?: pulumi.CustomResourceOptions): CustomDataset {
return new CustomDataset(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'azure:datafactory/customDataset:CustomDataset';
/**
* Returns true if the given object is an instance of CustomDataset. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is CustomDataset {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === CustomDataset.__pulumiType;
}
/**
* A map of additional properties to associate with the Data Factory Dataset.
*/
public readonly additionalProperties!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* List of tags that can be used for describing the Data Factory Dataset.
*/
public readonly annotations!: pulumi.Output<string[] | undefined>;
/**
* The Data Factory ID in which to associate the Dataset with. Changing this forces a new resource.
*/
public readonly dataFactoryId!: pulumi.Output<string>;
/**
* The description for the Data Factory Dataset.
*/
public readonly description!: pulumi.Output<string | undefined>;
/**
* The folder that this Dataset is in. If not specified, the Dataset will appear at the root level.
*/
public readonly folder!: pulumi.Output<string | undefined>;
/**
* A `linkedService` block as defined below.
*/
public readonly linkedService!: pulumi.Output<outputs.datafactory.CustomDatasetLinkedService>;
/**
* Specifies the name of the Data Factory Dataset. Changing this forces a new resource to be created. Must be globally unique. See the [Microsoft documentation](https://docs.microsoft.com/en-us/azure/data-factory/naming-rules) for all restrictions.
*/
public readonly name!: pulumi.Output<string>;
/**
* A map of parameters to associate with the Data Factory Dataset.
*/
public readonly parameters!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* A JSON object that contains the schema of the Data Factory Dataset.
*/
public readonly schemaJson!: pulumi.Output<string | undefined>;
/**
* The type of dataset that will be associated with Data Factory.
*/
public readonly type!: pulumi.Output<string>;
/**
* A JSON object that contains the properties of the Data Factory Dataset.
*/
public readonly typePropertiesJson!: pulumi.Output<string>;
/**
* Create a CustomDataset resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args: CustomDatasetArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: CustomDatasetArgs | CustomDatasetState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as CustomDatasetState | undefined;
inputs["additionalProperties"] = state ? state.additionalProperties : undefined;
inputs["annotations"] = state ? state.annotations : undefined;
inputs["dataFactoryId"] = state ? state.dataFactoryId : undefined;
inputs["description"] = state ? state.description : undefined;
inputs["folder"] = state ? state.folder : undefined;
inputs["linkedService"] = state ? state.linkedService : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["parameters"] = state ? state.parameters : undefined;
inputs["schemaJson"] = state ? state.schemaJson : undefined;
inputs["type"] = state ? state.type : undefined;
inputs["typePropertiesJson"] = state ? state.typePropertiesJson : undefined;
} else {
const args = argsOrState as CustomDatasetArgs | undefined;
if ((!args || args.dataFactoryId === undefined) && !opts.urn) {
throw new Error("Missing required property 'dataFactoryId'");
}
if ((!args || args.linkedService === undefined) && !opts.urn) {
throw new Error("Missing required property 'linkedService'");
}
if ((!args || args.type === undefined) && !opts.urn) {
throw new Error("Missing required property 'type'");
}
if ((!args || args.typePropertiesJson === undefined) && !opts.urn) {
throw new Error("Missing required property 'typePropertiesJson'");
}
inputs["additionalProperties"] = args ? args.additionalProperties : undefined;
inputs["annotations"] = args ? args.annotations : undefined;
inputs["dataFactoryId"] = args ? args.dataFactoryId : undefined;
inputs["description"] = args ? args.description : undefined;
inputs["folder"] = args ? args.folder : undefined;
inputs["linkedService"] = args ? args.linkedService : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["parameters"] = args ? args.parameters : undefined;
inputs["schemaJson"] = args ? args.schemaJson : undefined;
inputs["type"] = args ? args.type : undefined;
inputs["typePropertiesJson"] = args ? args.typePropertiesJson : undefined;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(CustomDataset.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering CustomDataset resources.
*/
export interface CustomDatasetState {
/**
* A map of additional properties to associate with the Data Factory Dataset.
*/
additionalProperties?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* List of tags that can be used for describing the Data Factory Dataset.
*/
annotations?: pulumi.Input<pulumi.Input<string>[]>;
/**
* The Data Factory ID in which to associate the Dataset with. Changing this forces a new resource.
*/
dataFactoryId?: pulumi.Input<string>;
/**
* The description for the Data Factory Dataset.
*/
description?: pulumi.Input<string>;
/**
* The folder that this Dataset is in. If not specified, the Dataset will appear at the root level.
*/
folder?: pulumi.Input<string>;
/**
* A `linkedService` block as defined below.
*/
linkedService?: pulumi.Input<inputs.datafactory.CustomDatasetLinkedService>;
/**
* Specifies the name of the Data Factory Dataset. Changing this forces a new resource to be created. Must be globally unique. See the [Microsoft documentation](https://docs.microsoft.com/en-us/azure/data-factory/naming-rules) for all restrictions.
*/
name?: pulumi.Input<string>;
/**
* A map of parameters to associate with the Data Factory Dataset.
*/
parameters?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* A JSON object that contains the schema of the Data Factory Dataset.
*/
schemaJson?: pulumi.Input<string>;
/**
* The type of dataset that will be associated with Data Factory.
*/
type?: pulumi.Input<string>;
/**
* A JSON object that contains the properties of the Data Factory Dataset.
*/
typePropertiesJson?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a CustomDataset resource.
*/
export interface CustomDatasetArgs {
/**
* A map of additional properties to associate with the Data Factory Dataset.
*/
additionalProperties?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* List of tags that can be used for describing the Data Factory Dataset.
*/
annotations?: pulumi.Input<pulumi.Input<string>[]>;
/**
* The Data Factory ID in which to associate the Dataset with. Changing this forces a new resource.
*/
dataFactoryId: pulumi.Input<string>;
/**
* The description for the Data Factory Dataset.
*/
description?: pulumi.Input<string>;
/**
* The folder that this Dataset is in. If not specified, the Dataset will appear at the root level.
*/
folder?: pulumi.Input<string>;
/**
* A `linkedService` block as defined below.
*/
linkedService: pulumi.Input<inputs.datafactory.CustomDatasetLinkedService>;
/**
* Specifies the name of the Data Factory Dataset. Changing this forces a new resource to be created. Must be globally unique. See the [Microsoft documentation](https://docs.microsoft.com/en-us/azure/data-factory/naming-rules) for all restrictions.
*/
name?: pulumi.Input<string>;
/**
* A map of parameters to associate with the Data Factory Dataset.
*/
parameters?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* A JSON object that contains the schema of the Data Factory Dataset.
*/
schemaJson?: pulumi.Input<string>;
/**
* The type of dataset that will be associated with Data Factory.
*/
type: pulumi.Input<string>;
/**
* A JSON object that contains the properties of the Data Factory Dataset.
*/
typePropertiesJson: pulumi.Input<string>;
} | the_stack |
import React from "react";
import {
ScrollView,
RefreshControl,
Platform,
SafeAreaView,
Image,
View,
} from "react-native";
import {
MediaRule,
isWidthGreaterThanOrEqualTo,
mergeRStyle,
} from "emotion-native-media-query";
import { BREAKPOINTS } from "helpers/constants";
import { getHomeAsync, Home } from "helpers/wpapi";
import Wrapper from "components/Wrapper";
import { TopBarLinks } from "components/site-header/TopBarLinks";
import LoadingView from "components/Loading";
import WPHead from "components/webHelpers/WPHead";
import WPFooter from "components/webHelpers/WPFooter";
import Head from "next/head";
import { MainSection } from "./MainSection";
import { LeftSection } from "./LeftSection";
import { GrindSection } from "./GrindSection";
import { OpinionSection } from "./OpinionSection";
import { CartoonsSection } from "./CartoonsSection";
import { HumorSection } from "./HumorSection";
import { MoreFromTheDailySection } from "./MoreFromTheDailySection";
import { DesktopRow } from "./DesktopRow";
import { Column } from "./Column";
import { getBorderValue } from "./getBorderValue";
import { SectionProps } from "./SectionProps";
import { SectionStyle, Section, SECTION_PADDING } from "components/Section";
import { SectionTitleWithLink } from "./SectionTitle";
import { TopThumbnailArticle } from "./TopThumbnailArticle";
import { TitleOnlyArticle } from "./TitleOnlyArticle";
import { HeadlineArticle } from "../../article-links-and-thumbnails/HeadlineArticle";
import { PodcastWidget } from "./PodcastWidget";
interface IndexProps {
homePosts?: Home;
Post;
navigation?: any;
refreshControl?: any;
}
interface IndexState {}
export default class HomePage extends React.Component<IndexProps, IndexState> {
static async getInitialProps(): Promise<any> {
const homePosts = await getHomeAsync();
return { homePosts };
}
render(): React.ReactNode {
const { homePosts } = this.props;
if (!homePosts) {
return <LoadingView />;
}
let featuredBeforeNews = true;
// Note that on web it is handled by the CSS `order` property and media query.
if (Platform.OS !== "web") {
if (isWidthGreaterThanOrEqualTo(BREAKPOINTS.TABLET)) {
featuredBeforeNews = false;
}
}
const FeaturedSection: React.ElementType = (fsProps: any) => {
return (
<MainSection
sectionTitle="Featured"
category={homePosts.tsdMeta.categories.featured}
content={homePosts.featured}
rStyle={{
[MediaRule.MaxWidth]: {
[BREAKPOINTS.MAX_WIDTH.TABLET]: {
...getBorderValue("Bottom"),
},
},
}}
{...fsProps}
/>
);
};
const NewsSection: React.ElementType = (nsProps: any) => {
return (
<LeftSection
sectionTitle="News"
category={homePosts.tsdMeta.categories.news}
content={homePosts.news}
rStyle={{
[MediaRule.MinWidth]: {
[BREAKPOINTS.TABLET]: {
...getBorderValue("Right"),
},
},
}}
{...nsProps}
/>
);
};
const ArtsAndLifeSection: React.ElementType = (nsProps: any) => {
return (
<Column
style={{
flexGrow: 3,
order: 2,
}}
rStyle={mergeRStyle(
{
[MediaRule.MinWidth]: {
[BREAKPOINTS.TABLET]: {
order: 1,
},
},
},
{
[MediaRule.MinWidth]: {
[BREAKPOINTS.TABLET]: {
...getBorderValue("Right"),
},
},
},
)}
>
<SectionStyle>
<SectionTitleWithLink
category={homePosts.tsdMeta.categories["arts-life"]}
homePageSpecial={true}
>
<Image
source={{
uri: "/static/sectionHeaders/artsAndLife.png",
}}
accessibilityLabel="Arts & Life"
resizeMode="contain"
style={{
width: 120,
height: 30,
}}
/>
</SectionTitleWithLink>
</SectionStyle>
<div style={{ marginTop: -35 }}>
<Section>
<View>
<TopThumbnailArticle post={homePosts.artsAndLife[0]} />
</View>
<View>
<TopThumbnailArticle post={homePosts.artsAndLife[1]} />
</View>
<View>
<TitleOnlyArticle post={homePosts.artsAndLife[2]} />
</View>
<View>
<TitleOnlyArticle post={homePosts.artsAndLife[3]} />
</View>
</Section>
</div>
</Column>
);
};
const MainSportsSection: React.ElementType = (msProps: SectionProps) => {
const content = homePosts.sports;
return (
<Column
style={{
flexGrow: 7,
order: 1,
}}
rStyle={mergeRStyle(
{
[MediaRule.MinWidth]: {
[BREAKPOINTS.TABLET]: {
order: 2,
},
},
},
{
[MediaRule.MaxWidth]: {
[BREAKPOINTS.MAX_WIDTH.TABLET]: {
...getBorderValue("Bottom"),
},
},
},
)}
>
<Section>
<SectionTitleWithLink
category={homePosts.tsdMeta.categories.sports}
homePageSpecial={true}
>
<Image
source={{
uri: "/static/sectionHeaders/sports.png",
}}
accessibilityLabel="Sports"
resizeMode="contain"
style={{
width: 100,
height: 25,
}}
/>
</SectionTitleWithLink>
<HeadlineArticle post={content[0]} style={{ marginBottom: 20 }} />
<DesktopRow>
<Column
rStyle={{
[MediaRule.MinWidth]: {
[BREAKPOINTS.TABLET]: {
paddingRight: SECTION_PADDING / 2,
},
},
}}
>
<TopThumbnailArticle post={content[1]} />
</Column>
<Column
rStyle={{
[MediaRule.MinWidth]: {
[BREAKPOINTS.TABLET]: {
paddingLeft: SECTION_PADDING / 2,
},
},
}}
>
<TopThumbnailArticle post={content[2]} />
</Column>
</DesktopRow>
</Section>
</Column>
);
};
return (
<>
<Head>
<meta
name="viewport"
content="initial-scale=1.0, width=device-width"
/>
</Head>
<SafeAreaView style={{ flex: 1 }}>
<WPHead base={homePosts} />
{Platform.OS !== "web" && (
<TopBarLinks itemStyle={{ color: "black" }} />
)}
<ScrollView
contentContainerStyle={{
flexDirection: "column",
}}
refreshControl={this.props.refreshControl}
>
<DesktopRow
style={{
...getBorderValue("Bottom"),
}}
>
<Column
style={{
flexGrow: 6,
}}
rStyle={{
[MediaRule.MaxWidth]: {
[BREAKPOINTS.MAX_WIDTH.TABLET]: {
...getBorderValue("Bottom"),
},
},
}}
>
<DesktopRow
style={{
...getBorderValue("Bottom"),
}}
>
{featuredBeforeNews ? (
<>
<FeaturedSection />
<NewsSection />
</>
) : (
<>
<NewsSection />
<FeaturedSection />
</>
)}
</DesktopRow>
<DesktopRow>
<ArtsAndLifeSection />
<MainSportsSection />
</DesktopRow>
</Column>
<Column
style={{
flexGrow: 3,
}}
rStyle={{
[MediaRule.MinWidth]: {
[BREAKPOINTS.TABLET]: {
...getBorderValue("Left"),
},
},
}}
>
<OpinionSection
content={homePosts.opinions}
category={homePosts.tsdMeta.categories.opinions}
style={{
...getBorderValue("Bottom"),
}}
/>
<CartoonsSection
content={homePosts.cartoons}
category={homePosts.tsdMeta.categories.cartoons}
style={{
...getBorderValue("Bottom"),
}}
rStyle={{
[MediaRule.MaxWidth]: {
[BREAKPOINTS.MAX_WIDTH.TABLET]: {
...getBorderValue("Bottom"),
},
},
}}
/>
<GrindSection
content={homePosts.theGrind}
category={homePosts.tsdMeta.categories.thegrind}
style={{
...getBorderValue("Bottom"),
}}
/>
<PodcastWidget
style={{
padding: "15px",
}}
/>
</Column>
</DesktopRow>
<HumorSection
category={homePosts.tsdMeta.categories.humor}
content={homePosts.humor}
/>
<MoreFromTheDailySection
category={null}
content={homePosts.moreFromTheDaily}
/>
</ScrollView>
<WPFooter base={homePosts} />
<div
dangerouslySetInnerHTML={{
__html: `<script type="application/ld+json">${JSON.stringify({
"@context": "http://schema.org",
"@type": "WebPage",
url: "https://stanforddaily.com",
thumbnailUrl:
"https://stanforddaily.com/static/cardinal-red-daily-s-logo.png",
})}</script>`,
}}
/>
{/* Parse.ly analytics tracking */}
<script
id="parsely-cfg"
src="//cdn.parsely.com/keys/stanforddaily.com/p.js"
/>
</SafeAreaView>
</>
);
}
}
export function HomePageWrapper(props): any {
const [refreshing, setRefreshing] = React.useState(false);
const wrapper: React.RefObject<Wrapper> = React.createRef();
return (
<Wrapper
class={HomePage}
ref={wrapper}
props={{
...props,
refreshControl: (
<RefreshControl
refreshing={refreshing}
onRefresh={async () => {
setRefreshing(true);
await wrapper.current._setInitialProps();
setRefreshing(false);
}}
/>
),
}}
getInitialProps={{}}
/>
);
}
HomePageWrapper.navigationOptions = {
title: "The Stanford Daily",
headerBackTitle: "Home",
headerTitleStyle: {
fontFamily: "Canterbury",
fontSize: 30,
fontWeight: undefined, // https://github.com/react-navigation/react-navigation/issues/542#issuecomment-438631938
},
}; | the_stack |
import { i18nMark } from "@lingui/react";
import { Trans } from "@lingui/macro";
import classNames from "classnames";
import { Dropdown, Form, Table, Tooltip } from "reactjs-components";
import { Link } from "react-router";
import PropTypes from "prop-types";
import * as React from "react";
import { Badge } from "@dcos/ui-kit";
import FilterBar from "#SRC/js/components/FilterBar";
import FilterHeadline from "#SRC/js/components/FilterHeadline";
import FilterInputText from "#SRC/js/components/FilterInputText";
import ResourceTableUtil from "#SRC/js/utils/ResourceTableUtil";
import StringUtil from "#SRC/js/utils/StringUtil";
import TableUtil from "#SRC/js/utils/TableUtil";
import AuthUtil from "../utils/AuthUtil";
import BulkOptions from "../constants/BulkOptions";
import GroupsActionsModal from "../submodules/groups/components/modals/GroupsActionsModal";
import ServiceAccountsActionsModal from "../submodules/service-accounts/components/ServiceAccountsActionsModal";
import UsersActionsModal from "../submodules/users/components/modals/UsersActionsModal";
function hypenize(str) {
return str.replace(/[A-Z]/g, (x) => `-${x.toLowerCase()}`);
}
class OrganizationTab extends React.Component {
static propTypes = {
items: PropTypes.array.isRequired,
itemID: PropTypes.string.isRequired,
itemName: PropTypes.string.isRequired,
};
state = {
checkableCount: 0,
checkedCount: 0,
showActionDropdown: false,
searchFilter: "all",
searchString: "",
selectedAction: null,
};
selectedIDSet = {};
UNSAFE_componentWillMount() {
this.resetTablewideCheckboxTabulations();
}
UNSAFE_componentWillReceiveProps(nextProps) {
if (nextProps.items.length !== this.props.items.length) {
this.resetTablewideCheckboxTabulations();
}
}
componentDidUpdate(prevProps, prevState) {
if (
prevState.searchFilter !== this.state.searchFilter ||
prevState.searchString !== this.state.searchString ||
prevProps.items.length !== this.props.items.length
) {
this.resetTablewideCheckboxTabulations();
}
}
handleActionSelection = (dropdownItem) => {
this.setState({
selectedAction: dropdownItem.id,
});
};
handleActionSelectionClose = () => {
this.setState({
selectedAction: null,
});
this.bulkCheck(false);
};
handleCheckboxChange = (prevCheckboxState, eventObject) => {
const isChecked = eventObject.fieldValue;
const checkedCount = this.state.checkedCount + (isChecked || -1);
const selectedIDSet = this.selectedIDSet;
selectedIDSet[eventObject.fieldName] = isChecked;
this.selectedIDSet = selectedIDSet;
this.setState({
checkedCount,
showActionDropdown: checkedCount > 0,
});
};
handleHeadingCheckboxChange = (prevCheckboxState, eventObject) => {
const isChecked = eventObject.fieldValue;
this.bulkCheck(isChecked);
};
handleSearchStringChange = (searchString = "") => {
this.setState({ searchString });
this.bulkCheck(false);
};
renderDescription = (prop, subject) => {
const isRemote = AuthUtil.isSubjectRemote(subject);
const itemName = hypenize(this.props.itemName);
let label = subject.get(prop);
const subjectID = subject.get(this.props.itemID);
if (isRemote) {
label = subject.get(this.props.itemID);
}
return (
<Link
to={`/organization/${itemName}s/${subjectID}`}
className="table-cell-link-secondary"
>
{label}
</Link>
);
};
renderID = (prop, subject) => {
let badge = null;
const itemName = hypenize(this.props.itemName);
const subjectID = subject.get(this.props.itemID);
let nameColClassnames = "column-12 text-overflow";
if (AuthUtil.isSubjectRemote(subject)) {
nameColClassnames = "column-9 column-jumbo-10 text-overflow";
badge = (
<div className="column-3 column-jumbo-2 text-align-right">
<Tooltip content="This user has been imported from an external identity provider.">
<Badge>
<Trans render="span">External</Trans>
</Badge>
</Tooltip>
</div>
);
}
return (
<div className="row flex">
<div className={nameColClassnames}>
<Link
className="table-cell-link-primary"
to={`/organization/${itemName}s/${subjectID}`}
>
{subject.get(prop)}
</Link>
</div>
{badge}
</div>
);
};
renderCheckbox = (prop, row) => {
const rowID = row[this.props.itemID];
const { checkableCount, checkedCount } = this.state;
let checked = null;
if (checkedCount === 0) {
checked = false;
} else if (checkedCount === checkableCount) {
checked = true;
} else {
checked = this.selectedIDSet[rowID];
}
return (
<Form
className="table-form-checkbox"
formGroupClass="form-group flush-bottom"
definition={[
{
checked,
value: checked,
fieldType: "checkbox",
labelClass: "form-row-element form-element-checkbox",
name: rowID,
showLabel: false,
},
]}
onChange={this.handleCheckboxChange}
/>
);
};
renderHeadingCheckbox = () => {
let checked = false;
let indeterminate = false;
switch (this.state.checkedCount) {
case 0:
checked = false;
break;
case this.state.checkableCount:
checked = true;
break;
default:
indeterminate = true;
break;
}
return (
<Form
className="table-form-checkbox"
formGroupClass="form-group flush-bottom"
definition={[
{
checked,
value: checked,
fieldType: "checkbox",
indeterminate,
labelClass: "form-row-element form-element-checkbox",
name: "headingCheckbox",
showLabel: false,
},
]}
onChange={this.handleHeadingCheckboxChange}
/>
);
};
getColGroup(itemName) {
switch (itemName) {
case "group":
return (
<colgroup>
<col style={{ width: "40px" }} />
<col />
</colgroup>
);
case "serviceAccount":
return (
<colgroup>
<col style={{ width: "40px" }} />
<col />
<col />
</colgroup>
);
case "user":
return (
<colgroup>
<col style={{ width: "40px" }} />
<col style={{ width: "45%" }} />
<col />
</colgroup>
);
default:
return null;
}
}
getGroupsClassName(prop, sortBy, row) {
return classNames({
clickable: row == null, // this is a header
});
}
getColumns(itemName) {
let className = ResourceTableUtil.getClassName;
const columns = [
{
className,
headerClassName: className,
prop: "selected",
render: this.renderCheckbox,
sortable: false,
heading: this.renderHeadingCheckbox,
},
];
const sortFunction = TableUtil.getSortFunction(
this.props.itemID,
(item, prop) => item.get(prop)
);
switch (itemName) {
case "group":
className = this.getGroupsClassName;
columns.push({
className,
headerClassName: className,
prop: "gid",
render: this.renderID,
sortable: true,
sortFunction,
heading: ResourceTableUtil.renderHeading({ gid: "ID" }),
});
break;
case "user":
case "serviceAccount":
let uid = "ID";
if (itemName === "user") {
uid = "Username";
}
columns.push(
{
cacheCell: true,
className,
headerClassName: className,
prop: "uid",
render: this.renderID,
sortable: true,
sortFunction,
heading: ResourceTableUtil.renderHeading({ uid }),
},
{
className,
headerClassName: className,
prop: "description",
render: this.renderDescription,
sortable: true,
sortFunction,
heading: ResourceTableUtil.renderHeading({
description:
itemName === "user"
? i18nMark("Full Name")
: i18nMark("Description"),
}),
}
);
break;
}
return columns;
}
getActionDropdown(itemName) {
if (!this.state.showActionDropdown) {
return null;
}
const actionPhrases = BulkOptions[itemName];
let initialID = null;
// Get first Action to set as initially selected option in dropdown.
initialID = Object.keys(actionPhrases)[0] || null;
return (
<Dropdown
anchorRight={true}
buttonClassName="button dropdown-toggle"
dropdownMenuClassName="dropdown-menu"
dropdownMenuListClassName="dropdown-menu-list"
dropdownMenuListItemClassName="clickable"
initialID={initialID}
items={this.getActionsDropdownItems(actionPhrases)}
onItemSelection={this.handleActionSelection}
scrollContainer=".gm-scroll-view"
scrollContainerParentSelector=".gm-prevented"
transition={true}
transitionName="dropdown-menu"
wrapperClassName="dropdown"
/>
);
}
getActionsDropdownItems(actionPhrases) {
return Object.keys(actionPhrases).map((action) => ({
html: actionPhrases[action].dropdownOption,
id: action,
selectedHtml: "Actions",
}));
}
getCheckedItemObjects(items, itemIDName) {
if (this.state.selectedAction) {
const checkboxStates = this.selectedIDSet;
const selectedItems = {};
Object.keys(checkboxStates).forEach((id) => {
if (checkboxStates[id] === true) {
selectedItems[id] = true;
}
});
return items.filter((item) => {
const itemID = item[itemIDName];
return selectedItems[itemID] || false;
});
}
return null;
}
getVisibleItems(items) {
let { searchFilter, searchString } = this.state;
searchString = searchString.toLowerCase();
switch (searchFilter) {
case "all":
break;
case "local":
items = items.filter((item) => !AuthUtil.isSubjectRemote(item));
break;
case "external":
items = items.filter((item) => AuthUtil.isSubjectRemote(item));
break;
}
if (searchString !== "") {
return items.filter((item) => {
let description = item.getDescription().toLowerCase();
const id = item.get(this.props.itemID).toLowerCase();
if (AuthUtil.isSubjectRemote(item)) {
description = "";
}
return (
description.indexOf(searchString) > -1 ||
id.indexOf(searchString) > -1
);
});
}
return items;
}
getActionsModal(action, items, itemID, itemType) {
if (action === null) {
return null;
}
const selectedItems = this.getCheckedItemObjects(items, itemID) || [];
const actionModalProps = {
action,
actionText: BulkOptions[itemType][action],
bodyClass: "modal-content allow-overflow",
itemID,
itemType,
onClose: this.handleActionSelectionClose,
selectedItems,
};
switch (itemType) {
case "group":
return <GroupsActionsModal {...actionModalProps} />;
case "serviceAccount":
return <ServiceAccountsActionsModal {...actionModalProps} />;
case "user":
return <UsersActionsModal {...actionModalProps} />;
default:
return null;
}
}
getSearchFilterChangeHandler(searchFilter) {
return () => {
this.bulkCheck(false);
this.setState({ searchFilter });
};
}
getFilterButtons(items) {
if (this.props.itemName !== "user") {
return null;
}
const external = items.filter(AuthUtil.isSubjectRemote);
const numbers = {
all: items.length,
local: items.length - external.length,
external: external.length,
};
const currentFilter = this.state.searchFilter;
const buttons = Object.entries(numbers).map(([filter, number]) => {
const classSet = classNames("button button-outline", {
active: filter === currentFilter,
});
return (
<button
key={filter}
className={classSet}
onClick={this.getSearchFilterChangeHandler(filter)}
>
{StringUtil.capitalize(filter)} ({number})
</button>
);
});
return <div className="button-group flush-bottom">{buttons}</div>;
}
getTableRowOptions = (row) => {
const selectedIDSet = this.selectedIDSet;
if (selectedIDSet[row[this.props.itemID]]) {
return { className: "selected" };
}
return {};
};
bulkCheck(isChecked) {
let checkedCount = 0;
const selectedIDSet = this.selectedIDSet;
Object.keys(selectedIDSet).forEach((id) => {
selectedIDSet[id] = isChecked;
});
this.selectedIDSet = selectedIDSet;
if (isChecked) {
checkedCount = this.state.checkableCount;
}
this.setState({
checkedCount,
showActionDropdown: checkedCount > 0,
});
}
resetTablewideCheckboxTabulations() {
let { items, itemID } = this.props;
items = this.getVisibleItems(items);
const selectedIDSet = {};
let checkableCount = 0;
// Initializing hash of items' IDs and corresponding checkbox state.
items.forEach((item) => {
const id = item.get(itemID);
checkableCount += 1;
selectedIDSet[id] = false;
});
this.selectedIDSet = selectedIDSet;
this.setState({ checkableCount });
}
resetFilter = () => {
this.setState({
searchString: "",
searchFilter: "all",
});
};
render() {
const { items, itemID, itemName } = this.props;
const {
selectedAction,
searchFilter,
searchString,
showActionDropdown,
} = this.state;
let capitalizedItemName = StringUtil.capitalize(itemName);
const columns = this.getColumns(itemName);
const visibleItems = this.getVisibleItems(items);
const filterButtons = this.getFilterButtons(visibleItems);
const actionDropdown = this.getActionDropdown(itemName);
const actionsModal = this.getActionsModal(
selectedAction,
items,
itemID,
itemName
);
// Pick the first column after the checkbox to default sort to
const sortProp = columns[1].prop;
let rightAlignLastNChildren = 0;
if (itemName === "serviceAccount") {
capitalizedItemName = "Service Account";
}
if (showActionDropdown) {
rightAlignLastNChildren = 1;
}
return (
<div className="flex-container-col">
<div className={`${itemName}s-table-header`}>
<FilterHeadline
currentLength={visibleItems.length}
isFiltering={searchFilter !== "all" || searchString !== ""}
name={capitalizedItemName}
onReset={this.resetFilter}
totalLength={items.length}
/>
<FilterBar rightAlignLastNChildren={rightAlignLastNChildren}>
<FilterInputText
className="flush-bottom"
searchString={searchString}
handleFilterChange={this.handleSearchStringChange}
/>
{filterButtons}
{actionDropdown}
</FilterBar>
{actionsModal}
</div>
<div className="page-content-fill flex-grow flex-container-col">
<Table
buildRowOptions={this.getTableRowOptions}
className="table table-flush table-borderless-outer
table-borderless-inner-columns table-hover flush-bottom"
columns={columns}
colGroup={this.getColGroup(itemName)}
containerSelector=".gm-scroll-view"
data={visibleItems}
itemHeight={TableUtil.getRowHeight()}
sortBy={{ prop: sortProp, order: "asc" }}
/>
</div>
</div>
);
}
}
export default OrganizationTab; | the_stack |
import {
FocusEvent,
KeyboardEventHandler,
KeyboardEvent as ReactKeyboardEvent,
useCallback,
useEffect,
useRef,
useState,
} from "react";
import { flatten2DArray, reverseArray } from "ariakit-utils/array";
import {
fireBlurEvent,
fireKeyboardEvent,
isSelfTarget,
} from "ariakit-utils/events";
import {
useEvent,
useForkRef,
useLiveRef,
useSafeLayoutEffect,
} from "ariakit-utils/hooks";
import { useStoreProvider } from "ariakit-utils/store";
import {
createComponent,
createElement,
createHook,
} from "ariakit-utils/system";
import { As, Props } from "ariakit-utils/types";
import { FocusableOptions, useFocusable } from "../focusable/focusable";
import {
CompositeContext,
Item,
findEnabledItemById,
findFirstEnabledItem,
groupItemsByRows,
} from "./__utils";
import { CompositeState } from "./composite-state";
function canProxyKeyboardEvent(event: ReactKeyboardEvent) {
if (!isSelfTarget(event)) return false;
if (event.metaKey) return false;
if (event.key === "Tab") return false;
// If the propagation of the event has been prevented, we don't want to proxy
// this event to the active item element. For example, on a combobox, the Home
// and End keys shouldn't propagate to the active item, but move the caret on
// the combobox input instead.
if (event.isPropagationStopped()) return false;
return true;
}
function useKeyboardEventProxy(
activeItem?: Item,
onKeyboardEvent?: KeyboardEventHandler
) {
return useEvent((event: ReactKeyboardEvent) => {
onKeyboardEvent?.(event);
if (event.defaultPrevented) return;
if (canProxyKeyboardEvent(event)) {
const activeElement = activeItem?.ref.current;
if (!activeElement) return;
const { view, ...eventInit } = event;
if (!fireKeyboardEvent(activeElement, event.type, eventInit)) {
event.preventDefault();
}
// The event will be triggered on the composite item and then
// propagated up to this composite element again, so we can pretend
// that it wasn't called on this component in the first place.
if (event.currentTarget.contains(activeElement)) {
event.stopPropagation();
}
}
});
}
function findFirstEnabledItemInTheLastRow(items: Item[]) {
return findFirstEnabledItem(
flatten2DArray(reverseArray(groupItemsByRows(items)))
);
}
function isItem(items: Item[], element?: Element | EventTarget | null) {
if (!element) return false;
return items.some((item) => item.ref.current === element);
}
function useScheduleFocus(activeItem?: Item) {
const [scheduled, setScheduled] = useState(false);
const schedule = useCallback(() => setScheduled(true), []);
useEffect(() => {
const activeElement = activeItem?.ref.current;
if (scheduled && activeElement) {
setScheduled(false);
activeElement.focus();
}
}, [activeItem, scheduled]);
return schedule;
}
/**
* A component hook that returns props that can be passed to `Role` or any other
* Ariakit component to render a composite widget.
* @see https://ariakit.org/components/composite
* @example
* ```jsx
* const state = useCompositeState();
* const props = useComposite({ state });
* <Role {...props}>
* <CompositeItem>Item 1</CompositeItem>
* <CompositeItem>Item 2</CompositeItem>
* </Role>
* ```
*/
export const useComposite = createHook<CompositeOptions>(
({ state, composite = true, focusOnMove = composite, ...props }) => {
const ref = useRef<HTMLDivElement>(null);
const virtualFocus = composite && state.virtualFocus;
const activeItem = findEnabledItemById(state.items, state.activeId);
const activeItemRef = useLiveRef(activeItem);
const previousElementRef = useRef<HTMLElement | null>(null);
const isSelfActive = state.activeId === null;
const isSelfAciveRef = useLiveRef(isSelfActive);
const scheduleFocus = useScheduleFocus(activeItem);
// Focus on the active item element.
useSafeLayoutEffect(() => {
if (!focusOnMove) return;
if (!state.moves) return;
const itemElement = activeItemRef.current?.ref.current;
if (!itemElement) return;
// We're scheduling the focus on the next tick to avoid the `onFocus`
// event on each item to be triggered before the state changes can
// propagate to them.
scheduleFocus();
}, [focusOnMove, state.moves]);
useEffect(() => {
if (!composite) return;
if (!state.moves) return;
if (!isSelfAciveRef.current) return;
const element = ref.current;
// When virtualFocus is enabled, calling composite.move(null) will not
// fire a blur event on the active item. So we need to do it manually.
const previousElement = previousElementRef.current;
if (previousElement) {
fireBlurEvent(previousElement, { relatedTarget: element });
}
// If composite.move(null) has been called, the composite container (this
// element) should receive focus.
element?.focus();
// And we have to clean up the previous element ref so an additional blur
// event is not fired on it, for example, when looping through items while
// includesBaseElement is true.
previousElementRef.current = null;
}, [composite, state.moves]);
const onKeyDownCapture = useKeyboardEventProxy(
activeItem,
props.onKeyDownCapture
);
const onKeyUpCapture = useKeyboardEventProxy(
activeItem,
props.onKeyUpCapture
);
const onFocusCaptureProp = props.onFocusCapture;
const onFocusCapture = useEvent((event: FocusEvent<HTMLDivElement>) => {
onFocusCaptureProp?.(event);
if (event.defaultPrevented) return;
if (!virtualFocus) return;
const previousActiveElement = event.relatedTarget as HTMLElement | null;
const previousActiveElementWasItem = isItem(
state.items,
previousActiveElement
);
if (isSelfTarget(event) && previousActiveElementWasItem) {
// Composite has been focused as a result of an item receiving focus.
// The composite item will move focus back to the composite container.
// In this case, we don't want to propagate this additional event nor
// call the onFocus handler passed to <Composite onFocus={...} />.
event.stopPropagation();
// We keep track of the previous active item element so we can manually
// fire a blur event on it later when the focus is moved to another item
// on the onBlurCapture event below.
previousElementRef.current = previousActiveElement;
}
});
const onFocusProp = props.onFocus;
const onFocus = useEvent((event: FocusEvent<HTMLDivElement>) => {
onFocusProp?.(event);
if (event.defaultPrevented) return;
if (!composite) return;
if (virtualFocus) {
// This means that the composite element has been focused while the
// composite item has not. For example, by clicking on the composite
// element without touching any item, or by tabbing into the composite
// element. In this case, we want to trigger focus on the item, just
// like it would happen with roving tabindex. When it receives focus,
// the composite item will move focus back to the composite element.
if (isSelfTarget(event)) {
if (activeItemRef.current?.ref.current) {
activeItemRef.current.ref.current.focus();
} else {
// If there's no active item, it might be because the state.items
// haven't been populated yet, for example, when the composite
// element is focused right after it gets mounted. So we schedule
// a user focus and make another attempt in an effect when the
// state.items is populated.
scheduleFocus();
}
}
} else if (isSelfTarget(event)) {
// When the roving tabindex composite gets intentionally focused (for
// example, by clicking directly on it, and not on an item), we make
// sure to set the activeId to null (which means the composite element
// itself has focus).
state.setActiveId(null);
}
});
const onBlurCaptureProp = props.onBlurCapture;
const onBlurCapture = useEvent((event: FocusEvent<HTMLDivElement>) => {
onBlurCaptureProp?.(event);
if (event.defaultPrevented) return;
if (!virtualFocus) return;
// When virtualFocus is set to true, we move focus from the composite
// container (this element) to the composite item that is being selected.
// Then we move focus back to the composite container. This is so we can
// provide the same API as the roving tabindex method, which means people
// can attach onFocus/onBlur handlers on the CompositeItem component
// regardless of whether virtualFocus is set to true or false. This
// sequence of blurring and focusing on items and on the composite element
// may be confusing, so we ignore intermediate focus and blur events by
// stopping their propagation.
const activeElement = activeItem?.ref.current || null;
const nextActiveElement = event.relatedTarget;
const nextActiveElementIsItem = isItem(state.items, nextActiveElement);
// This is an intermediate blur event: blurring the composite container
// to focus on an item (nextActiveElement).
if (isSelfTarget(event) && nextActiveElementIsItem) {
// The next active element will be the same as the active item in the
// state in these two scenarios:
// - Moving focus with keyboard: the state is updated before the blur
// event is triggered, so here the active item is already pointing
// to the next active element.
// - Clicking on the active item with a pointer: this will trigger
// blur on the composite element and then the next active element
// will be the same as the active item. Clicking on an item other
// than the active one doesn't end up here as the activeItem state
// will be updated only after that.
if (nextActiveElement === activeElement) {
const previousElement = previousElementRef.current;
// If there's a previous active item and it's not a click action, then
// we fire a blur event on it so it will work just like if it had DOM
// focus before (like when using roving tabindex).
if (previousElement && previousElement !== nextActiveElement) {
fireBlurEvent(previousElement, event);
}
}
// This will be true when the next active element is not the active
// element, but there's an active item. This will only happen when
// clicking with a pointer on a different item, when there's already an
// item selected, in which case activeElement is the item that is
// getting blurred, and nextActiveElement is the item that is being
// clicked.
else if (activeElement) {
fireBlurEvent(activeElement, event);
}
// We want to ignore intermediate blur events, so we stop the
// propagation of this event.
event.stopPropagation();
} else {
const targetIsItem = isItem(state.items, event.target);
// If target is not a composite item, it may be the composite element
// itself (isSelfTarget) or a tabbable element inside the composite
// element. This may be triggered by clicking outside of the composite
// element or by tabbing out of it. In either cases, we want to fire a
// blur event on the active item.
if (!targetIsItem && activeElement) {
fireBlurEvent(activeElement, event);
}
}
});
const onKeyDownProp = props.onKeyDown;
const onKeyDown = useEvent((event: ReactKeyboardEvent<HTMLDivElement>) => {
onKeyDownProp?.(event);
if (event.defaultPrevented) return;
if (!isSelfTarget(event)) return;
if (activeItemRef.current) return;
const isVertical = state.orientation !== "horizontal";
const isHorizontal = state.orientation !== "vertical";
const isGrid = !!findFirstEnabledItem(state.items)?.rowId;
const up = () => {
if (isGrid) {
const item =
state.items && findFirstEnabledItemInTheLastRow(state.items);
return item?.id;
}
return state.last();
};
const keyMap = {
ArrowUp: (isGrid || isVertical) && up,
ArrowRight: (isGrid || isHorizontal) && state.first,
ArrowDown: (isGrid || isVertical) && state.first,
ArrowLeft: (isGrid || isHorizontal) && state.last,
Home: state.first,
End: state.last,
PageUp: state.first,
PageDown: state.last,
};
const action = keyMap[event.key as keyof typeof keyMap];
if (action) {
const id = action();
if (id !== undefined) {
event.preventDefault();
state.move(id);
}
}
});
props = useStoreProvider({ state, ...props }, CompositeContext);
const activeId = activeItem?.id || undefined;
props = {
"aria-activedescendant": virtualFocus ? activeId : undefined,
...props,
ref: useForkRef(ref, composite ? state.baseRef : undefined, props.ref),
onKeyDownCapture,
onKeyUpCapture,
onFocusCapture,
onFocus,
onBlurCapture,
onKeyDown,
};
const focusable = composite && (virtualFocus || state.activeId === null);
props = useFocusable({ focusable, ...props });
return props;
}
);
/**
* A component that renders a composite widget.
* @see https://ariakit.org/components/composite
* @example
* ```jsx
* const composite = useCompositeState();
* <Composite state={composite}>
* <CompositeItem>Item 1</CompositeItem>
* <CompositeItem>Item 2</CompositeItem>
* </Composite>
* ```
*/
export const Composite = createComponent<CompositeOptions>((props) => {
const htmlProps = useComposite(props);
return createElement("div", htmlProps);
});
export type CompositeOptions<T extends As = "div"> = FocusableOptions<T> & {
/**
* Object returned by the `useCompositeState` hook.
*/
state: CompositeState;
/**
* Whether the component should behave as a composite widget. This prop should
* be set to `false` when combining different composite widgets where only one
* should behave as such.
* @default true
* @example
* ```jsx
* // Combining two composite widgets (combobox and menu), where only the
* // Combobox component should behave as a composite widget.
* const combobox = useComboboxState();
* const menu = useMenuState(combobox);
* <MenuButton state={menu}>Open Menu</MenuButton>
* <Menu state={menu} composite={false}>
* <Combobox state={combobox} />
* <ComboboxList state={combobox}>
* <ComboboxItem as={MenuItem}>Item 1</ComboboxItem>
* <ComboboxItem as={MenuItem}>Item 2</ComboboxItem>
* <ComboboxItem as={MenuItem}>Item 3</ComboboxItem>
* </ComboboxList>
* </Menu>
* ```
*/
composite?: boolean;
/**
* Whether the active composite item should receive focus when
* `composite.move` is called.
* @default true
*/
focusOnMove?: boolean;
};
export type CompositeProps<T extends As = "div"> = Props<CompositeOptions<T>>; | the_stack |
interface Item {
name: string;
route?: string;
content?: () => Promise<any>;
items?: Item[];
}
let list: Item[] = [
{
name: "General",
items: [
{
name: "Button",
route: "+/button/states",
content: () => import("./general/button/states")
},
{
route: "+/tab/states",
name: "Tab",
content: () => import("./general/tab/states")
},
{
route: "+/menu/states",
name: "Menu",
content: () => import("./general/menu/states")
},
{
route: "+/list/states",
name: "List",
content: () => import("./general/list/states")
},
{
route: "+/window/states",
name: "Window",
content: () => import("./general/window/states")
},
{
route: "+/toast/states",
name: "Toast",
content: () => import("./general/toast/states")
},
{
route: "+/section/states",
name: "Section",
content: () => import("./general/section/states")
},
{
route: "+/progressbar/states",
name: "ProgressBar",
content: () => import("./general/progressbar/states")
}
]
},
{
name: "Grid",
items: [
{
name: "Basic",
route: "+/grid/basic",
content: () => import("./general/grids/basic")
},
{
name: "Multiple Selection",
route: "+/grid/multi-select",
content: () => import("./general/grids/multi-select")
},
{
name: "Grouping",
route: "+/grid/grouping",
content: () => import("./general/grids/grouping")
},
{
name: "Dynamic Grouping",
route: "+/grid/dynamic-grouping",
content: () => import("./general/grids/dynamic-grouping")
},
{
name: "Row Drag & Drop",
route: "+/grid/drag-drop",
content: () => import("./general/grids/drag-drop")
},
{
name: "Filtering",
route: "+/grid/filtering",
content: () => import("./general/grids/filtering")
},
{
name: "Row Editing",
route: "+/grid/row-editing",
content: () => import("./general/grids/row-editing")
},
{
name: "Cell Editing",
route: "+/grid/cell-editing",
content: () => import("./general/grids/cell-editing")
},
{
name: "Form Editing",
route: "+/grid/form-editing",
content: () => import("./general/grids/form-editing")
},
{
name: "Row Expanding",
route: "+/grid/row-expanding",
content: () => import("./general/grids/row-expanding")
},
{
name: "Header Menu",
route: "+/grid/header-menu",
content: () => import("./general/grids/header-menu")
},
{
name: "Tree Grid",
route: "+/grid/tree-grid",
content: () => import("./general/grids/tree-grid")
},
{
name: "Complex Header",
route: "+/grid/complex-header",
content: () => import("./general/grids/complex-header")
},
{
name: "Buffering",
route: "+/grid/buffering",
content: () => import("./general/grids/buffering")
},
{
name: "Dashboard Grid",
route: "+/grid/dashboard-grid",
content: () => import("./general/grids/dashboard-grid")
},
{
name: "Misc",
route: "+/grid/misc",
content: () => import("./general/grids/misc")
}
]
},
{
name: "Forms",
items: [
{
route: "+/checkbox",
name: "Checkbox",
content: () => import("./forms/checkbox/states")
},
{
route: "+/radio",
name: "Radio",
content: () => import("./forms/radio/states")
},
{
route: "+/switch",
name: "Switch",
content: () => import("./forms/switch/states")
},
{
route: "+/text-field",
name: "TextField",
content: () => import("./forms/text-field/states")
},
{
route: "+/number-field",
name: "NumberField",
content: () => import("./forms/number-field/states")
},
{
route: "+/date-field",
name: "DateField",
content: () => import("./forms/date-field/states")
},
{
route: "+/calendar",
name: "Calendar",
content: () => import("./forms/calendar/states")
},
{
route: "+/month-picker",
name: "MonthPicker",
content: () => import("./forms/month-picker/states")
},
{
route: "+/month-field",
name: "MonthField",
content: () => import("./forms/month-field/states")
},
{
route: "+/text-area",
name: "TextArea",
content: () => import("./forms/text-area/states")
},
{
route: "+/select",
name: "Select",
content: () => import("./forms/select/states")
},
{
route: "+/lookup-field",
name: "LookupField",
content: () => import("./forms/lookup-field/states")
},
{
route: "+/color-field",
name: "ColorField",
content: () => import("./forms/color-field/states")
},
{
route: "+/color-picker",
name: "ColorPicker",
content: () => import("./forms/color-picker/states")
},
{
route: "+/slider",
name: "Slider",
content: () => import("./forms/slider/states")
},
{
route: "+/date-time-field",
name: "DateTimeField",
content: () => import("./forms/date-time-field/states")
}
]
},
{
name: "Charts",
items: [
{
route: "+/pie-chart/standard",
name: "Standard Pie Chart",
content: () => import("./charts/pie-chart/standard")
},
{
route: "+/pie-chart/multi-level",
name: "Multi-level Pie Chart",
content: () => import("./charts/pie-chart/multilevel")
},
{
route: "+/line-graph/standard",
name: "Line Graph",
content: () => import("./charts/line-graph/standard")
},
{
route: "+/line-graph/stacked",
name: "Stacked Line Graph",
content: () => import("./charts/line-graph/stacked")
},
{
route: "+/column-graph/standard",
name: "Column Chart",
content: () => import("./charts/column-graph/standard")
},
{
route: "+/column-graph/timeline",
name: "Timeline",
content: () => import("./charts/column-graph/timeline")
},
{
route: "+/column/stacked",
name: "Stacked Columns",
content: () => import("./charts/column/stacked")
},
{
route: "+/column/auto-column-width",
name: "Auto Stacked Columns",
content: () => import("./charts/column/auto-column-width")
},
{
route: "+/column/customized",
name: "Customized Columns",
content: () => import("./charts/column/customized")
},
{
route: "+/column/combination",
name: "Column Chart + Grid",
content: () => import("./charts/column/combination")
},
{
route: "+/column/normalized",
name: "Normalized Columns",
content: () => import("./charts/column/normalized")
},
{
route: "+/bar-graph/standard",
name: "Bar Chart",
content: () => import("./charts/bar-graph/standard")
},
{
route: "+/bar/stacked",
name: "Stacked Bar Chart",
content: () => import("./charts/bar/stacked")
},
{
route: "+/bar/bullets",
name: "Bullet Chart",
content: () => import("./charts/bar/bullets")
},
{
route: "+/scatter-graph/standard",
name: "Scatter Chart",
content: () => import("./charts/scatter-graph/standard")
},
{
route: "+/marker-line/standard",
name: "Marker Lines",
content: () => import("./charts/marker-line/standard")
},
{
route: "+/marker/standard",
name: "Markers",
content: () => import("./charts/marker/standard")
},
{
route: "+/range/standard",
name: "Range",
content: () => import("./charts/range/standard")
},
]
},
{
name: "Layout",
items: [
{
route: "+/flex-row/options",
name: "FlexRow",
content: () => import("./general/flex-row/options")
},
{
route: "+/flex-col/options",
name: "FlexCol",
content: () => import("./general/flex-col/options")
}
]
}
];
// export let sorted = list.map(section => {
// if (section.items) {
// section.items = [...section.items].sort((a, b) => {
// if (a.name >= b.name) return 1;
// else return -1;
// });
// }
//
// return section;
// });
export default list; | the_stack |
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { esIndex } from './consts';
import {Injectable, Inject} from "@angular/core";
/**
* Data abstraction layer is an absraction to some connector (for now realized {@link FirebaseConnector}, but you can create your own using this contract).
* To use some connector you must provide it in app.module.ts
* ```
* providers: [
* ...,
* {
* provide: 'Connector'
* useClass: FirebaseConnector
* }
* ]
* ```
* There are method with queryObject parameter. {@link ProductService} use them to work with products. Query object are generated in this service.
*/
@Injectable()
export class DbAbstractionLayer {
constructor(@Inject('Connector') private connector){
}
/**
* Add general category to database
*
* @param {FormGroup} generalCategoryForm form of general category
*/
addGeneralCategory(generalCategoryForm){
this.connector.addGeneralCategory(generalCategoryForm);
}
/**
* Add category to database
*
* @param {FormGroup} categoryForm form of category
*/
addCategory(categoryForm){
this.connector.addCategory(categoryForm);
}
/**
* Add new attribute to database
*
* @param {FormGroup} attributeForm form of attribute
* @param {string} categoryId id of category
*/
addAttribute(attributeForm, categoryId){
this.connector.addAttribute(attributeForm, categoryId);
}
/**
* Add new tag to database
*
* @param {FormGroup} tagForm form of tag
* @param {string} categoryId id of category
*/
addTag(tagForm, categoryId){
this.connector.addTag(tagForm, categoryId);
}
/**
* Add product to database
*
* @param {Object} product product Object
*/
addProduct(product){
this.connector.addProduct(product);
}
/**
* Returns products by query object (look to {@link ProductService} method getProductsByIds)
*/
getProductsByIds(queryObj){
return this.connector.requestFullData(esIndex, 'product', queryObj);
}
/**
* Returns basket content of specific user
*
* @param {string} userId user Id
*
* @returns {Observable} Observable of basket
*/
getBasketContent(id){
return this.connector.getBasketContent(id);
}
/**
* Initialize basket history for user. If you want to track basket history run this method when user sign in
*
* @param {string} userId userId or deviceId
*
*/
initializeBasketHistory(userId) {
return this.connector.initializeBasketHistory(userId);
}
/**
* Returns basket history subject
*
* @returns {Subject} basketHistory Subject of basketHistory
*/
getBasketHistorySubject(): Subject<any> {
return this.connector.getBasketHistorySubject();
}
/**
* Returns Rx Observable of basket history of user by userId or deviceId
*
* @param {string} userId userId or deviceId
*
* @returns {Observable} Rx Observable of basket history
*/
getBasketHistoryById(id) {
return this.connector.getBasketHistoryById(id);
}
/**
* Will be realized in next versions
*/
getСomparison(id){
return this.connector.getComparison(id);
}
/**
* Set new basket by user id or device id
* @param id userId or deviceId
* @param newBasket
*/
setNewBasket(id, newBasket){
return this.connector.setNewBasket(id, newBasket);
}
/**
* Will be realized in next versions
*/
addProductToComparison(id, product){
return this.connector.addProductToComparison(id, product);
}
/**
* Will be realized in next versions
*/
removeProductFromComparison(id, idInComparison){
return this.connector.removeProductFromComparison(id, idInComparison);
}
/**
* Gets data hits from ElasticSearch
*
* @param {string} index ElasticSearch index
* @param {string} type ElasticSearch type
* @param {Object} queryObj query object for ElasticSearch
*
* @returns {Observable} Observable of requested data hits
*/
requestData(esIndex, type, queryObj){
return this.connector.requestData(esIndex, type, queryObj);
}
/**
* Gets full data from ElasticSearch
*
* @param {string} index ElasticSearch index
* @param {string} type ElasticSearch type
* @param {Object} queryObj query object for ElasticSearch
*
* @returns {Observable} Observable of requested data
*/
requestFullData(esIndex, type, queryObj){
return this.connector.requestFullData(esIndex, type, queryObj);
}
/**
* Gets total item of data from ElasticSearch
*
* @param {string} index ElasticSearch index
* @param {string} type ElasticSearch type
* @param {Object} queryObj query object for ElasticSearch
*
* @returns {Observable} Observable of total item
*/
requestItemsTotal(esIndex, type, queryObj){
return this.connector.requestItemsTotal(esIndex, 'product', queryObj);
}
/**
* Return tags by query object
*
* @param {Object} queryObj ElasticSearch query object
*
* @returns {Observable} Observable of tags
*/
getTags(queryObj){
return this.connector.requestData(esIndex, 'tags', queryObj);
}
/**
* Return attributes by query object
*
* @param {Object} queryObj ElasticSearch query object
*
* @returns {Observable} Observable of attributes
*/
getAttributes(queryObj){
return this.connector.requestFullData(esIndex, 'attributes', queryObj);
}
/**
* Logout user
*/
logout(){
this.connector.logout();
}
/**
* Register user with email and password
*
* @param {string} email User email
* @param {string} password User password
*
* @returns Promise containing user data
*/
register(email, password){
return this.connector.register(email, password);
}
/**
* Register user with email and password. Save additional information in database
*
* @param registerForm Object that have email, password and any additional information about user.
* Additional information stores in database as user backet
*/
registerUser(registerForm){
return this.connector.registerUser(registerForm);
}
/**
* Get user data
*
* @param {string} uid user Id
*
* @returns {Observable} Observable of user data
*/
getUserData(uid){
return this.connector.getUserData(uid);
}
/**
* Login with email and password
*
* @param {string} email User email
* @param {string} password User password
*
* @returns Promise containing User
*/
loginEmail(email, password){
return this.connector.loginEmail(email, password);
}
/**
* Check old session flow using device id
*
* @param {string} deviceId User device Id
*/
checkOldSessionFlow(deviceId){
this.connector.checkOldSessionFlow(deviceId);
}
/**
* Connect [Session-flow]{@link https://www.npmjs.com/package/@nodeart/session-flow} to databese.
*
* @param {SessionFlow} sessionFlow SessionFlow service
* @param {string} deviceId User device id generated by SessionFlow
* @param {string} sessionId User session id generated by SessionFlow
*
*/
connectSessionFlowToDB(sessionFlow, deviceId, sessionId){
this.connector.connectSessionFlowToDB(sessionFlow, deviceId, sessionId);
}
/**
* Returns visited routes
*
* @returns array of visited routes objects
*/
getVisitedRoutes(){
return this.connector.getVisitedRoutes();
}
/**
* Returns user clicks
*
* @returns array of user clicks objects
*/
getUserClicks(){
return this.connector.getUserClicks();
}
/**
* Returns auth object. Avoid manipulating with connector directly. Use dal methods to communicate with connector
*
* @returns Auth object
*/
getAuth(){
return this.connector.getAuth();
}
/**
* Save new order to database
*
* @param {Object} paymentData
*
* @returns {Observable} Observable
*/
saveOrder(orderData) {
return this.connector.saveOrder(orderData);
}
/**
* Add payment requets. Server listens database backet with payments request and process coming requests
*
* @param {Object} data PaymentData
* @param {string} paymentMethod name of payment method
*
* @returns {Observable} Observable
*/
addPaymentRequest(data, paymentMethod){
return this.connector.addPaymentRequest(data, paymentMethod);
}
/**
* Returns payment response by id
*
* @param {string} paymentKey id of payment response. Payment request and payment response have same ids in their backets
*
* @returns {Observable} Observable of payment response
*/
listenPaymentResponse(paymentKey){
return this.connector.listenPaymentResponse(paymentKey);
}
/**
* Returns orders by user id
*
* @param {string} userId user id
*
* @returns {Observable} Observable of user orders
*/
getOrdersByUserId(userId) {
let queryObj = {
query: {
multi_match: {
query: userId,
fields: ["orderForm.userId"],
type: "phrase"
}
}
};
console.log(queryObj);
return this.connector.requestFullData(esIndex, 'orders', queryObj);
}
/**
* Send letter with password resetting to specific email
*
* @param {string} email User email
*
* @returns Promise containing void
*/
resetPassword(email) {
return this.connector.resetPassword(email);
}
/**
* Get order by Id
* @param id id of order
* @returns {Observable} Observable of order
*/
getOrderById(id) {
return this.connector.getOrderById(id);
}
/**
* Emits order object when new order added
*
* @returns {Observable} Observable of new order
*/
listenOrders() :Observable<any> {
return this.connector.listenOrders();
}
getOrderSubject() {
return this.connector.getOrderSubject();
}
getSeoText(url: string, indexBlock: number) :Observable<any>{
return this.connector.getSeoText(url, indexBlock);
}
} | the_stack |
class SoundExpression {
constructor(private notes: string) {
}
/**
* Starts to play a sound expression.
*/
//% block="play sound $this"
//% weight=80
//% blockGap=8
//% help=music/play
//% group="micro:bit (V2)"
//% parts=builtinspeaker
//% deprecated=1
play() {
music.__playSoundExpression(this.notes, false)
}
/**
* Plays a sound expression until finished
*/
//% block="play sound $this until done"
//% weight=81
//% blockGap=8
//% help=music/play-until-done
//% group="micro:bit (V2)"
//% parts=builtinspeaker
//% deprecated=1
playUntilDone() {
music.__playSoundExpression(this.notes, true)
}
getNotes() {
return this.notes;
}
}
enum WaveShape {
//% block="sine"
Sine = 0,
//% block="sawtooth"
Sawtooth = 1,
//% block="triangle"
Triangle = 2,
//% block="square"
Square = 3,
//% block="noise"
Noise = 4
}
enum InterpolationCurve {
//% block="linear"
Linear,
//% block="curve"
Curve,
//% block="logarithmic"
Logarithmic
}
enum SoundExpressionEffect {
//% block="none"
None = 0,
//% block="vibrato"
Vibrato = 1,
//% block="tremolo"
Tremolo = 2,
//% block="warble"
Warble = 3
}
enum SoundExpressionPlayMode {
//% block="until done"
UntilDone,
//% block="in background"
InBackground
}
namespace soundExpression {
//% fixedInstance whenUsed block="{id:soundexpression}giggle"
export const giggle = new SoundExpression("giggle");
//% fixedInstance whenUsed block="{id:soundexpression}happy"
export const happy = new SoundExpression("happy");
//% fixedInstance whenUsed block="{id:soundexpression}hello"
export const hello = new SoundExpression("hello");
//% fixedInstance whenUsed block="{id:soundexpression}mysterious"
export const mysterious = new SoundExpression("mysterious");
//% fixedInstance whenUsed block="{id:soundexpression}sad"
export const sad = new SoundExpression("sad");
//% fixedInstance whenUsed block="{id:soundexpression}slide"
export const slide = new SoundExpression("slide");
//% fixedInstance whenUsed block="{id:soundexpression}soaring"
export const soaring = new SoundExpression("soaring");
//% fixedInstance whenUsed block="{id:soundexpression}spring"
export const spring = new SoundExpression("spring");
//% fixedInstance whenUsed block="{id:soundexpression}twinkle"
export const twinkle = new SoundExpression("twinkle");
//% fixedInstance whenUsed block="{id:soundexpression}yawn"
export const yawn = new SoundExpression("yawn");
export enum InterpolationEffect {
None = 0,
Linear = 1,
Curve = 2,
ExponentialRising = 5,
ExponentialFalling = 6,
ArpeggioRisingMajor = 8,
ArpeggioRisingMinor = 10,
ArpeggioRisingDiminished = 12,
ArpeggioRisingChromatic = 14,
ArpeggioRisingWholeTone = 16,
ArpeggioFallingMajor = 9,
ArpeggioFallingMinor = 11,
ArpeggioFallingDiminished = 13,
ArpeggioFallingChromatic = 15,
ArpeggioFallingWholeTone = 17,
Logarithmic = 18
}
export class Sound {
src: string;
constructor() {
this.src = "000000000000000000000000000000000000000000000000000000000000000000000000"
}
get wave(): WaveShape {
return this.getValue(0, 1);
}
set wave(value: WaveShape) {
this.setValue(0, Math.constrain(value, 0, 4), 1);
}
get volume() {
return this.getValue(1, 4);
}
set volume(value: number) {
this.setValue(1, Math.constrain(value, 0, 1023), 4);
}
get frequency() {
return this.getValue(5, 4);
}
set frequency(value: number) {
this.setValue(5, value, 4);
}
get duration() {
return this.getValue(9, 4);
}
set duration(value: number) {
this.setValue(9, value, 4);
}
get shape(): InterpolationEffect {
return this.getValue(13, 2);
}
set shape(value: InterpolationEffect) {
this.setValue(13, value, 2);
}
get endFrequency() {
return this.getValue(18, 4);
}
set endFrequency(value: number) {
this.setValue(18, value, 4);
}
get endVolume() {
return this.getValue(26, 4);
}
set endVolume(value: number) {
this.setValue(26, Math.constrain(value, 0, 1023), 4);
}
get steps() {
return this.getValue(30, 4);
}
set steps(value: number) {
this.setValue(30, value, 4);
}
get fx(): SoundExpressionEffect {
return this.getValue(34, 2);
}
set fx(value: SoundExpressionEffect) {
this.setValue(34, Math.constrain(value, 0, 3), 2);
}
get fxParam() {
return this.getValue(36, 4);
}
set fxParam(value: number) {
this.setValue(36, value, 4);
}
get fxnSteps() {
return this.getValue(40, 4);
}
set fxnSteps(value: number) {
this.setValue(40, value, 4);
}
get frequencyRandomness() {
return this.getValue(44, 4);
}
set frequencyRandomness(value: number) {
this.setValue(44, value, 4);
}
get endFrequencyRandomness() {
return this.getValue(48, 4);
}
set endFrequencyRandomness(value: number) {
this.setValue(48, value, 4);
}
get volumeRandomness() {
return this.getValue(52, 4);
}
set volumeRandomness(value: number) {
this.setValue(52, value, 4);
}
get endVolumeRandomness() {
return this.getValue(56, 4);
}
set endVolumeRandomness(value: number) {
this.setValue(56, value, 4);
}
get durationRandomness() {
return this.getValue(60, 4);
}
set durationRandomness(value: number) {
this.setValue(60, value, 4);
}
get fxParamRandomness() {
return this.getValue(64, 4);
}
set fxParamRandomness(value: number) {
this.setValue(64, value, 4);
}
get fxnStepsRandomness() {
return this.getValue(68, 4);
}
set fxnStepsRandomness(value: number) {
this.setValue(68, value, 4);
}
copy() {
const result = new Sound();
result.src = this.src.slice(0);
return result;
}
protected setValue(offset: number, value: number, length: number) {
value = Math.constrain(value | 0, 0, Math.pow(10, length) - 1);
this.src = this.src.substr(0, offset) + formatNumber(value, length) + this.src.substr(offset + length);
}
protected getValue(offset: number, length: number) {
return parseInt(this.src.substr(offset, length));
}
}
function formatNumber(num: number, length: number) {
let result = num + "";
while (result.length < length) result = "0" + result;
return result;
}
export function playSound(toPlay: Sound | Sound[]) {
let src = "";
if (Array.isArray(toPlay)) {
src = (toPlay as Sound[]).map(s => s.src).join(",");
}
else {
src = (toPlay as Sound).src;
}
new SoundExpression(src).playUntilDone();
}
}
namespace music {
/**
* Play a sound effect from a sound expression string.
* @param sound expression string
* @param mode to play until done or in the background
*/
//% blockId=soundExpression_playSoundEffect
//% block="play sound $sound $mode"
//% sound.shadow=soundExpression_createSoundEffect
//% weight=100 help=music/play-sound-effect
//% blockGap=8
//% group="micro:bit (V2)"
export function playSoundEffect(sound: string, mode: SoundExpressionPlayMode) {
if (mode === SoundExpressionPlayMode.InBackground) {
new SoundExpression(sound).play();
}
else {
new SoundExpression(sound).playUntilDone();
}
}
/**
* Create a sound expression from a set of sound effect parameters.
* @param waveShape for the sound effect
* @param startFrequency for the sound effect waveform
* @param endFrequency for the sound effect waveform
* @param startVolume of the sound, or starting amplitude
* @param endVolume of the sound, or ending amplitude
* @param duration in milliseconds (ms) that sound will play for
* @param effect to apply to the waveform or volume
* @param interpolation for frequency scaling
*/
//% blockId=soundExpression_createSoundEffect
//% help=music/create-sound-effect
//% block="$waveShape|| start frequency $startFrequency end frequency $endFrequency duration $duration start volume $startVolume end volume $endVolume effect $effect interpolation $interpolation"
//% waveShape.defl=WaveShape.Sine
//% waveShape.fieldEditor=soundeffect
//% startFrequency.defl=5000
//% startFrequency.min=0
//% startFrequency.max=5000
//% endFrequency.defl=0
//% endFrequency.min=0
//% endFrequency.max=5000
//% startVolume.defl=255
//% startVolume.min=0
//% startVolume.max=255
//% endVolume.defl=0
//% endVolume.min=0
//% endVolume.max=255
//% duration.defl=500
//% duration.min=1
//% duration.max=9999
//% effect.defl=SoundExpressionEffect.None
//% interpolation.defl=InterpolationCurve.Linear
//% compileHiddenArguments=true
//% inlineInputMode="variable"
//% inlineInputModeLimit=3
//% expandableArgumentBreaks="3,5"
//% group="micro:bit (V2)"
export function createSoundEffect(waveShape: WaveShape, startFrequency: number, endFrequency: number, startVolume: number, endVolume: number, duration: number, effect: SoundExpressionEffect, interpolation: InterpolationCurve): string {
const sound = new soundExpression.Sound();
sound.wave = waveShape;
sound.frequency = startFrequency;
sound.volume = ((startVolume / 255) * 1023) | 0;
sound.endFrequency = endFrequency;
sound.endVolume = ((endVolume / 255) * 1023) | 0;
sound.duration = duration;
sound.fx = effect;
switch (interpolation) {
case InterpolationCurve.Linear:
sound.shape = soundExpression.InterpolationEffect.Linear;
sound.steps = 128;
break;
case InterpolationCurve.Curve:
sound.shape = soundExpression.InterpolationEffect.Curve;
sound.steps = 90;
break;
case InterpolationCurve.Logarithmic:
sound.shape = soundExpression.InterpolationEffect.Logarithmic;
sound.steps = 90;
break;
}
switch (sound.fx) {
case SoundExpressionEffect.Vibrato:
sound.fxnSteps = 512;
sound.fxParam = 2;
break;
case SoundExpressionEffect.Tremolo:
sound.fxnSteps = 900;
sound.fxParam = 3;
break;
case SoundExpressionEffect.Warble:
sound.fxnSteps = 700;
sound.fxParam = 2;
break;
}
return sound.src;
}
/**
* Get the sound expression string for a built-in a sound effect.
* @param soundExpression for a built-in sound effect
*/
//% blockId=soundExpression_builtinSoundEffect
//% block="$soundExpression"
//% blockGap=8
//% group="micro:bit (V2)"
//% toolboxParent=soundExpression_playSoundEffect
//% toolboxParentArgument=sound
//% weight=102 help=music/builtin-sound-effect
export function builtinSoundEffect(soundExpression: SoundExpression) {
return soundExpression.getNotes();
}
} | the_stack |
import { grpc } from '@improbable-eng/grpc-web'
import {
encrypt,
extractPublicKeyBytes,
Identity,
Public,
} from '@textile/crypto'
import {
CopyAuthOptions,
GrpcAuthentication,
WithKeyInfoOptions,
WithUserAuthOptions,
} from '@textile/grpc-authentication'
import { GetThreadResponse } from '@textile/hub-threads-client'
import { KeyInfo, UserAuth } from '@textile/security'
import {
deleteInboxMessage,
deleteSentboxMessage,
getMailboxID,
getThread,
getUsage,
GetUsageResponse,
InboxListOptions,
listInboxMessages,
listSentboxMessages,
listThreads,
MailboxEvent,
readInboxMessage,
sendMessage,
SentboxListOptions,
setupMailbox,
UsageOptions,
UserMessage,
watchMailbox,
} from './api'
/**
* Users a client wrapper for interacting with the Textile Users API.
*
* This API has the ability to:
*
* - Register new users with a User Group key and obtain a new API Token
*
* - Get and List all Threads created for/by the user in your app.
*
* - Create an inbox for the user or send message to another user's inbox.
*
* - Check, read, and delete messages in a user's inbox.
*
* @example
* Initialize a the User API and list their threads.
* ```typescript
* import { Users, UserAuth } from '@textile/hub'
*
* const example = async (auth: UserAuth) => {
* const api = Users.withUserAuth(auth)
* const list = api.listThreads()
* return list
* }
* ```
*
* @example
* Create a new inbox for the user
* ```typescript
* import { Users } from '@textile/hub'
*
* // This method requires you already authenticate the Users object.
* async function setupMailbox (users: Users) {
* await users.setupMailbox()
* }
* ```
*
* @example
* Send a message to a public key
* ```typescript
* import { Users, Identity, PublicKey } from "@textile/hub"
*
* // This method requires you already authenticate the Users object.
*
* async function example(users: Users, from: Identity, to: PublicKey, message: string) {
* const encoder = new TextEncoder()
* const body = encoder.encode(message)
* return await users.sendMessage(from, to, body)
* }
* ```
*/
export class Users extends GrpcAuthentication {
/**
* {@inheritDoc @textile/hub#GrpcAuthentication.copyAuth}
*
* @example
* Copy an authenticated Users api instance to Buckets.
* ```typescript
* import { Buckets, Users } from '@textile/hub'
*
* const usersToBuckets = async (user: Users) => {
* const buckets = Buckets.copyAuth(user)
* return buckets
* }
* ```
*
* @example
* Copy an authenticated Buckets api instance to Users.
* ```typescript
* import { Buckets, Users } from '@textile/hub'
*
* const bucketsToUsers = async (buckets: Buckets) => {
* const user = Users.copyAuth(buckets)
* return user
* }
* ```
*/
static copyAuth(auth: GrpcAuthentication, options?: CopyAuthOptions): Users {
return new Users(auth.context, options?.debug)
}
/**
* {@inheritDoc @textile/hub#GrpcAuthentication.withUserAuth}
*
* @example
* ```@typescript
* import { Users, UserAuth } from '@textile/hub'
*
* async function example (userAuth: UserAuth) {
* const users = await Users.withUserAuth(userAuth)
* }
* ```
*/
static withUserAuth(
auth: UserAuth | (() => Promise<UserAuth>),
options?: WithUserAuthOptions,
): Users {
const res = super.withUserAuth(auth, options)
return this.copyAuth(res, options)
}
/**
* {@inheritDoc @textile/hub#GrpcAuthentication.withKeyInfo}
*
* @example
* ```@typescript
* import { Users, KeyInfo } from '@textile/hub'
*
* async function start () {
* const keyInfo: KeyInfo = {
* key: '<api key>',
* secret: '<api secret>'
* }
* const users = await Users.withKeyInfo(keyInfo)
* }
* ```
*/
static async withKeyInfo(
key: KeyInfo,
options?: WithKeyInfoOptions,
): Promise<Users> {
const auth = await super.withKeyInfo(key, options)
return this.copyAuth(auth, options)
}
/**
* {@inheritDoc @textile/hub#GrpcAuthentication.withThread}
*
* @example
* ```@typescript
* import { Client, ThreadID } from '@textile/hub'
*
* async function example (threadID: ThreadID) {
* const id = threadID.toString()
* const users = await Users.withThread(id)
* }
* ```
*/
withThread(threadID?: string): void {
return super.withThread(threadID)
}
/**
* {@inheritDoc @textile/hub#GrpcAuthentication.getToken}
*
* @example
* ```@typescript
* import { Users, PrivateKey } from '@textile/hub'
*
* async function example (users: Users, identity: PrivateKey) {
* const token = await users.getToken(identity)
* return token // already added to `users` scope
* }
* ```
*/
async getToken(identity: Identity): Promise<string> {
return super.getToken(identity)
}
/**
* {@inheritDoc @textile/hub#GrpcAuthentication.getToken}
*/
setToken(token: string): Promise<void> {
return super.setToken(token)
}
/**
* {@inheritDoc @textile/hub#GrpcAuthentication.getTokenChallenge}
*
* @example
* ```typescript
* import { Users, PrivateKey } from '@textile/hub'
*
* async function example (users: Users, identity: PrivateKey) {
* const token = await users.getTokenChallenge(
* identity.public.toString(),
* (challenge: Uint8Array) => {
* return new Promise((resolve, reject) => {
* // This is where you should program PrivateKey to respond to challenge
* // Read more here: https://docs.textile.io/tutorials/hub/production-auth/
* })
* }
* )
* return token
* }
* ```
*/
async getTokenChallenge(
publicKey: string,
callback: (challenge: Uint8Array) => Uint8Array | Promise<Uint8Array>,
): Promise<string> {
return super.getTokenChallenge(publicKey, callback)
}
/**
* GetUsage returns current billing and usage information.
*
* @example
* ```typescript
* import { Users } from "@textile/hub"
*
* async function example(users: Users) {
* const usage = await users.getUsage()
* }
* ```
*/
async getUsage(options?: UsageOptions): Promise<GetUsageResponse> {
return getUsage(this, options)
}
/**
* Lists a users existing threads. This method
* requires a valid user, token, and session.
*
* @example
* ```typescript
* import { Users } from "@textile/hub"
*
* async function example(users: Users) {
* const list = await users.listThreads()
* }
* ```
*/
async listThreads(): Promise<Array<GetThreadResponse>> {
return listThreads(this)
}
/**
* Gets a users existing thread by name.
*
* @example
* ```typescript
* import { Users } from "@textile/hub"
*
* async function example(users: Users) {
* const thread = await users.getThread('thread-name')
* return thread
* }
* ```
*/
async getThread(name: string): Promise<GetThreadResponse> {
return getThread(this, name)
}
/**
* Setup a user's inbox. This is required for each new user.
* An inbox must be setup by the inbox owner (keys) before
* messages can be sent to it.
*
* @returns mailboxID
*
* @example
* ```typescript
* import { Users } from "@textile/hub"
*
* async function example(users: Users) {
* return await users.setupMailbox()
* }
* ```
*/
async setupMailbox(): Promise<string> {
return setupMailbox(this)
}
/**
* Returns the mailboxID of the current user if it exists.
*
* @returns {string} mailboxID
*/
async getMailboxID(): Promise<string> {
return getMailboxID(this)
}
/**
* A local user can author messages to remote user through their public-key
*
* @param from defines the local, sending, user. Any object that conforms to the Identity interface.
* @param to defines the remote, receiving user. Any object that conforms to the Public interface.
* @param body is the message body bytes in UInt8Array format.
*
* @example
* ```typescript
* import { Users, Identity, PublicKey } from "@textile/hub"
*
* async function example(users: Users, from: Identity, to: PublicKey, message: string) {
* const encoder = new TextEncoder()
* const body = encoder.encode(message)
* return await users.sendMessage(from, to, body)
* }
* ```
*/
async sendMessage(
from: Identity,
to: Public,
body: Uint8Array,
): Promise<UserMessage> {
const toBytes = extractPublicKeyBytes(to)
const fromBytes = extractPublicKeyBytes(from.public)
const fromBody = await encrypt(body, fromBytes)
const fromSig = await from.sign(fromBody)
const toBody = await encrypt(body, toBytes)
const toSig = await from.sign(toBody)
return sendMessage(
this,
from.public.toString(),
to.toString(),
toBody,
toSig,
fromBody,
fromSig,
)
}
/**
* List the inbox of the local user
*
* @example
* ```typescript
* import { Users, Status } from "@textile/hub"
*
* async function example(users: Users) {
* return await users.listInboxMessages({
* limit: 5,
* ascending: true,
* status: Status.UNREAD,
* })
* }
* ```
*/
async listInboxMessages(
opts?: InboxListOptions,
): Promise<Array<UserMessage>> {
return listInboxMessages(this, opts)
}
/**
* List the sent messages of the local user
*
* @example
* ```typescript
* import { Users } from "@textile/hub"
*
* async function example(users: Users) {
* return await users.listSentboxMessages({
* limit: 5,
* ascending: true,
* })
* }
* ```
*/
async listSentboxMessages(
opts?: SentboxListOptions,
): Promise<Array<UserMessage>> {
return listSentboxMessages(this, opts)
}
/**
* Mark a message as read
*
* @example
* ```typescript
* import { Users } from "@textile/hub"
*
* async function example(users: Users) {
* const res = await users.listInboxMessages({
* limit: 1,
* ascending: true,
* })
* if (res.length === 1) users.readInboxMessage(res[0].id)
* }
* ```
*/
async readInboxMessage(id: string): Promise<{ readAt: number }> {
return readInboxMessage(this, id)
}
/**
* Mark a message as read
*
* @example
* ```typescript
* import { Users } from "@textile/hub"
*
* async function example(users: Users) {
* const res = await users.listInboxMessages({
* limit: 1,
* ascending: true,
* })
* if (res.length === 1) users.deleteInboxMessage(res[0].id)
* }
* ```
*/
async deleteInboxMessage(id: string): Promise<void> {
return deleteInboxMessage(this, id)
}
/**
* Mark a message as read
*
* @example
* ```typescript
* import { Users } from "@textile/hub"
*
* async function example(users: Users) {
* const res = await users.listSentboxMessages({
* limit: 1,
* ascending: true,
* })
* if (res.length === 1) users.deleteInboxMessage(res[0].id)
* }
* ```
*/
async deleteSentboxMessage(id: string): Promise<void> {
return deleteSentboxMessage(this, id)
}
/**
* watchInbox watches the inbox for new mailbox events.
* Returns a listener of watch connectivity states.
* @returns listener. listener.close will stop watching.
* @param id the mailbox id
* @param callback handles each new mailbox event
*
* @example
* Listen and log all new inbox events
*
* ```typescript
* import { Users, MailboxEvent } from '@textile/hub'
*
* const callback = async (reply?: MailboxEvent, err?: Error) => {
* if (!reply || !reply.message) return console.log('no message')
* console.log(reply.type)
* }
*
* async function example (users: Users) {
* const mailboxID = await users.getMailboxID()
* const closer = await users.watchInbox(mailboxID, callback)
* return closer
* }
* ```
*
* @example
* Decrypt a new message in local user's inbox sent by listener callback
*
* ```typescript
* import { Users, MailboxEvent, PrivateKey } from '@textile/hub'
*
* const userID = PrivateKey.fromRandom()
*
* const callback = async (reply?: MailboxEvent, err?: Error) => {
* if (!reply || !reply.message) return console.log('no message')
* const bodyBytes = await userID.decrypt(reply.message.body)
*
* const decoder = new TextDecoder()
* const body = decoder.decode(bodyBytes)
*
* console.log(body)
* }
*
* // Requires userID already be authenticated to the Users API
* async function startListener(users: Users) {
* const mailboxID = await users.getMailboxID()
* const closer = await users.watchInbox(mailboxID, callback)
* }
* ```
*/
watchInbox(
id: string,
callback: (reply?: MailboxEvent, err?: Error) => void,
): grpc.Request {
return watchMailbox(this, id, 'inbox', callback)
}
/**
* watchSentbox watches the sentbox for new mailbox events.
* Returns a listener of watch connectivity states.
* @returns listener. listener.close will stop watching.
* @param id the mailbox id
* @param callback handles each new mailbox event.
*
* @example
* The local user's own sentbox can be decrypted with their private key
*
* ```typescript
* import { Users, MailboxEvent, PrivateKey } from '@textile/hub'
*
* const userID = PrivateKey.fromRandom()
*
* const callback = async (reply?: MailboxEvent, err?: Error) => {
* if (!reply || !reply.message) return console.log('no message')
* const bodyBytes = await userID.decrypt(reply.message.body)
*
* const decoder = new TextDecoder()
* const body = decoder.decode(bodyBytes)
*
* console.log(body)
* }
*
* // Requires userID already be authenticated to the Users API
* async function startListener(users: Users) {
* const mailboxID = await users.getMailboxID()
* const closer = await users.watchInbox(mailboxID, callback)
* }
* ```
*/
watchSentbox(
id: string,
callback: (reply?: MailboxEvent, err?: Error) => void,
): grpc.Request {
return watchMailbox(this, id, 'sentbox', callback)
}
} | the_stack |
import path from 'path';
import handlebars from 'handlebars';
import glob from 'glob-to-regexp';
import chalk from 'chalk';
import terser from 'terser';
import get from 'lodash/get';
import codeFrameColumns from '@babel/code-frame';
import { OutputChunk, OutputOptions, rollup, RollupOptions } from 'rollup';
import rollupIgnoreImport from 'rollup-plugin-ignore-import';
import rollupPostCss from 'rollup-plugin-postcss';
import rollupReplace from 'rollup-plugin-re';
import rollupIgnore from 'rollup-plugin-ignore';
import rollupResolve from '@rollup/plugin-node-resolve';
import rollupCommonjs from '@rollup/plugin-commonjs';
import rollupJson, { RollupJsonOptions } from '@rollup/plugin-json';
import rollupTypescript from 'rollup-plugin-typescript2';
import rollupBabel from 'rollup-plugin-babel';
import rollupHandlebars from 'rollup-plugin-hbs';
import rollupImage from 'rollup-plugin-img';
import rollupFilesize from 'rollup-plugin-filesize';
import rollupGlobals from 'rollup-plugin-node-globals';
import { meta } from './meta';
import { PackageConfig } from '../model/package-config';
import { PackerConfig } from '../model/packer-config';
import logger, { Logger } from '../common/logger';
import { LogLevel } from '../model/log-level';
import { mergeDeep, readFile, requireDependency, writeFile } from './util';
import { PackageModuleType } from '../model/package-module-type';
import { BabelConfig } from '../model/babel-config';
import fileSize from 'filesize';
import cssnano from 'cssnano';
import * as TS from 'typescript';
/**
* Get distribution banner comment.
* @param packerConfig Packer configuration object.
* @param packageConfig Package configuration object.
*/
export const getBanner = async (packerConfig: PackerConfig, packageConfig: PackageConfig) => {
if (packerConfig.license.banner) {
const bannerTemplate = await meta.readBannerTemplate();
return handlebars.compile(bannerTemplate)({
config: packerConfig,
pkg: packageConfig
});
}
};
/**
* Get rollup base configuration.
* @param packerConfig Packer configuration object.
* @param packageConfig Package configuration object.
* @param banner Banner comment.
* @param sourceMap If true, a separate sourcemap file will be created. If inline, the sourcemap will be appended to
* the resulting output file as a data URI.
*/
export const getBaseConfig = (
packerConfig: PackerConfig,
packageConfig: PackageConfig,
banner: string,
sourceMap?: boolean | 'inline'
) => {
return {
input: path.join(packerConfig.source, packerConfig.entry),
output: {
banner,
name: packageConfig.name,
sourcemap: typeof sourceMap !== 'undefined' ? sourceMap : packerConfig.compiler.sourceMap
}
};
};
/**
* Get rollup style build plugins.
* @param packerConfig Packer configuration object.
* @param packageConfig Package configuration object.
* @param watch Copy stylesheets artifacts to watch temp directory if true, else dist directory.
* @param main Indicate whether it is the main build task to emit stylesheets. Otherwise, ignore style sheet building
* unless style inline mode is enabled.
* @param log Logger reference.
*/
export const getStyleBuildPlugins = (
packerConfig: PackerConfig,
packageConfig: PackageConfig,
watch: boolean,
main: boolean,
log: Logger
) => {
if (!packerConfig.compiler.style) {
log.trace('style build disabled');
return [];
}
if (!main && !packerConfig.compiler.style.inline) {
log.trace('ignore style imports to avoid redundant style compilation');
return [
rollupIgnoreImport(
mergeDeep(
{
exclude: 'node_modules/**',
extensions: ['.scss', '.sass', '.styl', '.css', '.less']
},
packerConfig.compiler.advanced.rollup.pluginOptions.ignoreImport
)
)
];
}
log.trace('init style build plugins');
const styleDir = watch ? path.join(packerConfig.tmp, 'watch') : packerConfig.dist;
const fileName = packageConfig.name + '.css';
const styleDist = path.join(process.cwd(), styleDir, packerConfig.compiler.style.outDir, fileName);
log.trace('stylesheet dist file name %s', styleDist);
return [
rollupPostCss(
mergeDeep(
{
exclude: 'node_modules/**',
extract: packerConfig.compiler.style.inline ? false : styleDist,
config: {
path: path.join(process.cwd(), 'postcss.config.js'),
ctx: {
config: packerConfig
}
},
// disable sourcemaps when inline bundling
sourceMap: packerConfig.compiler.style.inline ? false : packerConfig.compiler.sourceMap
},
packerConfig.compiler.advanced.rollup.pluginOptions.postCss
)
)
];
};
/**
* Generate minified style sheets.
* @param packerConfig Packer configuration object.
* @param packageConfig Package configuration object.
* @param log Logger reference.
*/
export const generateMinStyleSheet = async (
packerConfig: PackerConfig,
packageConfig: PackageConfig,
log: Logger
): Promise<void> => {
if (!packerConfig.compiler.style || packerConfig.compiler.style.inline) {
return;
}
const nano = requireDependency<typeof cssnano>('cssnano', log);
const srcPath = path.join(process.cwd(), packerConfig.dist, packerConfig.compiler.style.outDir);
const srcFileName = `${packageConfig.name}.css`;
const srcFilePath = path.join(srcPath, srcFileName);
const srcMinFileName = `${packageConfig.name}.min.css`;
const srcMinFilePath = path.join(srcPath, srcMinFileName);
const srcCss = await readFile(srcFilePath);
const options: any = {
from: srcFileName,
to: srcMinFileName
};
// only set cssnano sourcemap options when sourcemap is true
if (packerConfig.compiler.sourceMap === true) {
const srcMapFilePath = path.join(srcPath, `${packageConfig.name}.css.map`);
const srcMapCss = await readFile(srcMapFilePath);
options.map = {
sourcesContent: true,
prev: srcMapCss
};
}
let result;
log.trace('cssnano options:\n%o', options);
try {
result = await nano.process(String(srcCss), mergeDeep(options, packerConfig.compiler.advanced.other.cssnano));
} catch (e) {
log.error('style minify failure:\n%s', e.stack || e.message);
process.exit(1);
}
await writeFile(srcMinFilePath, result.css);
// save sourcemap file only when sourcemap true
if (packerConfig.compiler.sourceMap === true) {
const srcMinMapFilePath = path.join(srcPath, `${srcMinFileName}.map`);
await writeFile(srcMinMapFilePath, result.map);
}
};
/**
* Get rollup dependency resolve plugins.
* @param packerConfig Packer configuration object.
*/
export const getDependencyResolvePlugins = (packerConfig: PackerConfig) => {
const mainFields = [ 'module', 'jsnext', 'main' ];
if (packerConfig.compiler.buildMode) {
mainFields.push('browser');
}
const plugins = [
rollupIgnore(packerConfig.ignore),
rollupResolve(
mergeDeep(
{
mainFields,
extensions: ['.mjs', '.js', '.jsx', '.json', '.node'],
browser: packerConfig.compiler.buildMode === 'browser',
preferBuiltins: true
},
packerConfig.compiler.advanced.rollup.pluginOptions.nodeResolve
)
),
rollupCommonjs(
mergeDeep(
{
include: 'node_modules/**'
},
packerConfig.compiler.advanced.rollup.pluginOptions.commonjs
)
),
rollupJson(packerConfig.compiler.advanced.rollup.pluginOptions.json as RollupJsonOptions)
];
// include global and builtin plugins only when browser build mode is enabled
if (packerConfig.compiler.buildMode === 'browser') {
plugins.push(rollupGlobals(packerConfig.compiler.advanced.rollup.pluginOptions.globals));
}
return plugins;
};
/**
* Get script build rollup plugins.
* @param packageModule Package module type.
* @param generateDefinition Generate type definitions if true.
* @param check Set to false to avoid doing any diagnostic checks on the code.
* @param packerConfig Packer configuration object.
* @param babelConfig Babel configuration object.
* @param typescript Typescript compiler reference.
* @param log Logger reference.
*/
export const getScriptBuildPlugin = (
packageModule: PackageModuleType,
generateDefinition: boolean,
check: boolean,
packerConfig: PackerConfig,
babelConfig: BabelConfig,
typescript: typeof TS,
log: Logger
) => {
const plugins = [];
if (packerConfig.compiler.script.preprocessor === 'typescript') {
const buildConf: RollupPluginTypescriptOptions = {
check,
tsconfig: `tsconfig.json`,
typescript,
cacheRoot: path.join(process.cwd(), packerConfig.tmp, 'build', packageModule, '.rts2_cache'),
clean: true
};
if (generateDefinition) {
buildConf.tsconfigOverride = {
compilerOptions: {
declaration: true,
declarationDir: path.join(process.cwd(), packerConfig.dist, packerConfig.compiler.script.tsd)
}
};
buildConf.useTsconfigDeclarationDir = true;
}
plugins.push(
rollupTypescript(mergeDeep(buildConf, packerConfig.compiler.advanced.rollup.pluginOptions.typescript))
);
}
const moduleConfig = get(babelConfig, `env.${packageModule}`);
if (!moduleConfig) {
log.error('%s module configuration not found in .babelrc', packageModule);
process.exit(1);
}
plugins.push(
rollupBabel(
mergeDeep(
{
babelrc: false,
exclude: 'node_modules/**',
extensions: ['.js', '.jsx', '.es6', '.es', '.mjs', '.ts', '.tsx'],
plugins: moduleConfig.plugins || [],
presets: moduleConfig.presets || [],
runtimeHelpers: true
},
packerConfig.compiler.advanced.rollup.pluginOptions.babel
)
)
);
return plugins;
};
/**
* Get pre bundle rollup plugins.
* @param packerConfig Packer configuration object.
*/
export const getPreBundlePlugins = (packerConfig: PackerConfig) => {
const plugins = [];
if (packerConfig.replacePatterns.length) {
plugins.push(
rollupReplace(
mergeDeep(
{
exclude: 'node_modules/**',
patterns: packerConfig.replacePatterns
},
packerConfig.compiler.advanced.rollup.pluginOptions.replace
)
)
);
}
plugins.push(
rollupHandlebars(packerConfig.compiler.advanced.rollup.pluginOptions.handlebars),
rollupImage(
mergeDeep(
{
exclude: 'node_modules/**',
extensions: /\.(png|jpg|jpeg|gif|svg)$/,
limit: packerConfig.compiler.script.image.inlineLimit,
output: path.join(packerConfig.dist, packerConfig.compiler.script.image.outDir)
},
packerConfig.compiler.advanced.rollup.pluginOptions.image
)
)
);
return plugins;
};
/**
* Get post bundle rollup plugins.
* @param task Gulp task name.
* @param type Package module type.
* @param packerConfig Packer config object.
*/
export const getPostBundlePlugins = (packerConfig: PackerConfig, task: string, type: PackageModuleType) => {
if (logger.level <= LogLevel.INFO) {
return [
rollupFilesize(
mergeDeep(
{
showMinifiedSize: false,
showBrotliSize: false,
showGzippedSize: false,
render: (options: any, sourceBundle: any, { gzipSize, bundleSize }): string => {
const bundleFormatted = `bundle size: ${chalk.red(bundleSize)}`;
return chalk.yellow(`${logger.currentTime} ${chalk.green(task)} ${type} ${bundleFormatted}`);
}
},
packerConfig.compiler.advanced.rollup.pluginOptions.filesize
)
)
];
}
return [];
};
/**
* Get custom rollup plugins included via packer config.
* @param packerConfig Packer configuration object.
* @param type Package module type.
*/
export const customRollupPlugins = (packerConfig: PackerConfig, type: PackageModuleType): any[] => {
if (packerConfig.compiler.customRollupPluginExtractor) {
return packerConfig.compiler.customRollupPluginExtractor(type, packerConfig);
}
return [];
};
/**
* Generate bundled artifacts via rollup.
* @param packerConfig Packer configuration object.
* @param packageConfig Package configuration object.
* @param bundleConfig Rollup bundle configuration object.
* @param type Package module type.
* @param minify Generate minified bundle artifact if true.
* @param trackBuildPerformance Track rollup build performance.
* @param log Logger reference.
*/
export const generateBundle = async (
packerConfig: PackerConfig,
packageConfig: PackageConfig,
bundleConfig: RollupOptions,
type: PackageModuleType,
minify: boolean,
trackBuildPerformance: boolean,
log: Logger
): Promise<void> => {
log.trace('%s bundle build start', type);
const bundle = await rollup(mergeDeep(bundleConfig, packerConfig.compiler.advanced.rollup.inputOptions));
const outputOptions = mergeDeep(bundleConfig.output as OutputOptions,
packerConfig.compiler.advanced.rollup.outputOptions);
const { output } = await bundle.write(outputOptions);
const chunks: OutputChunk[] = output.filter((chunk: any) => !chunk.isAsset) as OutputChunk[];
const { map, code } = chunks[0];
log.trace('%s bundle build end', type);
if (trackBuildPerformance) {
// Performance stats should be available on any log level
const messageBase = `${logger.currentTime} ${chalk.green(type)}`;
console.log(chalk.blue('%s bundle performance statistics:\n%o'), messageBase, bundle.getTimings());
}
if (minify) {
log.trace('%s minified bundle build start', type);
const minFileDist = (bundleConfig.output as OutputOptions).file.replace('.js', '.min.js');
const minMapFileDist = minFileDist.concat('.map');
const minFileName = path.basename(minFileDist);
const minMapFileName = minFileName.concat('.map');
let minSourceMapConfig: any = {
content: map,
filename: minFileName
};
if (packerConfig.compiler.sourceMap === 'inline') {
minSourceMapConfig.url = 'inline';
} else if (packerConfig.compiler.sourceMap) {
minSourceMapConfig.url = minMapFileName;
} else {
minSourceMapConfig = undefined;
}
const minData = terser.minify(
code,
mergeDeep(
{
sourceMap: minSourceMapConfig,
output: {
comments: /@preserve|@license|@cc_on/i
}
},
packerConfig.compiler.advanced.other.terser
)
);
log.trace('%s minified bundle terser config\n%o', type, minData);
if (minData.error) {
const { message, line, col: column } = minData.error;
log.error(
'%s bundle min build failure \n%s',
type,
codeFrameColumns(code, { start: { line, column } }, { message })
);
process.exit(1);
} else {
await writeFile(minFileDist, minData.code);
if (minSourceMapConfig && minSourceMapConfig.url === minMapFileName) {
log.trace('%s minified bundle write source maps', type);
await writeFile(minMapFileDist, minData.map);
}
if (logger.level <= LogLevel.INFO) {
const formatOptions = packerConfig.compiler.advanced.rollup.pluginOptions.filesize.format;
const size = fileSize(Buffer.byteLength(minData.code), mergeDeep({
base: 10
}, formatOptions));
const minType = `${type} minified size:`;
log.info(chalk.yellow(minType), chalk.red(size));
}
}
log.trace('%s minified bundle build end', type);
}
};
/**
* Get external dependency filter function.
* @param packerConfig Packer config object.
*/
export const getExternalFilter = (packerConfig: PackerConfig) => {
const filter = packerConfig.bundle.externals.map((external) => glob(external));
return (id: string) => {
return filter.some((include) => include.test(id));
};
};
/**
* Extract bundle external.
* @param packerConfig Packer config object.
*/
export const extractBundleExternals = (packerConfig: PackerConfig) => {
// Map externals from globals if mapExternals is true.
return packerConfig.bundle.mapExternals ? Object.keys(packerConfig.bundle.globals) : getExternalFilter(packerConfig);
}; | the_stack |
import React from 'react'
import { store } from '../../../store'
import { StoreContext } from 'storeon/react'
import { object, withKnobs, select, boolean, text } from '@storybook/addon-knobs'
import { withInfo } from '@storybook/addon-info'
import uiManagmentApi from '../../../api/uiManagment/uiManagmentApi'
import stylesApi from '../../../api/styles/stylesApi'
// import { darkTheme, lightTheme } from '../../../configs/styles'
// import { ru, en } from '../../../configs/languages'
import languagesApi from '../../../api/languages/languagesApi'
// import { settings } from '../../../configs/settings'
import settingsApi from '../../../api/settings/settingsApi'
import Sender from '../Sender'
import info from './SenderInfo.md'
import { iconsList } from '../../../configs/icons'
import '../../../styles/storyBookContainer.css'
export default {
title: 'Sender',
decorators: [withKnobs, withInfo],
parameters: {
info: {
text: info,
source: false,
propTables: false,
},
},
}
const groupUIManagment = 'UIManagment'
const groupStyles = 'Styles'
const groupLanguages = 'Languages'
const groupSettings = 'Settings'
// const storyDarkStyles = {
// mainContainer: {
// display: 'flex',
// backgroundColor: '#373737',
// padding: '8px',
// borderRadius: '10px',
// justifyContent: 'space-between',
// width: '100%',
// height: '10%',
// alignItems: 'center',
// },
// addFileButton: {
// border: 'none',
// display: 'flex',
// width: '13%',
// backgroundColor: '#373737',
// outline: 'none',
// color: 'white',
// fontSize: '12px',
// },
// form: {
// backgroundColor: '#575757',
// display: 'flex',
// justifyContent: 'space-around',
// width: '50%',
// height: '70%',
// borderRadius: '10px',
// },
// sendMessageButton: {
// backgroundColor: '#575757',
// border: 'none',
// display: 'flex',
// flexDirection: 'row-reverse',
// width: '13%',
// justifyContent: 'space-around',
// outline: 'none',
// color: '#9b9b9b',
// fontSize: '12px',
// },
// shareButton: {
// border: 'none',
// display: 'flex',
// width: '15%',
// justifyContent: 'space-between',
// backgroundColor: '#373737',
// outline: 'none',
// color: 'white',
// fontSize: '12px',
// },
// stickersButton: {
// border: 'none',
// width: '13%',
// display: 'flex',
// justifyContent: 'space-between',
// backgroundColor: '#373737',
// outline: 'none',
// color: 'white',
// fontSize: '12px',
// },
// textArea: {
// resize: 'none',
// border: 'none',
// outline: 'none',
// paddingTop: '5px',
// fontSize: '12px',
// width: '40%',
// backgroundColor: '#575757',
// color: 'white',
// },
// voiceButton: {
// border: 'none',
// width: '13%',
// display: 'flex',
// justifyContent: 'space-between',
// backgroundColor: '#373737',
// outline: 'none',
// color: 'white',
// fontSize: '12px',
// },
// }
// const storyLightStyles = {
// mainContainer: {
// display: 'flex',
// backgroundColor: '#4a76a8',
// padding: '8px',
// borderRadius: '10px',
// justifyContent: 'space-between',
// width: '100%',
// height: '10%',
// alignItems: 'center',
// },
// addFileButton: {
// border: 'none',
// display: 'flex',
// width: '13%',
// backgroundColor: '#4a76a8',
// outline: 'none',
// color: 'white',
// fontSize: '12px',
// },
// form: {
// backgroundColor: 'white',
// display: 'flex',
// justifyContent: 'space-around',
// width: '50%',
// height: '70%',
// borderRadius: '10px',
// },
// sendMessageButton: {
// backgroundColor: 'white',
// border: 'none',
// display: 'flex',
// flexDirection: 'row-reverse',
// width: '13%',
// justifyContent: 'space-around',
// outline: 'none',
// color: '#4a76a8',
// fontSize: '12px',
// },
// shareButton: {
// border: 'none',
// display: 'flex',
// width: '15%',
// justifyContent: 'space-between',
// backgroundColor: '#4a76a8',
// outline: 'none',
// color: 'white',
// fontSize: '12px',
// },
// stickersButton: {
// border: 'none',
// width: '13%',
// display: 'flex',
// justifyContent: 'space-between',
// backgroundColor: '#4a76a8',
// outline: 'none',
// color: 'white',
// fontSize: '12px',
// },
// textArea: {
// resize: 'none',
// border: 'none',
// outline: 'none',
// paddingTop: '5px',
// fontSize: '12px',
// width: '40%',
// backgroundColor: 'white',
// color: '#373737',
// },
// voiceButton: {
// border: 'none',
// width: '13%',
// display: 'flex',
// justifyContent: 'space-between',
// backgroundColor: '#4a76a8',
// outline: 'none',
// color: 'white',
// fontSize: '12px',
// },
// }
// stylesApi.styles('changeSender', { themeName: 'darkTheme', data: storyDarkStyles })
// stylesApi.styles('changeSender', { themeName: 'lightTheme', data: storyLightStyles })
// export const SenderComponent = () => {
// const addFileIcon = object('addFileIcon', settings.media.icons.addFileIcon, groupSettings)
// settingsApi.settings('changeIcon', { iconName: 'addFileIcon', iconData: addFileIcon })
// const addStickersIcon = object('addStickersIcon', settings.media.icons.addStickersIcon, groupSettings)
// settingsApi.settings('changeIcon', { iconName: 'addStickersIcon', iconData: addStickersIcon })
// const audioMessageIcon = object('audioMessageIcon', settings.media.icons.voiceIcon, groupSettings)
// settingsApi.settings('changeIcon', { iconName: 'voiceIcon', iconData: audioMessageIcon })
// const sendIcon = object('sendIcon', settings.media.icons.sendMessageIcon, groupSettings)
// settingsApi.settings('changeIcon', { iconName: 'sendMessageIcon', iconData: sendIcon })
// const shareIcon = object('shareIcon', settings.media.icons.shareIcon, groupSettings)
// settingsApi.settings('changeIcon', { iconName: 'shareIcon', iconData: shareIcon })
// const addFileButton = object('addFilerButton', uiManagmentSender.addFile, groupUIManagment)
// const addStickersButton = object('addStickersButton', uiManagmentSender.addStickers, groupUIManagment)
// const audioMessageButton = object('audioMessageButton', uiManagmentSender.audioMessage, groupUIManagment)
// const sendButton = object('sendButton', uiManagmentSender.send, groupUIManagment)
// const shareButton = object('shareButton', uiManagmentSender.share, groupUIManagment)
// const blockInput = boolean('blockInput', uiManagmentSender.blockInput, groupUIManagment)
// const blockSubmit = boolean('blockSubmit', uiManagmentSender.blockSubmit, groupUIManagment)
// uiManagmentApi.uiManagment('setUpSender', {
// addFile: addFileButton,
// addStickers: addStickersButton,
// audioMessage: audioMessageButton,
// send: sendButton,
// share: shareButton,
// blockInput: blockInput,
// blockSubmit: blockSubmit,
// })
// const activeLanguage = select('active', { en: 'en', ru: 'ru' }, 'en', groupLanguages)
// languagesApi.languages('changeLanguage', activeLanguage)
// const russian = object('Russian', ru.packet.Sender, groupLanguages)
// languagesApi.languages('changeDialog', { language: 'ru', data: russian })
// const english = object('English', en.packet.Sender, groupLanguages)
// languagesApi.languages('changeSender', { language: 'en', data: english })
// const activeTheme = select('active', { darkTheme: 'darkTheme', lightTheme: 'lightTheme' }, 'darkTheme', groupStyles)
// stylesApi.styles('switchTheme', activeTheme)
// const stylesDarkTheme = object('darkTheme', darkTheme.data.Sender, groupStyles)
// stylesApi.styles('changeSender', { themeName: 'darkTheme', data: stylesDarkTheme })
// const stylesLightTheme = object('lightTheme', lightTheme.data.Sender, groupStyles)
// stylesApi.styles('changeSender', { themeName: 'lightTheme', data: stylesLightTheme })
// return (
// <StoreContext.Provider value={store}>
// <Sender />
// </StoreContext.Provider>
// )
// }
const languagePacket = {
placeholder: (language: string, title: string) => text(`${language}/placeholder`, title, groupLanguages),
sendButtonTitle: (language: string, title: string) => text(`${language}/sendButtonTitle`, title, groupLanguages),
fileButtonTitle: (language: string, title: string) => text(`${language}/fileButtonTitle`, title, groupLanguages),
stickerButtonTitle: (language: string, title: string) =>
text(`${language}/stickerButtonTitle`, title, groupLanguages),
shareButtonTitle: (language: string, title: string) => text(`${language}/shareButtonTitle`, title, groupLanguages),
voiceButtonTitle: (language: string, title: string) => text(`${language}/voiceButtonTitle`, title, groupLanguages),
}
const stylesPacket = {
mainContainer: (themeName: string, data: any) => object(`${themeName}/mainContainer`, data, groupStyles),
form: (themeName: string, data: any) => object(`${themeName}/form`, data, groupStyles),
shareButton: (themeName: string, data: any) => object(`${themeName}/shareButton`, data, groupStyles),
stickersButton: (themeName: string, data: any) => object(`${themeName}/stickersButton`, data, groupStyles),
voiceButton: (themeName: string, data: any) => object(`${themeName}/voiceButton`, data, groupStyles),
addFileButton: (themeName: string, data: any) => object(`${themeName}/addFileButton`, data, groupStyles),
textArea: (themeName: string, data: any) => object(`${themeName}/textArea`, data, groupStyles),
sendMessageButton: (themeName: string, data: any) => object(`${themeName}/sendMessageButton`, data, groupStyles),
}
export const SenderComponent = () => {
//settings start
const addFileIcon = select('addFileIcon', iconsList, 'fas plus', groupSettings)
settingsApi.settings('changeIcon', { iconName: 'addFileIcon', iconData: { icon: addFileIcon.split(' ') } })
const addStickersIcon = select('addStickersIcon', iconsList, 'fas sticky-note', groupSettings)
settingsApi.settings('changeIcon', { iconName: 'addStickersIcon', iconData: { icon: addStickersIcon.split(' ') } })
const audioMessageIcon = select('audioMessageIcon', iconsList, 'fas microphone', groupSettings)
settingsApi.settings('changeIcon', { iconName: 'voiceIcon', iconData: { icon: audioMessageIcon.split(' ') } })
const sendIcon = select('sendIcon', iconsList, 'fas arrow-up', groupSettings)
settingsApi.settings('changeIcon', { iconName: 'sendMessageIcon', iconData: { icon: sendIcon.split(' ') } })
const shareIcon = select('shareIcon', iconsList, 'fas share-alt', groupSettings)
settingsApi.settings('changeIcon', { iconName: 'shareIcon', iconData: { icon: shareIcon.split(' ') } })
// settings end
//ui managment start
const uiManagmentSender = store.get().managment.getIn(['components', 'Sender'])
const addFileButton = boolean('addFileButton enabled', uiManagmentSender.addFile.enabled, groupUIManagment)
const titleAddFile = boolean('show addFileTitle', uiManagmentSender.addFile.withTitle, groupUIManagment)
const iconAddFile = boolean('show addFileIcon', uiManagmentSender.addFile.withIcon, groupUIManagment)
const addStickersButton = boolean(
'addStickersButton enabled',
uiManagmentSender.addStickers.enabled,
groupUIManagment
)
const titleAddStickers = boolean('show addStickersTitle', uiManagmentSender.addStickers.withTitle, groupUIManagment)
const iconAddStickers = boolean('show addStickersIcon', uiManagmentSender.addStickers.withIcon, groupUIManagment)
const audioMessageButton = boolean(
'audioMessageButton enabled',
uiManagmentSender.audioMessage.enabled,
groupUIManagment
)
const titleAudioMessage = boolean(
'show audioMessageTitle',
uiManagmentSender.audioMessage.withTitle,
groupUIManagment
)
const iconAudioMessage = boolean('show audioMessageIcon', uiManagmentSender.audioMessage.withIcon, groupUIManagment)
const sendButton = boolean('sendButton enabled', uiManagmentSender.send.enabled, groupUIManagment)
const titleSend = boolean('show sendTitle', uiManagmentSender.send.withTitle, groupUIManagment)
const iconSend = boolean('show sendIcon', uiManagmentSender.send.withIcon, groupUIManagment)
const shareButton = boolean('shareButton enabled', uiManagmentSender.share.enabled, groupUIManagment)
const titleShare = boolean('show shareTitle', uiManagmentSender.share.withTitle, groupUIManagment)
const iconShare = boolean('show shareIcon', uiManagmentSender.share.withIcon, groupUIManagment)
const blockInput = boolean('blockInput', uiManagmentSender.blockInput, groupUIManagment)
const blockSubmit = boolean('blockSubmit', uiManagmentSender.blockSubmit, groupUIManagment)
uiManagmentApi.uiManagment('setUpSender', {
share: { enabled: shareButton, withTitle: titleShare, withIcon: iconShare },
send: { enabled: sendButton, withTitle: titleSend, withIcon: iconSend },
audioMessage: { enabled: audioMessageButton, withTitle: titleAudioMessage, withIcon: iconAudioMessage },
addStickers: { enabled: addStickersButton, withTitle: titleAddStickers, withIcon: iconAddStickers },
addFile: { enabled: addFileButton, withTitle: titleAddFile, withIcon: iconAddFile },
blockInput,
blockSubmit,
})
// ui managment end
// languages start
const language = select('language', { en: 'en', ru: 'ru' }, 'en', groupLanguages)
languagesApi.languages('changeLanguage', language)
const activeLanguagePacket = store.get().languages.getIn(['stack', language, 'Sender'])
const fileButtonTitle = languagePacket.fileButtonTitle(language, activeLanguagePacket.fileButtonTitle)
const placeholder = languagePacket.placeholder(language, activeLanguagePacket.placeholder)
const sendButtonTitle = languagePacket.sendButtonTitle(language, activeLanguagePacket.sendButtonTitle)
const shareButtonTitle = languagePacket.shareButtonTitle(language, activeLanguagePacket.shareButtonTitle)
const stickerButtonTitle = languagePacket.stickerButtonTitle(language, activeLanguagePacket.stickerButtonTitle)
const voiceButtonTitle = languagePacket.voiceButtonTitle(language, activeLanguagePacket.voiceButtonTitle)
languagesApi.languages('changeSender', {
language: language,
data: { fileButtonTitle, placeholder, sendButtonTitle, shareButtonTitle, stickerButtonTitle, voiceButtonTitle },
})
// languages end
//styles start
const themeName = select(
'theme',
{ sovaDark: 'sovaDark', sovaLight: 'sovaLight', sovaGray: 'sovaGray' },
'sovaLight',
groupStyles
)
stylesApi.styles('switchTheme', themeName)
const activeThemePacket = store.get().styles.getIn(['stack', themeName, 'Sender'])
const mainContainer = stylesPacket.mainContainer(themeName, activeThemePacket.mainContainer)
const addFile = stylesPacket.addFileButton(themeName, activeThemePacket.addFileButton)
const form = stylesPacket.form(themeName, activeThemePacket.form)
const sendMessageButton = stylesPacket.sendMessageButton(themeName, activeThemePacket.sendMessageButton)
const share = stylesPacket.shareButton(themeName, activeThemePacket.shareButton)
const stickersButton = stylesPacket.stickersButton(themeName, activeThemePacket.stickersButton)
const textArea = stylesPacket.textArea(themeName, activeThemePacket.textArea)
const voiceButton = stylesPacket.voiceButton(themeName, activeThemePacket.voiceButton)
stylesApi.styles('changeSender', {
themeName: themeName,
data: {
mainContainer,
voiceButton,
addFileButton: addFile,
shareButton: share,
textArea,
stickersButton,
form,
sendMessageButton,
},
})
//styles end
return (
<StoreContext.Provider value={store}>
<div className="sova-ck-main">
<div className="sova-ck-chat">
<Sender />
</div>
</div>
</StoreContext.Provider>
)
} | the_stack |
import { readFileSync } from '../helpers/file-helper';
import { BpmnElement, BpmnVisualization, FlowKind, OverlayEdgePosition, OverlayShapePosition, ShapeBpmnElementKind } from '../../src/bpmn-visualization';
import { expectSvgEvent, expectSvgPool, expectSvgSequenceFlow, expectSvgTask, HtmlElementLookup } from './helpers/html-utils';
import { ExpectedBaseBpmnElement, expectEndEvent, expectPool, expectSequenceFlow, expectServiceTask, expectStartEvent, expectTask } from '../unit/helpers/bpmn-semantic-utils';
import { overlayEdgePositionValues, overlayShapePositionValues } from '../helpers/overlays';
const bpmnVisualization = initializeBpmnVisualization();
// use container id
function initializeBpmnVisualization(): BpmnVisualization {
const bpmnContainerId = 'bpmn-visualization-container';
// insert bpmn container
const containerDiv = document.createElement('div');
containerDiv.id = bpmnContainerId;
document.body.insertBefore(containerDiv, document.body.firstChild);
// initialize bpmn-visualization
return new BpmnVisualization({ container: bpmnContainerId });
}
function initializeBpmnVisualizationWithHtmlElement(): BpmnVisualization {
// insert bpmn container
const containerDiv = document.createElement('div');
containerDiv.id = 'bpmn-visualization-container-alternative';
document.body.insertBefore(containerDiv, document.body.firstChild);
// initialize bpmn-visualization
return new BpmnVisualization({ container: containerDiv });
}
describe.each`
bv | type
${bpmnVisualization} | ${'html id'}
${initializeBpmnVisualizationWithHtmlElement()} | ${'html element'}
`('Resulting DOM after diagram load - container set with "$type"', ({ bv }) => {
it('DOM should contains BPMN elements when loading simple-start-task-end.bpmn', async () => {
bv.load(readFileSync('../fixtures/bpmn/simple-start-task-end.bpmn'));
const htmlElementLookup = new HtmlElementLookup(bv);
htmlElementLookup.expectStartEvent('StartEvent_1');
htmlElementLookup.expectTask('Activity_1');
htmlElementLookup.expectEndEvent('EndEvent_1');
});
it('DOM should contains BPMN elements when loading model-complete-semantic.bpmn', async () => {
bv.load(readFileSync('../fixtures/bpmn/model-complete-semantic.bpmn'));
const htmlElementLookup = new HtmlElementLookup(bv);
htmlElementLookup.expectPool('participant_1_id');
htmlElementLookup.expectLane('lane_4_1_id');
htmlElementLookup.expectStartEvent('start_event_signal_id');
htmlElementLookup.expectIntermediateThrowEvent('intermediate_throw_event_message_id');
});
});
function expectStartEventBpmnElement(bpmnElement: BpmnElement, expected: ExpectedBaseBpmnElement): void {
expectStartEvent(bpmnElement.bpmnSemantic, expected);
expectSvgEvent(bpmnElement.htmlElement);
}
function expectEndEventBpmnElement(bpmnElement: BpmnElement, expected: ExpectedBaseBpmnElement): void {
expectEndEvent(bpmnElement.bpmnSemantic, expected);
expectSvgEvent(bpmnElement.htmlElement);
}
function expectSequenceFlowBpmnElement(bpmnElement: BpmnElement, expected: ExpectedBaseBpmnElement): void {
expectSequenceFlow(bpmnElement.bpmnSemantic, expected);
expectSvgSequenceFlow(bpmnElement.htmlElement);
}
function expectTaskBpmnElement(bpmnElement: BpmnElement, expected: ExpectedBaseBpmnElement): void {
expectTask(bpmnElement.bpmnSemantic, expected);
expectSvgTask(bpmnElement.htmlElement);
}
function expectServiceTaskBpmnElement(bpmnElement: BpmnElement, expected: ExpectedBaseBpmnElement): void {
expectServiceTask(bpmnElement.bpmnSemantic, expected);
expectSvgTask(bpmnElement.htmlElement);
}
function expectPoolBpmnElement(bpmnElement: BpmnElement, expected: ExpectedBaseBpmnElement): void {
expectPool(bpmnElement.bpmnSemantic, expected);
expectSvgPool(bpmnElement.htmlElement);
}
describe('Bpmn Elements registry - retrieve BPMN elements', () => {
describe('Get by ids', () => {
it('Pass several existing ids', async () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/simple-start-task-end.bpmn'));
const bpmnElements = bpmnVisualization.bpmnElementsRegistry.getElementsByIds(['StartEvent_1', 'Flow_2']);
expect(bpmnElements).toHaveLength(2);
expectStartEventBpmnElement(bpmnElements[0], { id: 'StartEvent_1', name: 'Start Event 1' });
expectSequenceFlowBpmnElement(bpmnElements[1], { id: 'Flow_2' });
});
it('Pass a single non existing id', async () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/simple-start-task-end.bpmn'));
const bpmnElements = bpmnVisualization.bpmnElementsRegistry.getElementsByIds('unknown');
expect(bpmnElements).toHaveLength(0);
});
it('Pass existing and non existing ids', async () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/simple-start-task-end.bpmn'));
const bpmnElements = bpmnVisualization.bpmnElementsRegistry.getElementsByIds(['StartEvent_1', 'unknown', 'Flow_1', 'another_unknown']);
expect(bpmnElements).toHaveLength(2);
});
});
describe('Get by kinds', () => {
it('Pass a single kind related to a single existing element', async () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/simple-start-task-end.bpmn'));
const bpmnElements = bpmnVisualization.bpmnElementsRegistry.getElementsByKinds(ShapeBpmnElementKind.TASK);
expect(bpmnElements).toHaveLength(1);
expectTaskBpmnElement(bpmnElements[0], { id: 'Activity_1', name: 'Task 1' });
});
it('Pass a single kind related to several existing elements', async () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/simple-start-task-end.bpmn'));
const bpmnElements = bpmnVisualization.bpmnElementsRegistry.getElementsByKinds(FlowKind.SEQUENCE_FLOW);
expect(bpmnElements).toHaveLength(2);
expectSequenceFlowBpmnElement(bpmnElements[0], { id: 'Flow_1', name: 'Sequence Flow 1' });
expectSequenceFlowBpmnElement(bpmnElements[1], { id: 'Flow_2' });
});
it('No elements for this kind', async () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/simple-start-task-end.bpmn'));
const bpmnElements = bpmnVisualization.bpmnElementsRegistry.getElementsByKinds(ShapeBpmnElementKind.SUB_PROCESS);
expect(bpmnElements).toHaveLength(0);
});
it('Pass a several kinds that all match existing elements', async () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/registry/1-pool-3-lanes-message-start-end-intermediate-events.bpmn'));
const bpmnElements = bpmnVisualization.bpmnElementsRegistry.getElementsByKinds([ShapeBpmnElementKind.EVENT_END, ShapeBpmnElementKind.POOL]);
expect(bpmnElements).toHaveLength(3);
expectEndEventBpmnElement(bpmnElements[0], { id: 'endEvent_terminate_1', name: 'terminate end 1' });
expectEndEventBpmnElement(bpmnElements[1], { id: 'endEvent_message_1', name: 'message end 2' });
expectPoolBpmnElement(bpmnElements[2], { id: 'Participant_1', name: 'Pool 1' });
});
it('Pass a several kinds that match existing and non-existing elements', async () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/registry/1-pool-3-lanes-message-start-end-intermediate-events.bpmn'));
const bpmnElements = bpmnVisualization.bpmnElementsRegistry.getElementsByKinds([ShapeBpmnElementKind.CALL_ACTIVITY, ShapeBpmnElementKind.TASK_SERVICE]);
expect(bpmnElements).toHaveLength(2);
expectServiceTaskBpmnElement(bpmnElements[0], { id: 'serviceTask_1_2', name: 'Service Task 1.2' });
expectServiceTaskBpmnElement(bpmnElements[1], { id: 'serviceTask_2_1', name: 'Service Task 2.1' });
});
});
});
describe('Bpmn Elements registry - CSS class management', () => {
describe('Add classes', () => {
it('Add one or several classes to one or several BPMN elements', () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/registry/1-pool-3-lanes-message-start-end-intermediate-events.bpmn'));
const htmlElementLookup = new HtmlElementLookup(bpmnVisualization);
// default classes
htmlElementLookup.expectServiceTask('serviceTask_1_2');
htmlElementLookup.expectEndEvent('endEvent_message_1');
// add a single class to a single element
bpmnVisualization.bpmnElementsRegistry.addCssClasses('serviceTask_1_2', 'class1');
htmlElementLookup.expectServiceTask('serviceTask_1_2', { additionalClasses: ['class1'] });
// add several classes to several elements
bpmnVisualization.bpmnElementsRegistry.addCssClasses(['endEvent_message_1', 'serviceTask_1_2'], ['class2', 'class3']);
htmlElementLookup.expectServiceTask('serviceTask_1_2', { additionalClasses: ['class1', 'class2', 'class3'] });
htmlElementLookup.expectEndEvent('endEvent_message_1', ['class2', 'class3']);
});
it('BPMN element does not exist', () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/simple-start-task-end.bpmn'));
const htmlElementLookup = new HtmlElementLookup(bpmnVisualization);
const nonExistingBpmnId = 'i-do-not-exist-for-add';
htmlElementLookup.expectNoElement(nonExistingBpmnId);
// this call ensures that there is not issue on the rendering part
bpmnVisualization.bpmnElementsRegistry.addCssClasses(nonExistingBpmnId, 'class1');
});
});
describe('Remove classes', () => {
it('Remove one or several classes to one or several BPMN elements', () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/registry/1-pool-3-lanes-message-start-end-intermediate-events.bpmn'));
const htmlElementLookup = new HtmlElementLookup(bpmnVisualization);
// default classes
htmlElementLookup.expectUserTask('userTask_0');
htmlElementLookup.expectLane('lane_01');
// remove a single class from a single element
bpmnVisualization.bpmnElementsRegistry.addCssClasses('userTask_0', 'class1');
htmlElementLookup.expectUserTask('userTask_0', ['class1']);
bpmnVisualization.bpmnElementsRegistry.removeCssClasses('userTask_0', 'class1');
htmlElementLookup.expectUserTask('userTask_0');
// remove several classes from several elements
bpmnVisualization.bpmnElementsRegistry.addCssClasses(['lane_01', 'userTask_0'], ['class1', 'class2', 'class3']);
bpmnVisualization.bpmnElementsRegistry.removeCssClasses(['lane_01', 'userTask_0'], ['class1', 'class3']);
htmlElementLookup.expectLane('lane_01', ['class2']);
htmlElementLookup.expectUserTask('userTask_0', ['class2']);
});
it('BPMN element does not exist', () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/simple-start-task-end.bpmn'));
const htmlElementLookup = new HtmlElementLookup(bpmnVisualization);
const nonExistingBpmnId = 'i-do-not-exist-for-removal';
htmlElementLookup.expectNoElement(nonExistingBpmnId);
// this call ensures that there is not issue on the rendering part
bpmnVisualization.bpmnElementsRegistry.removeCssClasses(nonExistingBpmnId, 'class1');
});
});
describe('Toggle classes', () => {
it('Toggle one or several classes to one or several BPMN elements', () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/registry/1-pool-3-lanes-message-start-end-intermediate-events.bpmn'));
const htmlElementLookup = new HtmlElementLookup(bpmnVisualization);
// toggle a classes for a single element
bpmnVisualization.bpmnElementsRegistry.toggleCssClasses('gateway_01', 'class1');
bpmnVisualization.bpmnElementsRegistry.toggleCssClasses('gateway_01', ['class1', 'class2']);
htmlElementLookup.expectExclusiveGateway('gateway_01', { additionalClasses: ['class2'] });
// toggle a classes for several elements
bpmnVisualization.bpmnElementsRegistry.toggleCssClasses(['lane_02', 'gateway_01'], ['class1', 'class2', 'class3']);
bpmnVisualization.bpmnElementsRegistry.toggleCssClasses(['lane_02', 'gateway_01'], ['class1', 'class3', 'class4']);
htmlElementLookup.expectLane('lane_02', ['class2', 'class4']);
htmlElementLookup.expectExclusiveGateway('gateway_01', { additionalClasses: ['class4'] });
});
it('BPMN element does not exist', () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/simple-start-task-end.bpmn'));
const htmlElementLookup = new HtmlElementLookup(bpmnVisualization);
const nonExistingBpmnId = 'i-do-not-exist-for-toggle';
htmlElementLookup.expectNoElement(nonExistingBpmnId);
// this call ensures that there is not issue on the rendering part
bpmnVisualization.bpmnElementsRegistry.toggleCssClasses(nonExistingBpmnId, 'class1');
});
});
});
describe('Bpmn Elements registry - Overlay management', () => {
describe('BPMN Shape', () => {
it('Add one overlay to a BPMN shape', () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/registry/1-pool-3-lanes-message-start-end-intermediate-events.bpmn'));
const htmlElementLookup = new HtmlElementLookup(bpmnVisualization);
htmlElementLookup.expectServiceTask('serviceTask_1_2');
// add a single overlay
const overlayLabel = '123';
bpmnVisualization.bpmnElementsRegistry.addOverlays('serviceTask_1_2', { label: overlayLabel, position: 'top-left' });
htmlElementLookup.expectServiceTask('serviceTask_1_2', { overlayLabel });
});
it.each(overlayShapePositionValues)("Ensure no issue when adding one overlay at position '%s' to a BPMN Shape", (position: OverlayShapePosition) => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/overlays/overlays.start.flow.task.gateway.bpmn'));
const htmlElementLookup = new HtmlElementLookup(bpmnVisualization);
htmlElementLookup.expectExclusiveGateway('Gateway_1');
bpmnVisualization.bpmnElementsRegistry.addOverlays('Gateway_1', { label: 'Yes', position: position });
htmlElementLookup.expectExclusiveGateway('Gateway_1', { overlayLabel: 'Yes' });
});
it('Remove all overlays from a BPMN shape', () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/registry/1-pool-3-lanes-message-start-end-intermediate-events.bpmn'));
const htmlElementLookup = new HtmlElementLookup(bpmnVisualization);
htmlElementLookup.expectServiceTask('serviceTask_1_2');
// remove all overlays
bpmnVisualization.bpmnElementsRegistry.addOverlays('serviceTask_1_2', { label: '8789', position: 'top-left' });
bpmnVisualization.bpmnElementsRegistry.removeAllOverlays('serviceTask_1_2');
htmlElementLookup.expectServiceTask('serviceTask_1_2');
});
});
describe('BPMN Edge', () => {
it.each(overlayEdgePositionValues)("Ensure no issue when adding one overlay at position '%s' to a BPMN Edge without waypoints", (position: OverlayEdgePosition) => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/overlays/overlays.start.flow.task.gateway.no.waypoints.bpmn'));
const htmlElementLookup = new HtmlElementLookup(bpmnVisualization);
htmlElementLookup.expectSequenceFlow('Flow_1');
bpmnVisualization.bpmnElementsRegistry.addOverlays('Flow_1', { label: 'important', position: position });
htmlElementLookup.expectSequenceFlow('Flow_1', { overlayLabel: 'important' });
});
it.each(overlayEdgePositionValues)("Ensure no issue when adding one overlay at position '%s' to a BPMN Edge with waypoints", (position: OverlayEdgePosition) => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/overlays/overlays.edges.associations.complex.paths.bpmn'));
const htmlElementLookup = new HtmlElementLookup(bpmnVisualization);
htmlElementLookup.expectAssociation('Association_3_waypoints');
bpmnVisualization.bpmnElementsRegistry.addOverlays('Association_3_waypoints', { label: 'warning', position: position });
htmlElementLookup.expectAssociation('Association_3_waypoints', { overlayLabel: 'warning' });
});
});
}); | the_stack |
import * as vscode from 'vscode';
import { IHistoryFileProperties, HistoryController } from './history.controller';
import { IHistorySettings, HistorySettings } from './history.settings';
// import path = require('path');
const enum EHistoryTreeItem {
None = 0,
Group,
File
}
const enum EHistoryTreeContentKind {
Current = 0,
All,
Search
}
export default class HistoryTreeProvider implements vscode.TreeDataProvider<HistoryItem> {
/* tslint:disable */
private _onDidChangeTreeData: vscode.EventEmitter<HistoryItem | undefined> = new vscode.EventEmitter<HistoryItem | undefined>();
readonly onDidChangeTreeData: vscode.Event<HistoryItem | undefined> = this._onDidChangeTreeData.event;
/* tslint:enable*/
private currentHistoryFile: string;
private currentHistoryPath: string;
private historyFiles: Object; // {yesterday: IHistoryFileProperties[]}
// save historyItem structure to be able to redraw
private tree = {}; // {yesterday: {grp: HistoryItem, items: HistoryItem[]}}
private selection: HistoryItem;
private noLimit = false;
private date; // calculs result of relative date against now()
private format; // function to format against locale
public contentKind: EHistoryTreeContentKind = 0;
private searchPattern: string;
constructor(private controller: HistoryController) {
this.initLocation();
}
initLocation(){
vscode.commands.executeCommand('setContext', 'local-history:treeLocation', HistorySettings.getTreeLocation());
}
getSettingsItem(): HistoryItem {
// Node only for settings...
switch (this.contentKind) {
case EHistoryTreeContentKind.All:
return new HistoryItem(this, 'Search: all', EHistoryTreeItem.None, null, this.currentHistoryPath);
break;
case EHistoryTreeContentKind.Current:
return new HistoryItem(this, 'Search: current', EHistoryTreeItem.None, null, this.currentHistoryFile);
break;
case EHistoryTreeContentKind.Search:
return new HistoryItem(this, `Search: ${this.searchPattern}`, EHistoryTreeItem.None, null, this.searchPattern);
break;
}
}
getTreeItem(element: HistoryItem): vscode.TreeItem {
return element;
}
getChildren(element?: HistoryItem): Promise<HistoryItem[]> {
return new Promise(resolve => {
// redraw
const keys = Object.keys(this.tree);
if (keys && keys.length) {
if (!element) {
const items = [];
items.push(this.getSettingsItem());
keys.forEach(key => items.push(this.tree[key].grp));
return resolve(items);
} else if (this.tree[element.label].items) {
return resolve(this.tree[element.label].items);
}
}
// rebuild
let items: HistoryItem[] = [];
if (!element) { // root
if (!this.historyFiles) {
if (!vscode.window.activeTextEditor || !vscode.window.activeTextEditor.document)
return resolve(items);
const filename = vscode.window.activeTextEditor.document.uri;
const settings = this.controller.getSettings(filename);
this.loadHistoryFile(filename, settings)
.then(() => {
items.push(this.getSettingsItem());
items.push(...this.loadHistoryGroups(this.historyFiles));
resolve(items);
});
} else {
items.push(this.getSettingsItem());
items.push(...this.loadHistoryGroups(this.historyFiles));
resolve(items);
}
} else {
if (element.kind === EHistoryTreeItem.Group) {
this.historyFiles[element.label].forEach((file) => {
items.push(new HistoryItem(this, this.format(file), EHistoryTreeItem.File,
vscode.Uri.file(file.file), element.label, true));
});
this.tree[element.label].items = items;
}
resolve(items);
}
});
}
private loadHistoryFile(fileName: vscode.Uri, settings: IHistorySettings): Promise<Object> {
return new Promise((resolve, reject) => {
let pattern;
switch (this.contentKind) {
case EHistoryTreeContentKind.All:
pattern = '**/*.*';
break;
case EHistoryTreeContentKind.Current:
pattern = fileName.fsPath;
break;
case EHistoryTreeContentKind.Search:
pattern = this.searchPattern;
break;
}
this.controller.findGlobalHistory(pattern, this.contentKind === EHistoryTreeContentKind.Current, settings, this.noLimit)
.then(findFiles => {
// Current file
if (this.contentKind === EHistoryTreeContentKind.Current) {
const historyFile = this.controller.decodeFile(fileName.fsPath, settings);
this.currentHistoryFile = historyFile && historyFile.file;
}
this.currentHistoryPath = settings.historyPath;
// History files
this.historyFiles = {};
this.format = (file) => {
const result = file.date.toLocaleString(settings.dateLocale);
if (this.contentKind !== EHistoryTreeContentKind.Current)
return `${file.name}${file.ext} (${result})`
return result;
};
let grp = 'new';
const files = findFiles;
if (files && files.length)
files.map(file => this.controller.decodeFile(file, settings))
.sort((f1, f2) => {
if (!f1 || !f2)
return 0;
if (f1.date > f2.date)
return -1;
if (f1.date < f2.date)
return 1;
return f1.name.localeCompare(f2.name);
})
.forEach((file, index) => {
if (file)
if (grp !== 'Older') {
grp = this.getRelativeDate(file.date);
if (!this.historyFiles[grp])
this.historyFiles[grp] = [file]
else
this.historyFiles[grp].push(file);
} else {
this.historyFiles[grp].push(file);
}
// else
// this.historyFiles['failed'].push(files[index]);
})
return resolve(this.historyFiles);
})
})
}
private loadHistoryGroups(historyFiles: Object): HistoryItem[] {
const items = [],
keys = historyFiles && Object.keys(historyFiles);
if (keys && keys.length > 0)
keys.forEach((key) => {
const item = new HistoryItem(this, key, EHistoryTreeItem.Group);
this.tree[key] = {grp: item};
items.push(item);
});
else
items.push(new HistoryItem(this, 'No history', EHistoryTreeItem.None));
return items;
}
private getRelativeDate(fileDate: Date) {
const hour = 60 * 60,
day = hour * 24,
ref = fileDate.getTime() / 1000;
if (!this.date) {
const dt = new Date(),
now = dt.getTime() / 1000,
today = dt.setHours(0,0,0,0) / 1000; // clear current hour
this.date = {
now: now,
today: today,
week: today - ((dt.getDay() || 7) - 1) * day, // 1st day of week (week start monday)
month: dt.setDate(1) / 1000, // 1st day of current month
eLastMonth: dt.setDate(0) / 1000, // last day of previous month
lastMonth: dt.setDate(1) / 1000 // 1st day of previous month
}
}
if (this.date.now - ref < hour)
return 'In the last hour'
else if (ref > this.date.today)
return 'Today'
else if (ref > this.date.today - day)
return 'Yesterday'
else if (ref > this.date.week)
return 'This week'
else if (ref > this.date.week - (day * 7))
return 'Last week'
else if (ref > this.date.month)
return 'This month'
else if (ref > this.date.lastMonth)
return 'Last month'
else
return 'Older'
}
// private changeItemSelection(select, item) {
// if (select)
// item.iconPath = this.selectIconPath
// else
// delete item.iconPath;
// }
private redraw() {
this._onDidChangeTreeData.fire();
}
public changeActiveFile() {
if (!vscode.window.activeTextEditor)
return;
const filename = vscode.window.activeTextEditor.document.uri;
const settings = this.controller.getSettings(filename);
const prop = this.controller.decodeFile(filename.fsPath, settings, false);
if (!prop || prop.file !== this.currentHistoryFile)
this.refresh();
}
public refresh(noLimit = false): void {
this.tree = {};
delete this.selection;
this.noLimit = noLimit;
delete this.currentHistoryFile;
delete this.currentHistoryPath;
delete this.historyFiles;
delete this.date;
this._onDidChangeTreeData.fire();
}
public more(): void {
if (!this.noLimit) {
this.refresh(true);
}
}
public deleteAll(): void {
let message;
switch (this.contentKind) {
case EHistoryTreeContentKind.All:
message = `Delete all history - ${this.currentHistoryPath}?`
break;
case EHistoryTreeContentKind.Current:
message = `Delete history for ${this.currentHistoryFile} ?`
break;
case EHistoryTreeContentKind.Search:
message = `Delete history for ${this.searchPattern} ?`
break;
}
vscode.window.showInformationMessage(message, {modal: true}, {title: 'Yes'}, {title: 'No', isCloseAffordance: true})
.then(sel => {
if (sel.title === 'Yes') {
switch (this.contentKind) {
case EHistoryTreeContentKind.All:
// Delete all history
this.controller.deleteAll(this.currentHistoryPath)
.then(() => this.refresh())
.catch(err => vscode.window.showErrorMessage(`Delete failed: ${err}`));
break;
case EHistoryTreeContentKind.Current:
// delete history for current file
this.controller.deleteHistory(this.currentHistoryFile)
.then(() => this.refresh())
.catch(err => vscode.window.showErrorMessage(`Delete failed: ${err}`));
break;
case EHistoryTreeContentKind.Search:
// Delete visible history files
const keys = Object.keys(this.historyFiles);
if (keys && keys.length) {
const items = [];
keys.forEach(key => items.push(...this.historyFiles[key].map(item => item.file)));
this.controller.deleteFiles(items)
.then(() => this.refresh())
.catch(err => vscode.window.showErrorMessage(`Delete failed: ${err}`));
}
break;
}
}
},
(err => { return; })
);
}
public show(file: vscode.Uri): void {
vscode.commands.executeCommand('vscode.open', file);
}
public showSide(element: HistoryItem): void {
if (element.kind === EHistoryTreeItem.File)
vscode.commands.executeCommand('vscode.open', element.file, Math.min(vscode.window.activeTextEditor.viewColumn + 1, 3));
}
public delete(element: HistoryItem): void {
if (element.kind === EHistoryTreeItem.File)
this.controller.deleteFile(element.file.fsPath)
.then(() => this.refresh());
else if (element.kind === EHistoryTreeItem.Group) {
this.controller.deleteFiles(
this.historyFiles[element.label].map((value: IHistoryFileProperties) => value.file))
.then(() => this.refresh());
}
}
public compareToCurrent(element: HistoryItem): void {
if (element.kind === EHistoryTreeItem.File) {
let currRange;
if (vscode.window.activeTextEditor && vscode.window.activeTextEditor.document &&
vscode.window.activeTextEditor.document.fileName === this.currentHistoryFile) {
const currPos = vscode.window.activeTextEditor.selection.active;
currRange = new vscode.Range(currPos, currPos);
};
this.controller.compare(element.file, vscode.Uri.file(this.currentHistoryFile), null, currRange);
}
}
public select(element: HistoryItem): void {
if (element.kind === EHistoryTreeItem.File) {
if (this.selection)
delete this.selection.iconPath;
this.selection = element;
// this.selection.iconPath = this.selectIconPath;
this.tree[element.grp].grp.collapsibleState = vscode.TreeItemCollapsibleState.Expanded;
this.redraw();
}
}
public compare(element: HistoryItem): void {
if (element.kind === EHistoryTreeItem.File) {
if (this.selection)
this.controller.compare(element.file, this.selection.file);
else
vscode.window.showErrorMessage('Select a history files to compare with');
}
}
public restore(element: HistoryItem): void {
if (element.kind === EHistoryTreeItem.File) {
this.controller.restore(element.file)
.then(() => this.refresh())
.catch(err => vscode.window.showErrorMessage(`Restore ${element.file.fsPath} failed. Error: ${err}`));
}
}
public forCurrentFile(): void{
this.contentKind = EHistoryTreeContentKind.Current;
this.refresh();
}
public forAll(): void{
this.contentKind = EHistoryTreeContentKind.All;
this.refresh();
}
public forSpecificFile(): void {
vscode.window.showInputBox({prompt: 'Specify what to search:', value: '**/*myFile*.*', valueSelection: [4,10]})
.then(value => {
if (value) {
this.searchPattern = value;
this.contentKind = EHistoryTreeContentKind.Search;
this.refresh();
}
});
}
}
class HistoryItem extends vscode.TreeItem {
public readonly kind: EHistoryTreeItem;
public readonly file: vscode.Uri;
public readonly grp: string;
constructor(provider: HistoryTreeProvider, label: string = '', kind: EHistoryTreeItem, file?: vscode.Uri,
grp?: string, showIcon?: boolean) {
super(label, kind === EHistoryTreeItem.Group ? vscode.TreeItemCollapsibleState.Collapsed : vscode.TreeItemCollapsibleState.None);
this.kind = kind;
this.file = file;
this.grp = this.kind !== EHistoryTreeItem.None ? grp : undefined;
switch (this.kind) {
case EHistoryTreeItem.File:
this.contextValue = 'localHistoryItem';
this.tooltip = file.fsPath; // TODO remove before .history
this.resourceUri = file;
if (showIcon)
this.iconPath = false;
break;
case EHistoryTreeItem.Group:
this.contextValue = 'localHistoryGrp';
break;
default: // EHistoryTreeItem.None
this.contextValue = 'localHistoryNone';
this.tooltip = grp;
}
// TODO: if current === file
if (provider.contentKind === EHistoryTreeContentKind.Current) {
this.command = this.kind === EHistoryTreeItem.File ? {
command: 'treeLocalHistory.compareToCurrentEntry',
title: 'Compare with current version',
arguments: [this]
} : undefined;
} else {
this.command = this.kind === EHistoryTreeItem.File ? {
command: 'treeLocalHistory.showEntry',
title: 'Open Local History',
arguments: [file]
} : undefined;
}
}
} | the_stack |
// (c) Dean McNamee <dean@gmail.com>, 2012.
//
// https://github.com/deanm/css-color-parser-js
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// http://www.w3.org/TR/css3-color/
module EZGUI.utils.ColorParser {
var kCSSColorTable = {
"transparent": [0, 0, 0, 0], "aliceblue": [240, 248, 255, 1],
"antiquewhite": [250, 235, 215, 1], "aqua": [0, 255, 255, 1],
"aquamarine": [127, 255, 212, 1], "azure": [240, 255, 255, 1],
"beige": [245, 245, 220, 1], "bisque": [255, 228, 196, 1],
"black": [0, 0, 0, 1], "blanchedalmond": [255, 235, 205, 1],
"blue": [0, 0, 255, 1], "blueviolet": [138, 43, 226, 1],
"brown": [165, 42, 42, 1], "burlywood": [222, 184, 135, 1],
"cadetblue": [95, 158, 160, 1], "chartreuse": [127, 255, 0, 1],
"chocolate": [210, 105, 30, 1], "coral": [255, 127, 80, 1],
"cornflowerblue": [100, 149, 237, 1], "cornsilk": [255, 248, 220, 1],
"crimson": [220, 20, 60, 1], "cyan": [0, 255, 255, 1],
"darkblue": [0, 0, 139, 1], "darkcyan": [0, 139, 139, 1],
"darkgoldenrod": [184, 134, 11, 1], "darkgray": [169, 169, 169, 1],
"darkgreen": [0, 100, 0, 1], "darkgrey": [169, 169, 169, 1],
"darkkhaki": [189, 183, 107, 1], "darkmagenta": [139, 0, 139, 1],
"darkolivegreen": [85, 107, 47, 1], "darkorange": [255, 140, 0, 1],
"darkorchid": [153, 50, 204, 1], "darkred": [139, 0, 0, 1],
"darksalmon": [233, 150, 122, 1], "darkseagreen": [143, 188, 143, 1],
"darkslateblue": [72, 61, 139, 1], "darkslategray": [47, 79, 79, 1],
"darkslategrey": [47, 79, 79, 1], "darkturquoise": [0, 206, 209, 1],
"darkviolet": [148, 0, 211, 1], "deeppink": [255, 20, 147, 1],
"deepskyblue": [0, 191, 255, 1], "dimgray": [105, 105, 105, 1],
"dimgrey": [105, 105, 105, 1], "dodgerblue": [30, 144, 255, 1],
"firebrick": [178, 34, 34, 1], "floralwhite": [255, 250, 240, 1],
"forestgreen": [34, 139, 34, 1], "fuchsia": [255, 0, 255, 1],
"gainsboro": [220, 220, 220, 1], "ghostwhite": [248, 248, 255, 1],
"gold": [255, 215, 0, 1], "goldenrod": [218, 165, 32, 1],
"gray": [128, 128, 128, 1], "green": [0, 128, 0, 1],
"greenyellow": [173, 255, 47, 1], "grey": [128, 128, 128, 1],
"honeydew": [240, 255, 240, 1], "hotpink": [255, 105, 180, 1],
"indianred": [205, 92, 92, 1], "indigo": [75, 0, 130, 1],
"ivory": [255, 255, 240, 1], "khaki": [240, 230, 140, 1],
"lavender": [230, 230, 250, 1], "lavenderblush": [255, 240, 245, 1],
"lawngreen": [124, 252, 0, 1], "lemonchiffon": [255, 250, 205, 1],
"lightblue": [173, 216, 230, 1], "lightcoral": [240, 128, 128, 1],
"lightcyan": [224, 255, 255, 1], "lightgoldenrodyellow": [250, 250, 210, 1],
"lightgray": [211, 211, 211, 1], "lightgreen": [144, 238, 144, 1],
"lightgrey": [211, 211, 211, 1], "lightpink": [255, 182, 193, 1],
"lightsalmon": [255, 160, 122, 1], "lightseagreen": [32, 178, 170, 1],
"lightskyblue": [135, 206, 250, 1], "lightslategray": [119, 136, 153, 1],
"lightslategrey": [119, 136, 153, 1], "lightsteelblue": [176, 196, 222, 1],
"lightyellow": [255, 255, 224, 1], "lime": [0, 255, 0, 1],
"limegreen": [50, 205, 50, 1], "linen": [250, 240, 230, 1],
"magenta": [255, 0, 255, 1], "maroon": [128, 0, 0, 1],
"mediumaquamarine": [102, 205, 170, 1], "mediumblue": [0, 0, 205, 1],
"mediumorchid": [186, 85, 211, 1], "mediumpurple": [147, 112, 219, 1],
"mediumseagreen": [60, 179, 113, 1], "mediumslateblue": [123, 104, 238, 1],
"mediumspringgreen": [0, 250, 154, 1], "mediumturquoise": [72, 209, 204, 1],
"mediumvioletred": [199, 21, 133, 1], "midnightblue": [25, 25, 112, 1],
"mintcream": [245, 255, 250, 1], "mistyrose": [255, 228, 225, 1],
"moccasin": [255, 228, 181, 1], "navajowhite": [255, 222, 173, 1],
"navy": [0, 0, 128, 1], "oldlace": [253, 245, 230, 1],
"olive": [128, 128, 0, 1], "olivedrab": [107, 142, 35, 1],
"orange": [255, 165, 0, 1], "orangered": [255, 69, 0, 1],
"orchid": [218, 112, 214, 1], "palegoldenrod": [238, 232, 170, 1],
"palegreen": [152, 251, 152, 1], "paleturquoise": [175, 238, 238, 1],
"palevioletred": [219, 112, 147, 1], "papayawhip": [255, 239, 213, 1],
"peachpuff": [255, 218, 185, 1], "peru": [205, 133, 63, 1],
"pink": [255, 192, 203, 1], "plum": [221, 160, 221, 1],
"powderblue": [176, 224, 230, 1], "purple": [128, 0, 128, 1],
"red": [255, 0, 0, 1], "rosybrown": [188, 143, 143, 1],
"royalblue": [65, 105, 225, 1], "saddlebrown": [139, 69, 19, 1],
"salmon": [250, 128, 114, 1], "sandybrown": [244, 164, 96, 1],
"seagreen": [46, 139, 87, 1], "seashell": [255, 245, 238, 1],
"sienna": [160, 82, 45, 1], "silver": [192, 192, 192, 1],
"skyblue": [135, 206, 235, 1], "slateblue": [106, 90, 205, 1],
"slategray": [112, 128, 144, 1], "slategrey": [112, 128, 144, 1],
"snow": [255, 250, 250, 1], "springgreen": [0, 255, 127, 1],
"steelblue": [70, 130, 180, 1], "tan": [210, 180, 140, 1],
"teal": [0, 128, 128, 1], "thistle": [216, 191, 216, 1],
"tomato": [255, 99, 71, 1], "turquoise": [64, 224, 208, 1],
"violet": [238, 130, 238, 1], "wheat": [245, 222, 179, 1],
"white": [255, 255, 255, 1], "whitesmoke": [245, 245, 245, 1],
"yellow": [255, 255, 0, 1], "yellowgreen": [154, 205, 50, 1]
}
function clamp_css_byte(i) { // Clamp to integer 0 .. 255.
i = Math.round(i); // Seems to be what Chrome does (vs truncation).
return i < 0 ? 0 : i > 255 ? 255 : i;
}
function clamp_css_float(f) { // Clamp to float 0.0 .. 1.0.
return f < 0 ? 0 : f > 1 ? 1 : f;
}
function parse_css_int(str) { // int or percentage.
if (str[str.length - 1] === '%')
return clamp_css_byte(parseFloat(str) / 100 * 255);
return clamp_css_byte(parseInt(str));
}
function parse_css_float(str) { // float or percentage.
if (str[str.length - 1] === '%')
return clamp_css_float(parseFloat(str) / 100);
return clamp_css_float(parseFloat(str));
}
function css_hue_to_rgb(m1, m2, h) {
if (h < 0) h += 1;
else if (h > 1) h -= 1;
if (h * 6 < 1) return m1 + (m2 - m1) * h * 6;
if (h * 2 < 1) return m2;
if (h * 3 < 2) return m1 + (m2 - m1) * (2 / 3 - h) * 6;
return m1;
}
export function parseToPixiColor(str) {
var rgb = parseToRGB(str);
if (!rgb) return -1;
var intRGB = rgb[0];
intRGB = (intRGB << 8) + rgb[1];
intRGB = (intRGB << 8) + rgb[2];
return intRGB;
}
export function parseToRGB(str) {
// Remove all whitespace, not compliant, but should just be more accepting.
var str = str.replace(/ /g, '').toLowerCase();
// Color keywords (and transparent) lookup.
if (str in kCSSColorTable) return kCSSColorTable[str].slice(); // dup.
// #abc and #abc123 syntax.
if (str[0] === '#') {
if (str.length === 4) {
var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
if (!(iv >= 0 && iv <= 0xfff)) return null; // Covers NaN.
return [((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
(iv & 0xf0) | ((iv & 0xf0) >> 4),
(iv & 0xf) | ((iv & 0xf) << 4),
1];
} else if (str.length === 7) {
var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
if (!(iv >= 0 && iv <= 0xffffff)) return null; // Covers NaN.
return [(iv & 0xff0000) >> 16,
(iv & 0xff00) >> 8,
iv & 0xff,
1];
}
return null;
}
var op = str.indexOf('('), ep = str.indexOf(')');
if (op !== -1 && ep + 1 === str.length) {
var fname = str.substr(0, op);
var params = str.substr(op + 1, ep - (op + 1)).split(',');
var alpha = 1; // To allow case fallthrough.
switch (fname) {
case 'rgba':
if (params.length !== 4) return null;
alpha = parse_css_float(params.pop());
// Fall through.
case 'rgb':
if (params.length !== 3) return null;
return [parse_css_int(params[0]),
parse_css_int(params[1]),
parse_css_int(params[2]),
alpha];
case 'hsla':
if (params.length !== 4) return null;
alpha = parse_css_float(params.pop());
// Fall through.
case 'hsl':
if (params.length !== 3) return null;
var h = (((parseFloat(params[0]) % 360) + 360) % 360) / 360; // 0 .. 1
// NOTE(deanm): According to the CSS spec s/l should only be
// percentages, but we don't bother and let float or percentage.
var s = parse_css_float(params[1]);
var l = parse_css_float(params[2]);
var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
var m1 = l * 2 - m2;
return [clamp_css_byte(css_hue_to_rgb(m1, m2, h + 1 / 3) * 255),
clamp_css_byte(css_hue_to_rgb(m1, m2, h) * 255),
clamp_css_byte(css_hue_to_rgb(m1, m2, h - 1 / 3) * 255),
alpha];
default:
return null;
}
}
return null;
}
} | the_stack |
// Hopefully this gets inlined!
function getPixelIndex(x: number, y: number, w: number) {
return (x + y * w) * 4
}
class CanvasRenderer extends Renderer {
tileDataCache: {[key: string]: any} = {}
init(): void {
heart.attach("cnv")
}
color(r: number, g: number, b: number, a: number=255): void {
heart.graphics.setColor(r, g, b, a)
}
rectangle(x: number, y: number, w: number, h: number, filled: boolean=true): void {
heart.graphics.rectangle(filled ? "fill" : "stroke", x, y, w, h)
}
text(txt: string, x: number, y: number): void {
heart.graphics.print(txt, x, y)
}
image(img: HTMLImageElement|HeartImage, x: number, y: number, w?: number, h?: number): void {
heart.graphics.draw(img, x, y, w, h)
}
clear(r: number, g: number, b: number): void {
heart.graphics.setBackgroundColor(r, g, b)
}
renderLitFloor(matrix: string[][], useColorTable: boolean=false) {
// get the screen framebuffer
const imageData = heart.ctx.getImageData(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)
const screenWidth = imageData.width;
let tmpCtx = null
let tileData
if(useColorTable) {
// XXX: hack
if(Lighting.colorLUT === null) {
Lighting.colorLUT = getFileJSON("lut/color_lut.json")
Lighting.colorRGB = getFileJSON("lut/color_rgb.json")
}
}
// reverse i to draw in the order Fallout 2 normally does
// otherwise there will be artifacts in the light rendering
// due to tile sizes being different and not overlapping properly
for(let i = matrix.length - 1; i >= 0; i--) {
for(let j = 0; j < matrix[0].length; j++) {
const tile = matrix[j][i]
if(tile === "grid000") continue
const img = "art/tiles/" + tile
if(images[img] !== undefined) {
const scr = tileToScreen(i, j)
if(scr.x+TILE_WIDTH < cameraX || scr.y+TILE_HEIGHT < cameraY ||
scr.x >= cameraX+SCREEN_WIDTH || scr.y >= cameraY+SCREEN_HEIGHT)
continue
const sx = scr.x - cameraX
const sy = scr.y - cameraY
// XXX: how correct is this?
const hex = hexFromScreen(scr.x - 13,
scr.y + 13)
if(this.tileDataCache[img] === undefined) {
// temp canvas to get tile framebuffer
if(!tmpCtx)
tmpCtx = document.createElement("canvas").getContext("2d")!
tmpCtx.drawImage(images[img].img, 0, 0)
tileData = tmpCtx.getImageData(0, 0, images[img].img.width, images[img].img.height)
this.tileDataCache[img] = tileData
}
else
tileData = this.tileDataCache[img]
const tileWidth = tileData.width
const isTriangleLit = Lighting.initTile(hex)
let framebuffer: number[]
let intensity_
if(isTriangleLit)
framebuffer = Lighting.computeFrame()
// render tile
const w = Math.min(SCREEN_WIDTH - sx, 80)
const h = Math.min(SCREEN_HEIGHT - sy, 36)
for(var y = 0; y < h; y++) {
for(var x = 0; x < w; x++) {
if((sx + x) < 0 || (sy + y) < 0)
continue
const tileIndex = getPixelIndex(x, y, tileWidth)
if(tileData.data[tileIndex + 3] === 0) // transparent pixel, skip
continue
if(isTriangleLit) {
intensity_ = framebuffer![160 + 80*y + x]
}
else { // uniformly lit
intensity_ = Lighting.vertices[3]
}
const screenIndex = getPixelIndex(sx + x, sy + y, screenWidth)
const intensity = Math.min(1.0, intensity_/65536) // tile intensity [0, 1]
// blit to the framebuffer
if(useColorTable) { // TODO: optimize
const orig_color = (tileData.data[tileIndex + 0] << 16) | (tileData.data[tileIndex + 1] << 8) | tileData.data[tileIndex + 2]
const palIdx = Lighting.colorLUT[orig_color] // NOTE: substitue 221 for white for drawing just the lightbuffer
const tableIdx = palIdx*256 + (intensity_/512 | 0)
const colorPal = Lighting.intensityColorTable[tableIdx]
const color = Lighting.colorRGB[colorPal]
imageData.data[screenIndex + 0] = color[0]
imageData.data[screenIndex + 1] = color[1]
imageData.data[screenIndex + 2] = color[2]
}
else { // just draw the source pixel with the light intensity
imageData.data[screenIndex + 0] = tileData.data[tileIndex + 0] * intensity | 0
imageData.data[screenIndex + 1] = tileData.data[tileIndex + 1] * intensity | 0
imageData.data[screenIndex + 2] = tileData.data[tileIndex + 2] * intensity | 0
}
}
}
}
}
}
// write the framebuffer back to the canvas
heart.ctx.putImageData(imageData, 0, 0)
}
drawTileMap(matrix: TileMap, offsetY: number): void {
for(var i = 0; i < matrix.length; i++) {
for(var j = 0; j < matrix[0].length; j++) {
var tile = matrix[j][i]
if(tile === "grid000") continue
var img = "art/tiles/" + tile
if(images[img] !== undefined) {
var scr = tileToScreen(i, j)
scr.y += offsetY
if(scr.x+TILE_WIDTH < cameraX || scr.y+TILE_HEIGHT < cameraY ||
scr.x >= cameraX+SCREEN_WIDTH || scr.y >= cameraY+SCREEN_HEIGHT)
continue
heart.graphics.draw(images[img], scr.x - cameraX, scr.y - cameraY)
}
else { // Try to lazy-load the missing tile
lazyLoadImage(img);
}
}
}
}
renderRoof(roof: TileMap): void {
this.drawTileMap(roof, -96)
}
renderFloor(floor: TileMap): void {
if(Config.engine.doFloorLighting)
this.renderLitFloor(floor, Config.engine.useLightColorLUT)
else
this.drawTileMap(floor, 0)
}
renderObjectOutlined(obj: Obj): void {
// Render an outlined object using the temporary canvas
//
// We render the outline by rendering the object 8 times for each 8 directions
// to achieve a uniformly spaced outline in all directions.
// We then draw over that silhouette, filling it with the outline color.
// Finally we can draw the actual object sprite over it normally.
if(!obj.outline)
throw Error("renderObjectOutlined received an object without an outline");
const renderInfo = this.objectRenderInfo(obj);
if(!renderInfo || !renderInfo.visible)
return;
if(!tempCanvasCtx) throw Error();
// Clear temp canvas
tempCanvasCtx.clearRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
const img = images[obj.art].img;
const w = renderInfo.frameWidth;
const h = renderInfo.frameHeight;
const srcX = renderInfo.spriteX;
// Draw object to temp canvas in 8 directions (up/down/left/right/diagonals)
// Note that we offset by (1, 1) so that we have a pixel reserved on the boundaries for the outline
tempCanvasCtx.drawImage(img, srcX, 0, w, h, 1+1, 0+1, w, h); // right
tempCanvasCtx.drawImage(img, srcX, 0, w, h, -1+1, 0+1, w, h); // left
tempCanvasCtx.drawImage(img, srcX, 0, w, h, 0+1, -1+1, w, h); // up
tempCanvasCtx.drawImage(img, srcX, 0, w, h, 0+1, 1+1, w, h); // down
tempCanvasCtx.drawImage(img, srcX, 0, w, h, -1+1, -1+1, w, h); // up-left
tempCanvasCtx.drawImage(img, srcX, 0, w, h, 1+1, 1+1, w, h); // down-right
tempCanvasCtx.drawImage(img, srcX, 0, w, h, -1+1, 1+1, w, h); // down-left
tempCanvasCtx.drawImage(img, srcX, 0, w, h, 1+1, -1+1, w, h); // down-right
// Use source-in blending to fill what we drew with the outline color
tempCanvasCtx.globalCompositeOperation = "source-in";
tempCanvasCtx.fillStyle = obj.outline;
tempCanvasCtx.fillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
// Revert back to the default source-over blend mode
tempCanvasCtx.globalCompositeOperation = "source-over";
// Render the object normally
tempCanvasCtx.drawImage(img, srcX, 0, w, h, 1, 1, w, h);
// Render the sprite from the temp canvas to the main canvas
heart.ctx.drawImage(tempCanvas, 0, 0, renderInfo.frameWidth + 2, renderInfo.frameHeight + 2,
renderInfo.x - cameraX,
renderInfo.y - cameraY,
renderInfo.frameWidth + 2, renderInfo.frameHeight + 2);
}
renderObject(obj: Obj): void {
const renderInfo = this.objectRenderInfo(obj);
if(!renderInfo || !renderInfo.visible)
return;
heart.ctx.drawImage(images[obj.art].img,
renderInfo.spriteX, 0, renderInfo.frameWidth, renderInfo.frameHeight,
renderInfo.x - cameraX,
renderInfo.y - cameraY,
renderInfo.frameWidth, renderInfo.frameHeight);
}
} | the_stack |
import Vec2 from "../../../matrix/vec2";
import Vec3 from "../../../matrix/vec3";
function Quadratic(x0, y0, x1, y1, x2, y2, resolution) {
function QuadraticBezierP0(t, p) {
const k = 1 - t;
return k * k * p;
}
function QuadraticBezierP1(t, p) {
return 2 * (1 - t) * t * p;
}
function QuadraticBezierP2(t, p) {
return t * t * p;
}
function QuadraticBezier(t, p0, p1, p2) {
return QuadraticBezierP0(t, p0) + QuadraticBezierP1(t, p1) +
QuadraticBezierP2(t, p2);
}
const dx = x1 - x0;
const dy = y1 - y0;
const len = Math.sqrt(dx * dx + dy * dy);
let divs = Math.ceil(len / resolution);
if (divs < 3) {
divs = 3;
}
const vertices = [];
for (let i = 1; i <= divs; i++) {
const x = QuadraticBezier(i / divs, x0, x1, x2);
const y = QuadraticBezier(i / divs, y0, y1, y2);
vertices.push(x, y);
}
return vertices;
}
function Line(x0, y0, x1, y1, resolution) {
return [x1, y1];
}
const PathParser = {
parse(data, resolution) {
data = data.split("\n").join("");
const list = data.split(" ").filter(Boolean);
const vertices = [];
const lines = [];
let i = 0;
let line = [];
let current = null;
while (i < list.length) {
switch (list[i++]) {
case "m": {
const x = Number(list[i++]);
const y = Number(list[i++]);
if (line.length) {
checkLineRing(line);
lines.push(line);
line = [];
}
vertices.push(x, y);
line.push(vertices.length / 2 - 1);
current = [x, y];
break;
}
case "q": {
const [x0, y0] = current;
const x2 = Number(list[i++]);
const y2 = Number(list[i++]);
const x1 = Number(list[i++]);
const y1 = Number(list[i++]);
const points = Quadratic(x0, y0, x1, y1, x2, y2, resolution);
for (let j = 0; j < points.length; j += 2) {
vertices.push(points[j], points[j + 1]);
line.push(vertices.length / 2 - 1);
}
current = [x2, y2];
break;
}
case "l": {
const x = Number(list[i++]);
const y = Number(list[i++]);
const [x0, y0] = current;
const points = Line(x0, y0, x, y, resolution);
for (let j = 0; j < points.length; j += 2) {
vertices.push(points[j], points[j + 1]);
line.push(vertices.length / 2 - 1);
}
current = [x, y];
break;
}
case "z": {
// line.push(line[0]);
break;
}
default:
throw new Error("parse path failed, unhandled item " + list[i]);
}
}
checkLineRing(line);
lines.push(line);
line = [];
function checkLineRing(theLine) {
const len = theLine.length;
const k = theLine[0];
const j = theLine[len - 1];
if (
vertices[k * 2] === vertices[j * 2] &&
vertices[k * 2 + 1] === vertices[j * 2 + 1] &&
j * 2 + 1 === vertices.length - 1
) {
vertices.pop();
vertices.pop();
theLine[len - 1] = k;
}
}
return { vertices, lines };
},
parseToLine(data, resolution) {
const { vertices, lines } = this.parse(data, resolution);
const indices = [];
lines.forEach((line, i) => {
line.forEach((item, j) => {
if (j !== 0) {
indices.push(line[j - 1], item);
}
});
});
const vertices3d = [];
for (let i = 0; i < vertices.length; i += 2) {
vertices3d.push(vertices[i], vertices[i + 1], 0);
}
return { vertices: vertices3d, indices };
},
parseToTriangles(data, resolution) {
const { vertices, lines } = this.parse(data, resolution);
const clonedLines = cloneLines(lines);
const { polygons, holes } = distinguish(lines);
const indices = earcut(polygons, holes, []);
const vertices3d = [];
const normals = [];
const uvs = [];
for (let i = 0; i < vertices.length; i += 2) {
vertices3d.push(vertices[i], vertices[i + 1], 0);
normals.push(0, 0, 1);
uvs.push(0, 0);
}
return {
vertices: vertices3d,
indices,
normals,
uvs,
lines: clonedLines,
};
function earcut(plgs, hles, triangles) {
if (hles.length > 0) {
const res = removeHoles(plgs, hles);
plgs = res.polygons;
hles = res.holes;
}
plgs.forEach((polygon) => {
triangles.push(...earcutPolygon(polygon));
});
return triangles;
}
function earcutPolygon(polygon) {
// console.log(polygon.join(','));
if (polygon.length < 3) {
throw new Error("not valid polygon");
} else if (polygon.length === 3) {
if (polygon[0] === polygon[2]) {
return [];
} else {
throw new Error("invalid polygon");
}
} else {
for (let i = 1; i < polygon.length - 1; i++) {
const [j0, j1, j2] = [
i === 0 ? polygon.length - 1 : i - 1,
i,
i === polygon.length - 1 ? 0 : i + 1,
];
const [i0, i1, i2] = [polygon[j0], polygon[j1], polygon[j2]];
if (isEar(j0, j1, j2, polygon)) {
polygon.splice(i, 1);
return [
i0, i1, i2, ...earcutPolygon(polygon),
];
}
}
throw new Error("hole not cleaned");
}
}
let clockwiseFactor = 1;
function distinguish(idcs) {
const plgs = [];
const hles = [];
idcs.forEach((list) => {
let sum = 0;
for (let i = 0; i < list.length - 1; i++) {
const j = i + 1;
const [x0, y0, x1, y1] = [...pt(list[i]), ...pt(list[j])];
sum += (x1 - x0) * (y1 + y0);
}
if (plgs.length === 0) {
clockwiseFactor = sum / Math.abs(sum);
}
if (sum * clockwiseFactor >= 0) {
plgs.push(list);
} else {
hles.push(list);
}
});
return {
polygons: plgs,
holes: hles,
};
}
function pt(i) {
return [vertices[i * 2], vertices[i * 2 + 1]];
}
// -1 for left side
// 1 for right side
// 0 for on the segment
// NaN for on the line but not on the segment
function sign(x, y, x0, y0, x1, y1) {
const res = (x - x1) * (y0 - y1) - (x0 - x1) * (y - y1);
if (res === 0) {
if ((x - x0) * (x - x1) <= 0 && (y - y0) * (y - y1) <= 0) {
return 0;
} else {
return NaN;
}
} else {
return res > 0 ? 1 : -1;
}
}
function insideTriangle(x, y, x0, y0, x1, y1, x2, y2) {
const s0 = sign(x, y, x0, y0, x1, y1);
const s1 = sign(x, y, x1, y1, x2, y2);
const s2 = sign(x, y, x2, y2, x0, y0);
if (isNaN(s0 * s1 * s2)) {
return false;
} else if (s0 * s1 * s2 === 0) {
return true;
} else if (s0 === s1 && s0 === s2) {
return true;
} else {
return false;
}
}
function isCross(x0, y0, x1, y1, x2, y2, x3, y3) {
const s0 = sign(x0, y0, x2, y2, x3, y3);
const s1 = sign(x1, y1, x2, y2, x3, y3);
const s2 = sign(x2, y2, x0, y0, x1, y1);
const s3 = sign(x3, y3, x0, y0, x1, y1);
const s = s0 * s1 * s2 * s3;
if (isNaN(s)) {
return false;
} else if (s === 0) {
return false;
} else if (s0 * s1 === -1 && s2 * s3 === -1) {
return true;
} else {
return false;
}
}
function isEar(j0, j1, j2, polygon) {
const [i0, i1, i2] = [polygon[j0], polygon[j1], polygon[j2]];
const [x0, y0, x1, y1, x2, y2] = [...pt(i0), ...pt(i1), ...pt(i2)];
const v1 = [x1 - x0, y1 - y0];
const v2 = [x2 - x1, y2 - y1];
const convex = sign(x2, y2, x0, y0, x1, y1) * clockwiseFactor <= 0;
if (!convex) {
return false;
}
for (let i = 0; i < polygon.length; i++) {
const ix = polygon[i];
if (ix !== i0 && ix !== i1 && ix !== i2) {
const [x, y] = pt(ix);
if (insideTriangle(x, y, x0, y0, x1, y1, x2, y2)) {
return false;
}
}
if (i !== polygon.length - 1) {
const jx = polygon[i + 1];
const [x0p, y0p, x1p, y1p] = [...pt(ix), ...pt(jx)];
if (isCross(x0, y0, x2, y2, x0p, y0p, x1p, y1p)) {
return false;
}
}
}
return true;
}
function removeHoles(plgs, hles) {
if (hles.length === 0) {
return {
polygons: plgs, holes,
};
}
for (let hi = 0; hi < hles.length; hi++) {
let hole = hles[hi];
for (let hvi = 0; hvi < hole.length; hvi++) {
const hv = hole[hvi];
const [hvx, hvy] = pt(hv);
for (let pi = 0; pi < plgs.length; pi++) {
const polygon = plgs[pi];
for (let pvi = 0; pvi < polygon.length; pvi++) {
const pv = polygon[pvi];
const [pvx, pvy] = pt(pv);
if (visible(hvx, hvy, pvx, pvy)) {
plgs.splice(pi, 1);
hles.splice(hi, 1);
hole.pop();
hole = hole.splice(hvi).concat(hole);
hole.push(hv);
polygon.splice(pvi + 1, 0, ...hole, pv);
plgs.push(polygon);
return removeHoles(plgs, hles);
}
}
}
throw new Error("can not find visible point pair");
}
}
function visible(x0, y0, x1, y1) {
const lns = [...polygons, ...holes];
for (let i = 0; i < lns.length; i++) {
const line = lns[i];
for (let j = 0; j < line.length - 1; j++) {
const [v2, v3] = [line[j], line[j + 1]];
const [x2, y2, x3, y3] = [...pt(v2), ...pt(v3)];
if (intersect(x0, y0, x1, y1, x2, y2, x3, y3)) {
return false;
}
}
}
return true;
}
function intersect(x0, y0, x1, y1, x2, y2, x3, y3) {
const s0 = sign(x0, y0, x2, y2, x3, y3);
const s1 = sign(x1, y1, x2, y2, x3, y3);
const s2 = sign(x2, y2, x0, y0, x1, y1);
const s3 = sign(x3, y3, x0, y0, x1, y1);
if (isNaN(s0 * s1 * s2 * s3)) {
return false;
}
if (s0 * s1 < 0 && s2 * s3 < 0) {
return true;
} else {
return false;
}
}
return {
polygons,
holes: [],
};
}
function cloneLines(lns) {
return lns.map((line) => [...line]);
}
},
parseToGeometry(data, thickness = 100, resolution = 10) {
const { vertices: f1Vertices, indices: f1Indices, lines } = this.parseToTriangles(data, resolution);
const f1Normals = [];
const f1UVs = [];
const f2Normals = [];
const f2UVs = [];
f1Vertices.forEach((v, i) => {
if (i % 3 === 2) {
f1Vertices[i] = thickness / 2;
f1Normals.push(0, 0, 1);
f1UVs.push(0, 0);
f2Normals.push(0, 0, -1);
f2UVs.push(0, 0);
}
});
const f2Vertices = f1Vertices.map((v, i) => {
if (i % 3 === 2) {
return -thickness / 2;
} else {
return v;
}
});
const f2Indices = [...f1Indices];
const f3Vertices = [];
const f3Indices = [];
const f3Normals = [];
const f3UVs = [];
lines.forEach((line) => {
for (let i = 0; i < line.length - 1; i++) {
const j = i + 1;
const [v1, v2, v3, v4] = [
pt(f1Vertices, line[i]),
pt(f1Vertices, line[j]),
pt(f2Vertices, line[i]),
pt(f2Vertices, line[j]),
];
const norm2 = normal(v1, v2, v4);
const norm = [norm2[0], norm2[1], norm2[2]];
const s = f3Vertices.length / 3;
f3Vertices.push(...v1 as [], ...v2 as [], ...v3 as [], ...v4 as []);
f3Normals.push(...norm, ...norm, ...norm, ...norm);
f3UVs.push(0, 0, 0, 0, 0, 0, 0, 0);
f3Indices.push(s, s + 1, s + 2, s + 1, s + 2, s + 3);
}
});
return merge(
[f1Vertices, f2Vertices, f3Vertices],
[f1Indices, f2Indices, f3Indices],
[f1Normals, f2Normals, f3Normals],
[f1UVs, f2UVs, f3UVs],
);
function merge(vList, iList, nList, uList) {
if (vList.length !== iList.length) {
throw new Error("merge vertices not valid");
}
let vertices = [];
let indices = [];
let normals = [];
let uvs = [];
for (let i = 0; i < vList.length; i++) {
const len = vertices.length / 3;
vertices = vertices.concat(vList[i]);
indices = indices.concat(iList[i].map((v) => v + len));
normals = normals.concat(...nList[i]);
uvs = normals.concat(...uList[i]);
}
return {
vertices, indices, normals, uvs,
};
}
function pt(vertices, i) {
return [
vertices[i * 3],
vertices[i * 3 + 1],
vertices[i * 3 + 2],
];
}
function normal(v1, v2, v3) {
const a1 = Vec3.subtract(Vec3.create(), v1, v2);
const a2 = Vec3.subtract(Vec3.create(), v2, v3);
return Vec3.cross(Vec3.create(), a1, a2);
}
},
};
export default PathParser; | the_stack |
import Stripe from "stripe";
import * as admin from "firebase-admin";
import * as functions from "firebase-functions";
import { order_status, next_transitions, order_status_keys, timeEventMapping } from "../common/constant";
import * as utils from "../lib/utils";
import { orderAccounting, createNewOrderData, updateOrderTotalDataAndUserLog } from "../functions/order";
import { sendMessageToCustomer, notifyNewOrderToRestaurant, notifyCanceledOrderToRestaurant } from "../functions/notify";
import { Context } from "../models/TestType";
import * as crypto from "crypto";
import moment from "moment-timezone";
const multiple = utils.getStripeRegion().multiple; // 100 for USD, 1 for JPY
const stripe = utils.get_stripe();
const getCustomerStripeInfo = async (db: any, customerUid: string) => {
const refStripe = db.doc(`/users/${customerUid}/system/stripe`);
const stripeInfo = (await refStripe.get()).data();
if (!stripeInfo) {
throw new functions.https.HttpsError("aborted", "No stripeInfo.");
}
return stripeInfo;
};
const getOrderData = async (transaction: any, orderRef: any) => {
const orderDoc = await transaction.get(orderRef);
const order = orderDoc.data();
if (!order) {
throw new functions.https.HttpsError("invalid-argument", "This order does not exist.");
}
order.id = orderDoc.id;
return order;
};
const getStripeOrderRecord = async (transaction: any, stripeRef: any) => {
const stripeRecord = (await transaction.get(stripeRef)).data();
if (!stripeRecord || !stripeRecord.paymentIntent || !stripeRecord.paymentIntent.id) {
throw new functions.https.HttpsError("failed-precondition", "This order has no paymentIntendId.");
}
return stripeRecord;
};
const getStripeAccount = async (db: any, restaurantOwnerUid: string) => {
const paymentSnapshot = await db.doc(`/admins/${restaurantOwnerUid}/public/payment`).get();
const stripeAccount = paymentSnapshot.data()?.stripe;
if (!stripeAccount) {
throw new functions.https.HttpsError("invalid-argument", "This restaurant does not support payment.");
}
return stripeAccount;
};
const getPaymentMethodData = async (db: any, restaurantOwnerUid: string, customerUid: string) => {
const stripeAccount = await getStripeAccount(db, restaurantOwnerUid);
const stripeInfo = await getCustomerStripeInfo(db, customerUid);
const token = await stripe.tokens.create(
{
customer: stripeInfo.customerId,
},
{
stripeAccount: stripeAccount,
}
);
const paymentMethodData = {
type: "card",
card: {
token: token.id,
},
};
return paymentMethodData;
};
// This function is called by user to create a "payment intent" (to start the payment transaction)
export const create = async (db: admin.firestore.Firestore, data: any, context: functions.https.CallableContext) => {
const customerUid = utils.validate_auth(context);
const { orderId, restaurantId, description, tip, sendSMS, timeToPickup, lng, memo } = data;
const _tip = Number(tip) || 0;
utils.validate_params({ orderId, restaurantId }); // lng, tip and sendSMS are optional
const restaurantData = await utils.get_restaurant(db, restaurantId);
const restaurantOwnerUid = restaurantData["uid"];
try {
const result = await db.runTransaction(async (transaction) => {
const stripeAccount = await getStripeAccount(db, restaurantOwnerUid);
const stripeRef = db.doc(`restaurants/${restaurantId}/orders/${orderId}/system/stripe`);
const orderRef = db.doc(`restaurants/${restaurantId}/orders/${orderId}`);
const order = await getOrderData(transaction, orderRef);
if (order.status !== order_status.validation_ok) {
throw new functions.https.HttpsError("failed-precondition", "This order is invalid.");
}
const totalChargeWithTipAndMultipled = Math.round((order.total + Math.max(0, _tip)) * multiple);
// We expect that there is a customer Id associated with a token
const payment_method_data = await getPaymentMethodData(db, restaurantOwnerUid, customerUid);
const request = {
setup_future_usage: "off_session",
amount: totalChargeWithTipAndMultipled,
description: `${description} ${orderId}`,
currency: utils.getStripeRegion().currency,
metadata: { uid: customerUid, restaurantId, orderId },
payment_method_data,
} as Stripe.PaymentIntentCreateParams;
const paymentIntent = await stripe.paymentIntents.create(request, {
idempotencyKey: orderRef.path,
stripeAccount,
});
const timePlaced = (timeToPickup && new admin.firestore.Timestamp(timeToPickup.seconds, timeToPickup.nanoseconds)) || admin.firestore.FieldValue.serverTimestamp();
await updateOrderTotalDataAndUserLog(db, transaction, customerUid, order.order, restaurantId, customerUid, timePlaced, true);
const updateData = {
status: order_status.order_placed,
totalCharge: totalChargeWithTipAndMultipled / multiple,
tip: Math.round(_tip * multiple) / multiple,
sendSMS: sendSMS || false,
updatedAt: admin.firestore.Timestamp.now(),
orderPlacedAt: admin.firestore.Timestamp.now(),
timePlaced,
description: request.description,
memo: memo || "",
payment: {
stripe: "pending",
},
};
transaction.set(orderRef, updateData, { merge: true });
transaction.set(
stripeRef,
{
paymentIntent,
},
{ merge: true }
);
Object.assign(order, updateData);
return { success: true, order };
});
await notifyNewOrderToRestaurant(db, restaurantId, result.order, restaurantData.restaurantName, lng);
return result;
} catch (error) {
throw utils.process_error(error);
}
};
// This function is called by admin to confurm a "payment intent" (to complete the payment transaction)
// order_accepted not ready_to_pickup.
export const confirm = async (db: admin.firestore.Firestore, data: any, context: functions.https.CallableContext) => {
const ownerUid = utils.validate_admin_auth(context);
const { restaurantId, orderId, lng, timezone, timeEstimated } = data;
utils.validate_params({ restaurantId, orderId });
const orderRef = db.doc(`restaurants/${restaurantId}/orders/${orderId}`);
const stripeRef = db.doc(`restaurants/${restaurantId}/orders/${orderId}/system/stripe`);
const restaurantData = await utils.get_restaurant(db, restaurantId);
const restaurantOwnerUid = restaurantData["uid"];
const stripeAccount = await getStripeAccount(db, restaurantOwnerUid);
if (restaurantOwnerUid !== ownerUid) {
throw new functions.https.HttpsError("permission-denied", "You do not have permission to confirm this request.");
}
try {
const result = await db.runTransaction(async (transaction) => {
const order = (await transaction.get(orderRef)).data();
if (!order) {
throw new functions.https.HttpsError("invalid-argument", "This order does not exist.");
}
order.id = orderId;
if (
order.status !== order_status.order_placed // from 2021-07-17
// && order.status !== order_status.order_accepted
) {
// obsolete but backward compability
throw new functions.https.HttpsError("failed-precondition", "This order is not ready yet.");
}
if (!order.payment || order.payment.stripe !== "pending") {
throw new functions.https.HttpsError("failed-precondition", "Stripe process was done.");
}
const nextStatus = next_transitions[order.status];
const stripeRecord = await getStripeOrderRecord(transaction, stripeRef);
const paymentIntentId = stripeRecord.paymentIntent.id;
const paymentIntent = await stripe.paymentIntents.confirm(paymentIntentId, {
idempotencyKey: order.id,
stripeAccount,
});
const updateTimeKey = timeEventMapping[order_status_keys[nextStatus]];
const updateData = {
status: nextStatus,
updatedAt: admin.firestore.Timestamp.now(),
[updateTimeKey]: admin.firestore.Timestamp.now(),
payment: {
stripe: "confirmed",
},
} as any;
if (nextStatus === order_status.order_accepted) {
updateData.timeEstimated = timeEstimated ? new admin.firestore.Timestamp(timeEstimated.seconds, timeEstimated.nanoseconds) : order.timePlaced;
order.timeEstimated = updateData.timeEstimated;
}
transaction.set(orderRef, updateData, { merge: true });
transaction.set(
stripeRef,
{
paymentIntent,
},
{ merge: true }
);
Object.assign(order, updateData);
return { success: true, order };
});
const orderData = result.order;
const params = {
time: moment(orderData.timeEstimated.toDate()).tz(timezone||"Asia/Tokyo").locale("ja").format("LLL")
};
console.log("timeEstimated", params["time"]);
await sendMessageToCustomer(db, lng, "msg_order_accepted", restaurantData.restaurantName, orderData, restaurantId, orderId, params);
return result;
} catch (error) {
throw utils.process_error(error);
}
};
// This function is called by user or admin to cencel an exsting order (before accepted by admin)
export const cancel = async (db: any, data: any, context: functions.https.CallableContext | Context) => {
const isAdmin = utils.is_admin_auth(context);
console.log("is_admin:" + String(isAdmin));
const uid = isAdmin ? utils.validate_admin_auth(context) : utils.validate_auth(context);
const { restaurantId, orderId, lng } = data;
utils.validate_params({ restaurantId, orderId }); // lng is optional
const orderRef = db.doc(`restaurants/${restaurantId}/orders/${orderId}`);
const stripeRef = db.doc(`restaurants/${restaurantId}/orders/${orderId}/system/stripe`);
const restaurant = await utils.get_restaurant(db, restaurantId);
const restaurantOwnerUid = restaurant["uid"];
try {
const result = await db.runTransaction(async (transaction) => {
const orderDoc = await transaction.get(orderRef);
const order = (orderDoc).data();
order.id = orderDoc.id;
if (!order) {
throw new functions.https.HttpsError("invalid-argument", "This order does not exist.");
}
if (isAdmin) {
// Admin can cancel it before confirmed
if (uid !== restaurantOwnerUid || order.status >= order_status.ready_to_pickup) {
throw new functions.https.HttpsError("permission-denied", "Invalid order state to cancel.");
}
} else {
// User can cancel an order before accepted
if (uid !== order.uid || order.status !== order_status.order_placed) {
throw new functions.https.HttpsError("permission-denied", "Invalid order state to cancel.");
}
}
const cancelTimeKey = uid === order.uid ? "orderCustomerCanceledAt" : "orderRestaurantCanceledAt";
if (!order.payment || !order.payment.stripe) {
// No payment transaction
await updateOrderTotalDataAndUserLog(db, transaction, order.uid, order.order, restaurantId, uid, order.timePlaced, false);
transaction.set(
orderRef,
{
timeCanceled: admin.firestore.FieldValue.serverTimestamp(),
[cancelTimeKey]: admin.firestore.FieldValue.serverTimestamp(),
updatedAt: admin.firestore.Timestamp.now(),
status: order_status.order_canceled,
uidCanceledBy: uid,
},
{ merge: true }
);
return { success: true, payment: false, order };
}
if (order.payment.stripe !== "pending") {
throw new functions.https.HttpsError("permission-denied", "Invalid payment state to cancel.");
}
const stripeRecord = await getStripeOrderRecord(transaction, stripeRef);
const paymentIntentId = stripeRecord.paymentIntent.id;
const stripeAccount = await getStripeAccount(db, restaurantOwnerUid);
const paymentIntent = await stripe.paymentIntents.cancel(paymentIntentId, {
idempotencyKey: `${order.id}-cancel`,
stripeAccount,
});
await updateOrderTotalDataAndUserLog(db, transaction, order.uid, order.order, restaurantId, restaurant.uid, order.timePlaced, false);
const updateData = {
timeCanceled: admin.firestore.FieldValue.serverTimestamp(),
[cancelTimeKey]: admin.firestore.FieldValue.serverTimestamp(),
status: order_status.order_canceled,
updatedAt: admin.firestore.Timestamp.now(),
uidCanceledBy: uid,
payment: {
stripe: "canceled",
},
};
transaction.set(orderRef, updateData, { merge: true });
transaction.set(
stripeRef,
{
paymentIntent,
},
{ merge: true }
);
Object.assign(order, updateData);
return {
success: true,
payment: "stripe",
byUser: uid === order.uid,
order,
};
});
if (isAdmin && result.order.sendSMS) {
await sendMessageToCustomer(db, lng, "msg_order_canceled", restaurant.restaurantName, result.order, restaurantId, orderId, {}, true);
}
if (!isAdmin) {
await notifyCanceledOrderToRestaurant(db, restaurantId, result.order, restaurant.restaurantName, lng);
}
return result;
} catch (error) {
throw utils.process_error(error);
}
};
// This function is called by admin to cencel an exsting order
export const cancelStripePayment = async (db: admin.firestore.Firestore, data: any, context: functions.https.CallableContext | Context) => {
const uid = utils.validate_admin_auth(context);
const { restaurantId, orderId, lng } = data;
utils.validate_params({ restaurantId, orderId }); // lng is optional
const orderRef = db.doc(`restaurants/${restaurantId}/orders/${orderId}`);
const stripeRef = db.doc(`restaurants/${restaurantId}/orders/${orderId}/system/stripe`);
const restaurant = await utils.get_restaurant(db, restaurantId);
const restaurantOwnerUid = restaurant["uid"];
const stripeAccount = await getStripeAccount(db, restaurantOwnerUid);
try {
const result = await db.runTransaction(async (transaction) => {
const order = (await transaction.get(orderRef)).data();
if (!order) {
throw new functions.https.HttpsError("invalid-argument", "This order does not exist.");
}
if (!order.payment || !order.payment.stripe || order.payment.stripe !== "pending") {
throw new functions.https.HttpsError("permission-denied", "Invalid order state to cancel payment.");
}
const stripeRecord = await getStripeOrderRecord(transaction, stripeRef);
const paymentIntentId = stripeRecord.paymentIntent.id;
const paymentIntent = await stripe.paymentIntents.cancel(paymentIntentId, {
idempotencyKey: `${order.id}-cancel`,
stripeAccount,
});
const updateData = {
orderRestaurantPaymentCanceledAt: admin.firestore.FieldValue.serverTimestamp(),
updatedAt: admin.firestore.Timestamp.now(),
uidPaymentCanceledBy: uid,
payment: {
stripe: "canceled",
},
};
transaction.set(orderRef, updateData, { merge: true });
transaction.set(
stripeRef,
{
paymentIntent,
},
{ merge: true }
);
Object.assign(order, updateData);
return { success: true, payment: "stripe", order };
});
if (result.order.sendSMS) {
await sendMessageToCustomer(db, lng, "msg_stripe_payment_canceled", restaurant.restaurantName, result.order, restaurantId, orderId, {}, true);
}
return { success: true, payment: "stripe" };
} catch (error) {
throw utils.process_error(error);
}
};
const getUpdateOrder = (newOrder, order, options, rawOptions) => {
const updateOrderData = {};
const updateOptions = {};
const updateRawOptions = {};
newOrder.forEach((data) => {
const { menuId, index } = data;
if (!utils.isEmpty(order[menuId]) && !utils.isEmpty(order[menuId][index])) {
if (utils.isEmpty(updateOrderData[menuId])) {
updateOrderData[menuId] = [];
updateOptions[menuId] = {};
updateRawOptions[menuId] = {};
}
updateOrderData[menuId].push(order[menuId][index]);
const optionIndex = updateOrderData[menuId].length - 1;
updateOptions[menuId][optionIndex] = options[menuId][optionIndex];
updateRawOptions[menuId][optionIndex] = rawOptions[menuId][optionIndex];
}
});
return {
updateOrderData,
updateOptions,
updateRawOptions,
};
};
export const orderChange = async (db: any, data: any, context: functions.https.CallableContext | Context) => {
const ownerUid = utils.validate_admin_auth(context);
const { restaurantId, orderId, newOrder, timezone, lng } = data;
utils.validate_params({ restaurantId, orderId, newOrder, timezone }); // lng, timeEstimated is optional
const restaurantRef = db.doc(`restaurants/${restaurantId}`);
const restaurantData = (await restaurantRef.get()).data() || {};
if (restaurantData.uid !== ownerUid) {
throw new functions.https.HttpsError("permission-denied", "The user does not have an authority to perform this operation.");
}
if (newOrder.length === 0) {
throw new functions.https.HttpsError("permission-denied", "Cannot be changed to an empty order.");
}
try {
const orderRef = db.doc(`restaurants/${restaurantId}/orders/${orderId}`);
const order = (await orderRef.get()).data();
if (!order) {
throw new functions.https.HttpsError("invalid-argument", "This order does not exist.");
}
if (!utils.isEmpty(order.orderUpdatedAt) || order.status !== order_status.order_placed) {
throw new functions.https.HttpsError("failed-precondition", "It is not possible to change the order.");
}
// generate new order
order.id = orderId;
const { updateOrderData, updateOptions, updateRawOptions } = getUpdateOrder(newOrder, order.order, order.options, order.rawOptions);
// update price
const baseData = {
order: updateOrderData,
rawOptions: updateRawOptions,
};
const { newOrderData, newItems, newPrices, food_sub_total, alcohol_sub_total } = await createNewOrderData(restaurantRef, orderRef, baseData, multiple);
const accountingResult = orderAccounting(restaurantData, food_sub_total, alcohol_sub_total, multiple);
// was created new order data
const orderUpdateData = {
order: newOrderData,
menuItems: newItems,
prices: newPrices,
options: updateOptions,
rawOptions: updateRawOptions,
sub_total: accountingResult.sub_total,
tax: accountingResult.tax,
inclusiveTax: accountingResult.inclusiveTax,
total: accountingResult.total,
totalCharge: accountingResult.total + (Number(order.tip) || 0),
accounting: {
food: {
revenue: accountingResult.food_sub_total,
tax: accountingResult.food_tax,
},
alcohol: {
revenue: accountingResult.alcohol_sub_total,
tax: accountingResult.alcohol_tax,
},
},
orderUpdatedAt: admin.firestore.Timestamp.now(),
};
if (!order.payment) {
orderRef.update(orderUpdateData);
} else {
// update stripe
await db.runTransaction(async (transaction) => {
const customerUid = order.uid;
const restaurantOwnerUid = restaurantData["uid"];
const stripeAccount = await getStripeAccount(db, restaurantOwnerUid);
const stripeRef = db.doc(`restaurants/${restaurantId}/orders/${orderId}/system/stripe`);
await getStripeOrderRecord(transaction, stripeRef);
(await transaction.get(orderRef)).data();
// get System Stripe
const payment_method_data = await getPaymentMethodData(db, restaurantOwnerUid, customerUid);
const description = `#${order.number} ${restaurantData.restaurantName} ${order.phoneNumber}`;
const request = {
setup_future_usage: "off_session",
amount: orderUpdateData.totalCharge * multiple,
description: `${description} ${orderId} orderChange`,
currency: utils.getStripeRegion().currency,
metadata: { uid: customerUid, restaurantId, orderId },
payment_method_data,
} as Stripe.PaymentIntentCreateParams;
const hash = crypto.createHash("sha256").update(JSON.stringify(newOrderData)).digest("hex");
const paymentIntent = await stripe.paymentIntents.create(request, {
idempotencyKey: orderRef.path + hash,
stripeAccount,
});
await transaction.update(orderRef, orderUpdateData);
await transaction.set(
stripeRef,
{
paymentIntent,
},
{ merge: true }
);
return {};
});
}
if (order.sendSMS) {
await sendMessageToCustomer(db, lng, "msg_order_updated", restaurantData.restaurantName, order, restaurantId, orderId, {}, true);
}
return {};
} catch (error) {
throw utils.process_error(error);
}
}; | the_stack |
import * as React from 'react';
import {
calculateDimensions,
setColGroupWidth,
getVisibleColGroup,
getScrollPosition,
throttle,
getDataItem,
} from '../utils';
import dataGridFormatter from '../functions/formatter';
import dataGridCollector from '../functions/collector';
import { IDataGrid } from '../common/@types';
import { DataGridEnums } from '../common/@enums';
export interface IDataGridStore extends IDataGrid.IStoreState {
setStoreState: IDataGrid.setStoreState;
dispatch: IDataGrid.dispatch;
}
const store: IDataGridStore = {
// 데이터 그리드 내부에서 사용하는 상태의 기본형.
sortInfo: {},
scrollLeft: 0,
scrollTop: 0,
selectionRows: {},
selectionCols: {},
focusedRow: -1,
focusedCol: -1,
selectionStartOffset: {},
selectionEndOffset: {},
selectionMinOffset: {},
selectionMaxOffset: {},
selectionSRow: -1,
selectionSCol: -1,
selectionERow: -1,
selectionECol: -1,
columnResizing: false,
columnResizerLeft: 0,
loading: false,
loadingData: false,
width: 0,
height: 0,
data: {},
dataLength: 0,
listSelectedAll: false,
colGroup: [],
asideColGroup: [],
leftHeaderColGroup: [],
headerColGroup: [],
asideHeaderData: { rows: [{ cols: [] }] },
leftHeaderData: { rows: [{ cols: [] }] },
headerData: { rows: [{ cols: [] }] },
asideBodyRowData: { rows: [{ cols: [] }] },
leftBodyRowData: { rows: [{ cols: [] }] },
bodyRowData: { rows: [{ cols: [] }] },
asideBodyGroupingData: { rows: [{ cols: [] }] },
leftBodyGroupingData: { rows: [{ cols: [] }] },
bodyGroupingData: { rows: [{ cols: [] }] },
colGroupMap: {},
bodyRowMap: {},
bodyGroupingMap: {},
options: {},
status: '',
styles: undefined,
predefinedFormatter: {},
predefinedCollector: {},
setStoreState: () => {},
dispatch: () => {},
};
const { Provider, Consumer } = React.createContext(store);
class StoreProvider extends React.Component<
IDataGrid.IStoreProps,
IDataGrid.IStoreState
> {
state = store;
static getDerivedStateFromProps(
nProps: IDataGrid.IStoreProps,
nState: IDataGrid.IStoreState,
) {
// console.log(
// 'getDerivedStateFromProps ~~',
// nProps.sortInfo !== nState.sortInfo,
// );
if (
nProps.loading === nState.loading &&
nProps.loadingData === nState.loadingData &&
nProps.data === nState.data &&
nProps.dataLength === nState.dataLength &&
nProps.selection === nState.selection &&
nProps.sortInfo === nState.sortInfo &&
nProps.width === nState.width &&
nProps.height === nState.height &&
nProps.scrollLeft === nState.scrollLeft &&
nProps.scrollTop === nState.scrollTop &&
nProps.columnHeight === nState.columnHeight &&
nProps.options === nState.options &&
nProps.status === nState.status &&
//
nProps.headerColGroup === nState.headerColGroup &&
nProps.headerTable === nState.headerTable &&
nProps.headerData === nState.headerData &&
nProps.asideHeaderData === nState.asideHeaderData &&
nProps.leftHeaderData === nState.leftHeaderData &&
//
nProps.bodyRowTable === nState.bodyRowTable &&
nProps.bodyRowData === nState.bodyRowData &&
nProps.bodyRowMap === nState.bodyRowMap &&
//
nProps.asideBodyRowData === nState.asideBodyRowData &&
nProps.leftBodyRowData === nState.leftBodyRowData &&
//
nProps.colGroup === nState.colGroup &&
nProps.colGroupMap === nState.colGroupMap &&
nProps.asideColGroup === nState.asideColGroup &&
nProps.leftHeaderColGroup === nState.leftHeaderColGroup &&
//
nProps.rootNode === nState.rootNode &&
nProps.clipBoardNode === nState.clipBoardNode &&
//
nProps.rootObject === nState.rootObject &&
nProps.onBeforeEvent === nState.onBeforeEvent &&
nProps.onScroll === nState.onScroll &&
nProps.onScrollEnd === nState.onScrollEnd &&
nProps.onChangeScrollSize === nState.onChangeScrollSize &&
nProps.onChangeSelection === nState.onChangeSelection &&
nProps.onChangeColumns === nState.onChangeColumns &&
nProps.onSelect === nState.onSelect &&
nProps.onRightClick === nState.onRightClick &&
nProps.onClick === nState.onClick &&
nProps.onError === nState.onError &&
nProps.onSort === nState.onSort &&
nProps.onEdit === nState.onEdit
) {
return null;
} else {
// store state | 현재 state복제
const { options = {} } = nProps;
const { frozenColumnIndex = 0 } = options; // 옵션은 외부에서 받은 값을 사용하고 state에서 값을 수정하면 안됨.
const storeState: IDataGrid.IStoreState = {
...nState,
};
// scrollTop prop 저장
storeState.pScrollTop = nProps.scrollTop;
storeState.pScrollLeft = nProps.scrollLeft;
storeState.loading = nProps.loading;
storeState.loadingData = nProps.loadingData;
storeState.width = nProps.width;
storeState.height = nProps.height;
// storeState.selection = nProps.selection;
storeState.pSortInfo = nProps.sortInfo;
storeState.options = nProps.options;
storeState.status = nProps.status;
storeState.rootNode = nProps.rootNode;
storeState.clipBoardNode = nProps.clipBoardNode;
storeState.rootObject = nProps.rootObject;
storeState.onBeforeEvent = nProps.onBeforeEvent;
storeState.onScroll = nProps.onScroll;
storeState.onScrollEnd = nProps.onScrollEnd;
storeState.onChangeScrollSize = nProps.onChangeScrollSize;
storeState.onChangeSelection = nProps.onChangeSelection;
storeState.onChangeColumns = nProps.onChangeColumns;
storeState.onSelect = nProps.onSelect;
storeState.onRightClick = nProps.onRightClick;
storeState.onClick = nProps.onClick;
storeState.onError = nProps.onError;
storeState.onSort = nProps.onSort;
storeState.onEdit = nProps.onEdit;
///
storeState.headerTable = nProps.headerTable;
storeState.bodyRowTable = nProps.bodyRowTable;
storeState.bodyRowMap = nProps.bodyRowMap;
storeState.asideHeaderData = nProps.asideHeaderData;
storeState.leftHeaderData = nProps.leftHeaderData;
storeState.headerData = nProps.headerData;
storeState.asideBodyRowData = nProps.asideBodyRowData;
storeState.leftBodyRowData = nProps.leftBodyRowData;
storeState.bodyRowData = nProps.bodyRowData;
storeState.colGroupMap = nProps.colGroupMap;
storeState.asideColGroup = nProps.asideColGroup;
storeState.autofitColGroup = nProps.autofitColGroup;
storeState.colGroup = nProps.colGroup;
storeState.footSumColumns = nProps.footSumColumns;
storeState.footSumTable = nProps.footSumTable;
storeState.leftFootSumData = nProps.leftFootSumData;
storeState.footSumData = nProps.footSumData;
const { frozenColumnIndex: PfrozenColumnIndex = 0 } =
storeState.options || {};
const changed = {
colGroup: false,
frozenColumnIndex: false,
styles: false,
visibleColGroup: false,
data: false,
};
// 다른 조건식 안에서 변경하여 처리할 수 있는 변수들 언더바(_)로 시작함.
let {
colGroup: _colGroup = [],
leftHeaderColGroup: _leftHeaderColGroup,
headerColGroup: _headerColGroup,
styles: _styles,
scrollLeft: _scrollLeft = 0,
scrollTop: _scrollTop = 0,
} = storeState;
// colGroup들의 너비합을 모르거나 변경된 경우.
// colGroup > width 연산
if (
nProps.colGroup !== nState.colGroup ||
nProps.options !== nState.options
) {
_colGroup = setColGroupWidth(
nProps.colGroup || [],
{ width: nProps.width || 0 },
nProps.options,
);
changed.colGroup = true;
}
if (changed.colGroup || frozenColumnIndex !== PfrozenColumnIndex) {
_leftHeaderColGroup = _colGroup.slice(0, frozenColumnIndex);
_headerColGroup = _colGroup.slice(frozenColumnIndex);
changed.frozenColumnIndex = true;
}
// case of change datalength
if (
nProps.data !== nState.data ||
nProps.dataLength !== nState.dataLength
) {
changed.data = true;
storeState.data = nProps.data;
storeState.dataLength = storeState.dataLength = nProps.dataLength;
// listSelectedAll is false when data empty
if (storeState.data && storeState.dataLength === 0) {
storeState.listSelectedAll = false;
}
}
if (
changed.data ||
changed.colGroup ||
changed.frozenColumnIndex ||
!storeState.styles ||
nProps.width !== nState.width ||
nProps.height !== nState.height
) {
// 스타일 초기화 안되어 있거나 크기를 다시 결정해야 하는 경우.
storeState.scrollTop = nProps.scrollTop;
storeState.scrollLeft = nProps.scrollLeft;
const dimensions = calculateDimensions(storeState, {
headerTable: nProps.headerTable,
colGroup: _colGroup,
headerColGroup: _headerColGroup,
bodyRowTable: nProps.bodyRowTable,
footSumColumns: nProps.footSumColumns,
dataLength: nProps.dataLength,
options: nProps.options,
});
_styles = dimensions.styles;
_scrollTop = dimensions.scrollTop;
_scrollLeft = dimensions.scrollLeft;
changed.styles = true;
}
if (changed.styles) {
const {
scrollContentWidth = 0,
scrollContentHeight = 0,
scrollContentContainerWidth = 0,
scrollContentContainerHeight = 0,
} = _styles || {};
const {
scrollTop: currScrollTop = 0,
scrollLeft: currScrollLeft = 0,
} = getScrollPosition(_scrollLeft || 0, _scrollTop || 0, {
scrollWidth: scrollContentWidth,
scrollHeight: scrollContentHeight,
clientWidth: scrollContentContainerWidth,
clientHeight: scrollContentContainerHeight,
});
_scrollTop = currScrollTop;
_scrollLeft = currScrollLeft;
}
let currScrollLeft, currScrollTop;
if (
nProps.scrollTop !== nState.pScrollTop ||
nProps.scrollLeft !== nState.pScrollLeft
) {
const {
scrollContentWidth = 0,
scrollContentHeight = 0,
scrollContentContainerWidth = 0,
scrollContentContainerHeight = 0,
} = _styles || {};
let {
scrollLeft: _currScrollLeft = 0,
scrollTop: _currScrollTop = 0,
} = getScrollPosition(nProps.scrollLeft || 0, nProps.scrollTop || 0, {
scrollWidth: scrollContentWidth,
scrollHeight: scrollContentHeight,
clientWidth: scrollContentContainerWidth,
clientHeight: scrollContentContainerHeight,
});
currScrollLeft = _currScrollLeft;
currScrollTop = _currScrollTop;
}
if (
typeof currScrollTop !== 'undefined' &&
nProps.scrollTop !== nState.pScrollTop
) {
_scrollTop = currScrollTop;
}
if (
typeof currScrollLeft !== 'undefined' &&
nProps.scrollLeft !== nState.pScrollLeft
) {
_scrollLeft = currScrollLeft;
}
if (nProps.selection !== nState.selection) {
storeState.selection = nProps.selection;
const {
rows = [],
cols = [],
focusedRow = -1,
focusedCol = -1,
isEditing = false,
} = nProps.selection || {};
storeState.selectionRows = {};
storeState.selectionCols = {};
storeState.selectionSCol = cols[0];
storeState.selectionECol = cols[cols.length - 1];
storeState.selectionSRow = rows[0];
storeState.selectionERow = rows[rows.length - 1];
rows.forEach(n => {
storeState.selectionRows![n] = true;
});
cols.forEach(n => {
storeState.selectionCols![n] = true;
});
storeState.focusedRow = focusedRow;
storeState.focusedCol = focusedCol;
// 에디팅이면 인라인 에디팅 상태추가.
if (isEditing) {
storeState.isInlineEditing = true;
storeState.inlineEditingCell = {
rowIndex: focusedRow,
colIndex: focusedCol,
};
}
}
// if (
// storeState.data &&
// nProps.selectedIndexes !== nState.selectedIndexes
// ) {
// Object.keys(storeState.data).forEach(k => {
// if (storeState.data) {
// storeState.data[k].selected = false;
// }
// });
// if (nProps.selectedIndexes) {
// nProps.selectedIndexes.forEach(
// idx => (storeState.data![idx].selected = true),
// );
// }
// }
if (nProps.sortInfo !== nState.pSortInfo) {
// changed sortInfo
storeState.sortInfo = nProps.sortInfo;
}
// 스타일 정의가 되어 있지 않은 경우 : 그리드가 한번도 그려진 적이 없는 상태.
if (
changed.colGroup ||
changed.frozenColumnIndex ||
!storeState.styles ||
nProps.width !== nState.width
) {
const visibleData = getVisibleColGroup(_headerColGroup, {
scrollLeft: _scrollLeft,
bodyRowData: storeState.bodyRowData,
footSumData: storeState.footSumData,
styles: _styles,
options: storeState.options,
});
storeState.visibleHeaderColGroup = visibleData.visibleHeaderColGroup;
storeState.visibleBodyRowData = visibleData.visibleBodyRowData;
storeState.visibleFootSumData = visibleData.visibleFootSumData;
storeState.printStartColIndex = visibleData.printStartColIndex;
storeState.printEndColIndex = visibleData.printEndColIndex;
changed.colGroup = true;
}
// 언더바로 시작하는 변수를 상태에 전달하기 위해 주입.
storeState.colGroup = _colGroup;
storeState.leftHeaderColGroup = _leftHeaderColGroup;
storeState.headerColGroup = _headerColGroup;
storeState.styles = _styles;
storeState.scrollLeft = _scrollLeft;
storeState.scrollTop = _scrollTop;
return storeState;
}
}
// state 가 업데이트 되기 전.
setStoreState = (newState: IDataGrid.IStoreState, callback?: () => void) => {
const {
scrollLeft = 0,
scrollTop = 0,
options = {},
styles = {},
headerColGroup = [],
bodyRowData = { rows: [{ cols: [] }] },
footSumData = { rows: [{ cols: [] }] },
onScrollEnd,
} = this.state;
const { scrollLeft: _scrollLeft, scrollTop: _scrollTop } = newState;
if (!newState.styles) {
newState.styles = { ...styles };
}
if (
typeof _scrollLeft !== 'undefined' ||
typeof _scrollTop !== 'undefined'
) {
const {
scrollContentWidth: scrollWidth = 0,
scrollContentHeight: scrollHeight = 0,
scrollContentContainerWidth: clientWidth = 0,
scrollContentContainerHeight: clientHeight = 0,
} = newState.styles;
let endOfScrollTop: boolean = false;
let endOfScrollLeft: boolean = false;
if (typeof _scrollLeft !== 'undefined') {
if (scrollLeft !== _scrollLeft) {
const visibleData = getVisibleColGroup(headerColGroup, {
scrollLeft: _scrollLeft,
bodyRowData: bodyRowData,
footSumData: footSumData,
styles: newState.styles,
options: options,
});
newState.visibleHeaderColGroup = visibleData.visibleHeaderColGroup;
newState.visibleBodyRowData = visibleData.visibleBodyRowData;
newState.visibleFootSumData = visibleData.visibleFootSumData;
newState.printStartColIndex = visibleData.printStartColIndex;
newState.printEndColIndex = visibleData.printEndColIndex;
if (clientWidth >= scrollWidth + _scrollLeft) {
endOfScrollLeft = true;
}
}
}
if (typeof _scrollTop !== 'undefined' && _scrollTop !== scrollTop) {
if (clientHeight >= scrollHeight + _scrollTop) {
endOfScrollTop = true;
}
}
if ((endOfScrollTop || endOfScrollLeft) && onScrollEnd) {
onScrollEnd({
endOfScrollTop,
endOfScrollLeft,
});
}
}
this.setState(newState, callback);
};
dispatch = (
dispatchType: DataGridEnums.DispatchTypes,
param: IDataGrid.DispatchParam,
) => {
const {
data = {},
dataLength = 0,
listSelectedAll = false,
colGroup = [],
rootNode,
focusedRow = -1,
sortInfo = {},
selectionSRow,
selectionSCol,
selectionERow,
selectionECol,
onSelect,
onSort,
onEdit,
onChangeColumns,
} = this.state;
const {
rowIndex,
col,
colIndex,
checked,
row,
value,
eventWhichKey,
keepEditing = false,
newWidth,
isInlineEditing,
inlineEditingCell,
newFocusedRow,
newFocusedCol,
scrollLeft,
} = param;
let selectedAll: boolean = listSelectedAll;
switch (dispatchType) {
case DataGridEnums.DispatchTypes.FILTER:
{
// const { colIndex, filterInfo } = param;
// const checkAll =
// filterInfo[colIndex] === false
// ? true
// : filterInfo[colIndex]._check_all_;
// if (checkAll) {
// filteredList =
// data &&
// data.filter((n: any) => {
// return (
// typeof n === 'undefined' ||
// !n[optionColumnKeys.deleted || '_deleted_']
// );
// });
// } else {
// filteredList = data.filter((n: any) => {
// if (n) {
// const value = n && n[colGroup[colIndex].key || ''];
// if (
// typeof n === 'undefined' ||
// n[optionColumnKeys.deleted || '_deleted_']
// ) {
// return false;
// }
// if (typeof value === 'undefined') {
// if (!filterInfo[colIndex]._UNDEFINED_) {
// return false;
// }
// } else {
// if (!filterInfo[colIndex][value]) {
// return false;
// }
// }
// return true;
// }
// return false;
// });
// }
// this.setStoreState({
// filteredList,
// filterInfo,
// scrollTop: 0,
// });
// if (onSelect) {
// onSelect({
// filteredList,
// });
// }
}
break;
case DataGridEnums.DispatchTypes.SORT:
{
if (typeof colIndex === 'undefined') {
return;
}
const { key: colKey = '' } = colGroup[colIndex];
let currentSortInfo: {
[key: string]: IDataGrid.ISortInfo;
} = {};
let seq: number = 0;
let sortInfos: IDataGrid.ISortInfo[] = [];
for (let k in sortInfo) {
if (sortInfo[k]) {
currentSortInfo[k] = sortInfo[k];
seq++;
}
}
if (currentSortInfo[colKey]) {
if (currentSortInfo[colKey].orderBy === 'desc') {
currentSortInfo[colKey].orderBy = 'asc';
} else if (currentSortInfo[colKey].orderBy === 'asc') {
delete currentSortInfo[colKey];
}
} else {
currentSortInfo[colKey] = {
seq: seq++,
orderBy: 'desc',
};
}
for (let k in currentSortInfo) {
if (currentSortInfo[k]) {
sortInfos[currentSortInfo[k].seq!] = {
key: k,
orderBy: currentSortInfo[k].orderBy,
};
}
}
sortInfos = sortInfos.filter(o => typeof o !== 'undefined');
if (onSort) {
onSort({
sortInfos,
});
}
}
break;
case DataGridEnums.DispatchTypes.UPDATE:
case DataGridEnums.DispatchTypes.UPDATE_ITEM:
let focusRow: number = focusedRow;
if (eventWhichKey) {
switch (eventWhichKey) {
case DataGridEnums.KeyCodes.UP_ARROW:
focusRow = focusedRow < 1 ? 0 : focusedRow - 1;
break;
case DataGridEnums.KeyCodes.DOWN_ARROW:
focusRow =
focusedRow + 1 >= dataLength ? dataLength - 1 : focusedRow + 1;
break;
default:
break;
}
}
// console.log('update datagrid', keepEditing);
if (!keepEditing) {
const newState: IDataGrid.IStoreState = {
isInlineEditing: false,
inlineEditingCell: {},
selectionRows: {
[focusRow]: true,
},
focusedRow: focusRow,
};
this.setStoreState(newState);
} else if (inlineEditingCell) {
const newState: IDataGrid.IStoreState = {
isInlineEditing,
inlineEditingCell,
};
if (newFocusedRow !== undefined) {
newState.focusedRow = newFocusedRow;
newState.focusedCol = newFocusedCol;
newState.selectionRows = { [newFocusedRow]: true };
newState.selectionCols = { [newFocusedCol]: true };
}
if (scrollLeft !== undefined) {
newState.scrollLeft = scrollLeft;
}
this.setStoreState(newState);
}
if (onEdit && value !== undefined) {
onEdit({
li: row,
col,
colIndex,
value,
checked,
eventWhichKey,
keepEditing,
});
}
if (keepEditing) {
this.dispatch(DataGridEnums.DispatchTypes.FOCUS_ROOT, {});
}
break;
case DataGridEnums.DispatchTypes.RESIZE_COL:
let _colGroup = [...(this.state.colGroup || [])];
_colGroup[col.colIndex]._width = _colGroup[
col.colIndex
].width = newWidth;
this.setStoreState({
colGroup: _colGroup,
columnResizing: false,
});
if (onChangeColumns) {
onChangeColumns({
colGroup: _colGroup,
});
}
break;
case DataGridEnums.DispatchTypes.SELECT:
let rowSelected: boolean = false;
const item = getDataItem(data, rowIndex);
if (checked === true) {
rowSelected = true;
} else if (checked === false) {
rowSelected = false;
} else {
rowSelected = !(item && item.selected);
}
if (!rowSelected) {
selectedAll = false;
}
if (onSelect) {
try {
onSelect({
li: rowIndex,
selected: rowSelected,
});
this.setStoreState({
listSelectedAll: selectedAll,
});
} catch (e) {}
}
break;
case DataGridEnums.DispatchTypes.SELECT_ALL:
if (checked === true) {
selectedAll = true;
} else if (checked === false) {
selectedAll = false;
} else {
selectedAll = !selectedAll;
}
if (onSelect) {
try {
onSelect({
selectedAll,
});
this.setStoreState({
listSelectedAll: selectedAll,
});
} catch (e) {}
}
break;
case DataGridEnums.DispatchTypes.CHANGE_SELECTION:
const { sRow, sCol, eRow, eCol } = param;
if (
selectionSRow !== sRow ||
selectionSCol !== sCol ||
selectionERow !== eRow ||
selectionECol !== eCol
) {
this.setStoreState({
selectionSRow: sRow,
selectionSCol: sCol,
selectionERow: eRow,
selectionECol: eCol,
});
}
break;
case DataGridEnums.DispatchTypes.FOCUS_ROOT:
if (rootNode && rootNode.current) {
rootNode.current.focus();
}
if (inlineEditingCell) {
this.setStoreState({
isInlineEditing,
inlineEditingCell,
});
}
break;
default:
break;
}
};
componentDidMount() {
// console.log('store did mount');
}
// tslint:disable-next-line: member-ordering
lazyComponentDidUpdate = throttle((pState: IDataGrid.IStoreState) => {}, 0, {
trailing: true,
});
componentDidUpdate(
pProps: IDataGrid.IStoreProps,
pState: IDataGrid.IStoreState,
) {
// this.lazyComponentDidUpdate(pState);
const { onScroll } = this.props;
const {
scrollLeft = 0,
scrollTop = 0,
options: { frozenRowIndex = 0 } = {},
styles: {
scrollContentContainerHeight = 0,
scrollContentHeight = 0,
scrollContentContainerWidth = 0,
scrollContentWidth = 0,
bodyTrHeight = 0,
bodyHeight = 0,
} = {},
onChangeSelection,
} = this.state;
// detect change scrollContent
if (pState.styles) {
const {
scrollContentHeight: _scrollContentHeight,
scrollContentWidth: _scrollContentWidth,
} = pState.styles;
if (
scrollContentHeight !== _scrollContentHeight ||
scrollContentWidth !== _scrollContentWidth
) {
this.props.onChangeScrollSize &&
this.props.onChangeScrollSize({
scrollContentContainerHeight,
scrollContentHeight,
scrollContentContainerWidth,
scrollContentWidth,
bodyTrHeight,
});
}
}
// detect change scrollTop
if (
onScroll &&
(pState.scrollTop !== this.state.scrollTop ||
pState.scrollLeft !== this.state.scrollLeft)
) {
const sRowIndex =
Math.floor(-scrollTop / (bodyTrHeight || 1)) + frozenRowIndex;
const eRowIndex =
sRowIndex + Math.ceil(bodyHeight / (bodyTrHeight || 1)) + 1;
onScroll({
scrollLeft: Number(scrollLeft),
scrollTop: Number(scrollTop),
sRowIndex,
eRowIndex,
});
}
// detect change selection
if (
onChangeSelection &&
(pState.focusedRow !== this.state.focusedRow ||
pState.focusedCol !== this.state.focusedCol ||
pState.selectionSRow !== this.state.selectionSRow ||
pState.selectionERow !== this.state.selectionERow ||
pState.selectionSCol !== this.state.selectionSCol ||
pState.selectionECol !== this.state.selectionECol)
) {
const {
selectionRows = [],
selectionCols = [],
focusedRow = -1,
focusedCol = -1,
} = this.state;
const sRowIndex =
Math.floor(-scrollTop / (bodyTrHeight || 1)) + frozenRowIndex;
const eRowIndex =
sRowIndex + Math.ceil(bodyHeight / (bodyTrHeight || 1)) + 1;
onChangeSelection({
rows: Object.keys(selectionRows).map(n => Number(n)),
cols: Object.keys(selectionCols).map(n => Number(n)),
focusedRow,
focusedCol,
scrollLeft: Number(scrollLeft),
scrollTop: Number(scrollTop),
sRowIndex,
eRowIndex,
});
}
}
componentWillUnmount() {
// console.log('store unMount');
}
render() {
return (
<Provider
value={{
...this.state,
...{
predefinedFormatter: { ...dataGridFormatter },
predefinedCollector: { ...dataGridCollector },
setStoreState: this.setStoreState,
dispatch: this.dispatch,
},
}}
>
{this.props.children}
</Provider>
);
}
}
export default { Provider: StoreProvider, Consumer }; | the_stack |
import * as fc from 'fast-check'
import { Applicative, Applicative1, Applicative2, Applicative2C, Applicative3 } from 'fp-ts/lib/Applicative'
import { Apply, Apply1, Apply2, Apply2C, Apply3 } from 'fp-ts/lib/Apply'
import { Eq, eqBoolean, eqNumber, eqString } from 'fp-ts/lib/Eq'
import { Field } from 'fp-ts/lib/Field'
import { Functor, Functor1, Functor2, Functor2C, Functor3 } from 'fp-ts/lib/Functor'
import { HKT, Kind, Kind2, Kind3, URIS, URIS2, URIS3 } from 'fp-ts/lib/HKT'
import { Monad, Monad1, Monad2, Monad2C, Monad3 } from 'fp-ts/lib/Monad'
import { Monoid } from 'fp-ts/lib/Monoid'
import { Ord } from 'fp-ts/lib/Ord'
import { Ring } from 'fp-ts/lib/Ring'
import { Semigroup } from 'fp-ts/lib/Semigroup'
import { Semiring } from 'fp-ts/lib/Semiring'
import * as laws from './laws'
/**
* Tests the `Eq` laws
*
* @since 0.0.1
*/
export const eq = <A>(E: Eq<A>, arb: fc.Arbitrary<A>): void => {
const reflexivity = fc.property(arb, laws.eq.reflexivity(E))
const symmetry = fc.property(arb, arb, laws.eq.simmetry(E))
const transitivity = fc.property(arb, arb, arb, laws.eq.transitivity(E))
fc.assert(reflexivity)
fc.assert(symmetry)
fc.assert(transitivity)
}
/**
* Tests the `Ord` laws
*
* @since 0.0.1
*/
export const ord = <A>(O: Ord<A>, arb: fc.Arbitrary<A>): void => {
eq(O, arb)
const totality = fc.property(arb, arb, laws.ord.totality(O))
const reflexivity = fc.property(arb, laws.ord.reflexivity(O))
const antisymmetry = fc.property(arb, arb, laws.ord.antisimmetry(O))
const transitivity = fc.property(arb, arb, arb, laws.ord.transitivity(O))
fc.assert(totality)
fc.assert(reflexivity)
fc.assert(antisymmetry)
fc.assert(transitivity)
}
/**
* Tests the `Semigroup` laws
*
* @example
* import * as laws from 'fp-ts-laws'
* import * as fc from 'fast-check'
* import { Semigroup } from 'fp-ts/lib/Semigroup'
* import { eqString } from 'fp-ts/lib/Eq'
*
* const semigroupSpace: Semigroup<string> = {
* concat: (x, y) => x + ' ' + y
* }
* laws.semigroup(semigroupSpace, eqString, fc.string())
*
* @since 0.0.1
*/
export const semigroup = <A>(S: Semigroup<A>, E: Eq<A>, arb: fc.Arbitrary<A>): void => {
const associativity = fc.property(arb, arb, arb, laws.semigroup.associativity(S, E))
fc.assert(associativity)
}
/**
* Tests the `Monoid` laws
*
* @since 0.0.1
*/
export const monoid = <A>(M: Monoid<A>, E: Eq<A>, arb: fc.Arbitrary<A>): void => {
semigroup(M, E, arb)
const rightIdentity = fc.property(arb, laws.monoid.rightIdentity(M, E))
const leftIdentity = fc.property(arb, laws.monoid.leftIdentity(M, E))
fc.assert(rightIdentity)
fc.assert(leftIdentity)
}
/**
* Tests the `Semiring` laws
*
* @since 0.0.1
*/
export const semiring = <A>(S: Semiring<A>, E: Eq<A>, arb: fc.Arbitrary<A>, seed?: number): void => {
const addAssociativity = fc.property(arb, arb, arb, laws.semiring.addAssociativity(S, E))
const addIdentity = fc.property(arb, laws.semiring.addIdentity(S, E))
const commutativity = fc.property(arb, arb, laws.semiring.commutativity(S, E))
const mulAssociativity = fc.property(arb, arb, arb, laws.semiring.mulAssociativity(S, E))
const mulIdentity = fc.property(arb, laws.semiring.mulIdentity(S, E))
const leftDistributivity = fc.property(arb, arb, arb, laws.semiring.leftDistributivity(S, E))
const rightDistributivity = fc.property(arb, arb, arb, laws.semiring.rightDistributivity(S, E))
const annihilation = fc.property(arb, laws.semiring.annihilation(S, E))
fc.assert(addAssociativity, { seed })
fc.assert(addIdentity, { seed })
fc.assert(commutativity, { seed })
fc.assert(mulAssociativity, { seed })
fc.assert(mulIdentity, { seed })
fc.assert(leftDistributivity, { seed })
fc.assert(rightDistributivity, { seed })
fc.assert(annihilation, { seed })
}
/**
* Tests the `Ring` laws
*
* @since 0.0.1
*/
export const ring = <A>(R: Ring<A>, S: Eq<A>, arb: fc.Arbitrary<A>, seed?: number): void => {
semiring(R, S, arb, seed)
const additiveInverse = fc.property(arb, laws.ring.additiveInverse(R, S))
fc.assert(additiveInverse)
}
/**
* Tests the `Field` laws
*
* @since 0.0.1
*/
export const field = <A>(F: Field<A>, S: Eq<A>, arb: fc.Arbitrary<A>, seed?: number): void => {
ring(F, S, arb, seed)
if (S.equals(F.zero, F.one)) {
throw new Error(`one should not be equal to zero`)
}
const commutativity = fc.property(arb, arb, laws.field.commutativity(F, S))
const integralDomain = fc.property(arb, arb, laws.field.integralDomain(F, S))
const nonNegativity = fc.property(arb, laws.field.nonNegativity(F, S))
const quotient = fc.property(arb, arb, laws.field.quotient(F, S))
const reminder = fc.property(arb, arb, laws.field.reminder(F, S))
const submultiplicative = fc.property(arb, arb, laws.field.submultiplicative(F, S))
const inverse = fc.property(arb, laws.field.inverse(F, S))
fc.assert(commutativity, { seed })
fc.assert(integralDomain, { seed })
fc.assert(nonNegativity, { seed })
fc.assert(quotient, { seed })
fc.assert(reminder, { seed })
fc.assert(submultiplicative, { seed })
fc.assert(inverse, { seed })
}
/**
* Tests the `Functor` laws
*
* @since 0.1.0
*/
export function functor<F extends URIS3>(
F: Functor3<F>
): <U, L>(
lift: <A>(a: fc.Arbitrary<A>) => fc.Arbitrary<Kind3<F, U, L, A>>,
liftEq: <A>(Sa: Eq<A>) => Eq<Kind3<F, U, L, A>>
) => void
export function functor<F extends URIS2>(
F: Functor2<F>
): <L>(
lift: <A>(a: fc.Arbitrary<A>) => fc.Arbitrary<Kind2<F, L, A>>,
liftEq: <A>(Sa: Eq<A>) => Eq<Kind2<F, L, A>>
) => void
export function functor<F extends URIS2, L>(
F: Functor2C<F, L>
): (lift: <A>(a: fc.Arbitrary<A>) => fc.Arbitrary<Kind2<F, L, A>>, liftEq: <A>(Sa: Eq<A>) => Eq<Kind2<F, L, A>>) => void
export function functor<F extends URIS>(
F: Functor1<F>
): (lift: <A>(a: fc.Arbitrary<A>) => fc.Arbitrary<Kind<F, A>>, liftEq: <A>(Sa: Eq<A>) => Eq<Kind<F, A>>) => void
export function functor<F>(
F: Functor<F>
): (lift: <A>(a: fc.Arbitrary<A>) => fc.Arbitrary<HKT<F, A>>, liftEq: <A>(Sa: Eq<A>) => Eq<HKT<F, A>>) => void
export function functor<F>(
F: Functor<F>
): (lift: <A>(a: fc.Arbitrary<A>) => fc.Arbitrary<HKT<F, A>>, liftEq: <A>(Sa: Eq<A>) => Eq<HKT<F, A>>) => void {
return (lift, liftEq) => {
const arb = lift(fc.string())
const Sa = liftEq(eqString)
const Sc = liftEq(eqNumber)
const identity = fc.property(arb, laws.functor.identity(F, Sa))
const ab = (s: string): number | undefined | null => (s.length === 1 ? undefined : s.length === 2 ? null : s.length)
const bc = (n: number | undefined | null): number => (n === undefined ? 1 : n === null ? 2 : n * 2)
const composition = fc.property(arb, laws.functor.composition(F, Sc, ab, bc))
fc.assert(identity)
fc.assert(composition)
}
}
/**
* Tests the `Apply` laws
*
* @since 0.1.0
*/
export function apply<F extends URIS3>(
F: Apply3<F>
): <U, L>(
lift: <A>(a: fc.Arbitrary<A>) => fc.Arbitrary<Kind3<F, U, L, A>>,
liftEq: <A>(Sa: Eq<A>) => Eq<Kind3<F, U, L, A>>
) => void
export function apply<F extends URIS2>(
F: Apply2<F>
): <L>(
lift: <A>(a: fc.Arbitrary<A>) => fc.Arbitrary<Kind2<F, L, A>>,
liftEq: <A>(Sa: Eq<A>) => Eq<Kind2<F, L, A>>
) => void
export function apply<F extends URIS2, L>(
F: Apply2C<F, L>
): (lift: <A>(a: fc.Arbitrary<A>) => fc.Arbitrary<Kind2<F, L, A>>, liftEq: <A>(Sa: Eq<A>) => Eq<Kind2<F, L, A>>) => void
export function apply<F extends URIS>(
F: Apply1<F>
): (lift: <A>(a: fc.Arbitrary<A>) => fc.Arbitrary<Kind<F, A>>, liftEq: <A>(Sa: Eq<A>) => Eq<Kind<F, A>>) => void
export function apply<F>(
F: Apply<F>
): (lift: <A>(a: fc.Arbitrary<A>) => fc.Arbitrary<HKT<F, A>>, liftEq: <A>(Sa: Eq<A>) => Eq<HKT<F, A>>) => void
export function apply<F>(
F: Apply<F>
): (lift: <A>(a: fc.Arbitrary<A>) => fc.Arbitrary<HKT<F, A>>, liftEq: <A>(Sa: Eq<A>) => Eq<HKT<F, A>>) => void {
const functorF = functor(F)
return (lift, liftEq) => {
functorF(lift, liftEq)
const Sc = liftEq(eqBoolean)
const arbFa = lift(fc.string())
const arbFab = lift(fc.constant((a: string) => a.length))
const arbFbc = lift(fc.constant((b: number) => b > 2))
const associativeComposition = fc.property(arbFa, arbFab, arbFbc, laws.apply.associativeComposition(F, Sc))
fc.assert(associativeComposition)
}
}
/**
* Tests the `Applicative` laws
*
* @since 0.1.0
*/
export function applicative<F extends URIS3>(
F: Applicative3<F>
): <U, L>(
lift: <A>(a: fc.Arbitrary<A>) => fc.Arbitrary<Kind3<F, U, L, A>>,
liftEq: <A>(Sa: Eq<A>) => Eq<Kind3<F, U, L, A>>
) => void
export function applicative<F extends URIS2>(
F: Applicative2<F>
): <L>(
lift: <A>(a: fc.Arbitrary<A>) => fc.Arbitrary<Kind2<F, L, A>>,
liftEq: <A>(Sa: Eq<A>) => Eq<Kind2<F, L, A>>
) => void
export function applicative<F extends URIS2, L>(
F: Applicative2C<F, L>
): (lift: <A>(a: fc.Arbitrary<A>) => fc.Arbitrary<Kind2<F, L, A>>, liftEq: <A>(Sa: Eq<A>) => Eq<Kind2<F, L, A>>) => void
export function applicative<F extends URIS>(
F: Applicative1<F>
): (lift: <A>(a: fc.Arbitrary<A>) => fc.Arbitrary<Kind<F, A>>, liftEq: <A>(Sa: Eq<A>) => Eq<Kind<F, A>>) => void
export function applicative<F>(
F: Applicative<F>
): (lift: <A>(a: fc.Arbitrary<A>) => fc.Arbitrary<HKT<F, A>>, liftEq: <A>(Sa: Eq<A>) => Eq<HKT<F, A>>) => void
export function applicative<F>(
F: Applicative<F>
): (lift: <A>(a: fc.Arbitrary<A>) => fc.Arbitrary<HKT<F, A>>, liftEq: <A>(Sa: Eq<A>) => Eq<HKT<F, A>>) => void {
const applyF = apply(F)
return (lift, liftEq) => {
applyF(lift, liftEq)
const arbFa = lift(fc.string())
const Sa = liftEq(eqString)
const Sb = liftEq(eqNumber)
const identity = fc.property(arbFa, laws.applicative.identity(F, Sa))
const ab = (s: string) => s.length
const homomorphism = fc.property(fc.string(), laws.applicative.homomorphism(F, Sb, ab))
const arbFab = lift(fc.constant(ab))
const interchange = fc.property(fc.string(), arbFab, laws.applicative.interchange(F, Sb))
const derivedMap = fc.property(arbFa, laws.applicative.derivedMap(F, Sb, ab))
fc.assert(identity)
fc.assert(homomorphism)
fc.assert(interchange)
fc.assert(derivedMap)
}
}
/**
* Tests the `Monad` laws
*
* @since 0.1.0
*/
export function monad<M extends URIS3>(M: Monad3<M>): <U, L>(liftEq: <A>(Sa: Eq<A>) => Eq<Kind3<M, U, L, A>>) => void
export function monad<M extends URIS2>(M: Monad2<M>): <L>(liftEq: <A>(Sa: Eq<A>) => Eq<Kind2<M, L, A>>) => void
export function monad<M extends URIS2, L>(M: Monad2C<M, L>): (liftEq: <A>(Sa: Eq<A>) => Eq<Kind2<M, L, A>>) => void
export function monad<M extends URIS>(M: Monad1<M>): (liftEq: <A>(Sa: Eq<A>) => Eq<Kind<M, A>>) => void
export function monad<M>(M: Monad<M>): (liftEq: <A>(Sa: Eq<A>) => Eq<HKT<M, A>>) => void
export function monad<M>(M: Monad<M>): (liftEq: <A>(Sa: Eq<A>) => Eq<HKT<M, A>>) => void {
const applicativeM = applicative(M)
return liftEq => {
applicativeM(arb => arb.map(M.of), liftEq)
const Sc = liftEq(eqBoolean)
const arbFa = fc.string().map(M.of)
const afb = (s: string) => M.of(s.length)
const bfc = (n: number) => M.of(n > 2)
const associativity = fc.property(arbFa, laws.chain.associativity(M, Sc, afb, bfc))
const Sb = liftEq(eqNumber)
const fab = M.of((a: string) => a.length)
const derivedAp = fc.property(arbFa, laws.chain.derivedAp(M, Sb, fab))
fc.assert(associativity)
fc.assert(derivedAp)
const arb = fc.string().map(M.of)
const Sa = liftEq(eqString)
const leftIdentity = fc.property(fc.string(), laws.monad.leftIdentity(M, Sb, afb))
const rightIdentity = fc.property(arb, laws.monad.rightIdentity(M, Sa))
const ab = (s: string) => s.length
const derivedMap = fc.property(arb, laws.monad.derivedMap(M, Sb, ab))
fc.assert(leftIdentity)
fc.assert(rightIdentity)
fc.assert(derivedMap)
}
} | the_stack |
import { doc } from "../dom/shortcuts";
import { OpState } from "../vdom/state";
import { withSchedulerTick } from "../scheduler";
import { EventHandlerNode, EventHandlerFlags } from "./event_handler";
import { DispatchTarget, dispatchEvent } from "./dispatch";
import { EVENT_CAPTURE_ACTIVE_OPTIONS } from "./utils";
export interface NativeEventSource<E extends Event> {
next: (event: E) => void;
}
export type NativeEventHandler<E extends Event> = (event: E, currentTarget: OpState, src: {}) => number | void;
const dispatchNativeEvent = (event: Event, currentTarget: DispatchTarget<NativeEventHandler<Event>>, src: {}) => (
currentTarget.h.h(event, currentTarget.t, src)
);
/**
* Creates a native event source.
*
* @typeparam E Native event type.
* @param flags See {@link NativeEventSourceFlags} for details.
* @param name Event name
* @param options Event handler options
* @returns {@link NativeEventSource} instance
*/
export function createNativeEventSource<E extends Event>(
name: string,
options: { capture?: boolean; passive?: boolean } | boolean = true,
): NativeEventSource<E> {
const source = {
next: (event: Event): void => {
dispatchEvent(source, event.target as Element, event);
},
};
doc.addEventListener(name, withSchedulerTick((event) => { source.next(event); }), options);
return source;
}
export function addNativeEventMiddleware<E extends Event>(
source: NativeEventSource<E>,
fn: (event: E, next: (event: E) => void) => void,
): void {
const next = source.next;
source.next = (event: E) => { fn(event, next); };
}
export const ABORT_EVENT = (
/*#__PURE__*/createNativeEventSource<UIEvent>("abort")
);
export const ACTIVATE_EVENT = (
/*#__PURE__*/createNativeEventSource<UIEvent>("activate")
);
export const ARIA_REQUEST_EVENT = (
/*#__PURE__*/createNativeEventSource<UIEvent>("ariarequest")
);
export const BEFORE_ACTIVATE_EVENT = (
/*#__PURE__*/createNativeEventSource<UIEvent>("beforeactivate")
);
export const BEFORE_COPY_EVENT = (
/*#__PURE__*/createNativeEventSource<ClipboardEvent>("beforecopy")
);
export const BEFORE_CUT_EVENT = (
/*#__PURE__*/createNativeEventSource<ClipboardEvent>("beforecut")
);
export const BEFORE_DEACTIVATE_EVENT = (
/*#__PURE__*/createNativeEventSource<UIEvent>("beforedeactivate")
);
export const BEFORE_PASTE_EVENT = (
/*#__PURE__*/createNativeEventSource<ClipboardEvent>("beforepaste")
);
export const BLUR_EVENT = (
/*#__PURE__*/createNativeEventSource<FocusEvent>("blur")
);
export const CAN_PLAY_EVENT = (
/*#__PURE__*/createNativeEventSource<Event>("canplay")
);
export const CAN_PLAYTHROUGH_EVENT = (
/*#__PURE__*/createNativeEventSource<Event>("canplaythrough")
);
export const CHANGE_EVENT = (
/*#__PURE__*/createNativeEventSource<Event>("change")
);
export const CLICK_EVENT = (
/*#__PURE__*/createNativeEventSource<MouseEvent>("click")
);
export const CONTEXT_MENU_EVENT = (
/*#__PURE__*/createNativeEventSource<PointerEvent>("contextmenu")
);
export const COPY_EVENT = (
/*#__PURE__*/createNativeEventSource<ClipboardEvent>("copy")
);
export const CUE_CHANGE_EVENT = (
/*#__PURE__*/createNativeEventSource<Event>("cuechange")
);
export const CUT_EVENT = (
/*#__PURE__*/createNativeEventSource<ClipboardEvent>("cut")
);
export const DOUBLE_CLICK_EVENT = (
/*#__PURE__*/createNativeEventSource<MouseEvent>("dblclick")
);
export const DEACTIVATE_EVENT = (
/*#__PURE__*/createNativeEventSource<UIEvent>("deactivate")
);
export const DRAG_EVENT = (
/*#__PURE__*/createNativeEventSource<DragEvent>("drag")
);
export const DRAG_END_EVENT = (
/*#__PURE__*/createNativeEventSource<DragEvent>("dragend")
);
export const DRAG_ENTER_EVENT = (
/*#__PURE__*/createNativeEventSource<DragEvent>("dragenter")
);
export const DRAG_LEAVE_EVENT = (
/*#__PURE__*/createNativeEventSource<DragEvent>("dragleave")
);
export const DRAG_OVER_EVENT = (
/*#__PURE__*/createNativeEventSource<DragEvent>("dragover")
);
export const DRAG_START_EVENT = (
/*#__PURE__*/createNativeEventSource<DragEvent>("dragstart")
);
export const DROP_EVENT = (
/*#__PURE__*/createNativeEventSource<DragEvent>("drop")
);
export const DURATION_CHANGE_EVENT = (
/*#__PURE__*/createNativeEventSource<Event>("durationchange")
);
export const EMPTIED_EVENT = (
/*#__PURE__*/createNativeEventSource<Event>("emptied")
);
export const ENCRYPTED_EVENT = (
/*#__PURE__*/createNativeEventSource<MediaEncryptedEvent>("encrypted")
);
export const ENDED_EVENT = (
/*#__PURE__*/createNativeEventSource<MediaStreamErrorEvent>("ended")
);
export const ERROR_EVENT = (
/*#__PURE__*/createNativeEventSource<ErrorEvent>("error")
);
export const FOCUS_EVENT = (
/*#__PURE__*/createNativeEventSource<FocusEvent>("focus")
);
export const GOT_POINTER_CAPTURE_EVENT = (
/*#__PURE__*/createNativeEventSource<PointerEvent>("gotpointercapture")
);
export const BEFORE_INPUT_EVENT = (
/*#__PURE__*/createNativeEventSource<Event>("beforeinput")
);
export const INPUT_EVENT = (
/*#__PURE__*/createNativeEventSource<Event>("input")
);
export const INVALID_EVENT = (
/*#__PURE__*/createNativeEventSource<Event>("invalid")
);
export const KEY_DOWN_EVENT = (
/*#__PURE__*/createNativeEventSource<KeyboardEvent>("keydown")
);
export const KEY_PRESS_EVENT = (
/*#__PURE__*/createNativeEventSource<KeyboardEvent>("keypress")
);
export const KEY_UP_EVENT = (
/*#__PURE__*/createNativeEventSource<KeyboardEvent>("keyup")
);
export const LOAD_EVENT = (
/*#__PURE__*/createNativeEventSource<Event>("load")
);
export const LOADED_DATA_EVENT = (
/*#__PURE__*/createNativeEventSource<Event>("loadeddata")
);
export const LOADED_METADATA_EVENT = (
/*#__PURE__*/createNativeEventSource<Event>("loadedmetadata")
);
export const LOAD_START_EVENT = (
/*#__PURE__*/createNativeEventSource<Event>("loadstart")
);
export const LOST_POINTER_CAPTURE_EVENT = (
/*#__PURE__*/createNativeEventSource<PointerEvent>("lostpointercapture")
);
export const MOUSE_DOWN_EVENT = (
/*#__PURE__*/createNativeEventSource<MouseEvent>("mousedown")
);
export const MOUSE_OUT_EVENT = (
/*#__PURE__*/createNativeEventSource<MouseEvent>("mouseout")
);
export const MOUSE_OVER_EVENT = (
/*#__PURE__*/createNativeEventSource<MouseEvent>("mouseover")
);
export const MOUSE_UP_EVENT = (
/*#__PURE__*/createNativeEventSource<MouseEvent>("mouseup")
);
export const PASTE_EVENT = (
/*#__PURE__*/createNativeEventSource<ClipboardEvent>("paste")
);
export const PAUSE_EVENT = (
/*#__PURE__*/createNativeEventSource<Event>("pause")
);
export const PLAY_EVENT = (
/*#__PURE__*/createNativeEventSource<Event>("play")
);
export const PLAYING_EVENT = (
/*#__PURE__*/createNativeEventSource<Event>("playing")
);
export const POINTER_CANCEL_EVENT = (
/*#__PURE__*/createNativeEventSource<PointerEvent>("pointercancel")
);
export const POINTER_DOWN_EVENT = (
/*#__PURE__*/createNativeEventSource<PointerEvent>("pointerdown")
);
export const POINTER_OUT_EVENT = (
/*#__PURE__*/createNativeEventSource<PointerEvent>("pointerout")
);
export const POINTER_OVER_EVENT = (
/*#__PURE__*/createNativeEventSource<PointerEvent>("pointerover")
);
export const POINTER_UP_EVENT = (
/*#__PURE__*/createNativeEventSource<PointerEvent>("pointerup")
);
export const PROGRESS_EVENT = (
/*#__PURE__*/createNativeEventSource<ProgressEvent>("progress")
);
export const RATE_CHANGE_EVENT = (
/*#__PURE__*/createNativeEventSource<Event>("ratechange")
);
export const RESET_EVENT = (
/*#__PURE__*/createNativeEventSource<Event>("reset")
);
export const SCROLL_EVENT = (
/*#__PURE__*/createNativeEventSource<UIEvent>("scroll")
);
export const SEEKED_EVENT = (
/*#__PURE__*/createNativeEventSource<Event>("seeked")
);
export const SEEKING_EVENT = (
/*#__PURE__*/createNativeEventSource<Event>("seeking")
);
export const SELECT_EVENT = (
/*#__PURE__*/createNativeEventSource<UIEvent>("select")
);
export const SELECT_START_EVENT = (
/*#__PURE__*/createNativeEventSource<Event>("selectstart")
);
export const STALLED_EVENT = (
/*#__PURE__*/createNativeEventSource<Event>("stalled")
);
export const SUBMIT_EVENT = (
/*#__PURE__*/createNativeEventSource<Event>("submit")
);
export const SUSPEND_EVENT = (
/*#__PURE__*/createNativeEventSource<Event>("suspend")
);
export const TIME_UPDATE_EVENT = (
/*#__PURE__*/createNativeEventSource<Event>("timeupdate")
);
export const TOUCH_CANCEL_EVENT = (
/*#__PURE__*/createNativeEventSource<TouchEvent>("touchcancel")
);
export const TOUCH_END_EVENT = (
/*#__PURE__*/createNativeEventSource<TouchEvent>("touchend")
);
export const TOUCH_START_EVENT = (
/*#__PURE__*/createNativeEventSource<TouchEvent>("touchstart")
);
export const TRANSITION_CANCEL_EVENT = (
/*#__PURE__*/createNativeEventSource<TransitionEvent>("transitioncancel")
);
export const TRANSITION_END_EVENT = (
/*#__PURE__*/createNativeEventSource<TransitionEvent>("transitionend")
);
export const TRANSITION_RUN_EVENT = (
/*#__PURE__*/createNativeEventSource<TransitionEvent>("transitionrun")
);
export const TRANSITION_START_EVENT = (
/*#__PURE__*/createNativeEventSource<TransitionEvent>("transitionstart")
);
export const UNLOAD_EVENT = (
/*#__PURE__*/createNativeEventSource<Event>("unload")
);
export const VOLUME_CHANGE_EVENT = (
/*#__PURE__*/createNativeEventSource<Event>("volumechange")
);
export const WAITING_EVENT = (
/*#__PURE__*/createNativeEventSource<Event>("waiting")
);
export const WHEEL_EVENT = (
/*#__PURE__*/createNativeEventSource<WheelEvent>("wheel")
);
export const ACTIVE_TOUCH_END_EVENT = (
/*#__PURE__*/createNativeEventSource<TouchEvent>("touchend", EVENT_CAPTURE_ACTIVE_OPTIONS)
);
export const ACTIVE_TOUCH_START_EVENT = (
/*#__PURE__*/createNativeEventSource<TouchEvent>("touchstart", EVENT_CAPTURE_ACTIVE_OPTIONS)
);
export const ACTIVE_WHEEL_EVENT = (
/*#__PURE__*/createNativeEventSource<WheelEvent>("wheel", EVENT_CAPTURE_ACTIVE_OPTIONS)
);
/**
* Helper function that creates native event handler factories.
*
* @param s Native event source.
* @returns Native event handler factory.
*/
export function nativeEventHandlerFactory(s: {}):
(h: NativeEventHandler<any>, capture?: boolean) => EventHandlerNode<any> {
const bubbleDescriptor = { s, h: dispatchNativeEvent, f: 0 };
const captureDescriptor = { s, h: dispatchNativeEvent, f: EventHandlerFlags.Capture };
return (h, capture) => ({
d: capture === true ? captureDescriptor : bubbleDescriptor,
h,
});
}
export const onAbort: <P>(
handler: NativeEventHandler<UIEvent>,
capture?: boolean,
) => EventHandlerNode<UIEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(ABORT_EVENT)
);
export const onActivate: <P>(
handler: NativeEventHandler<UIEvent>,
capture?: boolean,
) => EventHandlerNode<UIEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(ACTIVATE_EVENT)
);
export const onAriaRequest: <P>(
handler: NativeEventHandler<UIEvent>,
capture?: boolean,
) => EventHandlerNode<UIEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(ARIA_REQUEST_EVENT)
);
export const onBeforeActivate: <P>(
handler: NativeEventHandler<UIEvent>,
capture?: boolean,
) => EventHandlerNode<UIEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(BEFORE_ACTIVATE_EVENT)
);
export const onBeforeCopy: <P>(
handler: NativeEventHandler<ClipboardEvent>,
capture?: boolean,
) => EventHandlerNode<ClipboardEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(BEFORE_COPY_EVENT)
);
export const onBeforeCut: <P>(
handler: NativeEventHandler<ClipboardEvent>,
capture?: boolean,
) => EventHandlerNode<ClipboardEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(BEFORE_CUT_EVENT)
);
export const onBeforeDeactivate: <P>(
handler: NativeEventHandler<UIEvent>,
capture?: boolean,
) => EventHandlerNode<UIEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(BEFORE_DEACTIVATE_EVENT)
);
export const onBeforePaste: <P>(
handler: NativeEventHandler<ClipboardEvent>,
capture?: boolean,
) => EventHandlerNode<ClipboardEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(BEFORE_PASTE_EVENT)
);
export const onBlur: <P>(
handler: NativeEventHandler<FocusEvent>,
capture?: boolean,
) => EventHandlerNode<FocusEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(BLUR_EVENT)
);
export const onCanPlay: <P>(
handler: NativeEventHandler<Event>,
capture?: boolean,
) => EventHandlerNode<Event> = (
/*#__PURE__*/nativeEventHandlerFactory(CAN_PLAY_EVENT)
);
export const onCanPlaythrough: <P>(
handler: NativeEventHandler<Event>,
capture?: boolean,
) => EventHandlerNode<Event> = (
/*#__PURE__*/nativeEventHandlerFactory(CAN_PLAYTHROUGH_EVENT)
);
export const onChange: <P>(
handler: NativeEventHandler<Event>,
capture?: boolean,
) => EventHandlerNode<Event> = (
/*#__PURE__*/nativeEventHandlerFactory(CHANGE_EVENT)
);
export const onClick: <P>(
handler: NativeEventHandler<MouseEvent>,
capture?: boolean,
) => EventHandlerNode<MouseEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(CLICK_EVENT)
);
export const onContextMenu: <P>(
handler: NativeEventHandler<PointerEvent>,
capture?: boolean,
) => EventHandlerNode<PointerEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(CONTEXT_MENU_EVENT)
);
export const onCopy: <P>(
handler: NativeEventHandler<ClipboardEvent>,
capture?: boolean,
) => EventHandlerNode<ClipboardEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(COPY_EVENT)
);
export const onCueChange: <P>(
handler: NativeEventHandler<Event>,
capture?: boolean,
) => EventHandlerNode<Event> = (
/*#__PURE__*/nativeEventHandlerFactory(CUE_CHANGE_EVENT)
);
export const onCut: <P>(
handler: NativeEventHandler<ClipboardEvent>,
capture?: boolean,
) => EventHandlerNode<ClipboardEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(CUT_EVENT)
);
export const onDoubleClick: <P>(
handler: NativeEventHandler<MouseEvent>,
capture?: boolean,
) => EventHandlerNode<MouseEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(DOUBLE_CLICK_EVENT)
);
export const onDeactivate: <P>(
handler: NativeEventHandler<UIEvent>,
capture?: boolean,
) => EventHandlerNode<UIEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(DEACTIVATE_EVENT)
);
export const onDrag: <P>(
handler: NativeEventHandler<DragEvent>,
capture?: boolean,
) => EventHandlerNode<DragEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(DRAG_EVENT)
);
export const onDragEnd: <P>(
handler: NativeEventHandler<DragEvent>,
capture?: boolean,
) => EventHandlerNode<DragEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(DRAG_END_EVENT)
);
export const onDragEnter: <P>(
handler: NativeEventHandler<DragEvent>,
capture?: boolean,
) => EventHandlerNode<DragEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(DRAG_ENTER_EVENT)
);
export const onDragLeave: <P>(
handler: NativeEventHandler<DragEvent>,
capture?: boolean,
) => EventHandlerNode<DragEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(DRAG_LEAVE_EVENT)
);
export const onDragOver: <P>(
handler: NativeEventHandler<DragEvent>,
capture?: boolean,
) => EventHandlerNode<DragEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(DRAG_OVER_EVENT)
);
export const onDragStart: <P>(
handler: NativeEventHandler<DragEvent>,
capture?: boolean,
) => EventHandlerNode<DragEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(DRAG_START_EVENT)
);
export const onDrop: <P>(
handler: NativeEventHandler<DragEvent>,
capture?: boolean,
) => EventHandlerNode<DragEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(DROP_EVENT)
);
export const onDurationChange: <P>(
handler: NativeEventHandler<Event>,
capture?: boolean,
) => EventHandlerNode<Event> = (
/*#__PURE__*/nativeEventHandlerFactory(DURATION_CHANGE_EVENT)
);
export const onEmptied: <P>(
handler: NativeEventHandler<Event>,
capture?: boolean,
) => EventHandlerNode<Event> = (
/*#__PURE__*/nativeEventHandlerFactory(EMPTIED_EVENT)
);
export const onEncrypted: <P>(
handler: NativeEventHandler<MediaEncryptedEvent>,
capture?: boolean,
) => EventHandlerNode<MediaEncryptedEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(ENCRYPTED_EVENT)
);
export const onEnded: <P>(
handler: NativeEventHandler<MediaStreamErrorEvent>,
capture?: boolean,
) => EventHandlerNode<MediaStreamErrorEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(ENDED_EVENT)
);
export const onError: <P>(
handler: NativeEventHandler<ErrorEvent>,
capture?: boolean,
) => EventHandlerNode<ErrorEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(ERROR_EVENT)
);
export const onFocus: <P>(
handler: NativeEventHandler<FocusEvent>,
capture?: boolean,
) => EventHandlerNode<FocusEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(FOCUS_EVENT)
);
export const onGotPointerCapture: <P>(
handler: NativeEventHandler<PointerEvent>,
capture?: boolean,
) => EventHandlerNode<PointerEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(GOT_POINTER_CAPTURE_EVENT)
);
export const onBeforeInput: <P>(
handler: NativeEventHandler<Event>,
capture?: boolean,
) => EventHandlerNode<Event> = (
/*#__PURE__*/nativeEventHandlerFactory(BEFORE_INPUT_EVENT)
);
export const onInput: <P>(
handler: NativeEventHandler<Event>,
capture?: boolean,
) => EventHandlerNode<Event> = (
/*#__PURE__*/nativeEventHandlerFactory(INPUT_EVENT)
);
export const onInvalid: <P>(
handler: NativeEventHandler<Event>,
capture?: boolean,
) => EventHandlerNode<Event> = (
/*#__PURE__*/nativeEventHandlerFactory(INVALID_EVENT)
);
export const onKeyDown: <P>(
handler: NativeEventHandler<KeyboardEvent>,
capture?: boolean,
) => EventHandlerNode<KeyboardEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(KEY_DOWN_EVENT)
);
export const onKeyPress: <P>(
handler: NativeEventHandler<KeyboardEvent>,
capture?: boolean,
) => EventHandlerNode<KeyboardEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(KEY_PRESS_EVENT)
);
export const onKeyUp: <P>(
handler: NativeEventHandler<KeyboardEvent>,
capture?: boolean,
) => EventHandlerNode<KeyboardEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(KEY_UP_EVENT)
);
export const onLoad: <P>(
handler: NativeEventHandler<Event>,
capture?: boolean,
) => EventHandlerNode<Event> = (
/*#__PURE__*/nativeEventHandlerFactory(LOAD_EVENT)
);
export const onLoadedData: <P>(
handler: NativeEventHandler<Event>,
capture?: boolean,
) => EventHandlerNode<Event> = (
/*#__PURE__*/nativeEventHandlerFactory(LOADED_DATA_EVENT)
);
export const onLoadedMetadata: <P>(
handler: NativeEventHandler<Event>,
capture?: boolean,
) => EventHandlerNode<Event> = (
/*#__PURE__*/nativeEventHandlerFactory(LOADED_METADATA_EVENT)
);
export const onLoadStart: <P>(
handler: NativeEventHandler<Event>,
capture?: boolean,
) => EventHandlerNode<Event> = (
/*#__PURE__*/nativeEventHandlerFactory(LOAD_START_EVENT)
);
export const onLostPointerCapture: <P>(
handler: NativeEventHandler<PointerEvent>,
capture?: boolean,
) => EventHandlerNode<PointerEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(LOST_POINTER_CAPTURE_EVENT)
);
export const onMouseDown: <P>(
handler: NativeEventHandler<MouseEvent>,
capture?: boolean,
) => EventHandlerNode<MouseEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(MOUSE_DOWN_EVENT)
);
export const onMouseOut: <P>(
handler: NativeEventHandler<MouseEvent>,
capture?: boolean,
) => EventHandlerNode<MouseEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(MOUSE_OUT_EVENT)
);
export const onMouseOver: <P>(
handler: NativeEventHandler<MouseEvent>,
capture?: boolean,
) => EventHandlerNode<MouseEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(MOUSE_OVER_EVENT)
);
export const onMouseUp: <P>(
handler: NativeEventHandler<MouseEvent>,
capture?: boolean,
) => EventHandlerNode<MouseEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(MOUSE_UP_EVENT)
);
export const onPaste: <P>(
handler: NativeEventHandler<ClipboardEvent>,
capture?: boolean,
) => EventHandlerNode<ClipboardEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(PASTE_EVENT)
);
export const onPause: <P>(
handler: NativeEventHandler<Event>,
capture?: boolean,
) => EventHandlerNode<Event> = (
/*#__PURE__*/nativeEventHandlerFactory(PAUSE_EVENT)
);
export const onPlay: <P>(
handler: NativeEventHandler<Event>,
capture?: boolean,
) => EventHandlerNode<Event> = (
/*#__PURE__*/nativeEventHandlerFactory(PLAY_EVENT)
);
export const onPlaying: <P>(
handler: NativeEventHandler<Event>,
capture?: boolean,
) => EventHandlerNode<Event> = (
/*#__PURE__*/nativeEventHandlerFactory(PLAYING_EVENT)
);
export const onPointerCancel: <P>(
handler: NativeEventHandler<PointerEvent>,
capture?: boolean,
) => EventHandlerNode<PointerEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(POINTER_CANCEL_EVENT)
);
export const onPointerDown: <P>(
handler: NativeEventHandler<PointerEvent>,
capture?: boolean,
) => EventHandlerNode<PointerEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(POINTER_DOWN_EVENT)
);
export const onPointerOut: <P>(
handler: NativeEventHandler<PointerEvent>,
capture?: boolean,
) => EventHandlerNode<PointerEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(POINTER_OUT_EVENT)
);
export const onPointerOver: <P>(
handler: NativeEventHandler<PointerEvent>,
capture?: boolean,
) => EventHandlerNode<PointerEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(POINTER_OVER_EVENT)
);
export const onPointerUp: <P>(
handler: NativeEventHandler<PointerEvent>,
capture?: boolean,
) => EventHandlerNode<PointerEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(POINTER_UP_EVENT)
);
export const onProgress: <P>(
handler: NativeEventHandler<ProgressEvent>,
capture?: boolean,
) => EventHandlerNode<ProgressEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(PROGRESS_EVENT)
);
export const onRateChange: <P>(
handler: NativeEventHandler<Event>,
capture?: boolean,
) => EventHandlerNode<Event> = (
/*#__PURE__*/nativeEventHandlerFactory(RATE_CHANGE_EVENT)
);
export const onReset: <P>(
handler: NativeEventHandler<Event>,
capture?: boolean,
) => EventHandlerNode<Event> = (
/*#__PURE__*/nativeEventHandlerFactory(RESET_EVENT)
);
export const onScroll: <P>(
handler: NativeEventHandler<UIEvent>,
capture?: boolean,
) => EventHandlerNode<UIEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(SCROLL_EVENT)
);
export const onSeeked: <P>(
handler: NativeEventHandler<Event>,
capture?: boolean,
) => EventHandlerNode<Event> = (
/*#__PURE__*/nativeEventHandlerFactory(SEEKED_EVENT)
);
export const onSeeking: <P>(
handler: NativeEventHandler<Event>,
capture?: boolean,
) => EventHandlerNode<Event> = (
/*#__PURE__*/nativeEventHandlerFactory(SEEKING_EVENT)
);
export const onSelect: <P>(
handler: NativeEventHandler<UIEvent>,
capture?: boolean,
) => EventHandlerNode<UIEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(SELECT_EVENT)
);
export const onSelectStart: <P>(
handler: NativeEventHandler<Event>,
capture?: boolean,
) => EventHandlerNode<Event> = (
/*#__PURE__*/nativeEventHandlerFactory(SELECT_START_EVENT)
);
export const onStalled: <P>(
handler: NativeEventHandler<Event>,
capture?: boolean,
) => EventHandlerNode<Event> = (
/*#__PURE__*/nativeEventHandlerFactory(STALLED_EVENT)
);
export const onSubmit: <P>(
handler: NativeEventHandler<Event>,
capture?: boolean,
) => EventHandlerNode<Event> = (
/*#__PURE__*/nativeEventHandlerFactory(SUBMIT_EVENT)
);
export const onSuspend: <P>(
handler: NativeEventHandler<Event>,
capture?: boolean,
) => EventHandlerNode<Event> = (
/*#__PURE__*/nativeEventHandlerFactory(SUSPEND_EVENT)
);
export const onTimeUpdate: <P>(
handler: NativeEventHandler<Event>,
capture?: boolean,
) => EventHandlerNode<Event> = (
/*#__PURE__*/nativeEventHandlerFactory(TIME_UPDATE_EVENT)
);
export const onTouchCancel: <P>(
handler: NativeEventHandler<TouchEvent>,
capture?: boolean,
) => EventHandlerNode<TouchEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(TOUCH_CANCEL_EVENT)
);
export const onTouchEnd: <P>(
handler: NativeEventHandler<TouchEvent>,
capture?: boolean,
) => EventHandlerNode<TouchEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(TOUCH_END_EVENT)
);
export const onTouchStart: <P>(
handler: NativeEventHandler<TouchEvent>,
capture?: boolean,
) => EventHandlerNode<TouchEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(TOUCH_START_EVENT)
);
export const onTransitionCancel: <P>(
handler: NativeEventHandler<TransitionEvent>,
capture?: boolean,
) => EventHandlerNode<TransitionEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(TRANSITION_CANCEL_EVENT)
);
export const onTransitionEnd: <P>(
handler: NativeEventHandler<TransitionEvent>,
capture?: boolean,
) => EventHandlerNode<TransitionEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(TRANSITION_END_EVENT)
);
export const onTransitionRun: <P>(
handler: NativeEventHandler<TransitionEvent>,
capture?: boolean,
) => EventHandlerNode<TransitionEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(TRANSITION_RUN_EVENT)
);
export const onTransitionStart: <P>(
handler: NativeEventHandler<TransitionEvent>,
capture?: boolean,
) => EventHandlerNode<TransitionEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(TRANSITION_START_EVENT)
);
export const onUnload: <P>(
handler: NativeEventHandler<Event>,
capture?: boolean,
) => EventHandlerNode<Event> = (
/*#__PURE__*/nativeEventHandlerFactory(UNLOAD_EVENT)
);
export const onVolumeChange: <P>(
handler: NativeEventHandler<Event>,
capture?: boolean,
) => EventHandlerNode<Event> = (
/*#__PURE__*/nativeEventHandlerFactory(VOLUME_CHANGE_EVENT)
);
export const onWaiting: <P>(
handler: NativeEventHandler<Event>,
capture?: boolean,
) => EventHandlerNode<Event> = (
/*#__PURE__*/nativeEventHandlerFactory(WAITING_EVENT)
);
export const onWheel: <P>(
handler: NativeEventHandler<WheelEvent>,
capture?: boolean,
) => EventHandlerNode<WheelEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(WHEEL_EVENT)
);
export const onActiveTouchEnd: <P>(
handler: NativeEventHandler<TouchEvent>,
capture?: boolean,
) => EventHandlerNode<TouchEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(ACTIVE_TOUCH_END_EVENT)
);
export const onActiveTouchStart: <P>(
handler: NativeEventHandler<TouchEvent>,
capture?: boolean,
) => EventHandlerNode<TouchEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(ACTIVE_TOUCH_START_EVENT)
);
export const onActiveWheel: <P>(
handler: NativeEventHandler<WheelEvent>,
capture?: boolean,
) => EventHandlerNode<WheelEvent> = (
/*#__PURE__*/nativeEventHandlerFactory(ACTIVE_WHEEL_EVENT)
); | the_stack |
import { BaseResource, CloudError } from "ms-rest-azure";
import * as moment from "moment";
export {
BaseResource,
CloudError
};
/**
* Represents a tenant ID that is trusted by the cluster.
*/
export interface TrustedExternalTenant {
/**
* GUID representing an external tenant.
*/
value?: string;
}
/**
* Azure SKU definition.
*/
export interface AzureSku {
/**
* SKU name. Possible values include: 'D13_v2', 'D14_v2', 'L8', 'L16', 'D11_v2', 'D12_v2', 'L4'
*/
name: string;
/**
* SKU capacity.
*/
capacity?: number;
}
/**
* Azure capacity definition.
*/
export interface AzureCapacity {
/**
* Scale type. Possible values include: 'automatic', 'manual', 'none'
*/
scaleType: string;
/**
* Minimum allowed capacity.
*/
minimum: number;
/**
* Maximum allowed capacity.
*/
maximum: number;
/**
* The default capacity that would be used.
*/
default: number;
}
/**
* Azure resource SKU definition.
*/
export interface AzureResourceSku {
/**
* Resource Namespace and Type.
*/
resourceType?: string;
/**
* The SKU details.
*/
sku?: AzureSku;
/**
* The SKU capacity.
*/
capacity?: AzureCapacity;
}
/**
* A class that contains database statistics information.
*/
export interface DatabaseStatistics {
/**
* The database size - the total size of compressed data and index in bytes.
*/
size?: number;
}
export interface Resource extends BaseResource {
/**
* Fully qualified resource Id for the resource. Ex -
* /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}
*/
readonly id?: string;
/**
* The name of the resource
*/
readonly name?: string;
/**
* The type of the resource. Ex- Microsoft.Compute/virtualMachines or
* Microsoft.Storage/storageAccounts.
*/
readonly type?: string;
}
/**
* The resource model definition for a ARM tracked top level resource
*/
export interface TrackedResource extends Resource {
/**
* Resource tags.
*/
tags?: { [propertyName: string]: string };
/**
* The geo-location where the resource lives
*/
location: string;
}
/**
* Class representing a Kusto cluster.
*/
export interface Cluster extends TrackedResource {
/**
* The SKU of the cluster.
*/
sku: AzureSku;
/**
* The state of the resource. Possible values include: 'Creating', 'Unavailable', 'Running',
* 'Deleting', 'Deleted', 'Stopping', 'Stopped', 'Starting', 'Updating'
*/
readonly state?: string;
/**
* The provisioned state of the resource. Possible values include: 'Running', 'Creating',
* 'Deleting', 'Succeeded', 'Failed'
*/
readonly provisioningState?: string;
/**
* The cluster URI.
*/
readonly uri?: string;
/**
* The cluster data ingestion URI.
*/
readonly dataIngestionUri?: string;
/**
* The cluster's external tenants.
*/
trustedExternalTenants?: TrustedExternalTenant[];
}
/**
* Class representing an update to a Kusto cluster.
*/
export interface ClusterUpdate extends Resource {
/**
* Resource tags.
*/
tags?: { [propertyName: string]: string };
/**
* Resource location.
*/
location?: string;
/**
* The SKU of the cluster.
*/
sku?: AzureSku;
/**
* The state of the resource. Possible values include: 'Creating', 'Unavailable', 'Running',
* 'Deleting', 'Deleted', 'Stopping', 'Stopped', 'Starting', 'Updating'
*/
readonly state?: string;
/**
* The provisioned state of the resource. Possible values include: 'Running', 'Creating',
* 'Deleting', 'Succeeded', 'Failed'
*/
readonly provisioningState?: string;
/**
* The cluster URI.
*/
readonly uri?: string;
/**
* The cluster data ingestion URI.
*/
readonly dataIngestionUri?: string;
/**
* The cluster's external tenants.
*/
trustedExternalTenants?: TrustedExternalTenant[];
}
/**
* The resource model definition for a ARM proxy resource. It will have everything other than
* required location and tags
*/
export interface ProxyResource extends Resource {
}
/**
* Class representing a Kusto database.
*/
export interface Database extends ProxyResource {
/**
* Resource location.
*/
location?: string;
/**
* The provisioned state of the resource. Possible values include: 'Running', 'Creating',
* 'Deleting', 'Succeeded', 'Failed'
*/
readonly provisioningState?: string;
/**
* The time the data should be kept before it stops being accessible to queries in TimeSpan.
*/
softDeletePeriod?: moment.Duration;
/**
* The time the data that should be kept in cache for fast queries in TimeSpan.
*/
hotCachePeriod?: moment.Duration;
/**
* The statistics of the database.
*/
statistics?: DatabaseStatistics;
}
/**
* Class representing an update to a Kusto database.
*/
export interface DatabaseUpdate extends Resource {
/**
* Resource location.
*/
location?: string;
/**
* The provisioned state of the resource. Possible values include: 'Running', 'Creating',
* 'Deleting', 'Succeeded', 'Failed'
*/
readonly provisioningState?: string;
/**
* The time the data should be kept before it stops being accessible to queries in TimeSpan.
*/
softDeletePeriod?: moment.Duration;
/**
* The time the data that should be kept in cache for fast queries in TimeSpan.
*/
hotCachePeriod?: moment.Duration;
/**
* The statistics of the database.
*/
statistics?: DatabaseStatistics;
}
/**
* A class representing database principal entity.
*/
export interface DatabasePrincipal {
/**
* Database principal role. Possible values include: 'Admin', 'Ingestor', 'Monitor', 'User',
* 'UnrestrictedViewers', 'Viewer'
*/
role: string;
/**
* Database principal name.
*/
name: string;
/**
* Database principal type. Possible values include: 'App', 'Group', 'User'
*/
type: string;
/**
* Database principal fully qualified name.
*/
fqn?: string;
/**
* Database principal email if exists.
*/
email?: string;
/**
* Application id - relevant only for application principal type.
*/
appId?: string;
}
/**
* Class representing an data connection.
*/
export interface DataConnection extends ProxyResource {
/**
* Resource location.
*/
location?: string;
/**
* Polymorphic Discriminator
*/
kind: string;
}
/**
* The result returned from a data connection validation request.
*/
export interface DataConnectionValidationResult {
/**
* A message which indicates a problem in data connection validation.
*/
errorMessage?: string;
}
/**
* The list Kusto database principals operation request.
*/
export interface DatabasePrincipalListRequest {
/**
* The list of Kusto database principals.
*/
value?: DatabasePrincipal[];
}
/**
* Class representing an data connection validation.
*/
export interface DataConnectionValidation {
/**
* The name of the data connection.
*/
dataConnectionName?: string;
/**
* The data connection properties to validate.
*/
properties?: DataConnection;
}
/**
* Class representing an event hub data connection.
*/
export interface EventHubDataConnection extends DataConnection {
/**
* The resource ID of the event hub to be used to create a data connection.
*/
eventHubResourceId: string;
/**
* The event hub consumer group.
*/
consumerGroup: string;
/**
* The table where the data should be ingested. Optionally the table information can be added to
* each message.
*/
tableName?: string;
/**
* The mapping rule to be used to ingest the data. Optionally the mapping information can be
* added to each message.
*/
mappingRuleName?: string;
/**
* The data format of the message. Optionally the data format can be added to each message.
* Possible values include: 'MULTIJSON', 'JSON', 'CSV', 'TSV', 'SCSV', 'SOHSV', 'PSV', 'TXT',
* 'RAW', 'SINGLEJSON', 'AVRO'
*/
dataFormat?: string;
}
/**
* Class representing an Event Grid data connection.
*/
export interface EventGridDataConnection extends DataConnection {
/**
* The resource ID of the storage account where the data resides.
*/
storageAccountResourceId: string;
/**
* The resource ID where the event grid is configured to send events.
*/
eventHubResourceId: string;
/**
* The event hub consumer group.
*/
consumerGroup: string;
/**
* The table where the data should be ingested. Optionally the table information can be added to
* each message.
*/
tableName: string;
/**
* The mapping rule to be used to ingest the data. Optionally the mapping information can be
* added to each message.
*/
mappingRuleName?: string;
/**
* The data format of the message. Optionally the data format can be added to each message.
* Possible values include: 'MULTIJSON', 'JSON', 'CSV', 'TSV', 'SCSV', 'SOHSV', 'PSV', 'TXT',
* 'RAW', 'SINGLEJSON', 'AVRO'
*/
dataFormat: string;
}
/**
* The list Kusto data connection validation result.
*/
export interface DataConnectionValidationListResult {
/**
* The list of Kusto data connection validation errors.
*/
value?: DataConnectionValidationResult[];
}
/**
* The result returned from a cluster check name availability request.
*/
export interface ClusterCheckNameRequest {
/**
* Cluster name.
*/
name: string;
}
/**
* The result returned from a database check name availability request.
*/
export interface DatabaseCheckNameRequest {
/**
* Database name.
*/
name: string;
}
/**
* The result returned from a check name availability request.
*/
export interface CheckNameResult {
/**
* Specifies a Boolean value that indicates if the name is available.
*/
nameAvailable?: boolean;
/**
* The name that was checked.
*/
name?: string;
/**
* Message indicating an unavailable name due to a conflict, or a description of the naming rules
* that are violated.
*/
message?: string;
}
/**
* @summary The object that describes the operation.
*/
export interface OperationDisplay {
/**
* @summary Friendly name of the resource provider.
*/
provider?: string;
/**
* @summary The operation type.
* @description For example: read, write, delete.
*/
operation?: string;
/**
* @summary The resource type on which the operation is performed.
*/
resource?: string;
/**
* @summary The friendly name of the operation.
*/
description?: string;
}
/**
* @summary A REST API operation
*/
export interface Operation {
/**
* @summary The operation name.
* @description This is of the format {provider}/{resource}/{operation}.
*/
name?: string;
/**
* @summary The object that describes the operation.
*/
display?: OperationDisplay;
/**
* @summary The intended executor of the operation.
*/
origin?: string;
/**
* @summary Properties of the operation.
*/
properties?: any;
}
/**
* The resource model definition for a Azure Resource Manager resource with an etag.
*/
export interface AzureEntityResource extends Resource {
/**
* Resource Etag.
*/
readonly etag?: string;
}
/**
* The list Kusto clusters operation response.
*/
export interface ClusterListResult extends Array<Cluster> {
}
/**
* List of available SKUs for a new Kusto Cluster.
*/
export interface ListSkusResult extends Array<AzureSku> {
}
/**
* List of available SKUs for an existing Kusto Cluster.
*/
export interface ListResourceSkusResult extends Array<AzureResourceSku> {
}
/**
* The list Kusto databases operation response.
*/
export interface DatabaseListResult extends Array<Database> {
}
/**
* The list Kusto database principals operation response.
*/
export interface DatabasePrincipalListResult extends Array<DatabasePrincipal> {
}
/**
* The list Kusto data connections operation response.
*/
export interface DataConnectionListResult extends Array<DataConnection> {
}
/**
* @summary Result of the request to list REST API operations. It contains a list of operations and
* a URL nextLink to get the next set of results.
*/
export interface OperationListResult extends Array<Operation> {
/**
* @summary The URL to get the next set of operation list results if there are any.
*/
nextLink?: string;
} | the_stack |
import { gen, sampleOne } from 'testcheck';
import { text, relationship } from '@keystone-next/keystone/fields';
import { list } from '@keystone-next/keystone';
import { setupTestRunner } from '@keystone-next/keystone/testing';
import { apiTestConfig, expectSingleRelationshipError } from '../../utils';
const runner = setupTestRunner({
config: apiTestConfig({
lists: {
Group: list({
fields: {
name: text(),
},
}),
Event: list({
fields: {
title: text(),
group: relationship({ ref: 'Group' }),
},
}),
GroupNoRead: list({
fields: {
name: text(),
},
access: {
operation: { query: () => false },
},
}),
EventToGroupNoRead: list({
fields: {
title: text(),
group: relationship({ ref: 'GroupNoRead' }),
},
}),
GroupNoReadHard: list({
fields: { name: text() },
graphql: { omit: ['query'] },
}),
EventToGroupNoReadHard: list({
fields: {
title: text(),
group: relationship({ ref: 'GroupNoReadHard' }),
},
}),
GroupNoCreate: list({
fields: {
name: text(),
},
access: {
operation: { create: () => false },
},
}),
EventToGroupNoCreate: list({
fields: {
title: text(),
group: relationship({ ref: 'GroupNoCreate' }),
},
}),
GroupNoCreateHard: list({
fields: { name: text() },
graphql: { omit: ['create'] },
}),
EventToGroupNoCreateHard: list({
fields: {
title: text(),
group: relationship({ ref: 'GroupNoCreateHard' }),
},
}),
GroupNoUpdate: list({
fields: { name: text() },
access: { operation: { update: () => false } },
}),
EventToGroupNoUpdate: list({
fields: {
title: text(),
group: relationship({ ref: 'GroupNoUpdate' }),
},
}),
GroupNoUpdateHard: list({
fields: { name: text() },
graphql: { omit: ['update'] },
}),
EventToGroupNoUpdateHard: list({
fields: {
title: text(),
group: relationship({ ref: 'GroupNoUpdateHard' }),
},
}),
},
}),
});
describe('no access control', () => {
test(
'link nested from within create mutation',
runner(async ({ context }) => {
const groupName = sampleOne(gen.alphaNumString.notEmpty());
// Create an item to link against
const createGroup = await context.query.Group.createOne({ data: { name: groupName } });
// Create an item that does the linking
const event = await context.query.Event.createOne({
data: { title: 'A thing', group: { connect: { id: createGroup.id } } },
});
expect(event).toMatchObject({ id: expect.any(String) });
})
);
test(
'link nested from within update mutation',
runner(async ({ context }) => {
const groupName = sampleOne(gen.alphaNumString.notEmpty());
// Create an item to link against
const createGroup = await context.query.Group.createOne({ data: { name: groupName } });
// Create an item to update
const event = await context.query.Event.createOne({ data: { title: 'A thing' } });
// Update the item and link the relationship field
const _event = await context.query.Event.updateOne({
where: { id: event.id },
data: { title: 'A thing', group: { connect: { id: createGroup.id } } },
query: 'id group { id name }',
});
expect(_event).toMatchObject({
id: expect.any(String),
group: { id: expect.any(String), name: groupName },
});
})
);
});
describe('non-matching filter', () => {
test(
'errors if connecting an item which cannot be found during creating',
runner(async ({ context }) => {
const FAKE_ID = 'cabc123';
// Create an item that does the linking
const { data, errors } = await context.graphql.raw({
query: `
mutation {
createEvent(data: {
group: {
connect: { id: "${FAKE_ID}" }
}
}) {
id
}
}`,
});
expect(data).toEqual({ createEvent: null });
const message = `Access denied: You cannot perform the 'connect' operation on the item '{"id":"${FAKE_ID}"}'. It may not exist.`;
expectSingleRelationshipError(errors, 'createEvent', 'Event.group', message);
})
);
test(
'errors if connecting an item which cannot be found during update',
runner(async ({ context }) => {
const FAKE_ID = 'cabc123';
// Create an item to link against
const createEvent = await context.query.Event.createOne({ data: {} });
// Create an item that does the linking
const { data, errors } = await context.graphql.raw({
query: `
mutation {
updateEvent(
where: { id: "${createEvent.id}" },
data: {
group: {
connect: { id: "${FAKE_ID}" }
}
}
) {
id
}
}`,
});
expect(data).toEqual({ updateEvent: null });
const message = `Access denied: You cannot perform the 'connect' operation on the item '{"id":"${FAKE_ID}"}'. It may not exist.`;
expectSingleRelationshipError(errors, 'updateEvent', 'Event.group', message);
})
);
test(
'errors on incomplete data',
runner(async ({ context }) => {
// Create an item to link against
const createEvent = await context.query.Event.createOne({ data: {} });
// Create an item that does the linking
const { data, errors } = await context.graphql.raw({
query: `
mutation {
updateEvent(
where: { id: "${createEvent.id}" },
data: { group: {} }
) {
id
}
}`,
});
expect(data).toEqual({ updateEvent: null });
const message =
'Input error: You must provide one of "connect", "create" or "disconnect" in to-one relationship inputs for "update" operations.';
expectSingleRelationshipError(errors, 'updateEvent', 'Event.group', message);
})
);
});
describe('with access control', () => {
[
{ name: 'GroupNoRead', allowed: false, func: 'read: () => false' },
{ name: 'GroupNoReadHard', allowed: false, func: 'read: false' },
{ name: 'GroupNoCreate', allowed: true, func: 'create: () => false' },
{ name: 'GroupNoCreateHard', allowed: true, func: 'create: false' },
{ name: 'GroupNoUpdate', allowed: true, func: 'update: () => false' },
{ name: 'GroupNoUpdateHard', allowed: true, func: 'update: false' },
].forEach(group => {
describe(`${group.func} on related list`, () => {
if (group.allowed) {
test(
'does not throw error when linking nested within create mutation',
runner(async ({ context }) => {
const groupName = sampleOne(gen.alphaNumString.notEmpty());
// Create an item to link against
// We can't use the graphQL query here (it's `create: () => false`)
const { id } = await context.sudo().query[group.name].createOne({
data: { name: groupName },
});
expect(id).toBeTruthy();
// Create an item that does the linking
const data = await context.query[`EventTo${group.name}`].createOne({
data: { title: 'A thing', group: { connect: { id } } },
query: 'id group { id }',
});
expect(data).toMatchObject({ id: expect.any(String), group: { id } });
})
);
test(
'does not throw error when linking nested within update mutation',
runner(async ({ context }) => {
const groupName = sampleOne(gen.alphaNumString.notEmpty());
// Create an item to link against
const groupModel = await context.sudo().query[group.name].createOne({
data: { name: groupName },
});
expect(groupModel.id).toBeTruthy();
// Create an item to update
const eventModel = await context.sudo().query[`EventTo${group.name}`].createOne({
data: { title: 'A Thing' },
});
expect(eventModel.id).toBeTruthy();
// Update the item and link the relationship field
const data = await context.query[`EventTo${group.name}`].updateOne({
where: { id: eventModel.id },
data: { title: 'A thing', group: { connect: { id: groupModel.id } } },
query: 'id group { id name }',
});
expect(data).toMatchObject({
id: expect.any(String),
group: { id: expect.any(String), name: groupName },
});
// See that it actually stored the group ID on the Event record
const event = await context.sudo().query[`EventTo${group.name}`].findOne({
where: { id: data.id },
query: 'id group { id name }',
});
expect(event).toBeTruthy();
expect(event!.group).toBeTruthy();
expect(event!.group.name).toBe(groupName);
})
);
} else {
test(
'throws error when linking nested within update mutation',
runner(async ({ context }) => {
const groupName = sampleOne(gen.alphaNumString.notEmpty());
// Create an item to link against
const groupModel = await context.sudo().query[group.name].createOne({
data: { name: groupName },
});
expect(groupModel.id).toBeTruthy();
// Create an item to update
const eventModel = await context.query[`EventTo${group.name}`].createOne({
data: { title: 'A thing' },
});
expect(eventModel.id).toBeTruthy();
// Update the item and link the relationship field
const { data, errors } = await context.graphql.raw({
query: `
mutation {
updateEventTo${group.name}(
where: { id: "${eventModel.id}" }
data: {
title: "A thing",
group: { connect: { id: "${groupModel.id}" } }
}
) {
id
}
}`,
});
expect(data).toEqual({ [`updateEventTo${group.name}`]: null });
const message = `Access denied: You cannot perform the 'connect' operation on the item '{"id":"${groupModel.id}"}'. It may not exist.`;
expectSingleRelationshipError(
errors,
`updateEventTo${group.name}`,
`EventTo${group.name}.group`,
message
);
})
);
test(
'throws error when linking nested within create mutation',
runner(async ({ context }) => {
const groupName = sampleOne(gen.alphaNumString.notEmpty());
// Create an item to link against
const { id } = await context.sudo().query[group.name].createOne({
data: { name: groupName },
});
expect(id).toBeTruthy();
// Create an item that does the linking
const { data, errors } = await context.graphql.raw({
query: `
mutation {
createEventTo${group.name}(data: {
title: "A thing",
group: { connect: { id: "${id}" } }
}) {
id
}
}`,
});
expect(data).toEqual({ [`createEventTo${group.name}`]: null });
const message = `Access denied: You cannot perform the 'connect' operation on the item '{"id":"${id}"}'. It may not exist.`;
expectSingleRelationshipError(
errors,
`createEventTo${group.name}`,
`EventTo${group.name}.group`,
message
);
})
);
}
});
});
}); | the_stack |
import { ABSENT } from '@aws-cdk/assert-internal';
import '@aws-cdk/assert-internal/jest';
import { AutoScalingGroup } from '@aws-cdk/aws-autoscaling';
import * as autoscaling from '@aws-cdk/aws-autoscaling';
import { MachineImage } from '@aws-cdk/aws-ec2';
import * as ec2 from '@aws-cdk/aws-ec2';
import { AsgCapacityProvider } from '@aws-cdk/aws-ecs';
import * as ecs from '@aws-cdk/aws-ecs';
import * as sqs from '@aws-cdk/aws-sqs';
import { testDeprecated } from '@aws-cdk/cdk-build-tools';
import * as cdk from '@aws-cdk/core';
import * as cxapi from '@aws-cdk/cx-api';
import * as ecsPatterns from '../../lib';
test('test ECS queue worker service construct - with only required props', () => {
// GIVEN
const stack = new cdk.Stack();
const vpc = new ec2.Vpc(stack, 'VPC');
const cluster = new ecs.Cluster(stack, 'Cluster', { vpc });
cluster.addAsgCapacityProvider(new AsgCapacityProvider(stack, 'DefaultAutoScalingGroupProvider', {
autoScalingGroup: new AutoScalingGroup(stack, 'DefaultAutoScalingGroup', {
vpc,
instanceType: new ec2.InstanceType('t2.micro'),
machineImage: MachineImage.latestAmazonLinux(),
}),
}));
// WHEN
new ecsPatterns.QueueProcessingEc2Service(stack, 'Service', {
cluster,
memoryLimitMiB: 512,
image: ecs.ContainerImage.fromRegistry('test'),
});
// THEN - QueueWorker is of EC2 launch type, an SQS queue is created and all default properties are set.
expect(stack).toHaveResource('AWS::ECS::Service', {
DesiredCount: 1,
LaunchType: 'EC2',
});
expect(stack).toHaveResource('AWS::SQS::Queue', {
RedrivePolicy: {
deadLetterTargetArn: {
'Fn::GetAtt': [
'ServiceEcsProcessingDeadLetterQueue4A89196E',
'Arn',
],
},
maxReceiveCount: 3,
},
});
expect(stack).toHaveResource('AWS::SQS::Queue', {
MessageRetentionPeriod: 1209600,
});
expect(stack).toHaveResourceLike('AWS::ECS::TaskDefinition', {
ContainerDefinitions: [
{
Environment: [
{
Name: 'QUEUE_NAME',
Value: {
'Fn::GetAtt': [
'ServiceEcsProcessingQueueC266885C',
'QueueName',
],
},
},
],
LogConfiguration: {
LogDriver: 'awslogs',
Options: {
'awslogs-group': {
Ref: 'ServiceQueueProcessingTaskDefQueueProcessingContainerLogGroupD52338D1',
},
'awslogs-stream-prefix': 'Service',
'awslogs-region': {
Ref: 'AWS::Region',
},
},
},
Essential: true,
Image: 'test',
Memory: 512,
},
],
Family: 'ServiceQueueProcessingTaskDef83DB34F1',
});
});
test('test ECS queue worker service construct - with remove default desiredCount feature flag', () => {
// GIVEN
const stack = new cdk.Stack();
stack.node.setContext(cxapi.ECS_REMOVE_DEFAULT_DESIRED_COUNT, true);
const vpc = new ec2.Vpc(stack, 'VPC');
const cluster = new ecs.Cluster(stack, 'Cluster', { vpc });
cluster.addAsgCapacityProvider(new AsgCapacityProvider(stack, 'DefaultAutoScalingGroupProvider', {
autoScalingGroup: new AutoScalingGroup(stack, 'DefaultAutoScalingGroup', {
vpc,
instanceType: new ec2.InstanceType('t2.micro'),
machineImage: MachineImage.latestAmazonLinux(),
}),
}));
// WHEN
new ecsPatterns.QueueProcessingEc2Service(stack, 'Service', {
cluster,
memoryLimitMiB: 512,
image: ecs.ContainerImage.fromRegistry('test'),
});
// THEN - QueueWorker is of EC2 launch type, and desiredCount is not defined on the Ec2Service.
expect(stack).toHaveResource('AWS::ECS::Service', {
DesiredCount: ABSENT,
LaunchType: 'EC2',
});
});
test('test ECS queue worker service construct - with optional props for queues', () => {
// GIVEN
const stack = new cdk.Stack();
const vpc = new ec2.Vpc(stack, 'VPC');
const cluster = new ecs.Cluster(stack, 'Cluster', { vpc });
cluster.addAsgCapacityProvider(new AsgCapacityProvider(stack, 'DefaultAutoScalingGroupProvider', {
autoScalingGroup: new AutoScalingGroup(stack, 'DefaultAutoScalingGroup', {
vpc,
instanceType: new ec2.InstanceType('t2.micro'),
machineImage: MachineImage.latestAmazonLinux(),
}),
}));
// WHEN
new ecsPatterns.QueueProcessingEc2Service(stack, 'Service', {
cluster,
memoryLimitMiB: 512,
image: ecs.ContainerImage.fromRegistry('test'),
maxReceiveCount: 42,
retentionPeriod: cdk.Duration.days(7),
visibilityTimeout: cdk.Duration.minutes(5),
});
// THEN - QueueWorker is of EC2 launch type, an SQS queue is created and all default properties are set.
expect(stack).toHaveResource('AWS::ECS::Service', {
DesiredCount: 1,
LaunchType: 'EC2',
});
expect(stack).toHaveResource('AWS::SQS::Queue', {
RedrivePolicy: {
deadLetterTargetArn: {
'Fn::GetAtt': [
'ServiceEcsProcessingDeadLetterQueue4A89196E',
'Arn',
],
},
maxReceiveCount: 42,
},
VisibilityTimeout: 300,
});
expect(stack).toHaveResource('AWS::SQS::Queue', {
MessageRetentionPeriod: 604800,
});
expect(stack).toHaveResourceLike('AWS::ECS::TaskDefinition', {
ContainerDefinitions: [
{
Environment: [
{
Name: 'QUEUE_NAME',
Value: {
'Fn::GetAtt': [
'ServiceEcsProcessingQueueC266885C',
'QueueName',
],
},
},
],
LogConfiguration: {
LogDriver: 'awslogs',
Options: {
'awslogs-group': {
Ref: 'ServiceQueueProcessingTaskDefQueueProcessingContainerLogGroupD52338D1',
},
'awslogs-stream-prefix': 'Service',
'awslogs-region': {
Ref: 'AWS::Region',
},
},
},
Essential: true,
Image: 'test',
Memory: 512,
},
],
Family: 'ServiceQueueProcessingTaskDef83DB34F1',
});
});
testDeprecated('test ECS queue worker service construct - with optional props', () => {
// GIVEN
const stack = new cdk.Stack();
const vpc = new ec2.Vpc(stack, 'VPC');
const cluster = new ecs.Cluster(stack, 'Cluster', { vpc });
cluster.addAsgCapacityProvider(new AsgCapacityProvider(stack, 'DefaultAutoScalingGroupProvider', {
autoScalingGroup: new AutoScalingGroup(stack, 'DefaultAutoScalingGroup', {
vpc,
instanceType: new ec2.InstanceType('t2.micro'),
machineImage: MachineImage.latestAmazonLinux(),
}),
}));
const queue = new sqs.Queue(stack, 'ecs-test-queue', {
queueName: 'ecs-test-sqs-queue',
});
// WHEN
new ecsPatterns.QueueProcessingEc2Service(stack, 'Service', {
cluster,
memoryLimitMiB: 1024,
image: ecs.ContainerImage.fromRegistry('test'),
command: ['-c', '4', 'amazon.com'],
enableLogging: false,
desiredTaskCount: 2,
environment: {
TEST_ENVIRONMENT_VARIABLE1: 'test environment variable 1 value',
TEST_ENVIRONMENT_VARIABLE2: 'test environment variable 2 value',
},
queue,
maxScalingCapacity: 5,
minHealthyPercent: 60,
maxHealthyPercent: 150,
serviceName: 'ecs-test-service',
family: 'ecs-task-family',
circuitBreaker: { rollback: true },
gpuCount: 256,
});
// THEN - QueueWorker is of EC2 launch type, an SQS queue is created and all optional properties are set.
expect(stack).toHaveResource('AWS::ECS::Service', {
DesiredCount: 2,
DeploymentConfiguration: {
MinimumHealthyPercent: 60,
MaximumPercent: 150,
DeploymentCircuitBreaker: {
Enable: true,
Rollback: true,
},
},
LaunchType: 'EC2',
ServiceName: 'ecs-test-service',
DeploymentController: {
Type: 'ECS',
},
});
expect(stack).toHaveResource('AWS::SQS::Queue', {
QueueName: 'ecs-test-sqs-queue',
});
expect(stack).toHaveResourceLike('AWS::ECS::TaskDefinition', {
ContainerDefinitions: [
{
Command: [
'-c',
'4',
'amazon.com',
],
Environment: [
{
Name: 'TEST_ENVIRONMENT_VARIABLE1',
Value: 'test environment variable 1 value',
},
{
Name: 'TEST_ENVIRONMENT_VARIABLE2',
Value: 'test environment variable 2 value',
},
{
Name: 'QUEUE_NAME',
Value: {
'Fn::GetAtt': [
'ecstestqueueD1FDA34B',
'QueueName',
],
},
},
],
Image: 'test',
Memory: 1024,
ResourceRequirements: [
{
Type: 'GPU',
Value: '256',
},
],
},
],
Family: 'ecs-task-family',
});
});
testDeprecated('can set desiredTaskCount to 0', () => {
// GIVEN
const stack = new cdk.Stack();
const vpc = new ec2.Vpc(stack, 'VPC');
const cluster = new ecs.Cluster(stack, 'Cluster', { vpc });
cluster.addAsgCapacityProvider(new AsgCapacityProvider(stack, 'DefaultAutoScalingGroupProvider', {
autoScalingGroup: new AutoScalingGroup(stack, 'DefaultAutoScalingGroup', {
vpc,
instanceType: new ec2.InstanceType('t2.micro'),
machineImage: MachineImage.latestAmazonLinux(),
}),
}));
// WHEN
new ecsPatterns.QueueProcessingEc2Service(stack, 'Service', {
cluster,
desiredTaskCount: 0,
maxScalingCapacity: 2,
memoryLimitMiB: 512,
image: ecs.ContainerImage.fromRegistry('test'),
});
// THEN - QueueWorker is of EC2 launch type, an SQS queue is created and all default properties are set.
expect(stack).toHaveResource('AWS::ECS::Service', {
DesiredCount: 0,
LaunchType: 'EC2',
});
});
testDeprecated('throws if desiredTaskCount and maxScalingCapacity are 0', () => {
// GIVEN
const stack = new cdk.Stack();
const vpc = new ec2.Vpc(stack, 'VPC');
const cluster = new ecs.Cluster(stack, 'Cluster', { vpc });
cluster.addAsgCapacityProvider(new AsgCapacityProvider(stack, 'DefaultAutoScalingGroupProvider', {
autoScalingGroup: new AutoScalingGroup(stack, 'DefaultAutoScalingGroup', {
vpc,
instanceType: new ec2.InstanceType('t2.micro'),
machineImage: MachineImage.latestAmazonLinux(),
}),
}));
// THEN
expect(() =>
new ecsPatterns.QueueProcessingEc2Service(stack, 'Service', {
cluster,
desiredTaskCount: 0,
memoryLimitMiB: 512,
image: ecs.ContainerImage.fromRegistry('test'),
}),
).toThrow(/maxScalingCapacity must be set and greater than 0 if desiredCount is 0/);
});
test('can set custom containerName', () => {
// GIVEN
const stack = new cdk.Stack();
const vpc = new ec2.Vpc(stack, 'VPC');
const cluster = new ecs.Cluster(stack, 'Cluster', { vpc });
cluster.addAsgCapacityProvider(new AsgCapacityProvider(stack, 'DefaultAutoScalingGroupProvider', {
autoScalingGroup: new AutoScalingGroup(stack, 'DefaultAutoScalingGroup', {
vpc,
instanceType: new ec2.InstanceType('t2.micro'),
machineImage: MachineImage.latestAmazonLinux(),
}),
}));
// WHEN
new ecsPatterns.QueueProcessingEc2Service(stack, 'Service', {
cluster,
memoryLimitMiB: 512,
image: ecs.ContainerImage.fromRegistry('test'),
containerName: 'my-container',
});
// THEN
expect(stack).toHaveResourceLike('AWS::ECS::TaskDefinition', {
ContainerDefinitions: [
{
Name: 'my-container',
},
],
});
});
test('can set capacity provider strategies', () => {
// GIVEN
const stack = new cdk.Stack();
const vpc = new ec2.Vpc(stack, 'VPC');
const cluster = new ecs.Cluster(stack, 'Cluster', { vpc });
const autoScalingGroup = new autoscaling.AutoScalingGroup(stack, 'asg', {
vpc,
instanceType: new ec2.InstanceType('bogus'),
machineImage: ecs.EcsOptimizedImage.amazonLinux2(),
});
const capacityProvider = new ecs.AsgCapacityProvider(stack, 'provider', {
autoScalingGroup,
});
cluster.addAsgCapacityProvider(capacityProvider);
// WHEN
new ecsPatterns.QueueProcessingEc2Service(stack, 'Service', {
cluster,
image: ecs.ContainerImage.fromRegistry('test'),
memoryLimitMiB: 512,
capacityProviderStrategies: [
{
capacityProvider: capacityProvider.capacityProviderName,
},
],
});
// THEN
expect(stack).toHaveResource('AWS::ECS::Service', {
LaunchType: ABSENT,
CapacityProviderStrategy: [
{
CapacityProvider: {
Ref: 'providerD3FF4D3A',
},
},
],
});
}); | the_stack |
import { DbResult, QueryBinder, QueryOptionsBuilder, QueryRowFormat, QueryStats } from "@itwin/core-common";
import { expect } from "chai";
import { ECSqlStatement } from "../../ECSqlStatement";
import { IModelDb, SnapshotDb } from "../../IModelDb";
import { IModelHost } from "../../IModelHost";
import { IModelJsFs } from "../../IModelJsFs";
/* eslint-disable no-console */
describe.skip("Properties loading", () => {
let imodel: SnapshotDb;
before(async () => {
await IModelHost.startup();
});
after(async () => {
await IModelHost.shutdown();
});
beforeEach(() => {
const testIModelName: string = "D:/temp/test-file.bim";
imodel = SnapshotDb.openFile(testIModelName);
expect(imodel).is.not.null;
}); 291;
it.skip(`concurrent query ping test`, async function () {
this.timeout(0);
// eslint-disable-next-line no-console
console.log("Round trip time");
const startTime = new Date().getTime();
let rowCount = 0;
const ping = {
ping: {
resultSize: 0,
sleepTime: 0,
},
};
for (let i = 0; i < 246000; ++i) {
for await (const _row of imodel.query(JSON.stringify(ping), undefined, { rowFormat: QueryRowFormat.UseJsPropertyNames, usePrimaryConn: true })) {
++rowCount;
}
}
console.log(`Loaded - ${rowCount} in ${new Date().getTime() - startTime} ms`);
});
it.skip("Starting to load properties using ECSQL via ECSqlStatement", async function () {
this.timeout(0);
console.log("Starting to load properties using ECSQL via ECSqlStatement");
const startTime = new Date().getTime();
const propertiesCount = await new PropertyReaderStressTest(imodel, QueryMethod.WithConcurrentQuery).getElementsPropertiesECSQL(imodel);
console.log(`Loaded - ${propertiesCount} in ${new Date().getTime() - startTime} ms`);
});
});
interface TestQueryStats extends QueryStats {
execs: number;
}
enum QueryMethod {
WithPreparedStatement,
WithConcurrentQuery
}
class PropertyReaderStressTest {
private _queryTimes = new Map<string, TestQueryStats>();
public constructor(private _imodel: IModelDb, private _method: QueryMethod) {
}
public printTime(fileName: string) {
const allStats: TestQueryStats = { backendCpuTime: 0, backendRowsReturned: 0, backendMemUsed: 0, backendTotalTime: 0, totalTime: 0, retryCount: 0, execs: 0 };
let doc: string;
const headerLine = `nativeCpuTime,nativeMemUsed,nativeRowReturned,nativeTotalTime,totalTime,retryCount,execs,ecsql\r\n`;
doc = headerLine;
this._queryTimes.forEach((stats: TestQueryStats, ecsql: string) => {
allStats.backendCpuTime += stats.backendCpuTime;
allStats.backendMemUsed += stats.backendMemUsed;
allStats.backendRowsReturned += stats.backendRowsReturned;
allStats.backendTotalTime += stats.backendTotalTime;
allStats.totalTime += stats.totalTime;
allStats.retryCount += stats.retryCount;
allStats.execs += stats.execs;
const textLine = `${stats.backendCpuTime},${stats.backendMemUsed},${stats.backendRowsReturned},${stats.backendTotalTime},${stats.totalTime},${stats.retryCount},${stats.execs},"${ecsql.replace(/\n/g, " ").replace(/\r/g, " ").replace(/\s+/g, " ")}"\r\n`;
doc += textLine;
});
const totalLine = `${allStats.backendCpuTime},${allStats.backendMemUsed},${allStats.backendRowsReturned},${allStats.backendTotalTime},${allStats.totalTime},${allStats.retryCount},${allStats.execs},"***"\r\n`;
doc += totalLine;
IModelJsFs.writeFileSync(fileName, doc);
}
public async queryAll(ecsql: string, params?: QueryBinder) {
const builder = new QueryOptionsBuilder({ usePrimaryConn: true, abbreviateBlobs: true });
builder.setConvertClassIdsToNames(true);
builder.setRowFormat(QueryRowFormat.UseJsPropertyNames);
const reader = this._imodel.createQueryReader(ecsql, params, builder.getOptions());
const rows = await reader.toArray();
const curStats = { ...reader.stats, execs: 1 };
if (this._queryTimes.has(ecsql)) {
const stats = this._queryTimes.get(ecsql)!;
stats.backendCpuTime += curStats.backendCpuTime;
stats.backendMemUsed += curStats.backendMemUsed;
stats.backendRowsReturned += curStats.backendRowsReturned;
stats.backendTotalTime += curStats.backendTotalTime;
stats.totalTime += curStats.totalTime;
stats.execs++;
} else {
this._queryTimes.set(ecsql, curStats);
}
return rows;
}
public async getElementsPropertiesECSQL(db: IModelDb) {
const query = `
SELECT el.ECInstanceId id, '[' || schemaDef.Name || '].[' || classDef.Name || ']' className
FROM bis.Element el
JOIN meta.ECClassDef classDef ON classDef.ECInstanceId = el.ECClassId
JOIN meta.ECSchemaDef schemaDef ON schemaDef.ECInstanceId = classDef.Schema.Id`;
let propertiesCount = 0;
const startTime = new Date().getTime();
const blockSize = 3000;
let startTimeBlock = new Date().getTime();
for (const row of await this.queryAll(query, undefined)) {
const properties = await this.loadElementProperties(db, row.className, row.id);
expect(properties.id).to.be.eq(row.id);
propertiesCount++;
if (propertiesCount % blockSize === 0) {
const blockElapsedTime = ((new Date().getTime() - startTimeBlock) / 1000);
const overallSpeed = Math.round(propertiesCount / ((new Date().getTime() - startTime) / 1000));
const blockSpeed = Math.round(propertiesCount / (blockElapsedTime / 1000));
startTimeBlock = new Date().getTime();
console.log(`[block= %d] [overall = %d prop/sec] [thisBlock = %d prop/sec] [blockElapsed = %d sec]`, propertiesCount / blockSize, overallSpeed, blockSpeed, blockElapsedTime.toFixed(2));
// this.printTime("d:/temp/stats.csv");
}
}
return propertiesCount;
}
private async loadElementProperties(db: IModelDb, className: string, elementId: string) {
const elementProperties = await this.loadProperties(db, className, [elementId], true);
return {
...elementProperties[0],
...(await this.loadRelatedProperties(db, async () => this.queryGeometricElement3dTypeDefinitions(db, elementId), true)),
...(await this.loadRelatedProperties(db, async () => this.queryGeometricElement2dTypeDefinitions(db, elementId), true)),
...(await this.loadRelatedProperties(db, async () => this.queryElementLinks(db, elementId), false)),
...(await this.loadRelatedProperties(db, async () => this.queryGroupElementLinks(db, elementId), false)),
...(await this.loadRelatedProperties(db, async () => this.queryModelLinks(db, elementId), false)),
...(await this.loadRelatedProperties(db, async () => this.queryDrawingGraphicElements(db, elementId), false)),
...(await this.loadRelatedProperties(db, async () => this.queryGraphicalElement3dElements(db, elementId), false)),
...(await this.loadRelatedProperties(db, async () => this.queryExternalSourceRepositories(db, elementId), false)),
...(await this.loadRelatedProperties(db, async () => this.queryExternalSourceGroupRepositories(db, elementId), false)),
};
}
private async loadRelatedProperties(db: IModelDb, idsGetter: () => Promise<Map<string, string[]>>, loadAspects: boolean) {
const idsByClass = await idsGetter();
const properties: any = {};
for (const entry of idsByClass) {
properties[entry[0]] = await this.loadProperties(db, entry[0], entry[1], loadAspects);
}
return properties;
}
private async loadProperties(db: IModelDb, className: string, ids: string[], loadAspects: boolean) {
const query = `
SELECT ECInstanceId
FROM ${className}
WHERE ECInstanceId IN (${ids.map((_v, idx) => `:id${idx}`).join(",")})`;
const properties: any[] = [];
for (const row of await this.queryAll(query, QueryBinder.from(ids))) {
properties.push({
...this.collectProperties(row),
...(loadAspects ? await this.loadRelatedProperties(db, async () => this.queryUniqueAspects(db, row.Id), false) : {}),
...(loadAspects ? await this.loadRelatedProperties(db, async () => this.queryMultiAspects(db, row.Id), false) : {}),
});
}
return properties;
}
private async queryMultiAspects(db: IModelDb, elementId: string) {
const query = `
SELECT ma.ECInstanceId id, '[' || schemaDef.Name || '].[' || classDef.Name || ']' className
FROM bis.ElementMultiAspect ma
JOIN meta.ECClassDef classDef ON classDef.ECInstanceId = ma.ECClassId
JOIN meta.ECSchemaDef schemaDef ON schemaDef.ECInstanceId = classDef.Schema.Id
WHERE ma.Element.Id = :id`;
return this.queryRelatedClasses(db, query, QueryBinder.from({ id: elementId }));
}
private async queryUniqueAspects(db: IModelDb, elementId: string) {
const query = `
SELECT ua.ECInstanceId id, '[' || schemaDef.Name || '].[' || classDef.Name || ']' className
FROM bis.ElementUniqueAspect ua
JOIN meta.ECClassDef classDef ON classDef.ECInstanceId = ua.ECClassId
JOIN meta.ECSchemaDef schemaDef ON schemaDef.ECInstanceId = classDef.Schema.Id
WHERE ua.Element.Id = :id`;
return this.queryRelatedClasses(db, query, QueryBinder.from({ id: elementId }));
}
private async queryGeometricElement3dTypeDefinitions(db: IModelDb, elementId: string) {
const query = `
SELECT relType.TargetECInstanceId id, '[' || schemaDef.Name || '].[' || classDef.Name || ']' className
FROM bis.GeometricElement3dHasTypeDefinition relType
JOIN meta.ECClassDef classDef ON classDef.ECInstanceId = relType.TargetECClassId
JOIN meta.ECSchemaDef schemaDef ON schemaDef.ECInstanceId = classDef.Schema.Id
WHERE relType.SourceECInstanceId = :id`;
return this.queryRelatedClasses(db, query, QueryBinder.from({ id: elementId }));
}
private async queryGeometricElement2dTypeDefinitions(db: IModelDb, elementId: string) {
const query = `
SELECT relType.TargetECInstanceId id, '[' || schemaDef.Name || '].[' || classDef.Name || ']' className
FROM bis.GeometricElement2dHasTypeDefinition relType
JOIN meta.ECClassDef classDef ON classDef.ECInstanceId = relType.TargetECClassId
JOIN meta.ECSchemaDef schemaDef ON schemaDef.ECInstanceId = classDef.Schema.Id
WHERE relType.SourceECInstanceId = :id`;
return this.queryRelatedClasses(db, query, QueryBinder.from({ id: elementId }));
}
private async queryElementLinks(db: IModelDb, elementId: string) {
const query = `
SELECT relLink.TargetECInstanceId id, '[' || schemaDef.Name || '].[' || classDef.Name || ']' className
FROM bis.ElementHasLinks relLink
JOIN meta.ECClassDef classDef ON classDef.ECInstanceId = relLink.TargetECClassId
JOIN meta.ECSchemaDef schemaDef ON schemaDef.ECInstanceId = classDef.Schema.Id
WHERE relLink.SourceECInstanceId = :id`;
return this.queryRelatedClasses(db, query, QueryBinder.from({ id: elementId }));
}
private async queryGroupElementLinks(db: IModelDb, elementId: string) {
const query = `
SELECT relLink.TargetECInstanceId id, '[' || schemaDef.Name || '].[' || classDef.Name || ']' className
FROM bis.ElementHasLinks relLink
JOIN bis.ElementGroupsMembers relElementGroup ON relElementGroup.SourceECInstanceId = relLink.SourceECInstanceId
JOIN meta.ECClassDef classDef ON classDef.ECInstanceId = relLink.TargetECClassId
JOIN meta.ECSchemaDef schemaDef ON schemaDef.ECInstanceId = classDef.Schema.Id
WHERE relElementGroup.TargetECInstanceId = :id`;
return this.queryRelatedClasses(db, query, QueryBinder.from({ id: elementId }));
}
private async queryModelLinks(db: IModelDb, elementId: string) {
const query = `
SELECT relLink.TargetECInstanceId id, '[' || schemaDef.Name || '].[' || classDef.Name || ']' className
FROM bis.ElementHasLinks relLink
JOIN bis.ModelModelsElement relModelModels ON relModelModels.TargetECInstanceId = relLink.SourceECInstanceId
JOIN bis.ModelContainsElements relModelContains ON relModelContains.SourceECInstanceId = relModelModels.SourceECInstanceId
JOIN meta.ECClassDef classDef ON classDef.ECInstanceId = relLink.TargetECClassId
JOIN meta.ECSchemaDef schemaDef ON schemaDef.ECInstanceId = classDef.Schema.Id
WHERE relModelContains.TargetECInstanceId = :id`;
return this.queryRelatedClasses(db, query, QueryBinder.from({ id: elementId }));
}
private async queryDrawingGraphicElements(db: IModelDb, elementId: string) {
const query = `
SELECT relRepresents.SourceECInstanceId id, '[' || schemaDef.Name || '].[' || classDef.Name || ']' className
FROM bis.DrawingGraphicRepresentsElement relRepresents
JOIN meta.ECClassDef classDef ON classDef.ECInstanceId = relRepresents.SourceECClassId
JOIN meta.ECSchemaDef schemaDef ON schemaDef.ECInstanceId = classDef.Schema.Id
WHERE relRepresents.TargetECInstanceId = :id`;
return this.queryRelatedClasses(db, query, QueryBinder.from({ id: elementId }));
}
private async queryGraphicalElement3dElements(db: IModelDb, elementId: string) {
const query = `
SELECT relRepresents.SourceECInstanceId id, '[' || schemaDef.Name || '].[' || classDef.Name || ']' className
FROM bis.GraphicalElement3dRepresentsElement relRepresents
JOIN meta.ECClassDef classDef ON classDef.ECInstanceId = relRepresents.SourceECClassId
JOIN meta.ECSchemaDef schemaDef ON schemaDef.ECInstanceId = classDef.Schema.Id
WHERE relRepresents.TargetECInstanceId = :id`;
return this.queryRelatedClasses(db, query, QueryBinder.from({ id: elementId }));
}
private async queryExternalSourceRepositories(db: IModelDb, elementId: string) {
const query = `
SELECT relRepository.TargetECInstanceId id, '[' || schemaDef.Name || '].[' || classDef.Name || ']' className
FROM bis.ExternalSourceIsInRepository relRepository
JOIN bis.ElementIsFromSource relFromSource ON relFromSource.TargetECInstanceId = relRepository.SourceECInstanceId
JOIN bis.ExternalSourceAspect aspect ON aspect.ECInstanceId = relFromSource.SourceECInstanceId
JOIN meta.ECClassDef classDef ON classDef.ECInstanceId = relRepository.TargetECClassId
JOIN meta.ECSchemaDef schemaDef ON schemaDef.ECInstanceId = classDef.Schema.Id
WHERE aspect.Element.Id = :id`;
return this.queryRelatedClasses(db, query, QueryBinder.from({ id: elementId }));
}
private async queryExternalSourceGroupRepositories(db: IModelDb, elementId: string) {
const query = `
SELECT relRepository.TargetECInstanceId id, '[' || schemaDef.Name || '].[' || classDef.Name || ']' className
FROM bis.ExternalSourceIsInRepository relRepository
JOIN bis.ExternalSourceGroupGroupsSources relGroupSources ON relGroupSources.TargetECInstanceId = relRepository.SourceECInstanceId
JOIN bis.ElementIsFromSource relFromSource ON relFromSource.TargetECInstanceId = relGroupSources.SourceECInstanceId AND relFromSource.TargetECClassId IS (bis.ExternalSourceGroup)
JOIN bis.ExternalSourceAspect aspect ON aspect.ECInstanceId = relFromSource.SourceECInstanceId
JOIN meta.ECClassDef classDef ON classDef.ECInstanceId = relRepository.TargetECClassId
JOIN meta.ECSchemaDef schemaDef ON schemaDef.ECInstanceId = classDef.Schema.Id
WHERE aspect.Element.Id = :id`;
return this.queryRelatedClasses(db, query, QueryBinder.from({ id: elementId }));
}
private async queryRelatedClasses(db: IModelDb, query: string, bindings: object) {
if (this._method === QueryMethod.WithConcurrentQuery) {
return this.queryRelatedClassesWithConcurrentQuery(query, bindings);
}
return this.queryRelatedClassesWithECSqlStatement(db, query, bindings);
}
private async queryRelatedClassesWithConcurrentQuery(query: string, bindings: object) {
const relatedClasses = new Map<string, string[]>();
for (const row of await this.queryAll(query, QueryBinder.from(bindings))) {
const className = row.className ?? row.targetClassName ?? row.sourceClassName;
const relatedIds = relatedClasses.get(className);
if (!relatedIds) {
relatedClasses.set(className, [row.id]);
continue;
}
relatedIds.push(row.id);
}
return relatedClasses;
}
private queryRelatedClassesWithECSqlStatement(db: IModelDb, query: string, bindings: object) {
return db.withPreparedStatement(query, (stmt: ECSqlStatement) => {
stmt.bindValues(bindings);
const relatedClasses = new Map<string, string[]>();
while (stmt.step() === DbResult.BE_SQLITE_ROW) {
const row = stmt.getRow();
const className = row.className;
const relatedIds = relatedClasses.get(className);
if (!relatedIds) {
relatedClasses.set(className, [row.id]);
continue;
}
relatedIds.push(row.id);
}
return relatedClasses;
});
}
private _excludedProperties = new Set<string>(["element", "jsonProperties", "geometryStream"]);
private collectProperties(row: any) {
const element: any = {};
for (const prop in row) {
if (this._excludedProperties.has(prop))
continue;
element[prop] = row[prop];
}
return element;
}
} | the_stack |
'use strict';
import * as coqProto from '../coq-proto';
import * as text from '../../util/AnnotatedText';
import * as util from 'util';
import {Node} from './coq-xml';
export {Node} from './coq-xml';
import {StateId, EditId, Pair, StateFeedback, LtacProfTactic, LtacProfResults,
UnionL, UnionR, Union, OptionState, Subgoal, Goals, Location, MessageLevel,
Message, FailValue, UnfocusedGoalStack, SentenceStatus, FeedbackContent,
ValueReturn, CoqValue, CoqValueList, UnionCoqValue, CoqStatus} from '../coq-proto';
import {AnnotatedText} from '../../util/AnnotatedText';
// export interface TypedNode {
// $name: string;
// $text: string;
// /* attributes */
// $: { [key:string]:coqProto.CoqValue };
// /* children */
// $children : coqProto.CoqValue[];
// }
export namespace Nodes {
export interface StateIdNode {
$name: "state_id"
$: { val: number },
$children: {}[],
}
export interface EditIdNode {
$name: "edit_id"
$: { val: number }
$children: {}[],
}
export interface IntNode {
$name: "int",
$: { },
// $text: string
$children: {[0]: string} & {}[],
}
export interface BoolNode {
$name: "bool",
$: {val: boolean | "true" | "false"}
$children: {}[],
}
export interface StringNode {
$name: "string",
$: { },
// $text: string
$children: {[0]: string} & {}[],
}
export interface UnitNode {
$name: "unit",
$: { },
$children: {}[],
}
export interface PairNode {
$name: "pair",
$: { },
$children: {[0]: CoqValue, [1]: CoqValue} & void[]
}
export interface ListNode {
$name: "list",
$: { },
$children: CoqValue[]
}
export interface UnionNode {
$name: "union",
$: {val: 'in_l'|'in_r'},
$children: CoqValue[],
}
export interface OptionSomeNode {
$name: "option",
$: {val: 'some'},
$children: {[0]: CoqValue} & {}[],
}
export interface OptionNoneNode {
$name: "option",
$: {val: 'none'},
$children: {}[],
}
export type OptionNode = OptionSomeNode | OptionNoneNode;
export interface OptionValueIntNode {
$name: 'option_value',
$: {val: 'intvalue'},
option: number|null,
$children: {[0]: number|null} & {}[],
}
export interface OptionValueStringOptNode {
$name: 'option_value',
$: {val: 'stringoptvalue'},
option: string|null,
$children: {[0]: string|null} & {}[],
}
export interface OptionValueBoolNode {
$name: 'option_value',
$: {val: 'boolvalue'},
bool: boolean,
$children: {[0]: boolean} & {}[],
}
export interface OptionValueStringNode {
$name: 'option_value',
$: {val: 'stringvalue'},
$children: {[0]: string} & {}[],
}
export type OptionValueNode = OptionValueIntNode | OptionValueStringOptNode | OptionValueBoolNode | OptionValueStringNode;
export interface FeedbackNode {
$name: 'feedback' ,
$: {object: "state"|"edit", route: string},
$children: {[0]: StateId, [1]: FeedbackContent } & {}[]
}
export interface WorkerStatusNode {
$name: 'feedback_content',
$kind: "workerstatus", // set for type narrowing
$: {val: "workerstatus"},
$children: {[0]: Pair<string,string> } & {}[],
}
export interface FileDependencyNode {
$name: 'feedback_content',
$kind: "filedependency", // set for type narrowing
$: {val: "filedependency"},
$children: {[0]: string|null, [1]: string } & {}[],
}
export interface FileLoadedNode {
$name: 'feedback_content',
$kind: "fileloaded", // set for type narrowing
$: {val: "fileloaded"},
$children: {[0]: string, [1]: string } & {}[],
}
export interface GlobReferenceNode {
$name: 'feedback_content',
$kind: "globref", // set for type narrowing
$: {val: "globref"},
$children: {[0]: Location, [1]: string, [2]: string, [3]: string, [4]: string } & {}[],
}
export interface GlobDefinitionNode {
$name: 'feedback_content',
$kind: "globdef", // set for type narrowing
$: {val: "globdef"},
$children: {[0]: Location, [1]: string, [2]: string, [3]: string } & {}[],
}
export interface MessageFeedbackNode {
$name: 'feedback_content',
$kind: "message", // set for type narrowing
$: {val: "message"},
$children: {[0]: Message} & {}[],
}
export interface SentenceStatusAddedAxiomNode {
$name: 'feedback_content',
$kind: "addedaxiom", // set for type narrowing
$: {val: "addedaxiom"},
$children: {}[],
}
export interface ErrorMessageNode {
$name: 'feedback_content',
$kind: "errormsg", // set for type narrowing
$: {val: "errormsg"},
$children: {[0]: Location, [1]: string } & {}[],
}
export interface SentenceStatusProcessedNode {
$name: 'feedback_content',
$kind: "processed", // set for type narrowing
$: {val: "processed"},
$children: {}[],
}
export interface SentenceStatusIncompleteNode {
$name: 'feedback_content',
$kind: "incomplete", // set for type narrowing
$: {val: "incomplete"},
$children: {}[],
}
export interface SentenceStatusCompleteNode {
$name: 'feedback_content',
$kind: "complete", // set for type narrowing
$: {val: "complete"},
$children: {}[],
}
export interface SentenceStatusInProgressNode {
$name: 'feedback_content',
$kind: "inprogress", // set for type narrowing
$: {val: "inprogress"},
$children: {[0]: number } & {}[],
}
export interface SentenceStatusProcessingInNode {
$name: 'feedback_content',
$kind: "processingin", // set for type narrowing
$: {val: "processingin"},
$children: {[0]: string } & {}[],
}
export interface CustomFeeedbackNode {
$name: 'feedback_content',
$kind: "custom", // set for type narrowing
$: {val: "custom"},
$children: {[0]: Location|null, [1]: string, [2]: any } & {}[],
}
export interface LtacProfFeeedbackNode {
$name: 'feedback_content',
$kind: "custom", // set for type narrowing
$: {val: "custom"},
$children: {[0]: Location|null, [1]: "ltacprof", [2]: LtacProfResults } & {}[],
}
export type FeedbackContentNode =
WorkerStatusNode | FileDependencyNode | FileLoadedNode |
GlobReferenceNode | GlobDefinitionNode | MessageFeedbackNode | ErrorMessageNode |
SentenceStatusAddedAxiomNode | SentenceStatusProcessedNode | SentenceStatusIncompleteNode | SentenceStatusCompleteNode | SentenceStatusInProgressNode | SentenceStatusProcessingInNode |
CustomFeeedbackNode | LtacProfFeeedbackNode;
export interface LtacProfTacticNode {
$name: 'ltacprof_tactic',
$: {name: string, total: string, self: string, num_calls: string, max_total: string }
$children: LtacProfTactic[],
}
export interface LtacProfResultsNode {
$name: 'ltacprof',
$: {total_time: string }
$children: LtacProfTactic[],
}
export interface OptionStateNode {
$name: 'option_state',
$: { },
$children: {[0]: boolean, [1]: boolean, [2]: string, [3]: number|string|boolean} & {}[],
}
export interface GoalNode {
$name: 'goal',
$: { },
$children: {[0]: number, [1]: AnnotatedText[], [2]: AnnotatedText|null} & {}[]
}
export interface GoalsNode {
$name: 'goals',
$: { },
$children: {[0]: Subgoal[]|null, [1]: Pair<Subgoal[],Subgoal[]>[], [2]: Subgoal[]|null, [3]: Subgoal[]|null} & {}[]
}
export interface LocationNode {
$name: 'loc',
$: {start: string, stop: string},
$children: {}[],
}
export interface MessageLevelNode {
$name: 'message_level',
$: {val: string}
$children: {}[],
}
export interface MessageNode {
$name: 'message',
$children: {[0]: MessageLevel, [1]: AnnotatedText} & {}[]
message_level: MessageLevel,
}
export interface EvarNode {
$name: 'evar',
$: { },
$children: {[0]: string} & {}[],
}
export interface StatusNode {
$name: 'status',
$: { },
$children: {[0]: string[], [1]: string|null, [2]: string[], [3]: number} & {}[],
}
export interface CoqObjectNode<T> {
$name: 'coq_object',
$: { },
$children: {[0]: string[], [1]: string[], [2]: T} & {}[],
}
export interface CoqInfoNode {
$name: 'coq_info',
$: { },
$children: {[0]: string, [1]: string, [2]: string, [3]: string} & {}[]
}
export type TypedNode =
/** Raw nodes */
StateIdNode | EditIdNode | IntNode | StringNode | UnitNode | BoolNode |
PairNode | ListNode | UnionNode |
OptionNode | OptionValueNode | OptionStateNode |
GoalNode | GoalsNode |
LocationNode | MessageLevelNode | MessageNode |
LtacProfTacticNode | LtacProfResultsNode |
FeedbackNode | FeedbackContentNode |
StatusNode |
ValueNode;
export interface FailValueNode {
$name: 'value',
$: {val: 'fail', loc_s?: string, loc_e?: string},
$children: {[0]: StateId, [1]: AnnotatedText} & {}[],
}
export function optionIsSome(opt: OptionNode): opt is OptionSomeNode {
return opt.$.val === 'some';
}
export function optValIsInt(opt: OptionValueNode) : opt is OptionValueIntNode {
return opt.$.val === 'intvalue';
}
export function optValIsStringOpt(opt: OptionValueNode) : opt is OptionValueStringOptNode {
return opt.$.val === 'stringoptvalue';
}
export function optValIsBool(opt: OptionValueNode) : opt is OptionValueBoolNode {
return opt.$.val === 'boolvalue';
}
export function optValIsString(opt: OptionValueNode) : opt is OptionValueStringNode {
return opt.$.val === 'stringvalue';
}
export function isInl<X,Y>(value: Union<X,Y>) : value is UnionL<X> {
return value.tag === 'inl';
}
export interface GoodValueNode {
$name: 'value',
$: {val: 'good'},
$children: {[0]: ValueReturn } & {}[],
}
export type ValueNode = FailValueNode | GoodValueNode;
export function isFailValue(value: ValueNode) : value is FailValueNode {
return value.$.val === 'fail';
}
export function isGoodValue(value: ValueNode) : value is GoodValueNode {
return value.$.val === 'good';
}
}
function check(t:'state_id', r: StateId);
function check(t:'edit_id', r: EditId);
function check(t:'int', r: number);
function check(t:'bool', r: boolean);
function check(t:'string', r: string);
function check(t:'unit', r: {});
function check(t:'pair', r: Pair<CoqValue,CoqValue>);
function check(t:'list', r: CoqValueList);
function check(t:'ltacprof_tactic', r: LtacProfTactic);
function check(t:'ltacprof', r: LtacProfResults);
function check(t:'feedback_content', r: FeedbackContent);
function check(t:'feedback', r: StateFeedback);
function check(t:'union', r: UnionCoqValue);
function check(t:'option', r?: CoqValue);
function check(t:'option_value', r?: number|string|boolean);
function check(t:'option_state', r?: OptionState);
function check(t:'goal', r?: Subgoal);
function check(t:'goals', r?: Goals);
function check(t:'loc', r?: Location );
function check(t:'message_level', r?: MessageLevel );
function check(t:'message', r?: Message );
function check(t:'status', r?: CoqStatus );
function check(t:'value', r?: ValueReturn|FailValue );
function check(tag:string, result:CoqValue) : CoqValue {
return result;
}
function unreachable(x: never) : never { return x }
export abstract class Deserialize {
public constructor() {}
public deserialize(value: Node) : CoqValue {
return this.doDeserialize(value as any as Nodes.TypedNode);
}
private doDeserialize(value: Nodes.TypedNode) : CoqValue {
switch(value.$name)
{
case 'state_id':
return check(value.$name, +value.$.val);
case 'edit_id':
return check(value.$name, +value.$.val);
case 'int':
return check(value.$name, +value.$children[0]);
case 'string':
return check(value.$name, value.$children[0]);
case 'unit':
return check(value.$name, {});
case 'pair':
return check(value.$name, value.$children);
case 'list':
return check(value.$name, value.$children);
case 'bool':
if(typeof value.$.val === 'boolean')
return check(value.$name, value.$.val);
else if (value.$.val.toLocaleLowerCase() === 'true')
return check(value.$name, true);
else
return check(value.$name, false);
case 'union':
switch(value.$.val) {
case 'in_l': return check(value.$name, {tag: 'inl', value: value.$children[0]});
case 'in_r': return check(value.$name, {tag: 'inr', value: value.$children[0]});
}
break;
case 'option':
return check(value.$name, Nodes.optionIsSome(value) ? value.$children[0] : null)
case 'option_value': {
if(Nodes.optValIsInt(value))
return check(value.$name, value.option);
else if(Nodes.optValIsStringOpt(value))
return check(value.$name, value.option);
else if(Nodes.optValIsBool(value))
return check(value.$name, value.bool);
else if(Nodes.optValIsString(value))
return check(value.$name, value.$children[0]);
else
break
}
case 'option_state': {
return check(value.$name, {
synchronized: value.$children[0],
deprecated: value.$children[1],
name: value.$children[2],
value: value.$children[3],
})
}
case 'goal':
return check(value.$name, {
id: +value.$children[0],
hypotheses: value.$children[1],
goal: value.$children[2] || []
})
case 'goals': {
return check(value.$name, {
goals: value.$children[0] || [],
backgroundGoals: (value.$children[1] || [])
.reduce<UnfocusedGoalStack>
( (bg, v: Pair<Subgoal[],Subgoal[]>) => ({before: v[0], next: bg, after: v[1] }), null),
shelvedGoals: value.$children[2] || [],
abandonedGoals: value.$children[3] || []
})
} case 'loc':
return check(value.$name, {start: +value.$.start, stop: +value.$.stop})
case 'message_level':
return check(value.$name, coqProto.MessageLevel[value.$.val]);
case 'message':
return check(value.$name, {
level: value.message_level,
message: value.$children[1] || ""
});
case 'status':
return check(value.$name, {
path: value.$children[0],
proofName: value.$children[1],
allProofs: value.$children[2],
proofNumber: value.$children[3],
});
case 'value':
if(Nodes.isGoodValue(value))
return check(value.$name, {status: 'good', result: value.$children[0]})
else
return check(value.$name, {
status: 'fail',
stateId: value.$children[0],
message: value.$children[1] || "",
location: {start: +value.$.loc_s, stop: +value.$.loc_e},
} as FailValue);
case 'ltacprof_tactic':
return check(value.$name, {
name: value.$.name,
statistics: {
total: +value.$.total,
local: +value.$.self,
num_calls: +value.$.num_calls,
max_total: +value.$.max_total},
tactics: value.$children
});
case 'ltacprof':
return check(value.$name, {
total_time: +value.$.total_time,
tactics: value.$children
});
case 'feedback_content':
value.$kind = value.$.val;
return check(value.$name, this.deserializeFeedbackContent(value as Node));
case 'feedback': {
let objectId : coqProto.ObjectId;
if(value.$['object'] === 'state')
objectId = {objectKind: "stateid", stateId: +value['state_id']};
else if(value.$['object'] === 'edit')
objectId = {objectKind: "editid", editId: +value['edit_id']};
const result = Object.assign<coqProto.FeedbackBase, coqProto.FeedbackContent>({
objectId: objectId,
route: +(value.$.route || "0"),
}, value.$children[1]) /* TODO: TS 2.1 will equate A&(B|C)=(A&B)|(A&C) so this cast will not be necessary */ as coqProto.StateFeedback;
return check(value.$name, result);
}
default:
return unreachable(value);
}
}
public deserializeFeedbackContent(value: Node) : FeedbackContent {
return this.doDeserializeFeedbackContent(value as Nodes.FeedbackContentNode);
}
private doDeserializeFeedbackContent(value: Nodes.FeedbackContentNode) : FeedbackContent {
let result : coqProto.FeedbackContent;
switch (value.$kind)
{ case 'workerstatus': {
let statusStr = value.$children[0][1];
let reSearch = /^(?:proof:[ ]*)(.*)/.exec(statusStr);
if(reSearch)
result = {
feedbackKind: "worker-status",
id: value.$children[0][0],
state: coqProto.WorkerState.Proof,
ident: reSearch[1]
};
else
result = {
feedbackKind: "worker-status",
id: value.$children[0][0],
state: coqProto.WorkerState[statusStr]
};
return result;
} case 'filedependency': {
let file = value.$children[0] || "";
let dependency = value.$children[1];
result = {
feedbackKind: "file-dependency",
source: file,
dependsOn: dependency,
};
return result;
} case 'fileloaded':
result = {
feedbackKind: "file-loaded",
module: value.$children[0],
filename: value.$children[1]
};
return result;
// (Feedback.GlobRef (loc, filepath, modpath, ident, ty))
// Feedback.feedback (Feedback.GlobDef (loc, id, secpath, ty))
case 'globref':
result = {
feedbackKind: 'glob-ref',
location: value.$children[0],
filePath: value.$children[1],
modulePath: value.$children[2],
identity: value.$children[3],
type: value.$children[4],
}
console.log("glob-ref: " + util.inspect(result));
return result;
case 'globdef':
result = {
feedbackKind: 'glob-def',
location: value.$children[0],
identity: value.$children[1],
secPath: value.$children[2],
type: value.$children[3],
}
console.log("glob-def: " + util.inspect(result));
return result;
case 'message':
return {
feedbackKind: "message",
level: value.$children[0].level,
location: value.$children[0].location,
message: value.$children[0].message,
};
case 'errormsg':
return {
feedbackKind: "message",
level: coqProto.MessageLevel.Error,
location: value.$children[0],
message: value.$children[1]
};
case 'addedaxiom':
case 'processed':
case 'incomplete':
case 'complete':
result = {
feedbackKind: 'sentence-status',
status: SentenceStatus[value.$.val],
worker: "",
inProgressDelta: 0,
}
return result;
case 'inprogress': // has worker id
result = {
feedbackKind: 'sentence-status',
status: SentenceStatus[value.$.val],
worker: "",
inProgressDelta: value.$children[0],
}
return result;
case 'processingin': // change in the nuber of proofs being worked on
result = {
feedbackKind: 'sentence-status',
status: SentenceStatus[value.$.val],
worker: value.$children[0],
inProgressDelta: 0,
}
return result;
case 'custom': {
if(value.$children[1] === 'ltacprof_results')
result = Object.assign<{feedbackKind: "ltacprof"},LtacProfResults>(
{feedbackKind: "ltacprof"}, value.$children[2])
else
result = {
feedbackKind: "custom",
location: value.$children[0],
type: value.$children[1],
data: value.$children[2],
};
return result;
} default:
result = {
feedbackKind: "unknown",
data: (value as Node),
};
return result;
}
}
} | the_stack |
import {PinoLogger} from 'nestjs-pino';
import {
Currency,
EstimateGasEth,
fromXdcAddress,
generateAddressFromXPub,
generatePrivateKeyFromMnemonic,
generateWallet,
prepareXdcOrErc20SignedTransaction,
prepareXdcSmartContractWriteMethodInvocation,
sendXdcSmartContractReadMethodInvocationTransaction,
SmartContractMethodInvocation,
SmartContractReadMethodInvocation,
TransactionHash,
TransferErc20,
xdcGetGasPriceInWei,
} from '@tatumio/tatum';
import Web3 from 'web3';
import {fromWei} from 'web3-utils';
import axios from 'axios';
import {SignatureId} from '@tatumio/tatum/dist/src/model/response/common/SignatureId';
import {XdcError} from './XdcError';
import BigNumber from 'bignumber.js';
export abstract class XdcService {
private static mapBlock(block: any) {
return {
difficulty: parseInt(block.difficulty, 16),
extraData: block.extraData,
gasLimit: parseInt(block.gasLimit, 16),
gasUsed: parseInt(block.gasUsed, 16),
hash: block.hash,
logsBloom: block.logsBloom,
miner: block.miner,
nonce: block.nonce,
number: parseInt(block.number, 16),
parentHash: block.parentHash,
sha3Uncles: block.sha3Uncles,
size: parseInt(block.size, 16),
stateRoot: block.stateRoot,
timestamp: parseInt(block.timestamp, 16),
totalDifficulty: parseInt(block.totalDifficulty, 16),
transactions: block.transactions.map(XdcService.mapTransaction),
uncles: block.uncles,
};
}
private static mapTransaction(tx: any) {
return {
...tx,
blockNumber: parseInt(tx.blockNumber, 16),
gas: parseInt(tx.gas, 16),
nonce: parseInt(tx.nonce, 16),
transactionIndex: parseInt(tx.transactionIndex, 16),
value: new BigNumber(tx.value).toString(),
gasUsed: tx.gasUsed !== undefined ? new BigNumber(tx.gasUsed).toString() : undefined,
cumulativeGasUsed: tx.cumulativeGasUsed !== undefined ? new BigNumber(tx.cumulativeGasUsed).toString() : undefined,
transactionHash: tx.hash,
status: tx.status !== undefined ? !!parseInt(tx.status, 16) : undefined,
logs: tx.logs?.map(l => ({
...l,
logIndex: parseInt(l.logIndex, 16),
transactionIndex: parseInt(l.transactionIndex, 16),
blockNumber: parseInt(l.blockNumber, 16),
}))
};
};
protected constructor(protected readonly logger: PinoLogger) {
}
protected abstract isTestnet(): Promise<boolean>
protected abstract getNodesUrl(testnet: boolean): Promise<string[]>
protected abstract storeKMSTransaction(txData: string, currency: string, signatureId: string[], index?: number): Promise<string>;
protected abstract completeKMSTransaction(txId: string, signatureId: string): Promise<void>;
private async getFirstNodeUrl(testnet: boolean): Promise<string> {
const nodes = await this.getNodesUrl(testnet);
if (nodes.length === 0) {
new XdcError('Nodes url array must have at least one element.', 'xdc.nodes.url');
}
return nodes[0];
}
public async getClient(testnet: boolean): Promise<Web3> {
return new Web3(await this.getFirstNodeUrl(testnet));
}
public async broadcast(txData: string, signatureId?: string): Promise<{
txId: string,
failed?: boolean,
}> {
this.logger.info(`Broadcast tx for XDC with data '${txData}'`);
let txId;
try {
const url = (await this.getNodesUrl(await this.isTestnet()))[0];
const {result, error} = (await axios.post(url, {
jsonrpc: '2.0',
id: 0,
method: 'eth_sendRawTransaction',
params: [txData]
}, {headers: {'Content-Type': 'application/json'}})).data;
if (error) {
throw new XdcError(`Unable to broadcast transaction due to ${error.message}.`, 'xdc.broadcast.failed');
}
txId = result;
} catch (e) {
if (e.constructor.name === XdcError.name) {
throw e;
}
this.logger.error(e);
throw new XdcError(`Unable to broadcast transaction due to ${e.message}.`, 'xdc.broadcast.failed');
}
if (signatureId) {
try {
await this.completeKMSTransaction(txId, signatureId);
} catch (e) {
this.logger.error(e);
return {txId, failed: true};
}
}
return {txId};
}
public async getCurrentBlock(testnet?: boolean): Promise<number> {
const t = testnet === undefined ? await this.isTestnet() : testnet;
return (await this.getClient(t)).eth.getBlockNumber();
}
public async getBlock(hash: string | number, testnet?: boolean) {
const t = testnet === undefined ? await this.isTestnet() : testnet;
try {
const isHash = typeof hash === 'string' && hash.length >= 64;
const block = (await axios.post(await this.getFirstNodeUrl(t), {
jsonrpc: '2.0',
id: 0,
method: isHash ? 'eth_getBlockByHash' : 'eth_getBlockByNumber',
params: [
isHash ? hash : `0x${new BigNumber(hash).toString(16)}`,
true
]
}, {headers: {'Content-Type': 'application/json'}})).data.result;
return XdcService.mapBlock(block);
} catch (e) {
this.logger.error(e);
throw e;
}
}
public async getTransaction(txId: string, testnet?: boolean) {
const t = testnet === undefined ? await this.isTestnet() : testnet;
try {
const {r, s, v, hash, ...transaction} = (await axios.post(await this.getFirstNodeUrl(t), {
jsonrpc: '2.0',
id: 0,
method: 'eth_getTransactionByHash',
params: [
txId
]
}, {headers: {'Content-Type': 'application/json'}})).data?.result;
let receipt = {};
try {
receipt = (await axios.post(await this.getFirstNodeUrl(t), {
jsonrpc: '2.0',
id: 0,
method: 'eth_getTransactionReceipt',
params: [
txId
]
}, {headers: {'Content-Type': 'application/json'}})).data?.result;
} catch (_) {
transaction.transactionHash = hash;
}
return XdcService.mapTransaction({...transaction, ...receipt, hash});
} catch (e) {
this.logger.error(e);
throw new XdcError('Transaction not found. Possible not exists or is still pending.', 'tx.not.found');
}
}
private async broadcastOrStoreKMSTransaction({
transactionData,
signatureId,
index
}: BroadcastOrStoreKMSTransaction) {
if (signatureId) {
return {
signatureId: await this.storeKMSTransaction(transactionData, Currency.XDC, [signatureId], index),
};
}
return this.broadcast(transactionData);
}
public async web3Method(body: any) {
const node = await this.getFirstNodeUrl(await this.isTestnet());
return (await axios.post(node, body, {headers: {'Content-Type': 'application/json'}})).data;
}
public async generateWallet(mnemonic?: string) {
return generateWallet(Currency.XDC, await this.isTestnet(), mnemonic);
}
public async generatePrivateKey(mnemonic: string, index: number) {
const key = await generatePrivateKeyFromMnemonic(Currency.XDC, await this.isTestnet(), mnemonic, index);
return {key};
}
public async generateAddress(xpub: string, derivationIndex: string): Promise<{ address: string }> {
const address = await generateAddressFromXPub(Currency.XDC, await this.isTestnet(), xpub, parseInt(derivationIndex));
return {address};
}
public async estimateGas(body: EstimateGasEth): Promise<any> {
const client = await this.getClient(await this.isTestnet());
const _body = {
...body,
to: body.to ? fromXdcAddress(body.to) : undefined,
from: body.from ? fromXdcAddress(body.from) : undefined,
} as EstimateGasEth;
return {
gasLimit: await client.eth.estimateGas(_body),
gasPrice: await xdcGetGasPriceInWei(),
};
}
public async getBalance(address: string): Promise<{ balance: string }> {
const client = await this.getClient(await this.isTestnet());
return {balance: fromWei(await client.eth.getBalance(fromXdcAddress(address)), 'ether')};
}
public async sendXdcOrErc20Transaction(transfer: TransferErc20): Promise<TransactionHash | SignatureId> {
const transactionData = await prepareXdcOrErc20SignedTransaction({...transfer, currency: Currency.XDC}, await this.getFirstNodeUrl(await this.isTestnet()));
return this.broadcastOrStoreKMSTransaction({
transactionData,
signatureId: transfer.signatureId,
index: transfer.index
});
}
// public async sendCustomErc20Transaction(transferCustomErc20: TransferCustomErc20): Promise<TransactionHash | SignatureId> {
// const transactionData = await prepareXdcCustomErc20SignedTransaction(transferCustomErc20, await this.getFirstNodeUrl(await this.isTestnet()));
// return this.broadcastOrStoreKMSTransaction({
// transactionData,
// signatureId: transferCustomErc20.signatureId,
// index: transferCustomErc20.index
// });
// }
public async getTransactionCount(address: string) {
const client = await this.getClient(await this.isTestnet());
return client.eth.getTransactionCount(fromXdcAddress(address), 'pending');
}
public async invokeSmartContractMethod(smartContractMethodInvocation: SmartContractMethodInvocation | SmartContractReadMethodInvocation) {
const node = await this.getFirstNodeUrl(await this.isTestnet());
const params = smartContractMethodInvocation.params.map(e => `${e}`.startsWith('xdc') ? fromXdcAddress(e) : e);
const tx = {
...smartContractMethodInvocation,
params,
} as SmartContractMethodInvocation;
if (smartContractMethodInvocation.methodABI.stateMutability === 'view') {
return sendXdcSmartContractReadMethodInvocationTransaction(tx, node);
}
const transactionData = await prepareXdcSmartContractWriteMethodInvocation(tx, node);
return this.broadcastOrStoreKMSTransaction({
transactionData,
signatureId: tx.signatureId,
index: tx.index
});
}
} | the_stack |
* OpenAPI Petstore
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import * as runtime from '../runtime';
import {
ModelApiResponse,
ModelApiResponseFromJSON,
ModelApiResponseToJSON,
Pet,
PetFromJSON,
PetToJSON,
} from '../models';
export interface AddPetRequest {
pet: Pet;
}
export interface DeletePetRequest {
petId: number;
apiKey?: string;
}
export interface FindPetsByStatusRequest {
status: Array<FindPetsByStatusStatusEnum>;
}
export interface FindPetsByTagsRequest {
tags: Set<string>;
}
export interface GetPetByIdRequest {
petId: number;
}
export interface UpdatePetRequest {
pet: Pet;
}
export interface UpdatePetWithFormRequest {
petId: number;
name?: string;
status?: string;
}
export interface UploadFileRequest {
petId: number;
additionalMetadata?: string;
file?: Blob;
}
export interface UploadFileWithRequiredFileRequest {
petId: number;
requiredFile: Blob;
additionalMetadata?: string;
}
/**
*
*/
export class PetApi extends runtime.BaseAPI {
/**
* Add a new pet to the store
*/
async addPetRaw(requestParameters: AddPetRequest, initOverrides?: RequestInit): Promise<runtime.ApiResponse<void>> {
if (requestParameters.pet === null || requestParameters.pet === undefined) {
throw new runtime.RequiredError('pet','Required parameter requestParameters.pet was null or undefined when calling addPet.');
}
const queryParameters: any = {};
const headerParameters: runtime.HTTPHeaders = {};
headerParameters['Content-Type'] = 'application/json';
if (this.configuration && this.configuration.accessToken) {
// oauth required
headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]);
}
const response = await this.request({
path: `/pet`,
method: 'POST',
headers: headerParameters,
query: queryParameters,
body: PetToJSON(requestParameters.pet),
}, initOverrides);
return new runtime.VoidApiResponse(response);
}
/**
* Add a new pet to the store
*/
async addPet(requestParameters: AddPetRequest, initOverrides?: RequestInit): Promise<void> {
await this.addPetRaw(requestParameters, initOverrides);
}
/**
* Deletes a pet
*/
async deletePetRaw(requestParameters: DeletePetRequest, initOverrides?: RequestInit): Promise<runtime.ApiResponse<void>> {
if (requestParameters.petId === null || requestParameters.petId === undefined) {
throw new runtime.RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling deletePet.');
}
const queryParameters: any = {};
const headerParameters: runtime.HTTPHeaders = {};
if (requestParameters.apiKey !== undefined && requestParameters.apiKey !== null) {
headerParameters['api_key'] = String(requestParameters.apiKey);
}
if (this.configuration && this.configuration.accessToken) {
// oauth required
headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]);
}
const response = await this.request({
path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))),
method: 'DELETE',
headers: headerParameters,
query: queryParameters,
}, initOverrides);
return new runtime.VoidApiResponse(response);
}
/**
* Deletes a pet
*/
async deletePet(requestParameters: DeletePetRequest, initOverrides?: RequestInit): Promise<void> {
await this.deletePetRaw(requestParameters, initOverrides);
}
/**
* Multiple status values can be provided with comma separated strings
* Finds Pets by status
*/
async findPetsByStatusRaw(requestParameters: FindPetsByStatusRequest, initOverrides?: RequestInit): Promise<runtime.ApiResponse<Array<Pet>>> {
if (requestParameters.status === null || requestParameters.status === undefined) {
throw new runtime.RequiredError('status','Required parameter requestParameters.status was null or undefined when calling findPetsByStatus.');
}
const queryParameters: any = {};
if (requestParameters.status) {
queryParameters['status'] = requestParameters.status.join(runtime.COLLECTION_FORMATS["csv"]);
}
const headerParameters: runtime.HTTPHeaders = {};
if (this.configuration && this.configuration.accessToken) {
// oauth required
headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]);
}
const response = await this.request({
path: `/pet/findByStatus`,
method: 'GET',
headers: headerParameters,
query: queryParameters,
}, initOverrides);
return new runtime.JSONApiResponse(response, (jsonValue) => jsonValue.map(PetFromJSON));
}
/**
* Multiple status values can be provided with comma separated strings
* Finds Pets by status
*/
async findPetsByStatus(requestParameters: FindPetsByStatusRequest, initOverrides?: RequestInit): Promise<Array<Pet>> {
const response = await this.findPetsByStatusRaw(requestParameters, initOverrides);
return await response.value();
}
/**
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
* Finds Pets by tags
*/
async findPetsByTagsRaw(requestParameters: FindPetsByTagsRequest, initOverrides?: RequestInit): Promise<runtime.ApiResponse<Set<Pet>>> {
if (requestParameters.tags === null || requestParameters.tags === undefined) {
throw new runtime.RequiredError('tags','Required parameter requestParameters.tags was null or undefined when calling findPetsByTags.');
}
const queryParameters: any = {};
if (requestParameters.tags) {
queryParameters['tags'] = Array.from(requestParameters.tags).join(runtime.COLLECTION_FORMATS["csv"]);
}
const headerParameters: runtime.HTTPHeaders = {};
if (this.configuration && this.configuration.accessToken) {
// oauth required
headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]);
}
const response = await this.request({
path: `/pet/findByTags`,
method: 'GET',
headers: headerParameters,
query: queryParameters,
}, initOverrides);
return new runtime.JSONApiResponse(response, (jsonValue) => new Set(jsonValue.map(PetFromJSON)));
}
/**
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
* Finds Pets by tags
*/
async findPetsByTags(requestParameters: FindPetsByTagsRequest, initOverrides?: RequestInit): Promise<Set<Pet>> {
const response = await this.findPetsByTagsRaw(requestParameters, initOverrides);
return await response.value();
}
/**
* Returns a single pet
* Find pet by ID
*/
async getPetByIdRaw(requestParameters: GetPetByIdRequest, initOverrides?: RequestInit): Promise<runtime.ApiResponse<Pet>> {
if (requestParameters.petId === null || requestParameters.petId === undefined) {
throw new runtime.RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling getPetById.');
}
const queryParameters: any = {};
const headerParameters: runtime.HTTPHeaders = {};
if (this.configuration && this.configuration.apiKey) {
headerParameters["api_key"] = this.configuration.apiKey("api_key"); // api_key authentication
}
const response = await this.request({
path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))),
method: 'GET',
headers: headerParameters,
query: queryParameters,
}, initOverrides);
return new runtime.JSONApiResponse(response, (jsonValue) => PetFromJSON(jsonValue));
}
/**
* Returns a single pet
* Find pet by ID
*/
async getPetById(requestParameters: GetPetByIdRequest, initOverrides?: RequestInit): Promise<Pet> {
const response = await this.getPetByIdRaw(requestParameters, initOverrides);
return await response.value();
}
/**
* Update an existing pet
*/
async updatePetRaw(requestParameters: UpdatePetRequest, initOverrides?: RequestInit): Promise<runtime.ApiResponse<void>> {
if (requestParameters.pet === null || requestParameters.pet === undefined) {
throw new runtime.RequiredError('pet','Required parameter requestParameters.pet was null or undefined when calling updatePet.');
}
const queryParameters: any = {};
const headerParameters: runtime.HTTPHeaders = {};
headerParameters['Content-Type'] = 'application/json';
if (this.configuration && this.configuration.accessToken) {
// oauth required
headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]);
}
const response = await this.request({
path: `/pet`,
method: 'PUT',
headers: headerParameters,
query: queryParameters,
body: PetToJSON(requestParameters.pet),
}, initOverrides);
return new runtime.VoidApiResponse(response);
}
/**
* Update an existing pet
*/
async updatePet(requestParameters: UpdatePetRequest, initOverrides?: RequestInit): Promise<void> {
await this.updatePetRaw(requestParameters, initOverrides);
}
/**
* Updates a pet in the store with form data
*/
async updatePetWithFormRaw(requestParameters: UpdatePetWithFormRequest, initOverrides?: RequestInit): Promise<runtime.ApiResponse<void>> {
if (requestParameters.petId === null || requestParameters.petId === undefined) {
throw new runtime.RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling updatePetWithForm.');
}
const queryParameters: any = {};
const headerParameters: runtime.HTTPHeaders = {};
if (this.configuration && this.configuration.accessToken) {
// oauth required
headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]);
}
const consumes: runtime.Consume[] = [
{ contentType: 'application/x-www-form-urlencoded' },
];
// @ts-ignore: canConsumeForm may be unused
const canConsumeForm = runtime.canConsumeForm(consumes);
let formParams: { append(param: string, value: any): any };
let useForm = false;
if (useForm) {
formParams = new FormData();
} else {
formParams = new URLSearchParams();
}
if (requestParameters.name !== undefined) {
formParams.append('name', requestParameters.name as any);
}
if (requestParameters.status !== undefined) {
formParams.append('status', requestParameters.status as any);
}
const response = await this.request({
path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))),
method: 'POST',
headers: headerParameters,
query: queryParameters,
body: formParams,
}, initOverrides);
return new runtime.VoidApiResponse(response);
}
/**
* Updates a pet in the store with form data
*/
async updatePetWithForm(requestParameters: UpdatePetWithFormRequest, initOverrides?: RequestInit): Promise<void> {
await this.updatePetWithFormRaw(requestParameters, initOverrides);
}
/**
* uploads an image
*/
async uploadFileRaw(requestParameters: UploadFileRequest, initOverrides?: RequestInit): Promise<runtime.ApiResponse<ModelApiResponse>> {
if (requestParameters.petId === null || requestParameters.petId === undefined) {
throw new runtime.RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling uploadFile.');
}
const queryParameters: any = {};
const headerParameters: runtime.HTTPHeaders = {};
if (this.configuration && this.configuration.accessToken) {
// oauth required
headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]);
}
const consumes: runtime.Consume[] = [
{ contentType: 'multipart/form-data' },
];
// @ts-ignore: canConsumeForm may be unused
const canConsumeForm = runtime.canConsumeForm(consumes);
let formParams: { append(param: string, value: any): any };
let useForm = false;
// use FormData to transmit files using content-type "multipart/form-data"
useForm = canConsumeForm;
if (useForm) {
formParams = new FormData();
} else {
formParams = new URLSearchParams();
}
if (requestParameters.additionalMetadata !== undefined) {
formParams.append('additionalMetadata', requestParameters.additionalMetadata as any);
}
if (requestParameters.file !== undefined) {
formParams.append('file', requestParameters.file as any);
}
const response = await this.request({
path: `/pet/{petId}/uploadImage`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))),
method: 'POST',
headers: headerParameters,
query: queryParameters,
body: formParams,
}, initOverrides);
return new runtime.JSONApiResponse(response, (jsonValue) => ModelApiResponseFromJSON(jsonValue));
}
/**
* uploads an image
*/
async uploadFile(requestParameters: UploadFileRequest, initOverrides?: RequestInit): Promise<ModelApiResponse> {
const response = await this.uploadFileRaw(requestParameters, initOverrides);
return await response.value();
}
/**
* uploads an image (required)
*/
async uploadFileWithRequiredFileRaw(requestParameters: UploadFileWithRequiredFileRequest, initOverrides?: RequestInit): Promise<runtime.ApiResponse<ModelApiResponse>> {
if (requestParameters.petId === null || requestParameters.petId === undefined) {
throw new runtime.RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling uploadFileWithRequiredFile.');
}
if (requestParameters.requiredFile === null || requestParameters.requiredFile === undefined) {
throw new runtime.RequiredError('requiredFile','Required parameter requestParameters.requiredFile was null or undefined when calling uploadFileWithRequiredFile.');
}
const queryParameters: any = {};
const headerParameters: runtime.HTTPHeaders = {};
if (this.configuration && this.configuration.accessToken) {
// oauth required
headerParameters["Authorization"] = await this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]);
}
const consumes: runtime.Consume[] = [
{ contentType: 'multipart/form-data' },
];
// @ts-ignore: canConsumeForm may be unused
const canConsumeForm = runtime.canConsumeForm(consumes);
let formParams: { append(param: string, value: any): any };
let useForm = false;
// use FormData to transmit files using content-type "multipart/form-data"
useForm = canConsumeForm;
if (useForm) {
formParams = new FormData();
} else {
formParams = new URLSearchParams();
}
if (requestParameters.additionalMetadata !== undefined) {
formParams.append('additionalMetadata', requestParameters.additionalMetadata as any);
}
if (requestParameters.requiredFile !== undefined) {
formParams.append('requiredFile', requestParameters.requiredFile as any);
}
const response = await this.request({
path: `/fake/{petId}/uploadImageWithRequiredFile`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))),
method: 'POST',
headers: headerParameters,
query: queryParameters,
body: formParams,
}, initOverrides);
return new runtime.JSONApiResponse(response, (jsonValue) => ModelApiResponseFromJSON(jsonValue));
}
/**
* uploads an image (required)
*/
async uploadFileWithRequiredFile(requestParameters: UploadFileWithRequiredFileRequest, initOverrides?: RequestInit): Promise<ModelApiResponse> {
const response = await this.uploadFileWithRequiredFileRaw(requestParameters, initOverrides);
return await response.value();
}
}
/**
* @export
* @enum {string}
*/
export enum FindPetsByStatusStatusEnum {
Available = 'available',
Pending = 'pending',
Sold = 'sold'
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs, enums } from "../types";
import * as utilities from "../utilities";
/**
* Provides an OpsWorks stack resource.
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* const main = new aws.opsworks.Stack("main", {
* region: "us-west-1",
* serviceRoleArn: aws_iam_role.opsworks.arn,
* defaultInstanceProfileArn: aws_iam_instance_profile.opsworks.arn,
* tags: {
* Name: "foobar-stack",
* },
* customJson: `{
* "foobar": {
* "version": "1.0.0"
* }
* }
* `,
* });
* ```
*
* ## Import
*
* OpsWorks stacks can be imported using the `id`, e.g.
*
* ```sh
* $ pulumi import aws:opsworks/stack:Stack bar 00000000-0000-0000-0000-000000000000
* ```
*/
export class Stack extends pulumi.CustomResource {
/**
* Get an existing Stack resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param state Any extra arguments used during the lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: StackState, opts?: pulumi.CustomResourceOptions): Stack {
return new Stack(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'aws:opsworks/stack:Stack';
/**
* Returns true if the given object is an instance of Stack. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is Stack {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === Stack.__pulumiType;
}
/**
* If set to `"LATEST"`, OpsWorks will automatically install the latest version.
*/
public readonly agentVersion!: pulumi.Output<string>;
public /*out*/ readonly arn!: pulumi.Output<string>;
/**
* If `manageBerkshelf` is enabled, the version of Berkshelf to use.
*/
public readonly berkshelfVersion!: pulumi.Output<string | undefined>;
/**
* Color to paint next to the stack's resources in the OpsWorks console.
*/
public readonly color!: pulumi.Output<string | undefined>;
/**
* Name of the configuration manager to use. Defaults to "Chef".
*/
public readonly configurationManagerName!: pulumi.Output<string | undefined>;
/**
* Version of the configuration manager to use. Defaults to "11.4".
*/
public readonly configurationManagerVersion!: pulumi.Output<string | undefined>;
/**
* When `useCustomCookbooks` is set, provide this sub-object as
* described below.
*/
public readonly customCookbooksSources!: pulumi.Output<outputs.opsworks.StackCustomCookbooksSource[]>;
/**
* Custom JSON attributes to apply to the entire stack.
*/
public readonly customJson!: pulumi.Output<string | undefined>;
/**
* Name of the availability zone where instances will be created
* by default. This is required unless you set `vpcId`.
*/
public readonly defaultAvailabilityZone!: pulumi.Output<string>;
/**
* The ARN of an IAM Instance Profile that created instances
* will have by default.
*/
public readonly defaultInstanceProfileArn!: pulumi.Output<string>;
/**
* Name of OS that will be installed on instances by default.
*/
public readonly defaultOs!: pulumi.Output<string | undefined>;
/**
* Name of the type of root device instances will have by default.
*/
public readonly defaultRootDeviceType!: pulumi.Output<string | undefined>;
/**
* Name of the SSH keypair that instances will have by default.
*/
public readonly defaultSshKeyName!: pulumi.Output<string | undefined>;
/**
* Id of the subnet in which instances will be created by default. Mandatory
* if `vpcId` is set, and forbidden if it isn't.
*/
public readonly defaultSubnetId!: pulumi.Output<string>;
/**
* Keyword representing the naming scheme that will be used for instance hostnames
* within this stack.
*/
public readonly hostnameTheme!: pulumi.Output<string | undefined>;
/**
* Boolean value controlling whether Opsworks will run Berkshelf for this stack.
*/
public readonly manageBerkshelf!: pulumi.Output<boolean | undefined>;
/**
* The name of the stack.
*/
public readonly name!: pulumi.Output<string>;
/**
* The name of the region where the stack will exist.
*/
public readonly region!: pulumi.Output<string>;
/**
* The ARN of an IAM role that the OpsWorks service will act as.
*/
public readonly serviceRoleArn!: pulumi.Output<string>;
public /*out*/ readonly stackEndpoint!: pulumi.Output<string>;
/**
* A map of tags to assign to the resource. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level.
*/
public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* A map of tags assigned to the resource, including those inherited from the provider .
*/
public /*out*/ readonly tagsAll!: pulumi.Output<{[key: string]: string}>;
/**
* Boolean value controlling whether the custom cookbook settings are
* enabled.
*/
public readonly useCustomCookbooks!: pulumi.Output<boolean | undefined>;
/**
* Boolean value controlling whether the standard OpsWorks
* security groups apply to created instances.
*/
public readonly useOpsworksSecurityGroups!: pulumi.Output<boolean | undefined>;
/**
* The id of the VPC that this stack belongs to.
*/
public readonly vpcId!: pulumi.Output<string>;
/**
* Create a Stack resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args: StackArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: StackArgs | StackState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as StackState | undefined;
inputs["agentVersion"] = state ? state.agentVersion : undefined;
inputs["arn"] = state ? state.arn : undefined;
inputs["berkshelfVersion"] = state ? state.berkshelfVersion : undefined;
inputs["color"] = state ? state.color : undefined;
inputs["configurationManagerName"] = state ? state.configurationManagerName : undefined;
inputs["configurationManagerVersion"] = state ? state.configurationManagerVersion : undefined;
inputs["customCookbooksSources"] = state ? state.customCookbooksSources : undefined;
inputs["customJson"] = state ? state.customJson : undefined;
inputs["defaultAvailabilityZone"] = state ? state.defaultAvailabilityZone : undefined;
inputs["defaultInstanceProfileArn"] = state ? state.defaultInstanceProfileArn : undefined;
inputs["defaultOs"] = state ? state.defaultOs : undefined;
inputs["defaultRootDeviceType"] = state ? state.defaultRootDeviceType : undefined;
inputs["defaultSshKeyName"] = state ? state.defaultSshKeyName : undefined;
inputs["defaultSubnetId"] = state ? state.defaultSubnetId : undefined;
inputs["hostnameTheme"] = state ? state.hostnameTheme : undefined;
inputs["manageBerkshelf"] = state ? state.manageBerkshelf : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["region"] = state ? state.region : undefined;
inputs["serviceRoleArn"] = state ? state.serviceRoleArn : undefined;
inputs["stackEndpoint"] = state ? state.stackEndpoint : undefined;
inputs["tags"] = state ? state.tags : undefined;
inputs["tagsAll"] = state ? state.tagsAll : undefined;
inputs["useCustomCookbooks"] = state ? state.useCustomCookbooks : undefined;
inputs["useOpsworksSecurityGroups"] = state ? state.useOpsworksSecurityGroups : undefined;
inputs["vpcId"] = state ? state.vpcId : undefined;
} else {
const args = argsOrState as StackArgs | undefined;
if ((!args || args.defaultInstanceProfileArn === undefined) && !opts.urn) {
throw new Error("Missing required property 'defaultInstanceProfileArn'");
}
if ((!args || args.region === undefined) && !opts.urn) {
throw new Error("Missing required property 'region'");
}
if ((!args || args.serviceRoleArn === undefined) && !opts.urn) {
throw new Error("Missing required property 'serviceRoleArn'");
}
inputs["agentVersion"] = args ? args.agentVersion : undefined;
inputs["berkshelfVersion"] = args ? args.berkshelfVersion : undefined;
inputs["color"] = args ? args.color : undefined;
inputs["configurationManagerName"] = args ? args.configurationManagerName : undefined;
inputs["configurationManagerVersion"] = args ? args.configurationManagerVersion : undefined;
inputs["customCookbooksSources"] = args ? args.customCookbooksSources : undefined;
inputs["customJson"] = args ? args.customJson : undefined;
inputs["defaultAvailabilityZone"] = args ? args.defaultAvailabilityZone : undefined;
inputs["defaultInstanceProfileArn"] = args ? args.defaultInstanceProfileArn : undefined;
inputs["defaultOs"] = args ? args.defaultOs : undefined;
inputs["defaultRootDeviceType"] = args ? args.defaultRootDeviceType : undefined;
inputs["defaultSshKeyName"] = args ? args.defaultSshKeyName : undefined;
inputs["defaultSubnetId"] = args ? args.defaultSubnetId : undefined;
inputs["hostnameTheme"] = args ? args.hostnameTheme : undefined;
inputs["manageBerkshelf"] = args ? args.manageBerkshelf : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["region"] = args ? args.region : undefined;
inputs["serviceRoleArn"] = args ? args.serviceRoleArn : undefined;
inputs["tags"] = args ? args.tags : undefined;
inputs["useCustomCookbooks"] = args ? args.useCustomCookbooks : undefined;
inputs["useOpsworksSecurityGroups"] = args ? args.useOpsworksSecurityGroups : undefined;
inputs["vpcId"] = args ? args.vpcId : undefined;
inputs["arn"] = undefined /*out*/;
inputs["stackEndpoint"] = undefined /*out*/;
inputs["tagsAll"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(Stack.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering Stack resources.
*/
export interface StackState {
/**
* If set to `"LATEST"`, OpsWorks will automatically install the latest version.
*/
agentVersion?: pulumi.Input<string>;
arn?: pulumi.Input<string>;
/**
* If `manageBerkshelf` is enabled, the version of Berkshelf to use.
*/
berkshelfVersion?: pulumi.Input<string>;
/**
* Color to paint next to the stack's resources in the OpsWorks console.
*/
color?: pulumi.Input<string>;
/**
* Name of the configuration manager to use. Defaults to "Chef".
*/
configurationManagerName?: pulumi.Input<string>;
/**
* Version of the configuration manager to use. Defaults to "11.4".
*/
configurationManagerVersion?: pulumi.Input<string>;
/**
* When `useCustomCookbooks` is set, provide this sub-object as
* described below.
*/
customCookbooksSources?: pulumi.Input<pulumi.Input<inputs.opsworks.StackCustomCookbooksSource>[]>;
/**
* Custom JSON attributes to apply to the entire stack.
*/
customJson?: pulumi.Input<string>;
/**
* Name of the availability zone where instances will be created
* by default. This is required unless you set `vpcId`.
*/
defaultAvailabilityZone?: pulumi.Input<string>;
/**
* The ARN of an IAM Instance Profile that created instances
* will have by default.
*/
defaultInstanceProfileArn?: pulumi.Input<string>;
/**
* Name of OS that will be installed on instances by default.
*/
defaultOs?: pulumi.Input<string>;
/**
* Name of the type of root device instances will have by default.
*/
defaultRootDeviceType?: pulumi.Input<string>;
/**
* Name of the SSH keypair that instances will have by default.
*/
defaultSshKeyName?: pulumi.Input<string>;
/**
* Id of the subnet in which instances will be created by default. Mandatory
* if `vpcId` is set, and forbidden if it isn't.
*/
defaultSubnetId?: pulumi.Input<string>;
/**
* Keyword representing the naming scheme that will be used for instance hostnames
* within this stack.
*/
hostnameTheme?: pulumi.Input<string>;
/**
* Boolean value controlling whether Opsworks will run Berkshelf for this stack.
*/
manageBerkshelf?: pulumi.Input<boolean>;
/**
* The name of the stack.
*/
name?: pulumi.Input<string>;
/**
* The name of the region where the stack will exist.
*/
region?: pulumi.Input<string>;
/**
* The ARN of an IAM role that the OpsWorks service will act as.
*/
serviceRoleArn?: pulumi.Input<string>;
stackEndpoint?: pulumi.Input<string>;
/**
* A map of tags to assign to the resource. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* A map of tags assigned to the resource, including those inherited from the provider .
*/
tagsAll?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* Boolean value controlling whether the custom cookbook settings are
* enabled.
*/
useCustomCookbooks?: pulumi.Input<boolean>;
/**
* Boolean value controlling whether the standard OpsWorks
* security groups apply to created instances.
*/
useOpsworksSecurityGroups?: pulumi.Input<boolean>;
/**
* The id of the VPC that this stack belongs to.
*/
vpcId?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a Stack resource.
*/
export interface StackArgs {
/**
* If set to `"LATEST"`, OpsWorks will automatically install the latest version.
*/
agentVersion?: pulumi.Input<string>;
/**
* If `manageBerkshelf` is enabled, the version of Berkshelf to use.
*/
berkshelfVersion?: pulumi.Input<string>;
/**
* Color to paint next to the stack's resources in the OpsWorks console.
*/
color?: pulumi.Input<string>;
/**
* Name of the configuration manager to use. Defaults to "Chef".
*/
configurationManagerName?: pulumi.Input<string>;
/**
* Version of the configuration manager to use. Defaults to "11.4".
*/
configurationManagerVersion?: pulumi.Input<string>;
/**
* When `useCustomCookbooks` is set, provide this sub-object as
* described below.
*/
customCookbooksSources?: pulumi.Input<pulumi.Input<inputs.opsworks.StackCustomCookbooksSource>[]>;
/**
* Custom JSON attributes to apply to the entire stack.
*/
customJson?: pulumi.Input<string>;
/**
* Name of the availability zone where instances will be created
* by default. This is required unless you set `vpcId`.
*/
defaultAvailabilityZone?: pulumi.Input<string>;
/**
* The ARN of an IAM Instance Profile that created instances
* will have by default.
*/
defaultInstanceProfileArn: pulumi.Input<string>;
/**
* Name of OS that will be installed on instances by default.
*/
defaultOs?: pulumi.Input<string>;
/**
* Name of the type of root device instances will have by default.
*/
defaultRootDeviceType?: pulumi.Input<string>;
/**
* Name of the SSH keypair that instances will have by default.
*/
defaultSshKeyName?: pulumi.Input<string>;
/**
* Id of the subnet in which instances will be created by default. Mandatory
* if `vpcId` is set, and forbidden if it isn't.
*/
defaultSubnetId?: pulumi.Input<string>;
/**
* Keyword representing the naming scheme that will be used for instance hostnames
* within this stack.
*/
hostnameTheme?: pulumi.Input<string>;
/**
* Boolean value controlling whether Opsworks will run Berkshelf for this stack.
*/
manageBerkshelf?: pulumi.Input<boolean>;
/**
* The name of the stack.
*/
name?: pulumi.Input<string>;
/**
* The name of the region where the stack will exist.
*/
region: pulumi.Input<string>;
/**
* The ARN of an IAM role that the OpsWorks service will act as.
*/
serviceRoleArn: pulumi.Input<string>;
/**
* A map of tags to assign to the resource. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* Boolean value controlling whether the custom cookbook settings are
* enabled.
*/
useCustomCookbooks?: pulumi.Input<boolean>;
/**
* Boolean value controlling whether the standard OpsWorks
* security groups apply to created instances.
*/
useOpsworksSecurityGroups?: pulumi.Input<boolean>;
/**
* The id of the VPC that this stack belongs to.
*/
vpcId?: pulumi.Input<string>;
} | the_stack |
// This definition file is merge-compatible with ../gapi/gapi.d.ts
// Note the occurrences of "INCOMPLETE". For some interfaces and object types, I have only included
// the properties and methods that I've actually used so-far, and will add more as they become useful to me.
// Or, maybe you want to complete them?
// For Typescript newbs: To get shorter names, use e.g.
// type CollabModel = gapi.drive.realtime.Model;
// interface CollabList<T> extends gapi.drive.realtime.CollaborativeList<T> {}
// See section "Type Aliases" of http://www.typescriptlang.org/Content/TypeScript%20Language%20Specification.pdf
// gapi is a global var introduced by https://apis.google.com/js/api.js
declare namespace gapi.drive.realtime {
export type CollaborativeObjectType = 'EditableString' | 'Map' | 'List'
export type GoogEventHandler = ((evt:ObjectChangedEvent) => void) | ((e:Event) => void) | EventListener;
// Complete
// https://developers.google.com/google-apps/realtime/reference/gapi.drive.realtime.Collaborator
export class Collaborator {
// The HTML color associated with this collaborator. When possible, collaborators are assigned unique colors.
color : string;
// The display name for this collaborator.
displayName : string;
// True if this collaborator is anonymous, false otherwise.
isAnonymous : boolean
// True if this collaborator is the local user, false otherwise.
isMe : boolean;
// The permission ID for this collaborator. This ID is stable for a given user and is compatible with the
// Drive API permissions APIs. Use the userId property for all other uses.
permissionId : string;
// A URL that points to the profile photo for this collaborator, or to a generic profile photo for
// anonymous collaborators.
photoUrl : string;
// The session ID for this collaborator. A single user may have multiple sessions if they have the same document
// open on multiple devices or in multiple browser tabs.
sessionId : string;
// The user ID for this collaborator. This ID is stable for a given user and is compatible with most Google APIs
// except the Drive API permission APIs. For an ID which is compatible with the Drive API permission APIs,
// use the permissionId property.
userId : string;
constructor (sessionId:string, userId:string, displayName:string, color:string, isMe:boolean, isAnonymous:boolean,
photoUrl:string, permissionId:string);
}
// Complete
// https://developers.google.com/google-apps/realtime/reference/gapi.drive.realtime.CollaborativeObject
export class CollaborativeObject {
// The id of this collaborative object. Read-only.
id:string;
// The type of this collaborative object. For standard collaborative objects,
// see gapi.drive.realtime.CollaborrativeType for possible values; for custom collaborative objects, this value is
// application-defined.
// Addition: the possible values for standard objects are EditableString, List, and Map.
type:CollaborativeObjectType;
// Adds an event listener to the event target. The same handler can only be added once per the type.
// Even if you add the same handler multiple times using the same type then it will only be called once
// when the event is dispatched.
addEventListener(type:string, listener:GoogEventHandler, opt_capture?:boolean):void;
// Removes all event listeners from this object.
removeAllEventListeners():void;
// Removes an event listener from the event target. The handler must be the same object as the one added.
// If the handler has not been added then nothing is done.
removeEventListener(type:string, listener:GoogEventHandler, opt_capture?:boolean):void;
// Returns a string representation of this collaborative object.
toString():string;
}
// Complete
// https://developers.google.com/google-apps/realtime/reference/gapi.drive.realtime.IndexReference
export class IndexReference<V> extends CollaborativeObject {
// (Categories of) the shift behavior of an index reference when the element it points at is deleted.
static DeleteMode:{
SHIFT_AFTER_DELETE: string
SHIFT_BEFORE_DELETE: string
SHIFT_TO_INVALID: string
};
//The index of the current location the reference points to. Write to this property to change the referenced index.
index:number;
// The behavior of this index reference when the element it points at is deleted.
// @return one of the elements of DeleteMode
deleteMode():string;
// The object this reference points to. Read-only.
referencedObject():V;
}
// Complete
// https://developers.google.com/google-apps/realtime/reference/gapi.drive.realtime.CollaborativeMap
export class CollaborativeMap<V> extends CollaborativeObject {
size:number;
static type:'Map';
// Removes all entries.
clear():void;
// Removes the entry for the given key (if such an entry exists).
// @return the value that was mapped to this key, or null if there was no existing value.
delete(key:string):V;
// Returns the value mapped to the given key.
get(key:string):V;
// Checks if this map contains an entry for the given key.
has(key:string):boolean;
// Returns whether this map is empty.
isEmpty():boolean;
// Returns an array containing a copy of the items in this map. Modifications to the returned array do
// not modify this collaborative map.
// @return non-null Array of Arrays, where the inner arrays are tupples [string, V]
items():[string,V][];
// Returns an array containing a copy of the keys in this map. Modifications to the returned array
// do not modify this collaborative map.
keys():string[];
// Put the value into the map with the given key, overwriting an existing value for that key.
// @return the old map value, if any, that used to be mapped to the given key.
set(key:string, value:V):V;
// Returns an array containing a copy of the values in this map. Modifications to the returned array
// do not modify this collaborative map.
values():V[];
}
// Complete
// https://developers.google.com/google-apps/realtime/reference/gapi.drive.realtime.CollaborativeString
export class CollaborativeString extends CollaborativeObject {
// The length of the string. Read only.
length:number;
// The text of this collaborative string. Reading from this property is equivalent to calling getText(). Writing to this property is equivalent to calling setText().
text:string;
static type:'EditableString';
// Appends a string to the end of this one.
append(text:string):void;
// Gets a string representation of the collaborative string.
getText():string;
// Inserts a string into the collaborative string at a specific index.
insertString(index:number, text:string):void;
// Creates an IndexReference at the given {@code index}. If {@code canBeDeleted} is set, then a delete
// over the index will delete the reference. Otherwise the reference will shift to the beginning of the deleted range.
registerReference(index:number, canBeDeleted:boolean):IndexReference<CollaborativeString>;
// Deletes the text between startIndex (inclusive) and endIndex (exclusive).
removeRange(startIndex:number, endIndex:number):void;
// Sets the contents of this collaborative string. Note that this method performs a text diff between the
// current string contents and the new contents so that the string will be modified using the minimum number
// of text inserts and deletes possible to change the current contents to the newly-specified contents.
setText(text:string):void;
}
// Complete
// https://developers.google.com/google-apps/realtime/reference/gapi.drive.realtime.CollaborativeList
export class CollaborativeList<V> extends CollaborativeObject {
// The number of entries in the list. Assign to this field to reduce the size of the list.
// Note that the length given must be less than or equal to the current size.
// The length of a list cannot be extended in this way.
length:number;
static type:"List";
// Returns a copy of the contents of this collaborative list as an array.
// Changes to the returned object will not affect the original collaborative list.
asArray():V[];
// Removes all values from the list.
clear():void;
// Gets the value at the given index.
get(ind:number):V;
//Returns the first index of the given value, or -1 if it cannot be found.
indexOf(value:V, opt_comparatorFn?:(x1:V, x2:V) => boolean):number;
//Inserts an item into the list at a given index.
insert(index:number, value:V):void;
// Inserts a list of items into the list at a given index.
insertAll(index:number, values:V[]):void;
// Returns the last index of the given value, or -1 if it cannot be found.
lastIndexOf(value:V, opt_comparatorFn?:(x1:V, x2:V) => boolean):number;
//Moves a single element in this list (at index) to immediately before destinationIndex.
//Both indices are with respect to the position of elements before the move.
//For example, given the list: ['A', 'B', 'C']
//move(0, 0) is a no-op
//move(0, 1) is a no-op
//move(0, 2) yields ['B', 'A', 'C'] ('A' is moved to immediately before 'C')
//move(0, 3) yields ['B', 'C', 'A'] ('A' is moved to immediately before an imaginary element after the list end)
//move(1, 0) yields ['B', 'A', 'C'] ('B' is moved to immediately before 'A')
//move(1, 1) is a no-op
//move(1, 2) is a no-op
//move(1, 3) yields ['A', 'C', 'B'] ('B' is moved to immediately before an imaginary element after the list end)
move(index:number, destinationIndex:number):void;
// Moves a single element in this list (at index) to immediately before destinationIndex in the list destination.
// Both indices are with respect to the position of elements before the move.
// If the provided destination is this list, this function is identical to move(index, destinationIndex).
moveToList(index:number, destination:CollaborativeList<V>, destinationIndex:number):void;
// Adds an item to the end of the list.
// @return the new length of the list
push(value:V):number;
// Adds an array of values to the end of the list.
pushAll(values:V[]):void;
// Creates an IndexReference at the given index. If canBeDeleted is true, then a delete over the index will delete
// the reference. Otherwise the reference will shift to the beginning of the deleted range.
registerReference(index:number, canBeDeleted:boolean):IndexReference<CollaborativeList<V>>;
// Removes the item at the given index from the list.
remove(index:number):void;
// Removes the items between startIndex (inclusive) and endIndex (exclusive).
removeRange(startIndex:number, endIndex:number):void;
// Removes the first instance of the given value from the list.
// @return whether the item was removed
removeValue(value:V):boolean;
// Replaces items in the list with the given items, starting at the given index.
replaceRange(index:number, values:V[]):void;
// Sets the item at the given index
set(index:number, value:V):void;
}
// Complete
// https://developers.google.com/google-apps/realtime/reference/gapi.drive.realtime.Model
export class Model {
// Returns the collaborative object with the given id.
// @return non-null Object
getObject: (id:string) => CollaborativeObject;
// An estimate of the number of bytes used by data stored in the model.
bytesUsed:number;
// True if the model can currently redo.
canRedo:boolean;
// True if the model can currently undo.
canUndo:boolean;
// Creates the native JS object for a given collaborative object type.
// @return non-null Object
createJsObject(typeName:string):any;
// Adds an event listener to the event target.
// The same handler can only be added once per the type. Even if you add the same handler multiple times using the
// same type then it will only be called once when the event is dispatched.
addEventListener(type:string, listener:() => void | EventListener, opt_capture?:boolean):void;
// Starts a compound operation. If a name is given, that name will be recorded in the mutation for use in revision
// history, undo menus, etc. When beginCompoundOperation() is called, all subsequent edits to the data model will
// be batched together in the undo stack and revision history until endCompoundOperation() is called.
// Compound operations may be nested inside other compound operations.
// If the root compound operation is undoable, all nested compound operations must be undoable as well.
// If the root compound operation is non-undoable, nested operations can be undoable, although the entire operation
// will obey the root's opt_isUndoable value.
// Note that the compound operation MUST start and end in the same synchronous execution block. If this invariant
// is violated, the data model will become invalid and all future changes will fail.
beginCompoundOperation(opt_name?:string, opt_isUndoable?:boolean):void;
// Creates and returns a new collaborative object. This can be used to create custom collaborative objects.
// For built in types, use the specific create* functions.
// @return non-null Object
create(ref:string|Function, ...var_args:any[]):any;
// Creates a collaborative list.
createList<T>(opt_initialValue?:Array<T>):CollaborativeList<T>;
// Creates a collaborative map.
createMap<T>(opt_initialValue?:Array<[string,T]>):CollaborativeMap<T>;
// Creates a collaborative string.
createString(opt_initialValue?:string):CollaborativeString;
//Ends a compound operation. This method will throw an exception if no compound operation is in progress.
endCompoundOperation():void;
// Returns the root of the object model.
getRoot():CollaborativeMap<any>;
// The mode of the document. If true, the document is read-only. If false, it is editable.
isReadOnly():boolean;
// Redo the last thing the active collaborator undid.
redo():void;
// Removes all event listeners from this object.
removeAllEventListeners():void;
// Removes an event listener from the event target. The handler must be the same object as the one added.
// If the handler has not been added then nothing is done.
removeEventListener(type:string, listener:() => void | EventListener, opt_capture?:boolean):void;
// The current server revision number for this model. The revision number begins at 1 (the initial empty model)
// and is incremented each time the model is changed on the server (either by the current session or any
// other collaborator). Because this revision number includes only changes that the server knows about,
// it is only updated while this client is connected to the Realtime API server and it does not include changes
// that have not yet been saved to the server.
serverRevision():number;
// Serializes this data model to a JSON-based format which is compatible with the Realtime API's import/export
// REST API. The exported JSON can also be used with gapi.drive.realtime.loadFromJson to load an in-memory
// version of this data model which does not require a network connection.
// See https://developers.google.com/drive/v2/reference/realtime/update for more information.
toJson(opt_appId?:string, opt_revision?:number):string;
// Undo the last thing the active collaborator did.
undo():void;
}
export type EventType = 'object_changed' | 'values_set' | 'values_added' | 'values_removed' | 'value_changed' |
'text_inserted' | 'text_deleted' | 'collaborator_joined' | 'collaborator_left' | 'reference_shifted' |
'document_save_state_changed' | 'undo_redo_state_changed' | 'attribute_changed';
export const EventType:{
// A collaborative object has changed. This event wraps a specific event, and bubbles to ancestors.
// Defaults to object_changed.
OBJECT_CHANGED:'object_changed'
// Values in a list are changed in place.
// Defaults to values_set.
VALUES_SET:'values_set',
// New values have been added to the list.
// values_added
VALUES_ADDED:'values_added'
// Values have been removed from the list.
// values_removed
VALUES_REMOVED:'values_removed'
// A map or custom object value has changed. Note this could be a new value or deleted value.
// value_changed
VALUE_CHANGED:'value_changed'
// Text has been inserted into a string.
// text_inserted
TEXT_INSERTED:'text_inserted'
// Text has been removed from a string.
// text_deleted
TEXT_DELETED:'text_deleted'
// A new collaborator joined the document. Listen on the gapi.drive.realtime.Document for these changes.
// collaborator_joined
COLLABORATOR_JOINED:'collaborator_joined'
// A collaborator left the document. Listen on the gapi.drive.realtime.Document for these changes.
// collaborator_left
COLLABORATOR_LEFT:'collaborator_left'
// An index reference changed.
// reference_shifted
REFERENCE_SHIFTED:'reference_shifted'
// The document save state changed. Listen on the gapi.drive.realtime.Document for these changes.
// document_save_state_changed
DOCUMENT_SAVE_STATE_CHANGED:'document_save_state_changed'
// The model canUndo/canRedo state changed. Listen on the gapi.drive.realtime.Model for these changes.
// undo_redo_state_changed
UNDO_REDO_STATE_CHANGED:'undo_redo_state_changed'
// A metadata attribute of the document changed. This is fired on changes to:
// gapi.drive.realtime.Attribute.IS_READ_ONLY
// Listen on the gapi.drive.realtime.Document for these changes.
// attribute_changed
ATTRIBUTE_CHANGED:'attribute_changed'
}
// Complete
// https://developers.google.com/google-apps/realtime/reference/gapi.drive.realtime.BaseModelEvent
export interface BaseModelEvent {
// Whether this event bubbles.
bubbles : boolean;
// The list of names from the hierarchy of compound operations that initiated this event.
compoundOperationNames : string[];
// True if this event originated in the local session.
isLocal : boolean;
// True if this event originated from a redo call.
isRedo : boolean;
// True if this event originated from an undo call.
isUndo : boolean;
// Prevents an event from performing its default action. In the Realtime API, this function is only present
// for compatibility with the DOM event interface and therefore it does nothing.
preventDefault() : void;
// The id of the session that initiated this event.
sessionId : string;
// The collaborative object that initiated this event.
target : CollaborativeObject;
// The type of the event.
type : EventType;
// The user id of the user that initiated this event.
userId : string;
// Stops an event which bubbles from propagating to the target's parent.
stopPropagation() : void;
/* Parameters:
target
gapi.drive.realtime.CollaborativeObject
The collaborative object that initiated the event.
Value must not be null.
sessionId
string
The id of the session that initiated the event.
userId
string
The user id of the user that initiated the event.
compoundOperationNames
Array of string
The list of names from the hierarchy of compound operations that initiated the event.
Value must not be null.
isLocal
boolean
True if the event originated in the local session.
isUndo
boolean
True if the event originated from an undo call.
isRedo
boolean
True if the event originated from a redo call.
*/
new (target:CollaborativeObject, sessionId:string, userId:string, compoundOperationNames:string[],
isLocal:boolean, isUndo:boolean, isRedo:boolean) : BaseModelEvent;
}
// Complete
// https://developers.google.com/google-apps/realtime/reference/gapi.drive.realtime.ObjectChangedEvent
export interface ObjectChangedEvent extends BaseModelEvent {
// parameters as in BaseModelEvent above except for addition of:
// events:
// Array of gapi.drive.realtime.BaseModelEvent
// The specific events that document the changes that occurred on the object.
// Value must not be null.
new (target:CollaborativeObject, sessionId:string, userId:string, compoundOperationNames:string[],
isLocal:boolean, isUndo:boolean, isRedo:boolean, events:BaseModelEvent[]) : ObjectChangedEvent;
// The specific events that document the changes that occurred on the object.
events : BaseModelEvent[];
}
// https://developers.google.com/google-apps/realtime/reference/gapi.drive.realtime.ValuesAddedEvent
export interface ValuesAddedEvent<V> extends BaseModelEvent {
new (target:CollaborativeObject, sessionId:string, userId:string, compoundOperationNames:string[],
isLocal:boolean, isUndo:boolean, isRedo:boolean, index:number,
values:V[], movedFromList:CollaborativeList<V>, movedFromIndex:number):ValuesAddedEvent<V>;
// The index of the first added value
index:number;
// The index in the source collaborative list that the values were moved from, or null if this insert is not the result of a move operation.
movedFromIndex:number;
// The collaborative list that the values were moved from, or null if this insertion is not the result of a move operation.
movedFromList:CollaborativeList<V>;
}
// https://developers.google.com/google-apps/realtime/reference/gapi.drive.realtime.ValuesRemovedEvent
export interface ValuesRemovedEvent<V> extends BaseModelEvent {
new (target:CollaborativeObject, sessionId:string, userId:string, compoundOperationNames:string[],
isLocal:boolean, isUndo:boolean, isRedo:boolean, index:number,
values:V[], movedToList:CollaborativeList<V>, movedToIndex:number):ValuesRemovedEvent<V>;
// The index of the first removed value.
index:number;
// The index in the collaborative list that the values were moved to, or null if this delete is not the result of a move operation.
movedToIndex:number;
// The collaborative list that the values were moved to, or null if this delete is not the result of a move operation.
movedToList:CollaborativeList<V>;
}
// Complete
// https://developers.google.com/google-apps/realtime/reference/gapi.drive.realtime.Document
export class Document {
// Whether the document is closed. Read-only; call close() to close the document.
isClosed : boolean;
// Whether the document is stored in Google Drive. Read-only.
// This property is false for documents created using gapi.drive.realtime.newInMemoryDocument or
// gapi.drive.realtime.loadFromJson and true for all other documents.
isInGoogleDrive : boolean;
// The approximate amount of time (in milliseconds) that changes have been waiting to be saved in Google Drive.
// If there are no unsaved changes or this is an in-memory document, this value is always 0.
// This value should remain low (for example, less than a few seconds) as long as the network is healthy and
// changes are being saved as quickly as they are generated. If the network is unreliable or down, or if changes
// are being made to the model more quickly than they can be saved, this value will continue to grow until the
// network catches up and the changes are successfully saved.
saveDelay : number;
// Adds an event listener to the event target. The same handler can only be added once per the type.
// Even if you add the same handler multiple times using the same type then it will only be called once when
// the event is dispatched.
addEventListener(type:string, listener:GoogEventHandler, opt_capture?:boolean) : void;
// Closes the document and disconnects from the server.
// After this function is called, event listeners will no longer fire and attempts to access the document, model,
// or model objects will throw a gapi.drive.realtime.DocumentClosedError.
// Calling this function after the document has been closed will have no effect.
close():void;
// Gets an array of collaborators active in this session. Each collaborator is a jsMap with these fields:
// sessionId, userId, displayName, color, isMe, isAnonymous.
getCollaborators() : Collaborator[];
// Gets the collaborative model associated with this document.
// @return non-null Model
getModel():Model;
// Removes all event listeners from this object.
removeAllEventListeners() : void;
// Removes an event listener from the event target. The handler must be the same object as the one added.
// If the handler has not been added then nothing is done.
removeEventListener(type:string, listener:GoogEventHandler, opt_capture?:boolean) : void;
// Saves a copy of this document to a new file. After this function is called, all changes to this document no
// longer affect the old document and are instead saved to the new file.
// The provided file ID must refer to a valid file in Drive which does not have any Realtime data for your app.
// This function can also be used on an in-memory file to convert it to a Drive-connected file.
saveAs(fileId:string) : void;
}
// Complete
// https://developers.google.com/google-apps/realtime/reference/gapi.drive.realtime#.ErrorType
export type ErrorType =
"concurrent_creation" | "invalid_compound_operation" | "invalid_json_syntax" |
"missing_property" | "not_found" | "forbidden" | "server_error" | "client_error" |
"token_refresh_required" | "invalid_element_type" | "no_write_permission" |
"fatal_network_error" | "unexpected_element";
export const ErrorType : {
// Another user created the document's initial state after
// gapi.drive.realtime.load was called but before the local
// creation was saved.
CONCURRENT_CREATION: ErrorType,
// A compound operation was still open at the end of a
// synchronous block. Compound operations must always
// be ended in the same synchronous block that they
// are started.
INVALID_COMPOUND_OPERATION: ErrorType,
// The user tried to decode a brix model that
// contained invalid json.
INVALID_JSON_SYNTAX: ErrorType,
// The user tried to decode a brix model that was
// missing a neccessary property.
MISSING_PROPERTY: ErrorType,
// The provided document ID could not be found.
NOT_FOUND: ErrorType,
// The user associated with the provided OAuth token
// is not authorized to access the provided document
// ID.
FORBIDDEN: ErrorType,
// An internal error occurred in the Drive Realtime
// API server.
SERVER_ERROR: ErrorType,
// An internal error occurred in the Drive Realtime API client.
CLIENT_ERROR: ErrorType,
// The provided OAuth token is no longer valid and
// must be refreshed.
TOKEN_REFRESH_REQUIRED: ErrorType,
// The provided JSON element does not have the
// expected type.
INVALID_ELEMENT_TYPE: ErrorType,
// The user does not have permission to edit the
// document.
NO_WRITE_PERMISSION: ErrorType,
// A network error occurred on a request to the
// Realtime API server for a request which can not be
// retried. The document may no longer be used after
// this error has occurred. This error can only be
// corrected by reloading the document.
FATAL_NETWORK_ERROR: ErrorType,
// The provided JSON element has the correct JSON type
// but does not have the correct expected Realtime
// type.
UNEXPECTED_ELEMENT: ErrorType,
};
// Complete
// https://developers.google.com/google-apps/realtime/reference/gapi.drive.realtime.Error
export class Error {
constructor (type: string, message: string, isFatal: boolean);
// The type of the error that occurred.
type: ErrorType;
// A message describing the error.
message: string;
// Whether the error is fatal. Fatal errors cannot be recovered
// from and require the document to be reloaded.
isFatal: boolean;
// Returns a string representation of the error object.
toString(): string;
}
// Complete
// Opens the debugger application on the current page. The debugger shows all realtime documents that the
// page has loaded and is able to view, edit and debug all aspects of each realtime document.
export function debug() : void;
/* Creates a new file with fake network communications. This file will not talk to the server and will only
exist in memory for as long as the browser session persists.
https://developers.google.com/google-apps/realtime/reference/gapi.drive.realtime#.newInMemoryDocument
@Param opt_onLoaded {function(non-null gapi.drive.realtime.Document)}
A callback that will be called when the realtime document is ready. The created or opened realtime document
object will be passed to this function.
@Param opt_initializerFn {function(non-null gapi.drive.realtime.Model)}
An optional initialization function that will be called before onLoaded only the first time that the document
is loaded. The document's gapi.drive.realtime.Model object will be passed to this function.
@Param opt_errorFn {function(non-null gapi.drive.realtime.Error)}
An optional error handling function that will be called if an error occurs while the document is being
loaded or edited. A gapi.drive.realtime.Error object describing the error will be passed to this function.
*/
export function newInMemoryDocument(
opt_onLoaded? : (d:Document) => void,
opt_initializerFn? : (m:Model) => void,
opt_errorFn? : (e:gapi.drive.realtime.Error) => void
) : Document;
/* Loads an existing file by id.
https://developers.google.com/google-apps/realtime/reference/gapi.drive.realtime#.load
@Param fileId {string} Id of the file to load.
@Param onLoaded {function(non-null gapi.drive.realtime.Document)}
A callback that will be called when the realtime document is ready. The created or opened realtime document
object will be passed to this function.
@Param opt_initializerFn {function(non-null gapi.drive.realtime.Model)}
An optional initialization function that will be called before onLoaded only the first time that the document
is loaded. The document's gapi.drive.realtime.Model object will be passed to this function.
@Param opt_errorFn {function(non-null gapi.drive.realtime.Error)}
An optional error handling function that will be called if an error occurs while the document is being
loaded or edited. A gapi.drive.realtime.Error object describing the error will be passed to this function.
*/
export function load(
fileId:string,
onLoaded? : (d:Document) => void,
opt_initializerFn? : (m:Model) => void,
opt_errorFn? : (e:Error) => void
):void;
export function loadAppDataDocument(
onLoaded:(x:Document) => void,
opt_initializerFn?:(x:Model) => void,
opt_errorFn?:(e:Error) => void
):void
// Loads an in-memory document from a json string.
// This document does not talk to the server and will only exist in memory for as long as the browser session exists.
export function loadFromJson(
json:string,
opt_errorFn?:(e:Error) => void
):Document
}
declare namespace gapi.drive.realtime.databinding {
// COMPLETE
// https://developers.google.com/google-apps/realtime/reference/gapi.drive.realtime.databinding.Binding
export interface Binding {
// Throws gapi.drive.realtime.databinding.AlreadyBoundError If domElement has already been bound.
// The collaborative object to bind.
collaborativeObject : CollaborativeObject;
// The DOM element that the collaborative object is bound to. Value must not be null.
domElement : Element;
// Unbinds the domElement from collaborativeObject.
unbind() : void;
}
export function bindString(s:CollaborativeString, textinput:HTMLInputElement) : Binding
}
// rtclient is a global var introduced by realtime-client-utils.js
declare namespace rtclient {
// INCOMPLETE
export interface RealtimeLoader {
start():void;
load():void;
handleErrors(e:gapi.drive.realtime.Error):void;
}
interface RealtimeLoaderFactory {
new (options:LoaderOptions) : RealtimeLoader;
}
// ***********************************
// NOTE THIS IS OUT OF DATE. realtime-client-utils.js has been rewritten, with the new version "Realtime Utils 1.0.0".
// Will add typings for the new version later.
// The remainder of this file types some (not all) things in realtime-client-utils.js, found here:
// https://developers.google.com/google-apps/realtime/realtime-quickstart
// and
// https://apis.google.com/js/api.js
// ***********************************
// Complete
export interface LoaderOptions {
// Your Application ID from the Google APIs Console.
appId: string;
// Autocreate files right after auth automatically.
autoCreate: boolean;
// Client ID from the console.
clientId: string;
// The ID of the button to click to authorize. Must be a DOM element ID.
authButtonElementId: string;
// The MIME type of newly created Drive Files. By default the application
// specific MIME type will be used:
// application/vnd.google-apps.drive-sdk.
newFileMimeType: string;
//newFileMimeType = null // default
// Function to be called to initialize custom Collaborative Objects types.
registerTypes: () => void;
// The name of newly created Drive files, if no title is specified.
defaultTitle: string;
// Function to be called after authorization and before loading files.
afterAuth: () => void;
// Function to be called when a Realtime model is first created.
initializeModel: (model:gapi.drive.realtime.Model) => void;
// Function to be called every time a Realtime file is loaded.
onFileLoaded: (rtdoc:gapi.drive.realtime.Document) => void;
}
// INCOMPLETE
export interface DriveAPIFileResource {
id: string;
}
// INCOMPLETE
export interface ClientUtils {
// INCOMPLETE
params: {
// string containing one or more file ids separated by spaces.
fileIds : string
};
RealtimeLoader : RealtimeLoaderFactory;
/**
* Creates a new Realtime file.
* @param title {string} title of the newly created file.
* @param mimeType {string} the MIME type of the new file.
* @param callback {(file:DriveAPIFileResource) => void} the callback to call after creation.
*/
createRealtimeFile(title:string, mimeType:string, callback:(file:DriveAPIFileResource) => void) : void;
}
export var RealtimeLoader : RealtimeLoaderFactory
/**
* Creates a new Realtime file.
* @param title {string} title of the newly created file.
* @param mimeType {string} the MIME type of the new file.
* @param callback {(file:DriveAPIFileResource) => void} the callback to call after creation.
*/
export function createRealtimeFile(title:string, mimeType:string, callback:(file:DriveAPIFileResource) => void) : void
}
// INCOMPLETE
declare namespace rtclient.params {
// string containing one or more file ids separated by spaces.
export var fileIds:string
} | the_stack |
declare namespace dojox {
namespace mdnd {
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/mdnd/AreaManager.html
*
* Drag And Drop manager
*
*/
class AreaManager {
constructor();
/**
* CSS class enabled an area if areaClass is defined
*
*/
"areaClass": string;
/**
* Enable the refresh of registered areas on drag start.
*
*/
"autoRefresh": boolean;
/**
* CSS class enabled a drag handle.
*
*/
"dragHandleClass": string;
/**
* To add an item programmatically.
*
* @param area a node corresponding to the D&D Area
* @param node the node which has to be treated.
* @param index the place in the area
* @param notCheckParent
*/
addDragItem(area: HTMLElement, node: HTMLElement, index: number, notCheckParent: boolean): any;
/**
* Destroy the component.
*
*/
destroy(): void;
/**
* find the nearest target area according to coordinates.
* Coordinates are representing by an object : for example, {'x':10,'y':10}
*
* @param coords an object encapsulating X and Y position
* @param size an object encapsulating the area size
*/
findCurrentIndexArea(coords: Object, size: Object): any;
/**
* Initialize the manager by calling the registerByClass method
*
*/
init(): void;
/**
* Search the right place to insert the dropIndicator and display the dropIndicator.
*
* @param coords an object encapsulating X and Y position
* @param size an object encapsulating width and height values
*/
placeDropIndicator(coords: Object, size: Object): any;
/**
* Register all Dnd Areas identified by the attribute areaClass :
* insert Dnd Areas using the specific sort of dropMode.
*
*/
registerByClass(): void;
/**
* To register Dnd Area : insert the DndArea using the specific sort of dropMode.
*
* @param area a DOM node corresponding to the Dnd Area
* @param notInitAreas if false or undefined, init the areas.
*/
registerByNode(area: HTMLElement, notInitAreas: boolean): void;
/**
* Delete a moveable item programmatically. The node is removed from the area.
*
* @param area A node corresponding to the DndArea.
* @param node The node which has to be treated.
*/
removeDragItem(area: HTMLElement, node: HTMLElement): any;
/**
* Unregister a D&D Area and its children into the AreaManager.
*
* @param area A node corresponding to the D&D Area.
*/
unregister(area: HTMLElement): any;
/**
* Occurs when the dojo.dnd.Moveable.onDrag is fired.
* Search the nearest target area and called the placeDropIndicator
*
* @param node The node which is dragged
* @param coords an object encapsulating X and Y position
* @param size an object encapsulating width and height values
* @param mousePosition coordinates of mouse
*/
onDrag(node: HTMLElement, coords: Object, size: Object, mousePosition: Object): void;
/**
* Optionally called by the getTargetArea method of TargetFinder class.
*
* @param coords coordinates of the dragged Node.
* @param size size of the dragged Node.
*/
onDragEnter(coords: Object, size: Object): void;
/**
* Optionally called by the getTargetArea method of TargetFinder class.
*
* @param coords coordinates of the dragged Node.
* @param size size of the dragged Node.
*/
onDragExit(coords: Object, size: Object): void;
/**
* Initialize the drag (see dojox.mdnd.Moveable.initOffsetDrag())
*
* @param node The node which is about to be dragged
* @param coords an object encapsulating X and Y position
* @param size an object encapsulating width and height values
*/
onDragStart(node: HTMLElement, coords: Object, size: Object): void;
/**
* Drop the dragged item where the dropIndicator is displayed.
*
* @param node The node which is about to be dropped
*/
onDrop(node: HTMLElement): void;
/**
* Cancel the drop.
* The dragNode returns into the source.
*
*/
onDropCancel(): void;
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/mdnd/AutoScroll.html
*
* Activate scrolling while dragging a widget.
*
*/
class AutoScroll {
constructor();
/**
* default mouse move offset
*
*/
"interval": number;
/**
* Default mouse margin
*
*/
"marginMouse": number;
/**
*
*/
"recursiveTimer": number;
/**
* Check if an autoScroll have to be launched.
*
* @param e
*/
checkAutoScroll(e: Event): void;
/**
*
*/
destroy(): void;
/**
* Set the visible part of the window. Varies accordion to Navigator.
*
*/
getViewport(): void;
/**
*
*/
init(): void;
/**
* Set the hightest heigh and width authorized scroll.
*
*/
setAutoScrollMaxPage(): void;
/**
* set the node which is dragged
*
* @param node node to scroll
*/
setAutoScrollNode(node: HTMLElement): void;
/**
* Stop the autoscroll.
*
*/
stopAutoScroll(): void;
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/mdnd/DropIndicator.html
*
* DropIndicator managment for DnD.
*
*/
class DropIndicator {
constructor();
/**
* the drop indicator node
*
*/
"node": HTMLElement;
/**
* destroy the dropIndicator
*
*/
destroy(): void;
/**
* Place the DropIndicator in the right place
*
* @param area the dnd targer area node
* @param nodeRef node where the dropIndicator have to be placed into the area
* @param size
*/
place(area: HTMLElement, nodeRef: HTMLElement, size: Object): any;
/**
* remove the DropIndicator (not destroy)
*
*/
remove(): void;
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/mdnd/LazyManager.html
*
* This class allows to launch a drag and drop dojo on the fly.
*
*/
class LazyManager {
constructor();
/**
* cancel a drag and drop dojo on the fly.
*
*/
cancelDrag(): void;
/**
*
*/
destroy(): void;
/**
*
* @param draggedNode
*/
getItem(draggedNode: HTMLElement): Object;
/**
* launch a dojo drag and drop on the fly.
*
* @param e
* @param draggedNode Optional
*/
startDrag(e: Event, draggedNode: HTMLElement): void;
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/mdnd/Moveable.html
*
* Allow end-users to track a DOM node into the web page
*
* @param params Hash of parameters
* @param node The draggable node
*/
class Moveable {
constructor(params: Object, node: HTMLElement);
/**
* The user clicks on the handle, but the drag action will really begin
* if they track the main node to more than 3 pixels.
*
*/
"dragDistance": number;
/**
* The node on which the user clicks to drag the main node.
*
*/
"handle": HTMLElement;
/**
* A flag to control a drag action if a form element has been focused.
* If true, the drag action is not executed.
*
*/
"skip": boolean;
/**
* Delecte associated events
*
*/
destroy(): void;
/**
* Initialize the gap between main node coordinates and the clicked point.
* Call the onDragStart method.
*
* @param e A DOM event
*/
initOffsetDrag(e: Event): void;
/**
* identify the type of target node associated with a DOM event.
*
* @param e a DOM event
*/
isFormElement(e: Event): any;
/**
* Stub function.
* Notes : border box model for size value, margin box model for coordinates
*
* @param node a DOM node
* @param coords position of the main node (equals to css left/top properties)
* @param size an object encapsulating width and height values
* @param mousePosition coordiantes of mouse
*/
onDrag(node: HTMLElement, coords: Object, size: Object, mousePosition: Object): void;
/**
* Stub function
* Notes : Coordinates don't contain margins
*
* @param node a DOM node
*/
onDragEnd(node: HTMLElement): void;
/**
* Stub function.
* Notes : border box model
*
* @param node a DOM node
* @param coords absolute position of the main node
* @param size an object encapsulating width an height values
*/
onDragStart(node: HTMLElement, coords: Object, size: Object): void;
/**
* Occurs when the user moves the mouse after clicking on the
* handle.
* Determinate when the drag action will have to begin (see
* dragDistance).
*
* @param e A DOM event
*/
onFirstMove(e: Event): void;
/**
* Occurs when the user clicks on the handle node.
* Skip the drag action if a specific node is targeted.
* Listens to mouseup and mousemove events on to the HTML document.
*
* @param e a DOM event
*/
onMouseDown(e: Event): void;
/**
* Occurs when the user releases the mouse
* Calls the onDragEnd method.
*
* @param e a DOM event
*/
onMouseUp(e: Event): void;
/**
* Occurs when the user moves the mouse.
* Calls the onDrag method.
*
* @param e a DOM event
*/
onMove(e: Event): void;
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/mdnd/PureSource.html
*
* A Source Object, which can be used only as a DnD source.
* A Source can contained several dnd items.
* A dnd item is not a source.
*
* @param node Node or node's id to build the source on.
* @param params OptionalAny property of this class may be configured via the paramsobject which is mixed-in to the 'dojo.dnd.Source' instance.
*/
class PureSource extends dojo.dnd.Selector {
constructor(node: HTMLElement, params?: Object);
/**
* Indicates whether to allow dnd item nodes to be nested within other elements.
* By default this is false, indicating that only direct children of the container can
* be draggable dnd item nodes
*
*/
"allowNested": boolean;
/**
*
*/
"copyOnly": boolean;
/**
* The DOM node the mouse is currently hovered over
*
*/
"current": HTMLElement;
/**
*
*/
"generateText": boolean;
/**
*
*/
"horizontal": boolean;
/**
*
*/
"isSource": boolean;
/**
* Map from an item's id (which is also the DOMNode's id) to
* the dojo/dnd/Container.Item itself.
*
*/
"map": Object;
/**
* The set of id's that are currently selected, such that this.selection[id] == 1
* if the node w/that id is selected. Can iterate over selected node's id's like:
*
* for(var id in this.selection)
*
*/
"selection": Object;
/**
*
*/
"singular": boolean;
/**
*
*/
"skipForm": boolean;
/**
*
*/
"targetState": string;
/**
*
*/
"withHandles": boolean;
/**
* removes all data items from the map
*
*/
clearItems(): void;
/**
* Returns true, if we need to copy items, false to move.
* It is separated to be overwritten dynamically, if needed.
*
* @param keyPressed The "copy" was pressed.
*/
copyState(keyPressed: boolean): any;
/**
* creator function, dummy at the moment
*
*/
creator(): void;
/**
* deletes all selected items
*
*/
deleteSelectedNodes(): Function;
/**
* removes a data item from the map by its key (id)
*
* @param key
*/
delItem(key: String): void;
/**
* Prepares the object to be garbage-collected.
*
*/
destroy(): void;
/**
*
* @param type
* @param event
*/
emit(type: any, event: any): any;
/**
* iterates over a data map skipping members that
* are present in the empty object (IE and/or 3rd-party libraries).
*
* @param f
* @param o Optional
*/
forInItems(f: Function, o: Object): String;
/**
* iterates over selected items;
* see dojo/dnd/Container.forInItems() for details
*
* @param f
* @param o Optional
*/
forInSelectedItems(f: Function, o: Object): void;
/**
* returns a list (an array) of all valid child nodes
*
*/
getAllNodes(): any;
/**
* returns a data item by its key (id)
*
* @param key
*/
getItem(key: String): any;
/**
* returns a list (an array) of selected nodes
*
*/
getSelectedNodes(): any;
/**
* inserts an array of new nodes before/after an anchor node
*
* @param data Logical representation of the object being dragged.If the drag object's type is "text" then data is a String,if it's another type then data could be a different Object,perhaps a name/value hash.
* @param before insert before the anchor, if true, and after the anchor otherwise
* @param anchor the anchor node to be used as a point of insertion
*/
insertNodes(data: Object, before: boolean, anchor: HTMLElement): Function;
/**
* inserts new data items (see dojo/dnd/Container.insertNodes() method for details)
*
* @param addSelected all new nodes will be added to selected items, if true, no selection change otherwise
* @param data a list of data items, which should be processed by the creator function
* @param before insert before the anchor, if true, and after the anchor otherwise
* @param anchor the anchor node to be used as a point of insertion
*/
insertNodes(addSelected: boolean, data: any[], before: boolean, anchor: HTMLElement): Function;
/**
* Markup methods.
*
* @param params ???
* @param node ???
*/
markupFactory(params: Object, node: HTMLElement): any;
/**
*
* @param type
* @param listener
*/
on(type: any, listener: any): any;
/**
* selects all items
*
*/
selectAll(): any;
/**
* unselects all items
*
*/
selectNone(): any;
/**
* associates a data item with its key (id)
*
* @param key
* @param data
*/
setItem(key: String, data: any): void;
/**
* collects valid child items and populate the map
*
*/
startup(): void;
/**
* sync up the node list with the data map
*
*/
sync(): Function;
/**
* Topic event processor for /dnd/cancel, called to cancel the Dnd
* operation.
*
*/
onDndCancel(): void;
/**
* Event processor for onmousedown.
*
* @param e Mouse event.
*/
onMouseDown(e: Event): void;
/**
* Event processor for onmousemove.
*
* @param e Mouse event.
*/
onMouseMove(e: Event): void;
/**
* event processor for onmouseout
*
* @param e mouse event
*/
onMouseOut(e: Event): void;
/**
* event processor for onmouseover or touch, to mark that element as the current element
*
* @param e mouse event
*/
onMouseOver(e: Event): void;
/**
* Event processor for onmouseup.
*
* @param e Mouse event
*/
onMouseUp(e: Event): void;
/**
* Called once, when mouse is out our container.
*
*/
onOutEvent(): void;
/**
* Called once, when mouse is over our container.
*
*/
onOverEvent(): void;
/**
* event processor for onselectevent and ondragevent
*
* @param e mouse event
*/
onSelectStart(e: Event): void;
}
namespace adapter {
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/mdnd/adapter/DndFromDojo.html
*
* Allow communication between Dojo dnd items and DojoX D&D areas
*
*/
class DndFromDojo {
constructor();
/**
* size by default of dropIndicator (display only into a D&D Area)
*
*/
"dropIndicatorSize": Object;
/**
* Check if a dragNode is accepted into a dojo target.
*
* @param node The dragged node.
* @param accept Object containing the type accepted for a target dojo.
*/
isAccepted(node: HTMLElement, accept: Object): any;
/**
* Subscribe to somes topics of dojo drag and drop.
*
*/
subscribeDnd(): void;
/**
* Unsubscribe to some topics of dojo drag and drop.
*
*/
unsubscribeDnd(): void;
/**
* Called when the mouse enters or exits of a source dojo.
*
* @param source the dojo source/target
*/
onDndSource(source: Object): void;
/**
* Occurs when the user drages an DOJO dnd item inside a D&D dojoX area.
*
*/
onDragEnter(): void;
/**
* Occurs when the user leaves a D&D dojoX area after dragging an DOJO dnd item over it.
*
*/
onDragExit(): void;
/**
* Occurs when the "/dnd/start" topic is published.
*
* @param source the source which provides items
* @param nodes the list of transferred items
* @param copy copy items, if true, move items otherwise
*/
onDragStart(source: Object, nodes: any[], copy: boolean): void;
/**
* Occurs when the user leaves a D&D dojox area after dragging an DOJO dnd item over it.
*
* @param source the source which provides items
* @param nodes the list of transferred items
* @param copy copy items, if true, move items otherwise
*/
onDrop(source: Object, nodes: any[], copy: boolean): void;
/**
* Occurs when the "/dnd/cancel" topic is published.
*
*/
onDropCancel(): void;
/**
* Occurs when the user moves the mouse.
*
* @param e the DOM event
*/
onMouseMove(e: Event): void;
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/mdnd/adapter/DndToDojo.html
*
* Allow communication between an item of dojox D&D area to a target dojo.
*
*/
class DndToDojo {
constructor();
/**
* Return true if the dragged node is accepted.
* This method has to be overwritten according to registered target.
*
* @param draggedNode
* @param target
*/
isAccepted(draggedNode: HTMLElement, target: Object): boolean;
/**
* Refresh the coordinates of all registered dojo target.
*
*/
refresh(): void;
/**
* Refresh the coordinates of registered dojo target with a specific type.
*
* @param type A String to identify dojo targets.
*/
refreshByType(type: String): void;
/**
* Register a target dojo.
* The target is represented by an object containing :
*
* the dojo area node
* the type reference to identify a group node
* the coords of the area to enable refresh position
*
* @param area The DOM node which has to be registered.
* @param type A String to identify the node.
* @param dojoTarget True if the dojo D&D have to be enable when mouse is hover the registered target dojo.
*/
register(area: HTMLElement, type: String, dojoTarget: boolean): void;
/**
* Unregister all targets dojo.
*
*/
unregister(): void;
/**
* Unregister a target dojo.
*
* @param area The DOM node of target dojo.
*/
unregisterByNode(area: HTMLElement): void;
/**
* Unregister several targets dojo having the same type passing in parameter.
*
* @param type A String to identify dojo targets.
*/
unregisterByType(type: String): void;
/**
* Call when the mouse enters in a registered dojo target.
*
* @param e The current Javascript Event.
*/
onDragEnter(e: Event): void;
/**
* Call when the mouse exit of a registered dojo target.
*
* @param e current javscript event
*/
onDragExit(e: Event): void;
/**
* Called when an onmouseup event is loaded on a registered target dojo.
*
* @param e Event object.
*/
onDrop(e: Event): void;
/**
* Call when the mouse moving after an onStartDrag of AreaManger.
* Check if the coordinates of the mouse is in a dojo target.
*
* @param e Event object.
*/
onMouseMove(e: Event): void;
}
}
namespace dropMode {
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/mdnd/dropMode/DefaultDropMode.html
*
* Enabled a type of calcul for Dnd.
* Default class to find the nearest target.
*
*/
class DefaultDropMode {
constructor();
/**
* Add a DnD Area into an array sorting by the x position.
*
* @param areas array of areas
* @param object data type of a DndArea
*/
addArea(areas: any[], object: Object): any;
/**
*
*/
destroy(): void;
/**
* return coordinates of the draggable item
* return for:
*
* X point : the middle
* Y point : search if the user goes up or goes down with their mouse.
* Up : top of the draggable item
* Down : bottom of the draggable item
*
* @param coords an object encapsulating X and Y position
* @param size an object encapsulating width and height values
* @param mousePosition coordinates of mouse
*/
getDragPoint(coords: Object, size: Object, mousePosition: Object): any;
/**
* Return the index where the drop has to be placed.
*
* @param targetArea a DnD area object
* @param coords coordinates [x,y] of the draggable item
*/
getDropIndex(targetArea: Object, coords: Object): any;
/**
* get the nearest DnD area.
* Coordinates are basically provided by the getDragPoint method.
*
* @param areaList a list of DnD areas objects
* @param coords coordinates [x,y] of the dragItem
* @param currentIndexArea an index representing the active DnD area
*/
getTargetArea(areaList: any[], coords: Object, currentIndexArea: number): any;
/**
* initialize the horizontal line in order to determinate the drop zone.
*
* @param area the DnD area
*/
initItems(area: Object): void;
/**
* take into account the drop indicator DOM element in order to compute horizontal lines
*
* @param area a DnD area object
* @param indexItem index of a draggable item
* @param size dropIndicator size
* @param added boolean to know if a dropIndicator has been added or deleted
*/
refreshItems(area: Object, indexItem: number, size: Object, added: boolean): void;
/**
* Refresh intervals between areas to determinate the nearest area to drop an item.
* Algorithm :
* the marker should be the vertical line passing by the
* central point between two contiguous areas.
* Note:
* If the page has only one targetArea, it's not necessary to calculate coords.
*
* @param areaList array of areas
*/
updateAreas(areaList: any[]): void;
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/mdnd/dropMode/OverDropMode.html
*
* Default class to find the nearest target only if the mouse is over an area.
*
*/
class OverDropMode {
constructor();
/**
* Add a D&D Area into an array sorting by the x position.
*
* @param areas array of areas
* @param object data type of a DndArea
*/
addArea(areas: any[], object: Object): any;
/**
*
*/
destroy(): void;
/**
* return coordinates of the draggable item.
*
* For X point : the x position of mouse
* For Y point : the y position of mouse
*
* @param coords an object encapsulating X and Y position
* @param size an object encapsulating width and height values
* @param mousePosition coordinates of mouse
*/
getDragPoint(coords: Object, size: Object, mousePosition: Object): any;
/**
* Return the index where the drop has to be placed.
*
* @param targetArea a D&D area object.
* @param coords coordinates [x,y] of the draggable item.
*/
getDropIndex(targetArea: Object, coords: Object): any;
/**
* get the nearest D&D area.
*
* @param areaList a list of D&D areas objects
* @param coords coordinates [x,y] of the dragItem (see getDragPoint())
* @param currentIndexArea an index representing the active D&D area
*/
getTargetArea(areaList: any[], coords: Object, currentIndexArea: number): any;
/**
* initialize the horizontal line in order to determinate the drop zone.
*
* @param area the D&D area.
*/
initItems(area: Object): void;
/**
* take into account the drop indicator DOM element in order to compute horizontal lines
*
* @param area a D&D area object
* @param indexItem index of a draggable item
* @param size dropIndicator size
* @param added boolean to know if a dropIndicator has been added or deleted
*/
refreshItems(area: Object, indexItem: number, size: Object, added: boolean): void;
/**
* refresh areas position and size to determinate the nearest area to drop an item
* the area position (and size) is equal to the postion of the domNode associated.
*
* @param areaList array of areas
*/
updateAreas(areaList: any[]): void;
}
/**
* Permalink: http://dojotoolkit.org/api/1.9/dojox/mdnd/dropMode/VerticalDropMode.html
*
* Enabled a type of calcul for Dnd.
* Default class to find the nearest target.
*
*/
class VerticalDropMode {
constructor();
/**
* Add a DnD Area into an array sorting by the x position.
*
* @param areas array of areas
* @param object data type of a DndArea
*/
addArea(areas: any[], object: Object): any;
/**
*
*/
destroy(): void;
/**
* return coordinates of the draggable item
* return for:
*
* X point : the middle
* Y point : search if the user goes up or goes down with their mouse.
* Up : top of the draggable item
* Down : bottom of the draggable item
*
* @param coords an object encapsulating X and Y position
* @param size an object encapsulating width and height values
* @param mousePosition coordinates of mouse
*/
getDragPoint(coords: Object, size: Object, mousePosition: Object): any;
/**
* Return the index where the drop has to be placed.
*
* @param targetArea a DnD area object
* @param coords coordinates [x,y] of the draggable item
*/
getDropIndex(targetArea: Object, coords: Object): any;
/**
* get the nearest DnD area.
* Coordinates are basically provided by the getDragPoint method.
*
* @param areaList a list of DnD areas objects
* @param coords coordinates [x,y] of the dragItem
* @param currentIndexArea an index representing the active DnD area
*/
getTargetArea(areaList: any[], coords: Object, currentIndexArea: number): any;
/**
* initialize the horizontal line in order to determinate the drop zone.
*
* @param area the DnD area
*/
initItems(area: Object): void;
/**
* take into account the drop indicator DOM element in order to compute horizontal lines
*
* @param area a DnD area object
* @param indexItem index of a draggable item
* @param size dropIndicator size
* @param added boolean to know if a dropIndicator has been added or deleted
*/
refreshItems(area: Object, indexItem: number, size: Object, added: boolean): void;
/**
* Refresh intervals between areas to determinate the nearest area to drop an item.
* Algorithm :
* the marker should be the vertical line passing by the
* central point between two contiguous areas.
* Note:
* If the page has only one targetArea, it's not necessary to calculate coords.
*
* @param areaList array of areas
*/
updateAreas(areaList: any[]): void;
}
}
}
}
declare module "dojox/mdnd/AutoScroll" {
var exp: dojox.mdnd.AutoScroll
export=exp;
}
declare module "dojox/mdnd/DropIndicator" {
var exp: dojox.mdnd.DropIndicator
export=exp;
}
declare module "dojox/mdnd/AreaManager" {
var exp: dojox.mdnd.AreaManager
export=exp;
}
declare module "dojox/mdnd/LazyManager" {
var exp: dojox.mdnd.LazyManager
export=exp;
}
declare module "dojox/mdnd/Moveable" {
var exp: dojox.mdnd.Moveable
export=exp;
}
declare module "dojox/mdnd/PureSource" {
var exp: dojox.mdnd.PureSource
export=exp;
}
declare module "dojox/mdnd/adapter/DndFromDojo" {
var exp: dojox.mdnd.adapter.DndFromDojo
export=exp;
}
declare module "dojox/mdnd/adapter/DndToDojo" {
var exp: dojox.mdnd.adapter.DndToDojo
export=exp;
}
declare module "dojox/mdnd/dropMode/DefaultDropMode" {
var exp: dojox.mdnd.dropMode.DefaultDropMode
export=exp;
}
declare module "dojox/mdnd/dropMode/OverDropMode" {
var exp: dojox.mdnd.dropMode.OverDropMode
export=exp;
}
declare module "dojox/mdnd/dropMode/VerticalDropMode" {
var exp: dojox.mdnd.dropMode.VerticalDropMode
export=exp;
} | the_stack |
import { TimeEntity } from '../../utils/entity-utils';
import BaseTokenizer from './base';
import { WS, makeToken } from './helpers';
const NUMBERS : Record<string, number> = {
zero: 0,
un: 1,
uno: 1,
due: 2,
tre: 3,
quattro: 4,
cinque: 5,
sei: 6,
sette: 7,
otto: 8,
nove: 9,
dieci: 10,
undici: 11,
dodici: 12,
tredici: 13,
quattordici: 14,
quindici: 15,
sedici: 16,
diciassette: 17,
diciotto: 18,
diciannove: 19,
// the form without the final vowel is used when followed by "uno" or "otto"
vent: 20,
venti: 20,
trent: 30,
trenta: 30,
quarant: 40,
quaranta: 40,
cinquant: 50,
cinquanta: 50,
sessant: 60,
sessanta: 60,
settant: 70,
settanta: 70,
ottant: 80,
ottanta: 80,
novant: 90,
novanta: 90,
};
const MULTIPLIERS : Record<string, number> = {
cent: 100,
cento: 100,
mille: 1000,
mila: 1000,
milione: 1e6,
milioni: 1e6,
miliardo: 1e9,
miliardi: 1e9,
// AFAIK, nothing is commonly used above this
// Wikipedia has definitions for "biliardo" and "triliardo"
// but they are confusing and too big to be useful
// also, people commonly say "duemila miliardi"
};
const MONTHS : Record<string, number> = {
gen: 1,
feb: 2,
mar: 3,
apr: 4,
mag: 5,
giu: 6,
lug: 7,
ago: 8,
'set': 9, // "set" is a JS keyword
ott: 10,
nov: 11,
dic: 12
};
const CURRENCIES : Record<string, string> = {
'dollaro': 'usd',
'dollari': 'usd',
'sterlina': 'gbp',
'sterline': 'gbp',
'pence': '0.01gbp',
'penny': '0.01gbp',
'yen': 'jpy',
'euro': 'eur',
'eurocent': '0.01eur',
'cent': '0.01eur',
'won': 'krw',
'yuan': 'cny',
'$': 'usd',
'C$': 'cad',
'A$': 'aud',
'£': 'gbp',
'€': 'eur',
'₩': 'krw',
// this is ambiguous, could be jpy or cny
'¥': 'jpy',
};
export default class ItalianTokenizer extends BaseTokenizer {
protected _initAbbrv() {
// always attach the apostrophe to the preceding word
this._addDefinition('APWORD', /{LETTER}+'/);
// common abbreviations
// other abbreviations that TINT (CoreNLP for Italian) included were Geom., Avv., Mons. and many others
// but I don't think they're very useful
this._addDefinition('ABBRV_TITLE', /sig\.(?:r[aei])?|dott\.(?:ssa)?|prof\.(?:ssa)?/);
// initialisms are as in english (same observations apply more or less)
// note: in italian this also covers corporate abbreviations (S.p.A., S.r.l.)
this._addDefinition('INITIALISM', /(?:{LETTER}\.)+/);
this._lexer.addRule(/{ABBRV_TITLE}|{INITIALISM}/,
(lexer) => makeToken(lexer.index, lexer.text));
}
protected _addIntlPrefix(text : string) {
// assume Italian/Italy locale
if (!text.startsWith('+'))
text = '+39' + text;
return text;
}
private _parseWordNumber(text : string) {
// the logic for this function is exactly the same as the English version, except
// that in Italian there are no spaces before the suffixes "cento" (hundred) and "mila" (thousands)
// so to parse a number in word we need to use another regular expression
// "value" is the total number, "current" is a single piece before a multiplier ("thousand", "billion", etc.)
let value = 0;
let current = 0;
// remove junk
text = text.replace(/[ \t\n\r\v\u180e\u2000-\u200b\u202f\u205f\u3000\ufeff-]+(?:e[ \t\n\r\v\u180e\u2000-\u200b\u202f\u205f\u3000\ufeff]+)*/g, '');
// turn ordinals into cardinals
text = text
.replace(/prim[oaei]|unesim[oaie]/, 'uno')
.replace(/second[oaei]|duesim[oaie]/, 'due')
.replace(/terz[oaei]|treesim[oaie]/, 'tre')
.replace(/quart[oaei]|treesim[oaie]/, 'quattro')
.replace(/quint[oaei]|cinquesim[oaie]/, 'cinque')
.replace(/sest[oaei]|seiesim[oaie]/, 'sei')
.replace(/settim[oaei]|settesim[oaie]/, 'sette')
.replace(/ottav[oaei]|ottesim[oaie]/, 'otto')
.replace(/nono[oaei]|novesim[oaie]/, 'nove')
.replace(/decim[oaei]/, 'dieci')
// "undecimo" is an archaic form of "undicesimo"
.replace(/undecim[oaei]|undicesim[oaie]/, 'undici')
.replace(/duodecim[oaei]|dodicesim[oaei]/, 'dodici')
// ending in "i"
.replace(/(tredic|quattrodic|quindic|sedic|vent)esim[oaei]/, '$1i')
// ending in "e"
.replace(/(diciassett|diciannov|mill|milion)esim[oaei]/, '$1e')
// ending in "o"
.replace(/(diciott|cent|miliard)esim[oaei]/, '$1o')
// ending in "a"
.replace(/(trent|quarant|cinquant|sessant|settant|ottant|novant)esim[oaei]/, '$1a');
// now find the next part
// note that in case of ambiguity ("tre" / "tredici") the left-most match in the regexp wins, not the longest
const partregexp = /tredici|quattordici|quindici|sedici|diciasette|diciotto|diciannove|venti?|trenta?|quaranta?|cinquanta?|sessanta?|settanta?|ottanta?|novanta?|due|tre|quattro|cinque|sei|sette|otto|nove|dieci|undici|dodici|cento?|mille|mila|milion[ei]|miliard[oi]|uno?|[0-9.,]+/y;
let match = partregexp.exec(text);
while (match !== null) {
const part = match[0];
if (part in MULTIPLIERS) {
const multiplier = MULTIPLIERS[part];
if (current === 0)
current = 1;
if (multiplier === 100) {
current *= 100;
} else {
value += current * multiplier;
current = 0;
}
} else if (part in NUMBERS) {
current += NUMBERS[part];
} else {
current += this._parseDecimalNumber(part);
}
match = partregexp.exec(text);
}
value += current;
return value;
}
private _normalizeNumber(num : number) {
let wholepart, fracpart;
if (num < 0) {
wholepart = Math.ceil(num);
fracpart = wholepart - num;
} else {
wholepart = Math.floor(num);
fracpart = num - wholepart;
}
// fracpart will be a number between 0 and 1 so in decimal it will start as "0."...
fracpart = String(fracpart).substring(2);
if (fracpart)
return `${wholepart},${fracpart}`;
else
return String(wholepart);
}
protected _parseDecimalNumber(text : string) {
// remove any ".", replace "," with "." and remove any leading 0 or +
const normalized = text.replace(/\./g, '').replace(/,/g, '.').replace(/^[0+]+/g, '');
return parseFloat(normalized);
}
protected _initNumbers() {
// numbers in digit
// note: Italian uses "," as the decimal separator and "." as the thousand separator!
// hence, the "normalized" form of numbers is different
this._addDefinition('DIGITS', /[0-9]+(\.[0-9]+)*/);
this._addDefinition('DECIMAL_NUMBER', /{DIGITS}(?:,{DIGITS})?/);
this._lexer.addRule(/[+-]?{DECIMAL_NUMBER}/, (lexer) => {
const value = this._parseDecimalNumber(lexer.text);
return makeToken(lexer.index, lexer.text, this._normalizeNumber(value));
});
// currencies
this._lexer.addRule(/{DECIMAL_NUMBER}{WS}(dollar[oi]|euro(?:cent)?|cent|sterlin[ae]|pence|penny|yen|won|yuan|usd|cad|aud|chf|eur|gbp|cny|jpy|krw)/, (lexer) => {
const [num, unitword] = lexer.text.split(WS);
let value = this._parseDecimalNumber(num);
let unit = unitword;
if (unit in CURRENCIES)
unit = CURRENCIES[unit];
if (unit.startsWith('0.01')) {
value *= 0.01;
unit = unit.substring(4);
}
return makeToken(lexer.index, lexer.text, this._normalizeNumber(value) + ' ' + unit, 'CURRENCY', { value, unit });
});
this._lexer.addRule(/(?:C\$|A\$|[$£€₩¥]){WS}?{DECIMAL_NUMBER}/, (lexer) => {
let unit = lexer.text.match(/C\$|A\$|[$£€₩¥]/)![0];
unit = CURRENCIES[unit];
const num = lexer.text.replace(/(?:C\$|A\$|[$£€₩¥])/g, '').replace(WS, '');
const value = this._parseDecimalNumber(num);
return makeToken(lexer.index, lexer.text, this._normalizeNumber(value) + ' ' + unit, 'CURRENCY', { value, unit });
});
// numbers in words
// - "zero" is not a number (cannot be compounded with other number words)
// - "un"/"uno"/"una" are not normalized when alone
// - small numbers (2 to 12) are normalized to digits
// - other numbers are converted to NUMBER tokens
// 2 to 9
this._addDefinition('ONE_DIGIT_NUMBER', /due|tre|quattro|cinque|sei|sette|otto|nove/);
// 2 to 12
this._addDefinition('SMALL_NUMBER', /{ONE_DIGIT_NUMBER}|dieci|undici|dodici/);
this._lexer.addRule(/{SMALL_NUMBER}/, (lexer) => {
const value = this._parseWordNumber(lexer.text);
return makeToken(lexer.index, lexer.text, this._normalizeNumber(value));
});
// 13 to 19, or (20 to 90) optionally followed by ((- or whitespace) followed by 1 to 10)
// special cases: when followed by 1 or 8 (which start with vowel)
this._addDefinition('MEDIUM_NUMBER', /tredici|quattordici|quindici|sedici|diciassette|diciotto|diciannove|(?:vent|trent|quarant|cinquant|sessant|settant|ottant|novant)(?:uno|otto)|(?:venti|trenta|quaranta|cinquanta|sessanta|settanta|ottanta|novanta)(?:due|tre|quattro|cinque|sei|sette|otto|nove)?/);
// 100 and above
// we accept both cause otherwise the grammar really gets out of hand
// note: space is optional between number parts
this._addDefinition('NUMBER_SEP', /{WS}?(?:e{WS})?/);
// 1 to 99, as used by large and huge numbers
this._addDefinition('LARGE_NUMBER_TRAIL', /{NUMBER_SEP}(uno|{SMALL_NUMBER}|{MEDIUM_NUMBER}|{DECIMAL_NUMBER})/);
// 100 to 999
// (unlike in English, you cannot use a 11-99 number with "cento"
// "twenty two hundreds" would always be said as "duemiladuecento" aka "two thousands two hundreds")
this._addDefinition('LARGE_NUMBER', /{ONE_DIGIT_NUMBER}?cento{LARGE_NUMBER_TRAIL}?/);
// 1000 and above (1000 is a special case)
// note that "milioni" and "miliardi" have a space but "mila" does not
this._addDefinition('HUGE_NUMBER_CHUNK', /mille|(?:{SMALL_NUMBER}|{MEDIUM_NUMBER}|{LARGE_NUMBER}|{DECIMAL_NUMBER})mila|(?:un|{SMALL_NUMBER}|{MEDIUM_NUMBER}|{LARGE_NUMBER}|{DECIMAL_NUMBER}){WS}(milion[ei]|miliard[ei])/);
this._addDefinition('HUGE_NUMBER', /{HUGE_NUMBER_CHUNK}(?:{NUMBER_SEP}{HUGE_NUMBER_CHUNK})*(?:{NUMBER_SEP}{LARGE_NUMBER}|{LARGE_NUMBER_TRAIL})?/);
// medium, large and huge numbers are normalized
this._lexer.addRule(/(?:{HUGE_NUMBER}|{LARGE_NUMBER}|{MEDIUM_NUMBER})(?!{LETTER})/, (lexer) => {
const value = this._parseWordNumber(lexer.text);
return makeToken(lexer.index, lexer.text, this._normalizeNumber(value));
});
}
protected _initOrdinals() {
// ordinals in digits are written as digit followed by "º" (MASCULINE ORDINAL INDICATOR) or "ª" (FEMININE ORDINAL INDICATOR)
// but those characters have a compatibility decomposition "o" and "a"
// so we see "1o" and "1a"
//
// actual ASCII "o" is not quite as definitive compared to the ordinal indicator, so we do not
// process ordinal numbers in any form, and simply split the number from the ordinal suffix
// the neural parser will then learn when "a" and "o" are ordinal indicators and when they are not
//
// people also use "°" (DEGREE SIGN) in place of "º", because "°" is available on common keyboards
// but we want to recognize temperatures, so we let that be its own token
// ordinals in words
// - "zeroth" is not an ordinal (cannot be compounded with other number words)
// - the last digit of an ordinal >= 20 ("unesimo", "duesimo", etc.) is not the same as an ordinal < 10 (primo, secondo, terzo, etc.)
// - small ordinals (1st to 12th) are untouched
// - other ordinals are converted to NUMBER tokens
// 1st to 9th
this._addDefinition('ONE_DIGIT_ORDINAL', /(?:un|du|tre|quattr|cinqu|sei|sett|ott|nov)esim[oaei]/);
this._addDefinition('SMALL_ORDINAL', /{ONE_DIGIT_ORDINAL}|undicesim[oaei]|undecim[oaei]|dodicesim[oaei]|duodecim[oaei]/);
// 13th to 19th, or 20th, 30th, 40th, 50th, 60th, 70th, 80th, 90th, or (20 to 90) followed by 1 to 10
this._addDefinition('MEDIUM_ORDINAL', /(?:tredic|quattordic|quindic|sedic|diciasett|diciott|diciannov|vent|trent|quarant|cinquant|sessant|settant|ottant)esim[oaei]|(?:venti?|trenta?|quaranta?|cinquanta?|sessanta?|settanta?|ottanta?|novanta?){ONE_DIGIT_ORDINAL}/);
// ending in 00th but not 000th: 100th, 200th, 300th, ... 1100th, 1200th, ...
this._addDefinition('HUNDRED_LARGE_ORDINAL', /(?:{HUGE_NUMBER_CHUNK}{NUMBER_SEP})*(?:(?:{SMALL_NUMBER}|{MEDIUM_NUMBER}))?centesim[oaei]/);
// ending in 000th: 1000th, 2000th, 22000th, 300000th, 1000000th, 1500000th, ...
// note that "duemilionesimo" is ambiguous with "duemilione" so we need to do some regexp gymnastics to parse it properly
this._addDefinition('THOUSAND_LARGE_ORDINAL', /{SMALL_NUMBER}?(?:millesim[oaei]|milionesim[oaei]|miliardesim[oaei])|(?:{HUGE_NUMBER}|{LARGE_NUMBER}|{MEDIUM_NUMBER})(?:millesim[oaei]|milionesim[oaei]|miliardesim[oaei])/);
// 101th and above, excluding those ending in 00th
this._addDefinition('OTHER_LARGE_ORDINAL', /(?:{HUGE_NUMBER}|{LARGE_NUMBER}){NUMBER_SEP}(?:{SMALL_ORDINAL}|{MEDIUM_ORDINAL})/);
// medium and large ordinals are normalized
this._lexer.addRule(/(?:{HUNDRED_LARGE_ORDINAL}|{THOUSAND_LARGE_ORDINAL}|{OTHER_LARGE_ORDINAL}|{MEDIUM_ORDINAL})(?!{LETTER})/, (lexer) => {
const value = this._parseWordNumber(lexer.text);
// normalize to a string without an ordinal marker (see above for why we cannot use "º")
const normalized = String(value);
return makeToken(lexer.index, lexer.text, normalized);
});
}
protected _initTimes() {
// Written Italian uses a simple 24 hour clock
// Proper punctuation (as enforced by spellcheckers and autocomplete) uses ":" to separate hour minute and second
// but it's common to see "." instead (and apparently some depraved people use "," too?)
// "." makes too much confusion with numbers so we pretend it doesn't exist
// hopefully speech to text won't give us too much grief
super._initTimes();
// Colloquial Italian, on the other hand, uses a 12 hour clock
// but you would never see that in numeric form or with minutes
// only with colloquial form like "tre del pomeriggio" (three in the afternoon) or
// "sette e mezza di sera" (half past seven in the evening)
// (more rarely, "sette e venti" (7:20) o "otto meno cinque" (five minutes to eight)
//
// These expressions are very ambiguous so we opt to let the neural network deal with it
// (it's easy to synthesize enough training data with templates)
}
private _extractWordMonth(text : string) {
const word = /gen|feb|mar|apr|mag|giu|lug|ago|set|ott|nov|dic/.exec(text.toLowerCase())!;
return MONTHS[word[0]];
}
private _parseWordDate(text : string, parseDay : boolean, parseYear : boolean, parseTime : ((x : string) => TimeEntity)|null) {
// this is the same logic as English (the order is the same as British English: day month year)
const month = this._extractWordMonth(text);
const digitreg = /[0-9]+/g;
let day = -1;
if (parseDay) {
// find the first sequence of digits to get the day
day = parseInt(digitreg.exec(text)![0]);
}
let year = -1;
if (parseYear) {
// find the next sequence of digits to get the year
// (digitreg is a global regex so it will start matching from the end of the previous match)
year = parseInt(digitreg.exec(text)![0]);
}
if (parseTime) {
// if we have a time, pick the remaining of the string and parse it
const time = parseTime(text.substring(digitreg.lastIndex));
return { year, month, day, hour: time.hour, minute: time.minute, second: time.second, timezone: undefined };
} else {
return { year, month, day, hour: 0, minute: 0, second: 0, timezone: undefined };
}
}
protected _initDates() {
// init ISO date recognition
super._initDates();
this._addDefinition('ABBRV_DAY', /(?:lun|mar|mer|gio|ven|sab|dom)\./);
// note: we're operating in NFKD so the accent is separate from the vowel it attaches to
this._addDefinition('LONG_DAY', /(?:lune|marte|mercole|giove|vener)di\u0300|sabato|domenica/);
// a number between 1 and 31
// days are not ordinals in Italian, except for the first day of the month
// see above for why we include ° (DEGREE SIGN) and "o" here
this._addDefinition('NUMERIC_DAY', /1[oº°]|[12][0-9]|3[01]|[1-9]/);
this._addDefinition('ABBRV_MONTH', /(?:gen|feb|mar|apr|mag|giu|lug|sett?|ott|nov|dic)\.?/);
this._addDefinition('LONG_MONTH', /gennaio|febbraio|marzo|aprile|maggio|giugno|luglio|agosto|settembre|ottobre|novembre|dicembre/);
// optional (day name followed by comma followed by whitespace), followed by day, optional "di" (= "of"), month
// "Martedì, 7 Luglio", "1º Maggio", "30 Apr.", "2 di Agosto"
this._addDefinition('DAY_MONTH', /(?:(?:{ABBRV_DAY}|{LONG_DAY}),?{WS})?{NUMERIC_DAY}{WS}(?:di{WS})?(?:{LONG_MONTH}|{ABBRV_MONTH})(?!{LETTER})/);
// (unlike English, the month never precedes the day)
// dates with words
// day and month
this._lexer.addRule(/{DAY_MONTH}/, (lexer) => {
const parsed = this._parseWordDate(lexer.text, true, false, null);
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
// day, month and year
this._lexer.addRule(/{DAY_MONTH}{WS}[0-9]{4}(?![0-9])/, (lexer) => {
const parsed = this._parseWordDate(lexer.text, true, true, null);
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
// month and year
// XXX: CoreNLP/almond-tokenizer would parse this as today's date, in the given month
// but maybe it should parse as the first day of the given month instead?
this._lexer.addRule(/(?:{LONG_MONTH}|{ABBRV_MONTH}){WS}[0-9]{4}(?![0-9])/, (lexer) => {
const parsed = this._parseWordDate(lexer.text, false, true, null);
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
// day and month followed by comma, followed by optional "alle" or "all'" (= "at"), followed by a time
this._lexer.addRule(/{DAY_MONTH},?{WS}(?:alle{WS}|all')?{PLAIN_TIME}/, (lexer) => {
const parsed = this._parseWordDate(lexer.text, true, false, (text) => this._parse12HrTime(text, '24h'));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
// day, month and year, followed by optional "alle" or "all'" (= "at"), followed by a time
this._lexer.addRule(/{DAY_MONTH}{WS}[0-9]{4}(?![0-9]),?{WS}(?:alle{WS}|all')?{PLAIN_TIME}/, (lexer) => {
const parsed = this._parseWordDate(lexer.text, true, true, (text) => this._parse12HrTime(text, '24h'));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
// numeric dates
// day/month/year
this._addDefinition('NUMERIC_DATE', /(?:[12][0-9]|3[01]|0?[1-9])\/(?:1[012]|0?[1-9])\/[0-9]{4}(?![0-9])/);
// day.month.year
// day/month (only applicable with other signals that make it a date)
this._addDefinition('NUMERIC_DATE_SHORT', /(?:[12][0-9]|3[01]|0?[1-9])\/(?:1[012]|0?[1-9])/);
this._lexer.addRule(/{NUMERIC_DATE}/, (lexer) => {
const parsed = this._parseNumericDate(lexer.text, 'dmy', null);
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
// with time
this._lexer.addRule(/(?:{NUMERIC_DATE}|{NUMERIC_DATE_SHORT}),?{WS}(?:alle{WS}|all')?{PLAIN_TIME}/, (lexer) => {
const parsed = this._parseNumericDate(lexer.text, 'dmy', (text) => this._parse12HrTime(text, '24h'));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
}
} | the_stack |
import * as Faker from 'faker';
import {
AsyncSystemConfig,
AsyncSystemValue,
BaseConfig,
ClusterItems,
SharedAsyncSystemConfig,
UnitConfig,
} from '../models';
import {KeyValToKeyValProducer} from '../models/utils';
import {NonPrimitiveUnitBase} from '../lib/abstract-non-primitive-unit-base';
import {UnitBase} from '../lib/abstract-unit-base';
import {GenericUnit} from '../lib/generic-unit';
import {BoolUnit} from '../lib/bool-unit';
import {StringUnit} from '../lib/string-unit';
import {NumUnit} from '../lib/num-unit';
import {DictUnit} from '../lib/dict-unit';
import {ListUnit} from '../lib/list-unit';
import {Action} from '../lib/action';
import {AsyncSystem} from '../lib/async-system';
import {Cluster} from '../lib/cluster';
import {isDict, isObject, isNumber, makeNonEnumerable} from '../utils/funcs';
export const UNITS_CTORS = [GenericUnit, BoolUnit, StringUnit, NumUnit, DictUnit, ListUnit];
export const UNITS_CTORS_COUNT = UNITS_CTORS.length;
export const ALL_CTORS = [...UNITS_CTORS, Action, AsyncSystem, Cluster];
export const RANDOM_VALUE_PRODUCERS: Array<(nestingLvl?: number) => any> = [
() => randomBoolean(),
() => randomString(),
() => randomString(),
() => randomWholeNumber(),
() => randomWholeNumber(),
randomDictObject,
randomDictObject,
randomDictObject,
randomArray,
randomArray,
randomArray,
// () => NaN, // this will cause "toEqual" and "toBe" to fail
() => (randomBoolean(0.8) ? 1 : -1) * Infinity,
() => undefined,
() => null,
];
export const RANDOM_CONFIG_OPTIONS_VALUE_PRODUCERS: Required<KeyValToKeyValProducer<
SharedAsyncSystemConfig<any, any, any> & Omit<UnitConfig<any>, 'initialValue'>
>> = {
// SharedUnitConfig
replay: (validness?, nestingLvl?) => booleanOrRandomValue(validness, nestingLvl),
cacheSize: (validness?, nestingLvl?) => numberOrRandomValue(validness, nestingLvl, 0, 20),
immutable: (validness?, nestingLvl?) => booleanOrRandomValue(validness, nestingLvl),
persistent: (validness?, nestingLvl?) => booleanOrRandomValue(validness, nestingLvl),
storage: (validness?, nestingLvl?) =>
randomBoolean(validness)
? selectRandom([localStorage, sessionStorage])
: randomValue(nestingLvl),
distinctDispatchCheck: (validness?, nestingLvl?) => booleanOrRandomValue(validness, nestingLvl),
// UnitConfig
id: (validness?, nestingLvl?) => stringOrRandomValue(validness, nestingLvl),
customDispatchCheck: (validness?, nestingLvl?) =>
randomBoolean(validness) ? randomFn(nestingLvl) : randomValue(1),
dispatchDebounce: (validness?, nestingLvl?) =>
randomBoolean(validness)
? randomBoolean(0.8)
? randomNumber()
: randomBoolean()
: randomValue(nestingLvl),
dispatchDebounceMode: (validness?, nestingLvl?) =>
randomBoolean(validness)
? [undefined, 'START', 'END', 'BOTH'][randomNumber(0, 3)]
: randomValue(nestingLvl),
// SharedAsyncSystemConfig
clearErrorOnData: (validness?, nestingLvl?) => booleanOrRandomValue(validness, nestingLvl),
clearErrorOnQuery: (validness?, nestingLvl?) => booleanOrRandomValue(validness, nestingLvl),
clearDataOnError: (validness?, nestingLvl?) => booleanOrRandomValue(validness, nestingLvl),
clearDataOnQuery: (validness?, nestingLvl?) => booleanOrRandomValue(validness, nestingLvl),
clearQueryOnData: (validness?, nestingLvl?) => booleanOrRandomValue(validness, nestingLvl),
clearQueryOnError: (validness?, nestingLvl?) => booleanOrRandomValue(validness, nestingLvl),
autoUpdatePendingValue: (validness?, nestingLvl?) => booleanOrRandomValue(validness, nestingLvl),
freezeQueryWhilePending: (validness?, nestingLvl?) => booleanOrRandomValue(validness, nestingLvl),
};
export const LIST_UNIT_MUTATION_FNS = [
(unit: ListUnit<any>) => unit.dispatch(randomArray(1)),
(unit: ListUnit<any>) => unit.dispatch(() => randomArray(1)),
(unit: ListUnit<any>) => unit.push(...randomArray(1)),
(unit: ListUnit<any>) => unit.pop(),
(unit: ListUnit<any>) => unit.shift(),
(unit: ListUnit<any>) => unit.unshift(...randomArray(1)),
(unit: ListUnit<any>) => unit.splice(randomNumber(), randomNumber(), ...randomArray(1)),
(unit: ListUnit<any>) => unit.fill(randomValue(1), randomNumber(), randomNumber()),
(unit: ListUnit<any>) => unit.copyWithin(randomNumber(), randomNumber(), randomNumber()),
(unit: ListUnit<any>) => unit.reverse(),
(unit: ListUnit<any>) => unit.sort(randomFn()),
(unit: ListUnit<any>) => unit.set(randomNumber(), randomValue(1)),
(unit: ListUnit<any>) => unit.insert(randomNumber(), ...randomArray(1)),
(unit: ListUnit<any>) => unit.remove(...multipleOf(randomNumber)),
(unit: ListUnit<any>) => unit.removeIf(randomFn()),
(unit: ListUnit<any>) => unit.delete(...multipleOf(randomNumber)),
(unit: ListUnit<any>) => unit.deleteIf(randomFn()),
];
export const DICT_UNIT_MUTATION_FNS = [
(unit: DictUnit<any>) => unit.dispatch(randomDictObject(1)),
(unit: DictUnit<any>) => unit.dispatch(() => randomDictObject(1)),
(unit: DictUnit<any>) => unit.set(randomNumber(), randomValue(1)),
(unit: DictUnit<any>) =>
unit.delete(...randomSelectMultiple(unit.objectKeys().concat(randomKeys() as any))),
(unit: DictUnit<any>) => unit.deleteIf(randomFn()),
(unit: DictUnit<any>) => unit.assign(...randomArray(2)),
];
export const UNIT_CACHE_NAVIGATION_FNS = [
(unit: UnitBase<any> | GenericUnit<any>, skipNil = randomBoolean()) => unit.goBack(skipNil),
(unit: UnitBase<any> | GenericUnit<any>, skipNil = randomBoolean()) => unit.goForward(skipNil),
(unit: UnitBase<any>) => unit.jump(-randomNumber(1, unit.cacheIndex)),
(unit: UnitBase<any>) => unit.jump(randomNumber(1, unit.cachedValuesCount - 1 - unit.cacheIndex)),
];
// tslint:disable-next-line:ban-types
export function randomFn(nestingLvl = 1): (...args) => any {
const randValue = randomValue(nestingLvl);
return () => randValue;
}
// returns a pure function that returns same random value everytime
// for a specific number argument `n`
export function randomValuePureFn(): (n: number) => any {
const values = randomValues();
return (n: number) => values[n % values.length];
}
export function randomSortPredicate(): (a: any, b: any) => number {
const desc = Faker.random.boolean();
return (a, b) => {
if (a > b) {
return desc ? -1 : 1;
} else if (a < b) {
return desc ? 1 : -1;
}
return 0;
};
}
export function randomWholeNumber(max?: number): number {
return (randomBoolean(0.8) ? 1 : -1) * Faker.random.number(max);
}
export function randomNumber(min?: number, max?: number): number {
return Faker.random.number({min, max});
}
export function randomString(): string {
return selectRandom([Faker.random.words, Faker.random.word, Faker.random.alphaNumeric])();
}
export function randomNumOrStr(): string | number {
return selectRandom([randomNumber, randomString])();
}
export function randomNumsAndStrings(): (string | number)[] {
return multipleOf(randomNumOrStr);
}
// increased truthiness range: {0, 1}, or negative for decreased truthiness
export function randomBoolean(truthiness = 0): boolean {
// .5 becomes true, hence divided to provide range {0, 1}
return !!Math.round(Math.random() + truthiness / 2);
}
export function booleanOrRandomValue(validness = 0.7, nestingLvl = 1) {
return randomBoolean(validness) ? randomBoolean() : randomValue(nestingLvl);
}
export function stringOrRandomValue(validness = 0.7, nestingLvl = 1) {
return randomBoolean(validness) ? randomString() : randomValue(nestingLvl);
}
export function numberOrRandomValue(validness = 0.7, nestingLvl = 1, min?: number, max?: number) {
return randomBoolean(validness) ? randomNumber(min, max) : randomValue(nestingLvl);
}
export function randomArray(nestingLvl = 2, maxLength = 6): any[] {
if (nestingLvl < 0 || !isNumber(nestingLvl)) {
return ['END'];
}
const isSameType = randomBoolean(-0.7); // less chances
let randomValueProducer = randomValue;
if (isSameType) {
randomValueProducer = selectRandom([
() => randomWholeNumber(),
() => randomWholeNumber(),
() => randomBoolean(),
() => randomString(),
() => randomArray(nestingLvl),
() => randomDictObject(nestingLvl),
]);
}
return Array(randomNumber(0, maxLength))
.fill(null)
.map(() => randomValueProducer(nestingLvl));
}
export function selectRandom(list: any[]) {
return list[randomNumber(0, list.length - 1)];
}
export function randomSelectMultiple<T extends any[]>(list: T, max = 6): T {
return Faker.helpers.shuffle(list).slice(Math.min(randomNumber(0, list.length), max)) as T;
}
export function multipleOf<T>(producer: () => T, max = 6, min = 1): T[] {
return Array(randomNumber(min, max)).fill(null).map(producer);
}
export function randomKeys(max = 3, min = 0) {
return multipleOf(randomNumOrStr, max, min);
}
export function randomDictObject(nestingLvl = 2, maxKeys = 3) {
if (nestingLvl < 0 || !isNumber(nestingLvl)) {
return {END: true};
}
return randomKeys(maxKeys).reduce((reduced, key) => {
reduced[key] = randomValue(nestingLvl);
return reduced;
}, {});
}
export function randomValues(nestingLvl = 2) {
return randomSelectMultiple(RANDOM_VALUE_PRODUCERS).map(gen => gen(nestingLvl));
}
export function randomValue(nestingLvl = 2) {
--nestingLvl;
return selectRandom(RANDOM_VALUE_PRODUCERS)(nestingLvl);
}
export function randomValidValue<
T extends UnitBase<any> | Action<any>,
C extends BaseConfig | UnitConfig<any>
>(o: (new (config?: C) => T) | T, nestingLvl = 2, maxKeys = 3, maxLength = 5) {
const isCtor = typeof o === 'function';
const ctorName = isCtor ? (o as new () => UnitBase<any>).name : o.constructor.name;
switch (ctorName) {
case 'BoolUnit':
return randomBoolean();
case 'NumUnit':
return randomWholeNumber();
case 'StringUnit':
return randomString();
case 'ListUnit':
return randomArray(maxLength);
case 'DictUnit':
return randomDictObject(nestingLvl, maxKeys);
case 'Action':
case 'GenericUnit':
return randomValue(nestingLvl);
}
}
export function unitsDefaultValue<T extends UnitBase<any>>(
unit: (new (config?: UnitConfig<any>) => T) | T
) {
const isCtor = typeof unit === 'function';
const ctorName = isCtor ? (unit as new () => UnitBase<any>).name : unit.constructor.name;
switch (ctorName) {
case 'BoolUnit':
return false;
case 'NumUnit':
return 0;
case 'StringUnit':
return '';
case 'ListUnit':
return [];
case 'DictUnit':
return {};
case 'GenericUnit':
return undefined;
}
}
export function differentValue<T extends any>(v: T): T {
switch (typeof v) {
case 'boolean':
return !v as T;
case 'number':
return (isFinite(v) ? v + 1 + randomNumber() : randomNumber(0, Number.MAX_SAFE_INTEGER)) as T;
case 'string':
return (v + ' ' + randomString()) as T;
case 'undefined':
return randomValue(1) || (randomNumber() as T);
case 'object':
return (Array.isArray(v)
? v.concat(randomArray(1, 5)).concat(1)
: Object.assign({}, v, randomDictObject(1), {id: (v as any)?.id + 1})) as T;
}
}
export function times(count: number, callback: (counter: number) => any) {
return () =>
Array(count)
.fill(null)
.forEach((v, i) => callback(i));
}
export function randomConfig<K extends string>(
configOptions: K[],
nestingLvl = 1
): {[key in K]: any} {
return (
Faker.helpers
.shuffle(configOptions) // shuffle the options to pick random options every time
.slice(0, randomNumber(0, configOptions.length - 1)) // pick some random options
// generate a config object from options
.reduce((reduced, option) => {
// generate a config object from options
reduced[option as string] = randomValue(nestingLvl);
return reduced;
}, {}) as {[key in K]: any}
);
}
export function somewhatValidConfig(
configOptions: Array<keyof UnitConfig<any>>,
o: (new () => UnitBase<any> | Action<any>) | UnitBase<any> | Action<any>,
validness = 0.7,
nestingLvl = 1
): UnitConfig<any> {
return (
Faker.helpers
.shuffle(configOptions) // shuffle the options to pick random options every time
.slice(0, randomNumber(0, configOptions.length - 1)) // pick some random options
// generate a config object from options
.reduce((reduced, option) => {
// generate a config object from options
switch (option) {
case 'initialValue':
reduced[option] = randomInitialValue(o, validness, nestingLvl);
break;
default:
reduced[option] = RANDOM_CONFIG_OPTIONS_VALUE_PRODUCERS[option](validness, nestingLvl);
}
return reduced;
}, {})
);
}
export function randomAsyncSystemConfig(
configOptions: Array<keyof AsyncSystemConfig<any, any, any>>,
unitsConfigOptions: Array<keyof UnitConfig<any>>,
validness = 0.7,
nestingLvl = 1
): AsyncSystemConfig<any, any, any> {
return Faker.helpers
.shuffle(configOptions) // shuffle the options to pick random options every time
.slice(0, randomNumber(0, configOptions.length - 1)) // pick some random options
.reduce((reduced, option) => {
// generate a config object from options
switch (option) {
case 'initialValue':
reduced[option] = randomAsyncSystemInitialValue(validness, nestingLvl);
break;
case 'UNITS':
case 'QUERY_UNIT':
case 'DATA_UNIT':
case 'ERROR_UNIT':
reduced[option] = somewhatValidConfig(
unitsConfigOptions,
GenericUnit,
validness,
nestingLvl
);
break;
case 'PENDING_UNIT':
reduced[option] = somewhatValidConfig(
unitsConfigOptions,
BoolUnit,
validness,
nestingLvl
);
break;
default:
reduced[option] = RANDOM_CONFIG_OPTIONS_VALUE_PRODUCERS[option](validness, nestingLvl);
}
return reduced;
}, {});
}
export function randomInitialValue(
unit: (new () => UnitBase<any> | Action<any>) | UnitBase<any> | Action<any>,
validness = 0.7,
nestingLvl = 1
) {
return randomBoolean(validness) ? randomValidValue(unit) : randomValue(nestingLvl);
}
export function randomAsyncSystemInitialValue(validness = 0.7, nestingLvl = 1) {
return {
query: randomInitialValue(GenericUnit, validness, nestingLvl),
data: randomInitialValue(GenericUnit, validness, nestingLvl),
error: randomInitialValue(GenericUnit, validness, nestingLvl),
pending: randomInitialValue(BoolUnit, validness, nestingLvl),
} as AsyncSystemValue<any, any, any>;
}
export function randomUnitCtor(): new (config?: UnitConfig<any>) => UnitBase<any> &
NonPrimitiveUnitBase<any> {
return selectRandom(UNITS_CTORS);
}
export function randomUnit(config?: UnitConfig<any>) {
const unitCtor = randomUnitCtor();
return new unitCtor(config);
}
export function randomClusterItems(nestingLvl = 2, maxItems = 5): ClusterItems {
--nestingLvl;
const itemsKeys = randomKeys(maxItems, 1);
const itemsCtors = itemsKeys.map(() => selectRandom(ALL_CTORS));
return itemsKeys.reduce((reduced, key, index) => {
if (itemsCtors[index] === Cluster) {
if (nestingLvl >= 0) {
const nestedClusterItems = randomClusterItems(nestingLvl, maxItems);
reduced[key] = new itemsCtors[index](
// cluster needs at least one item, otherwise it throws error
Object.keys(nestedClusterItems).length ? nestedClusterItems : {unit: randomUnit()}
);
}
} else {
reduced[key] = new itemsCtors[index]();
}
return reduced;
}, {});
}
export function randomMutation<T>(o: T): void {
if (o == null || typeof o !== 'object') {
return;
}
if (Array.isArray(o)) {
o.forEach(v => randomMutation(v));
switch (randomNumber(0, 4)) {
case 0:
o.splice(randomNumber(0, o.length), randomNumber(0, o.length), randomValue(1));
break;
case 1:
o[randomNumOrStr()] = randomValue(1);
break;
case 2:
o.length ? o.pop() : o.push(randomValue(1));
break;
case 3:
o.length ? o.shift() : o.push(randomValue(1));
break;
case 4:
if (o.length) {
delete o[selectRandom(Object.keys(o))];
} else {
o.push(randomValue(1));
}
}
} else if (isDict(o)) {
const keys = Object.keys(o);
keys.forEach(k => randomMutation(o[k]));
if (!keys.length || randomBoolean()) {
o[randomNumOrStr()] = randomValue(1);
} else {
delete o[selectRandom(keys)];
}
}
}
export function safeStringify(
o: any,
replacer?: (this: any, key: string, value: any) => any,
space?: string | number
) {
try {
return JSON.stringify(o, replacer, space) || String(o);
} catch (e1) {
try {
return String(o);
} catch (e2) {
return '';
}
}
}
export function findRandomPath(o: any): (string | number)[] {
if (!isObject(o) || randomBoolean(-0.6)) {
return [];
}
if (Array.isArray(o)) {
const randIndex = randomNumber(0, o.length - 1);
return !o.length ? [] : [randIndex, ...findRandomPath(o[randIndex])];
}
const randKey = selectRandom(Object.keys(o));
return randKey == null ? [] : [randKey, ...findRandomPath(o[randKey])];
}
export function findEqualitiesByReference(A: any, B: any): any[] {
if (A == null || B == null || typeof A !== 'object' || typeof B !== 'object') {
return [];
}
if (A === B) {
return [A]; // or [B]
}
const deepObjectExtract = (o, r = []) => {
if (o == null || typeof o !== 'object') {
return r;
}
r.push(o);
if (!Array.isArray(o)) {
o = Object.values(o);
}
o.forEach(c => deepObjectExtract(c, r));
return r;
};
const AO = deepObjectExtract(A);
const BO = deepObjectExtract(B);
return AO.filter(o => BO.includes(o));
}
export const CUSTOM_MATCHERS = {
toHaveSharedReferenceIn: () => {
return {
compare: (actual, expected) => {
const equalitiesByReference = findEqualitiesByReference(actual, expected);
const pass = equalitiesByReference.length > 0;
const message = pass
? ''
: `Expected ${safeStringify(
actual
)} to have at least one shared reference with/in ${safeStringify(expected)}.`;
return {pass, message};
},
negativeCompare: (actual, expected) => {
const equalitiesByReference = findEqualitiesByReference(actual, expected);
const pass = !isObject(actual) || !isObject(expected) || equalitiesByReference.length === 0;
const message = pass
? ''
: `Expected ${safeStringify(
actual
)} to not have any shared reference with/in ${safeStringify(
expected
)}, but found the following: ${safeStringify(equalitiesByReference)}`;
return {pass, message};
},
};
},
};
export class MockStorage implements Storage {
private readonly store: {[key: string]: string} = {};
get length(): number {
return Object.keys(this.store).length;
}
constructor() {
makeNonEnumerable(this);
return new Proxy(this, {
set: (target, prop, value) => Reflect.set(this.store, prop, value),
get: (target, prop) => {
return prop !== 'store' &&
(this.hasOwnProperty(prop) || Object.getPrototypeOf(this).hasOwnProperty(prop))
? typeof this[prop] === 'function'
? this[prop].bind(this)
: Reflect.get(this, prop)
: Reflect.get(this.store, prop);
},
has: (target, prop: string) =>
(prop !== 'store' && Reflect.has(target, prop)) || Reflect.has(this.store, prop),
deleteProperty: (target, prop) => Reflect.deleteProperty(this.store, prop),
defineProperty: (target, prop, attributes) =>
Reflect.defineProperty(this.store, prop, attributes),
ownKeys: () => Reflect.ownKeys(this.store),
getOwnPropertyDescriptor: (target, prop) =>
Reflect.getOwnPropertyDescriptor(this.store, prop),
});
}
setItem(key: string, value: string): void {
this.store[key] = value + '';
}
getItem(key: string): string | null {
return this.store[key] ?? null;
}
removeItem(key: string): void {
delete this.store[key];
}
key(index: number): string | null {
return Object.keys(this.store)[index] ?? null;
}
clear(): void {
Object.keys(this.store).forEach(key => {
delete this.store[key];
});
}
} | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as msRestAzure from "@azure/ms-rest-azure-js";
import * as Models from "../models";
import * as Mappers from "../models/privateZonesMappers";
import * as Parameters from "../models/parameters";
import { PrivateDnsManagementClientContext } from "../privateDnsManagementClientContext";
/** Class representing a PrivateZones. */
export class PrivateZones {
private readonly client: PrivateDnsManagementClientContext;
/**
* Create a PrivateZones.
* @param {PrivateDnsManagementClientContext} client Reference to the service client.
*/
constructor(client: PrivateDnsManagementClientContext) {
this.client = client;
}
/**
* Creates or updates a Private DNS zone. Does not modify Links to virtual networks or DNS records
* within the zone.
* @param resourceGroupName The name of the resource group.
* @param privateZoneName The name of the Private DNS zone (without a terminating dot).
* @param parameters Parameters supplied to the CreateOrUpdate operation.
* @param [options] The optional parameters
* @returns Promise<Models.PrivateZonesCreateOrUpdateResponse>
*/
createOrUpdate(resourceGroupName: string, privateZoneName: string, parameters: Models.PrivateZone, options?: Models.PrivateZonesCreateOrUpdateOptionalParams): Promise<Models.PrivateZonesCreateOrUpdateResponse> {
return this.beginCreateOrUpdate(resourceGroupName,privateZoneName,parameters,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.PrivateZonesCreateOrUpdateResponse>;
}
/**
* Updates a Private DNS zone. Does not modify virtual network links or DNS records within the
* zone.
* @param resourceGroupName The name of the resource group.
* @param privateZoneName The name of the Private DNS zone (without a terminating dot).
* @param parameters Parameters supplied to the Update operation.
* @param [options] The optional parameters
* @returns Promise<Models.PrivateZonesUpdateResponse>
*/
update(resourceGroupName: string, privateZoneName: string, parameters: Models.PrivateZone, options?: Models.PrivateZonesUpdateOptionalParams): Promise<Models.PrivateZonesUpdateResponse> {
return this.beginUpdate(resourceGroupName,privateZoneName,parameters,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.PrivateZonesUpdateResponse>;
}
/**
* Deletes a Private DNS zone. WARNING: All DNS records in the zone will also be deleted. This
* operation cannot be undone. Private DNS zone cannot be deleted unless all virtual network links
* to it are removed.
* @param resourceGroupName The name of the resource group.
* @param privateZoneName The name of the Private DNS zone (without a terminating dot).
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(resourceGroupName: string, privateZoneName: string, options?: Models.PrivateZonesDeleteMethodOptionalParams): Promise<msRest.RestResponse> {
return this.beginDeleteMethod(resourceGroupName,privateZoneName,options)
.then(lroPoller => lroPoller.pollUntilFinished());
}
/**
* Gets a Private DNS zone. Retrieves the zone properties, but not the virtual networks links or
* the record sets within the zone.
* @param resourceGroupName The name of the resource group.
* @param privateZoneName The name of the Private DNS zone (without a terminating dot).
* @param [options] The optional parameters
* @returns Promise<Models.PrivateZonesGetResponse>
*/
get(resourceGroupName: string, privateZoneName: string, options?: msRest.RequestOptionsBase): Promise<Models.PrivateZonesGetResponse>;
/**
* @param resourceGroupName The name of the resource group.
* @param privateZoneName The name of the Private DNS zone (without a terminating dot).
* @param callback The callback
*/
get(resourceGroupName: string, privateZoneName: string, callback: msRest.ServiceCallback<Models.PrivateZone>): void;
/**
* @param resourceGroupName The name of the resource group.
* @param privateZoneName The name of the Private DNS zone (without a terminating dot).
* @param options The optional parameters
* @param callback The callback
*/
get(resourceGroupName: string, privateZoneName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PrivateZone>): void;
get(resourceGroupName: string, privateZoneName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PrivateZone>, callback?: msRest.ServiceCallback<Models.PrivateZone>): Promise<Models.PrivateZonesGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
privateZoneName,
options
},
getOperationSpec,
callback) as Promise<Models.PrivateZonesGetResponse>;
}
/**
* Lists the Private DNS zones in all resource groups in a subscription.
* @param [options] The optional parameters
* @returns Promise<Models.PrivateZonesListResponse>
*/
list(options?: Models.PrivateZonesListOptionalParams): Promise<Models.PrivateZonesListResponse>;
/**
* @param callback The callback
*/
list(callback: msRest.ServiceCallback<Models.PrivateZoneListResult>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
list(options: Models.PrivateZonesListOptionalParams, callback: msRest.ServiceCallback<Models.PrivateZoneListResult>): void;
list(options?: Models.PrivateZonesListOptionalParams | msRest.ServiceCallback<Models.PrivateZoneListResult>, callback?: msRest.ServiceCallback<Models.PrivateZoneListResult>): Promise<Models.PrivateZonesListResponse> {
return this.client.sendOperationRequest(
{
options
},
listOperationSpec,
callback) as Promise<Models.PrivateZonesListResponse>;
}
/**
* Lists the Private DNS zones within a resource group.
* @param resourceGroupName The name of the resource group.
* @param [options] The optional parameters
* @returns Promise<Models.PrivateZonesListByResourceGroupResponse>
*/
listByResourceGroup(resourceGroupName: string, options?: Models.PrivateZonesListByResourceGroupOptionalParams): Promise<Models.PrivateZonesListByResourceGroupResponse>;
/**
* @param resourceGroupName The name of the resource group.
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.PrivateZoneListResult>): void;
/**
* @param resourceGroupName The name of the resource group.
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, options: Models.PrivateZonesListByResourceGroupOptionalParams, callback: msRest.ServiceCallback<Models.PrivateZoneListResult>): void;
listByResourceGroup(resourceGroupName: string, options?: Models.PrivateZonesListByResourceGroupOptionalParams | msRest.ServiceCallback<Models.PrivateZoneListResult>, callback?: msRest.ServiceCallback<Models.PrivateZoneListResult>): Promise<Models.PrivateZonesListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
options
},
listByResourceGroupOperationSpec,
callback) as Promise<Models.PrivateZonesListByResourceGroupResponse>;
}
/**
* Creates or updates a Private DNS zone. Does not modify Links to virtual networks or DNS records
* within the zone.
* @param resourceGroupName The name of the resource group.
* @param privateZoneName The name of the Private DNS zone (without a terminating dot).
* @param parameters Parameters supplied to the CreateOrUpdate operation.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginCreateOrUpdate(resourceGroupName: string, privateZoneName: string, parameters: Models.PrivateZone, options?: Models.PrivateZonesBeginCreateOrUpdateOptionalParams): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
privateZoneName,
parameters,
options
},
beginCreateOrUpdateOperationSpec,
options);
}
/**
* Updates a Private DNS zone. Does not modify virtual network links or DNS records within the
* zone.
* @param resourceGroupName The name of the resource group.
* @param privateZoneName The name of the Private DNS zone (without a terminating dot).
* @param parameters Parameters supplied to the Update operation.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginUpdate(resourceGroupName: string, privateZoneName: string, parameters: Models.PrivateZone, options?: Models.PrivateZonesBeginUpdateOptionalParams): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
privateZoneName,
parameters,
options
},
beginUpdateOperationSpec,
options);
}
/**
* Deletes a Private DNS zone. WARNING: All DNS records in the zone will also be deleted. This
* operation cannot be undone. Private DNS zone cannot be deleted unless all virtual network links
* to it are removed.
* @param resourceGroupName The name of the resource group.
* @param privateZoneName The name of the Private DNS zone (without a terminating dot).
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginDeleteMethod(resourceGroupName: string, privateZoneName: string, options?: Models.PrivateZonesBeginDeleteMethodOptionalParams): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
privateZoneName,
options
},
beginDeleteMethodOperationSpec,
options);
}
/**
* Lists the Private DNS zones in all resource groups in a subscription.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.PrivateZonesListNextResponse>
*/
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.PrivateZonesListNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PrivateZoneListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PrivateZoneListResult>): void;
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PrivateZoneListResult>, callback?: msRest.ServiceCallback<Models.PrivateZoneListResult>): Promise<Models.PrivateZonesListNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listNextOperationSpec,
callback) as Promise<Models.PrivateZonesListNextResponse>;
}
/**
* Lists the Private DNS zones within a resource group.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.PrivateZonesListByResourceGroupNextResponse>
*/
listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.PrivateZonesListByResourceGroupNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PrivateZoneListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PrivateZoneListResult>): void;
listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PrivateZoneListResult>, callback?: msRest.ServiceCallback<Models.PrivateZoneListResult>): Promise<Models.PrivateZonesListByResourceGroupNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByResourceGroupNextOperationSpec,
callback) as Promise<Models.PrivateZonesListByResourceGroupNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateDnsZones/{privateZoneName}",
urlParameters: [
Parameters.resourceGroupName,
Parameters.privateZoneName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PrivateZone
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.Network/privateDnsZones",
urlParameters: [
Parameters.subscriptionId
],
queryParameters: [
Parameters.top,
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PrivateZoneListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listByResourceGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateDnsZones",
urlParameters: [
Parameters.resourceGroupName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.top,
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PrivateZoneListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginCreateOrUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateDnsZones/{privateZoneName}",
urlParameters: [
Parameters.resourceGroupName,
Parameters.privateZoneName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.ifMatch,
Parameters.ifNoneMatch,
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.PrivateZone,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.PrivateZone
},
201: {
bodyMapper: Mappers.PrivateZone
},
202: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateDnsZones/{privateZoneName}",
urlParameters: [
Parameters.resourceGroupName,
Parameters.privateZoneName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.ifMatch,
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.PrivateZone,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.PrivateZone
},
202: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const beginDeleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateDnsZones/{privateZoneName}",
urlParameters: [
Parameters.resourceGroupName,
Parameters.privateZoneName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.ifMatch,
Parameters.acceptLanguage
],
responses: {
200: {},
202: {},
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PrivateZoneListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listByResourceGroupNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PrivateZoneListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
}; | the_stack |
import * as azure from "@pulumi/azure";
import * as pulumi from "@pulumi/pulumi";
import * as cdnManagement from "@azure/arm-cdn";
import { ServiceClientCredentials } from "@azure/ms-rest-js";
import * as msRestAzure from "@azure/ms-rest-nodeauth";
/**
* CustomDomainOptions represents the inputs to the dynamic resource.
* Any property of type `Input<T>` will automatically be resolved to their type `T`
* by the custom dynamic resource before passing them to the functions in the
* dynamic resource provider.
*/
export interface CustomDomainOptions {
resourceGroupName: pulumi.Input<string>;
profileName: pulumi.Input<string>;
endpointName: pulumi.Input<string>;
customDomainHostName: pulumi.Input<string>;
httpsEnabled: pulumi.Input<boolean>;
}
/**
* DynamicProviderInputs represents the inputs that are passed as inputs
* to each function in the implementation of a `pulumi.dynamic.ResourceProvider`.
* The property names in this must match `CustomDomainOptions`.
*/
interface DynamicProviderInputs {
resourceGroupName: string;
profileName: string;
endpointName: string;
customDomainHostName: string;
httpsEnabled: boolean;
}
/**
* DynamicProviderOutputs represents the output type of `create` function in the
* dynamic resource provider.
*/
interface DynamicProviderOutputs extends DynamicProviderInputs, cdnManagement.CdnManagementModels.CustomDomainsCreateResponse {
name: string;
}
class CDNCustomDomainResourceProvider implements pulumi.dynamic.ResourceProvider {
private name: string;
constructor(name: string) {
this.name = name;
}
private async getCDNManagementClient(): Promise<cdnManagement.CdnManagementClient> {
let clientID = azure.config.clientId;
let clientSecret = azure.config.clientSecret;
let tenantID = azure.config.tenantId;
let subscriptionID = azure.config.subscriptionId;
let credentials: ServiceClientCredentials;
// If at least one of them is empty, try looking at the env vars.
if (!clientID || !clientSecret || !tenantID || !subscriptionID) {
await pulumi.log.info("Checking env vars for ARM credentials.", undefined, undefined, true);
clientID = process.env["ARM_CLIENT_ID"];
clientSecret = process.env["ARM_CLIENT_SECRET"];
tenantID = process.env["ARM_TENANT_ID"];
subscriptionID = process.env["ARM_SUBSCRIPTION_ID"];
}
// If they are still empty, try to get the creds from Az CLI.
if (!clientID || !clientSecret || !tenantID || !subscriptionID) {
await pulumi.log.info("Env vars did not contain ARM credentials. Trying Az CLI.", undefined, undefined, true);
// `create()` will throw an error if the Az CLI is not installed or `az login` has never been run.
const cliCredentials = await msRestAzure.AzureCliCredentials.create();
subscriptionID = cliCredentials.subscriptionInfo.id;
credentials = cliCredentials;
await pulumi.log.info("Using credentials from Az CLI.", undefined, undefined, true);
} else {
credentials = await msRestAzure.loginWithServicePrincipalSecret(clientID, clientSecret, tenantID);
}
return new cdnManagement.CdnManagementClient(credentials, subscriptionID);
}
async check(olds: DynamicProviderInputs, news: DynamicProviderInputs): Promise<pulumi.dynamic.CheckResult> {
// If none of the CDN properties changed, then there is nothing to be validated.
if (olds.profileName === news.profileName &&
olds.endpointName === news.endpointName &&
olds.customDomainHostName === news.customDomainHostName) {
return { inputs: news };
}
const failures: pulumi.dynamic.CheckFailure[] = [];
if (!news.endpointName) {
failures.push({
property: "endpointName",
reason: "endpointName is required",
});
}
if (!news.profileName) {
failures.push({
property: "profileName",
reason: "profileName is required",
});
}
if (!news.customDomainHostName) {
failures.push({
property: "customDomainHostName",
reason: "customDomainHostName is required",
});
}
if (failures.length > 0) {
return { failures: failures };
}
return { inputs: news };
}
async diff(id: string, previousOutput: DynamicProviderOutputs, news: DynamicProviderInputs): Promise<pulumi.dynamic.DiffResult> {
const replaces: string[] = [];
let changes = false;
let deleteBeforeReplace = false;
if (previousOutput.customDomainHostName !== news.customDomainHostName || previousOutput.name !== this.name) {
await pulumi.log.warn("Changing the domain name properties will cause downtime.", undefined, undefined, true);
changes = true;
deleteBeforeReplace = true;
if (previousOutput.customDomainHostName !== news.customDomainHostName) {
replaces.push("customDomainHostName");
}
if (previousOutput.name !== this.name) {
replaces.push("customDomainName");
}
}
if (previousOutput.endpointName !== news.endpointName) {
changes = true;
deleteBeforeReplace = true;
replaces.push("endpointName");
}
// HTTPS can be enabled/disabled in-place.
if (previousOutput.httpsEnabled !== news.httpsEnabled) {
changes = true;
replaces.push("httpsEnabled");
}
return {
deleteBeforeReplace: deleteBeforeReplace,
replaces: replaces,
changes: changes,
};
}
async create(inputs: DynamicProviderInputs): Promise<pulumi.dynamic.CreateResult> {
const cdnClient = await this.getCDNManagementClient();
const validationOutput = await cdnClient.endpoints.validateCustomDomain(
inputs.resourceGroupName,
inputs.profileName,
inputs.endpointName,
inputs.customDomainHostName);
if (!validationOutput.customDomainValidated) {
throw new Error(`Validation of custom domain failed with ${validationOutput.reason}`);
}
const result =
await cdnClient.customDomains.create(
inputs.resourceGroupName,
inputs.profileName,
inputs.endpointName,
this.name,
inputs.customDomainHostName);
if (inputs.httpsEnabled) {
await pulumi.log.info("Enabling HTTPS for the custom domain", undefined, undefined, true);
await cdnClient.customDomains.enableCustomHttps(
inputs.resourceGroupName,
inputs.profileName,
inputs.endpointName,
this.name,
{
customDomainHttpsParameters: {
certificateSource: "Cdn",
certificateSourceParameters: {
certificateType: "Dedicated",
},
protocolType: "ServerNameIndication",
},
});
}
const outs: DynamicProviderOutputs = {
...result,
name: this.name,
resourceGroupName: inputs.resourceGroupName,
profileName: inputs.profileName,
endpointName: inputs.endpointName,
customDomainHostName: inputs.customDomainHostName,
httpsEnabled: inputs.httpsEnabled,
};
return { id: result.id!, outs: outs };
}
async read(id: string, props: DynamicProviderOutputs): Promise<pulumi.dynamic.ReadResult> {
const cdnClient = await this.getCDNManagementClient();
const result = await cdnClient.customDomains.get(props.resourceGroupName, props.profileName, props.endpointName, this.name);
return {
id: result.id,
props: { ...props, ...result },
};
}
async delete(id: string, props: DynamicProviderOutputs): Promise<void> {
const cdnClient = await this.getCDNManagementClient();
const result = await cdnClient.customDomains.deleteMethod(props.resourceGroupName, props.profileName, props.endpointName, this.name);
if (result._response.status >= 400) {
throw new Error("Error response received while trying to delete the custom domain.");
}
if (!result.resourceState) {
return;
}
if (result.resourceState !== "Deleting") {
throw new Error(`Provisioning state of the custom domain was expected to be 'Deleting', but was ${result.resourceState}.`);
}
await pulumi.log.info(
"The request to delete was successful. However, it can take a minute or two to fully complete deletion.",
undefined,
undefined,
true);
}
/**
* The only thing that the update method really updates in the custom domain is the HTTPS enablement.
*/
async update(id: string, currentOutputs: DynamicProviderOutputs, newInputs: DynamicProviderInputs): Promise<pulumi.dynamic.UpdateResult> {
const cdnClient = await this.getCDNManagementClient();
if (newInputs.httpsEnabled) {
await cdnClient.customDomains.enableCustomHttps(
newInputs.resourceGroupName,
newInputs.profileName,
newInputs.endpointName,
this.name,
{
customDomainHttpsParameters: {
certificateSource: "Cdn",
certificateSourceParameters: {
certificateType: "Dedicated",
},
protocolType: "ServerNameIndication",
},
});
currentOutputs.httpsEnabled = true;
return { outs: currentOutputs };
}
await cdnClient.customDomains.disableCustomHttps(
newInputs.resourceGroupName,
newInputs.profileName,
newInputs.endpointName,
this.name);
currentOutputs.httpsEnabled = false;
return { outs: currentOutputs };
}
}
/**
* CDNCustomDomainResource is a resource that can be used to create
* custom domains against Azure CDN resources.
* The Azure CDN resource itself must exist in order to create a custom domain for it.
*
* Outputs from the dynamic resource provider must be declared in the dynamic resource itself
* as `public readonly` members with the type `Output<T>`. These are automatically set by the dynamic
* provider engine. The names of these properties must match the names of the properties exactly as
* returned in the outputs of the dynamic resource provider functions.
*/
export class CDNCustomDomainResource extends pulumi.dynamic.Resource {
/**
* These are the same properties that were originally passed as inputs, but available as outputs
* for convenience. The names of these properties must match with `CustomDomainOptions`.
*/
public readonly resourceGroupName: pulumi.Output<string>;
public readonly profileName: pulumi.Output<string>;
public readonly endpointName: pulumi.Output<string>;
public readonly customDomainHostName: pulumi.Output<string>;
public readonly httpsEnabled: pulumi.Output<boolean>;
// The following are properties set by the CDN rest client.
public readonly customHttpsProvisioningState: pulumi.Output<cdnManagement.CdnManagementModels.CustomHttpsProvisioningState>;
public readonly customHttpsProvisioningSubstate: pulumi.Output<cdnManagement.CdnManagementModels.CustomHttpsProvisioningSubstate>;
public readonly provisioningState: pulumi.Output<string>;
public readonly resourceState: pulumi.Output<cdnManagement.CdnManagementModels.CustomDomainResourceState>;
public readonly type: pulumi.Output<string>;
constructor(name: string, args: CustomDomainOptions, opts?: pulumi.CustomResourceOptions) {
super(new CDNCustomDomainResourceProvider(name), `azure:cdn:Endpoint:CustomDomains:${name}`, args, opts);
}
} | the_stack |
import { GraphQLResolveInfo } from 'graphql';
import {
FieldKind,
FieldMap,
FieldNullability,
FieldOptionsFromKind,
InputFieldMap,
InputFieldsFromShape,
InputShapeFromFields,
InterfaceParam,
ListResolveValue,
MaybePromise,
ObjectRef,
OutputShape,
OutputType,
SchemaTypes,
ShapeFromTypeParam,
ShapeWithNullability,
typeBrandKey,
TypeParam,
} from '@giraphql/core';
import { PrismaObjectFieldBuilder } from './field-builder';
export interface PrismaDelegate {
findUnique: (...args: any[]) => Promise<unknown>;
}
type RelationKeys<T> = {
[K in keyof T]: T[K] extends (args: {}) => {
then: (cb: (result: unknown) => unknown) => unknown;
}
? K
: never;
}[keyof T];
export type ModelTypes<Model extends {}> = Model extends {
findUnique: (
options: infer UniqueOptions & {
where?: infer Where | null | undefined;
select?: infer Select | null | undefined;
} & (
| {
include?: infer Include | null | undefined;
}
| {}
),
) => infer Chain & {
then: (cb: (result: infer Shape | null) => unknown) => unknown;
};
}
? PrismaModelTypes & {
Shape: Shape;
Include: unknown extends Include ? never : Include;
Where: Where;
Fields: keyof Select;
ListRelation: ListRelationFields<Include> & string;
Relations: {
[RelationName in RelationKeys<Chain>]: Chain[RelationName] extends (args: {}) => {
then: (cb: (result: infer Relation) => unknown) => unknown;
}
? { Shape: Relation; Types: PrismaModelTypes }
: never;
};
}
: never;
export interface PrismaModelTypes {
Shape: {};
Include: unknown;
Where: {};
Fields: string;
ListRelations: string;
Relations: Record<
string,
{
Shape: unknown;
Types: PrismaModelTypes;
}
>;
}
export type ListRelationFields<T> = {
[K in keyof T]: T[K] extends infer Option
? Option extends { orderBy?: unknown }
? K
: never
: never;
}[keyof T];
export type PrismaObjectFieldsShape<
Types extends SchemaTypes,
Model extends PrismaModelTypes,
NeedsResolve extends boolean,
Shape extends object,
> = (t: PrismaObjectFieldBuilder<Types, Model, NeedsResolve, Shape>) => FieldMap;
export type ShapeFromInclude<Model extends PrismaModelTypes, Include> = {} extends Include
? Model['Shape']
: {
[K in keyof Include &
keyof Model['Relations']]: Model['Relations'][K]['Shape'] extends infer RelationShape
? RelationShape extends (infer ItemShape)[]
? (ItemShape &
(Include[K] extends { include?: infer NestedInclude & object }
? ShapeFromInclude<Model['Relations'][K]['Types'], NestedInclude>
: {}))[]
: RelationShape &
(
| (Include[K] extends { include?: infer NestedInclude & object }
? ShapeFromInclude<Model['Relations'][K]['Types'], NestedInclude>
: {})
| null
)
: never;
};
export type ShapeWithInclude<
Model extends PrismaModelTypes,
Include extends Model['Include'],
> = Model['Shape'] & ([Include] extends [never] ? {} : ShapeFromInclude<Model, Include>);
export type PrismaObjectTypeOptions<
Types extends SchemaTypes,
Model extends PrismaModelTypes,
Interfaces extends InterfaceParam<Types>[],
FindUnique,
Include extends Model['Include'],
Shape extends object,
> = Omit<
| GiraphQLSchemaTypes.ObjectTypeOptions<Types, ObjectRef<Shape>>
| GiraphQLSchemaTypes.ObjectTypeWithInterfaceOptions<Types, ObjectRef<Shape>, Interfaces>,
'fields'
> & {
name?: string;
include?: Include;
fields?: PrismaObjectFieldsShape<Types, Model, FindUnique extends null ? true : false, Shape>;
findUnique: FindUnique & (((parent: Shape, context: Types['Context']) => Model['Where']) | null);
};
export type PrismaNodeOptions<
Types extends SchemaTypes,
Model extends PrismaModelTypes,
Interfaces extends InterfaceParam<Types>[],
Include extends Model['Include'],
Shape extends object,
> = Omit<
| GiraphQLSchemaTypes.ObjectTypeOptions<Types, Shape>
| GiraphQLSchemaTypes.ObjectTypeWithInterfaceOptions<Types, ObjectRef<Shape>, Interfaces>,
'fields' | 'isTypeOf'
> & {
name?: string;
include?: Include;
id: Omit<
FieldOptionsFromKind<
Types,
Shape,
'ID',
false,
{},
'Object',
OutputShape<Types, 'ID'>,
MaybePromise<OutputShape<Types, 'ID'>>
>,
'args' | 'nullable' | 'resolve' | 'type'
> & {
resolve: (parent: Shape, context: Types['Context']) => MaybePromise<OutputShape<Types, 'ID'>>;
};
fields?: PrismaObjectFieldsShape<Types, Model, false, Shape>;
findUnique: (id: string, context: Types['Context']) => Model['Where'];
};
export type QueryForField<
Types extends SchemaTypes,
Args extends InputFieldMap,
Include,
> = Include extends { where?: unknown }
?
| Omit<Include, 'include' | 'select'>
| ((
args: InputShapeFromFields<Args>,
ctx: Types['Context'],
) => Omit<Include, 'include' | 'select'>)
: never;
export type IncludeFromRelation<
Model extends PrismaModelTypes,
Field extends keyof Model['Include'],
> = Model['Include'][Field] extends infer Include
? Include extends {
include?: infer T;
}
? NonNullable<T>
: never
: never;
export type CursorFromRelation<
Model extends PrismaModelTypes,
Field extends Model['ListRelations'],
> = Field extends keyof Model['Include']
? Model['Include'][Field] extends infer Include
? Include extends { cursor?: infer T }
? keyof T
: never
: never
: never;
export type RefForRelation<
Model extends PrismaModelTypes,
Field extends keyof Model['Relations'],
> = Model['Relations'][Field] extends unknown[]
? [ObjectRef<Model['Relations'][Field]>]
: ObjectRef<Model['Relations'][Field]>;
export type RelatedFieldOptions<
Types extends SchemaTypes,
Model extends PrismaModelTypes,
Field extends keyof Model['Relations'],
Nullable extends boolean,
Args extends InputFieldMap,
ResolveReturnShape,
NeedsResolve extends boolean,
Shape,
> = Omit<
GiraphQLSchemaTypes.ObjectFieldOptions<
Types,
Shape,
RefForRelation<Model, Field>,
Nullable,
Args,
ResolveReturnShape
>,
'resolve' | 'type'
> &
(NeedsResolve extends false
? {
resolve?: (
query: { include?: IncludeFromRelation<Model, Field & keyof Model['Include']> },
parent: Shape,
args: InputShapeFromFields<Args>,
context: Types['Context'],
info: GraphQLResolveInfo,
) => MaybePromise<
ShapeWithNullability<Types, Model['Relations'][Field]['Shape'], Nullable>
>;
}
: {
resolve: (
query: { include?: IncludeFromRelation<Model, Field & keyof Model['Include']> },
parent: Shape,
args: InputShapeFromFields<Args>,
context: Types['Context'],
info: GraphQLResolveInfo,
) => MaybePromise<
ShapeWithNullability<Types, Model['Relations'][Field]['Shape'], Nullable>
>;
}) & {
query?: QueryForField<Types, Args, Model['Include'][Field & keyof Model['Include']]>;
};
export type RelationCountOptions<
Types extends SchemaTypes,
Shape,
NeedsResolve extends boolean,
> = Omit<
GiraphQLSchemaTypes.ObjectFieldOptions<Types, Shape, 'Int', false, {}, number>,
'resolve' | 'type'
> &
(NeedsResolve extends false
? {
resolve?: (
parent: Shape,
args: {},
context: Types['Context'],
info: GraphQLResolveInfo,
) => MaybePromise<number>;
}
: {
resolve: (
parent: Shape,
args: {},
context: Types['Context'],
info: GraphQLResolveInfo,
) => MaybePromise<number>;
});
export type PrismaFieldOptions<
Types extends SchemaTypes,
ParentShape,
Type extends keyof Types['PrismaTypes'] | [keyof Types['PrismaTypes']],
Model extends PrismaModelTypes,
Param extends TypeParam<Types>,
Args extends InputFieldMap,
Nullable extends FieldNullability<Param>,
ResolveReturnShape,
Kind extends FieldKind = FieldKind,
> = Omit<
FieldOptionsFromKind<
Types,
ParentShape,
Param,
Nullable,
Args,
Kind,
ParentShape,
ResolveReturnShape
>,
'resolve' | 'type'
> & {
type: Type;
resolve: (
query: {
include?: Model['Include'];
},
parent: ParentShape,
args: InputShapeFromFields<Args>,
context: Types['Context'],
info: GraphQLResolveInfo,
) => ShapeFromTypeParam<Types, Param, Nullable> extends infer Shape
? [Shape] extends [[readonly (infer Item)[] | null | undefined]]
? ListResolveValue<Shape, Item, ResolveReturnShape>
: MaybePromise<Shape>
: never;
};
export type PrismaConnectionFieldOptions<
Types extends SchemaTypes,
ParentShape,
Type extends keyof Types['PrismaTypes'],
Model extends PrismaModelTypes,
Param extends OutputType<Types>,
Nullable extends boolean,
Args extends InputFieldMap,
ResolveReturnShape,
Kind extends FieldKind,
// eslint-disable-next-line @typescript-eslint/sort-type-union-intersection-members
> = Omit<
GiraphQLSchemaTypes.ConnectionFieldOptions<
Types,
ParentShape,
Param,
Nullable,
Args,
ResolveReturnShape
>,
'resolve' | 'type'
> &
Omit<
FieldOptionsFromKind<
Types,
ParentShape,
Param,
Nullable,
Args & InputFieldsFromShape<GiraphQLSchemaTypes.DefaultConnectionArguments>,
Kind,
ParentShape,
ResolveReturnShape
>,
'args' | 'resolve' | 'type'
> & {
type: Type;
cursor: string & keyof Model['Where'];
defaultSize?: number;
maxSize?: number;
resolve: (
query: {
include?: Model['Include'];
cursor?: {};
take: number;
skip: number;
},
parent: ParentShape,
args: GiraphQLSchemaTypes.DefaultConnectionArguments & InputShapeFromFields<Args>,
context: Types['Context'],
info: GraphQLResolveInfo,
) => MaybePromise<Model['Shape'][]>;
};
export type RelatedConnectionOptions<
Types extends SchemaTypes,
Model extends PrismaModelTypes,
Field extends Model['ListRelations'],
Nullable extends boolean,
Args extends InputFieldMap,
NeedsResolve extends boolean,
// eslint-disable-next-line @typescript-eslint/sort-type-union-intersection-members
> = Omit<
GiraphQLSchemaTypes.ObjectFieldOptions<
Types,
Model['Shape'],
ObjectRef<unknown>,
Nullable,
Args,
unknown
>,
'resolve' | 'type'
> &
Omit<
GiraphQLSchemaTypes.ConnectionFieldOptions<
Types,
Model['Shape'],
ObjectRef<unknown>,
Nullable,
Args,
unknown
>,
'resolve' | 'type'
> & {
query?: QueryForField<Types, Args, Model['Include'][Field & keyof Model['Include']]>;
cursor: CursorFromRelation<Model, Field>;
defaultSize?: number;
maxSize?: number;
totalCount?: NeedsResolve extends false ? boolean : false;
} & (NeedsResolve extends false
? {
resolve?: (
query: {
include?: Model['Include'];
cursor?: {};
take: number;
skip: number;
},
parent: Model['Shape'],
args: InputShapeFromFields<Args>,
context: Types['Context'],
info: GraphQLResolveInfo,
) => MaybePromise<Model['Relations'][Field & keyof Model['Relations']]>;
}
: {
resolve: (
query: {
include?: Model['Include'];
cursor?: {};
take: number;
skip: number;
},
parent: Model['Shape'],
args: InputShapeFromFields<Args>,
context: Types['Context'],
info: GraphQLResolveInfo,
) => MaybePromise<Model['Relations'][Field & keyof Model['Relations']]>;
});
export type WithBrand<T> = T & { [typeBrandKey]: string };
export type IncludeMap = Record<string, Record<string, unknown> | boolean>;
export interface IncludeCounts {
current: Record<string, boolean>;
parent: Record<string, boolean>;
}
export type LoaderMappings = Record<
string,
{
field: string;
alias?: string;
mappings: LoaderMappings;
indirectPath: string[];
}[]
>;
export interface SubFieldInclude {
type?: string;
name: string;
}
export interface IndirectLoadMap {
subFields: SubFieldInclude[];
path: string[];
} | the_stack |
import { Direction, Directionality } from '@angular/cdk/bidi';
import { LEFT_ARROW, RIGHT_ARROW } from '@angular/cdk/keycodes';
import {
ConnectedPosition,
FlexibleConnectedPositionStrategy,
Overlay,
OverlayConfig,
OverlayRef,
ScrollStrategy,
} from '@angular/cdk/overlay';
import { normalizePassiveListenerOptions } from '@angular/cdk/platform';
import { TemplatePortal } from '@angular/cdk/portal';
import {
AfterContentInit,
Directive,
ElementRef,
EventEmitter,
Input,
OnDestroy,
OnInit,
Optional,
Output,
Self,
ViewContainerRef,
} from '@angular/core';
import { NxTriggerButton } from '@aposin/ng-aquila/overlay';
import { asapScheduler, fromEvent, merge, Observable, of as observableOf, Subscription } from 'rxjs';
import { delay, filter, map, take, takeUntil } from 'rxjs/operators';
import { throwNxContextMenuMissingError } from './context-menu-errors';
import { NxContextMenuItemComponent } from './context-menu-item.component';
import { NxContextMenuComponent } from './context-menu.component';
/** Default top padding of the menu panel. */
export const MENU_PANEL_TOP_PADDING = 8;
export const MENU_PANEL_OFFSET_Y = 8;
export const MENU_PANEL_OFFSET_X = 8;
export type NxContextMenuScrollStrategy = 'close' | 'reposition';
/** Options for binding a passive event listener. */
const passiveEventListenerOptions = normalizePassiveListenerOptions({
passive: true
});
/**
* This directive is intended to be used in conjunction with an nx-context-menu tag.
* It is responsible for toggling the display of the provided context menu instance.
*/
@Directive({
selector: `[nxContextMenuTriggerFor]`,
host: {
'aria-haspopup': 'true',
'[attr.aria-expanded]': 'contextMenuOpen || null',
'(mousedown)': '_handleMousedown($event)',
'(keydown)': '_handleKeydown($event)',
'(click)': '_handleClick($event)'
},
exportAs: 'nxContextMenuTrigger'
})
export class NxContextMenuTriggerDirective
implements AfterContentInit, OnInit, OnDestroy {
private _portal!: TemplatePortal;
private _overlayRef: OverlayRef | null = null;
private _contextMenuOpen: boolean = false;
private _closingActionsSubscription = Subscription.EMPTY;
private _hoverSubscription = Subscription.EMPTY;
private _contextMenuCloseSubscription = Subscription.EMPTY;
private _dirChangeSubscription = Subscription.EMPTY;
private _documentClickObservable: Observable<MouseEvent>;
private _scrollStrategy: () => ScrollStrategy;
/** References the context menu instance that the trigger is associated with. */
@Input('nxContextMenuTriggerFor')
get contextMenu() {
return this._contextMenu;
}
set contextMenu(contextMenu: NxContextMenuComponent) {
if (contextMenu === this._contextMenu) {
return;
}
this._contextMenu = contextMenu;
this._contextMenuCloseSubscription.unsubscribe();
if (contextMenu) {
this._contextMenuCloseSubscription = contextMenu.closed
.asObservable()
.subscribe(reason => {
this._destroyMenu();
// If a click closed the menu, we should close the entire chain of nested menus.
if ((reason === 'click' || reason === 'tab') && this._parentMenu) {
this._parentMenu.closed.emit(reason);
}
});
}
}
private _contextMenu!: NxContextMenuComponent;
@Input()
set scrollStrategy(value: NxContextMenuScrollStrategy) {
if (value === 'close') {
this._scrollStrategy = this._overlay.scrollStrategies.close;
} else {
this._scrollStrategy = this._overlay.scrollStrategies.reposition;
}
}
/** Whether the context menu is open. */
get contextMenuOpen(): boolean {
return this._contextMenuOpen;
}
/** The text direction of the containing app. */
private get dir(): Direction {
return this._dir?.value === 'rtl' ? 'rtl' : 'ltr';
}
/** Data to be passed along to any lazily-rendered content. */
@Input('nxContextMenuTriggerData') contextMenuData!: Object;
/** Event emitted when the associated context menu is opened. */
@Output() readonly contextMenuOpened: EventEmitter<void> = new EventEmitter<void>();
/** Event emitted when the associated context menu is closed. */
@Output() readonly contextMenuClosed: EventEmitter<void> = new EventEmitter<void>();
constructor(
private _overlay: Overlay,
private _element: ElementRef<HTMLElement>,
private _viewContainerRef: ViewContainerRef,
@Optional() private _parentMenu: NxContextMenuComponent,
@Optional()
@Self()
private _contextMenuItemInstance: NxContextMenuItemComponent,
@Optional() private _dir: Directionality,
@Optional() @Self() private _triggerButton: NxTriggerButton) {
if (_contextMenuItemInstance) {
_contextMenuItemInstance._triggersSubmenu = this.triggersSubmenu();
}
this._scrollStrategy = this._overlay.scrollStrategies.reposition;
this._documentClickObservable = fromEvent<MouseEvent>(document, 'click');
}
ngOnInit() {
this._dirChangeSubscription = this._dir.change.subscribe(() => {
if (this.contextMenuOpen) {
// HINT: closing menu on direction change.
// When user re-opens it, the overlay and menu will be initialized properly, based on new direction.
this.closeContextMenu();
}
});
}
ngAfterContentInit() {
this._checkContextMenu();
this._handleHover();
}
ngOnDestroy() {
if (this._overlayRef) {
this._overlayRef.dispose();
this._overlayRef = null;
}
this._contextMenuCloseSubscription.unsubscribe();
this._closingActionsSubscription.unsubscribe();
this._hoverSubscription.unsubscribe();
this._dirChangeSubscription.unsubscribe();
}
/** Whether the context menu triggers a sub-menu or a top-level one. */
triggersSubmenu(): boolean {
return !!(this._contextMenuItemInstance && this._parentMenu);
}
/** Toggles the context menu between the open and closed states. */
toggleContextMenu(): void {
return this.contextMenuOpen
? this.closeContextMenu()
: this.openContextMenu();
}
/** Opens the context menu. */
openContextMenu(): void {
if (this.contextMenuOpen) {
return;
}
this._checkContextMenu();
const overlayRef = this._createOverlay();
const overlayConfig = overlayRef.getConfig();
this._setPosition(
overlayConfig.positionStrategy as FlexibleConnectedPositionStrategy
);
overlayRef.attach(this._getPortal());
if (this.contextMenu.lazyContent) {
this.contextMenu.lazyContent.attach(this.contextMenuData);
}
this._closingActionsSubscription = this._contextMenuClosingActions().subscribe(
() => this.closeContextMenu()
);
this._initContextMenu();
if (this.contextMenu instanceof NxContextMenuComponent) {
this.contextMenu._startAnimation();
}
if (this._triggerButton) {
this._triggerButton.setTriggerActive();
this.contextMenu.closed.pipe(take(1)).subscribe(() => this._triggerButton.setTriggerInactive());
}
this._waitForClose();
}
/** Closes the context menu. */
closeContextMenu(): void {
this.contextMenu.closed.emit();
}
/** Closes the context menu and does the necessary cleanup. */
private _destroyMenu() {
if (!this._overlayRef || !this.contextMenuOpen) {
return;
}
const contextMenu = this.contextMenu;
this._closingActionsSubscription.unsubscribe();
this._overlayRef.detach();
contextMenu._resetAnimation();
if (contextMenu.lazyContent) {
// Wait for the exit animation to finish before detaching the content.
contextMenu._animationDone
.pipe(
filter(event => event.toState === 'void'),
take(1),
// Interrupt if the content got re-attached.
takeUntil(contextMenu.lazyContent._attached)
)
.subscribe({
next: () =>
contextMenu.lazyContent && contextMenu.lazyContent.detach(),
// No matter whether the content got re-attached, reset the menu.
complete: () => this._resetContextMenu()
});
} else {
this._resetContextMenu();
}
}
/**
* This method sets the context menu state to open and focuses the first item if
* the context menu was opened via the keyboard.
*/
private _initContextMenu(): void {
this.contextMenu.parentMenu = this.triggersSubmenu()
? this._parentMenu
: undefined;
this.contextMenu.direction = this.dir;
this._setIsContextMenuOpen(true);
this.contextMenu.focusFirstItem();
}
/**
* Focuses the context menu trigger.
*/
focus() {
this._element.nativeElement.focus();
}
/**
* This method resets the context menu when it's closed, most importantly restoring
* focus to the context menu trigger if the context menu was opened via the keyboard.
*/
private _resetContextMenu(): void {
this._setIsContextMenuOpen(false);
this.focus();
}
/** Set state rather than toggle to support triggers sharing a menu. */
private _setIsContextMenuOpen(isOpen: boolean): void {
this._contextMenuOpen = isOpen;
this._contextMenuOpen
? this.contextMenuOpened.emit()
: this.contextMenuClosed.emit();
if (this.triggersSubmenu()) {
this._contextMenuItemInstance._highlighted = isOpen;
}
}
/**
* This method checks that a valid instance of NxContextMenuComponent has been passed into
* nxContextMenuTriggerFor. If not, an exception is thrown.
*/
private _checkContextMenu() {
if (!this.contextMenu) {
throwNxContextMenuMissingError();
}
}
/**
* This method creates the overlay from the provided menu's template and saves its
* OverlayRef so that it can be attached to the DOM when openContextMenu is called.
*/
private _createOverlay(): OverlayRef {
if (!this._overlayRef) {
const config = this._getOverlayConfig();
this._overlayRef = this._overlay.create(config);
// Consume the `keydownEvents` in order to prevent them from going to another overlay.
this._overlayRef.keydownEvents().subscribe();
}
return this._overlayRef;
}
/**
* This method builds the configuration object needed to create the overlay, the OverlayState.
* @returns OverlayConfig
*/
private _getOverlayConfig(): OverlayConfig {
return new OverlayConfig({
positionStrategy: this._overlay
.position()
.flexibleConnectedTo(this._element)
.withLockedPosition()
.withFlexibleDimensions(false)
.withTransformOriginOn('.nx-context-menu'),
scrollStrategy: this._scrollStrategy(),
direction: this._dir
});
}
/**
* Sets the appropriate positions on a position strategy
* so the overlay connects with the trigger correctly.
* @param positionStrategy Strategy whose position to update.
*/
private _setPosition(positionStrategy: FlexibleConnectedPositionStrategy) {
let originX = 'start';
let originFallbackX = 'end';
const overlayY = 'top';
const overlayFallbackY = 'bottom';
let originY = overlayY;
let originFallbackY = overlayFallbackY;
let overlayX = originX;
let overlayFallbackX = originFallbackX;
let offsetX = 0;
let offsetY = 0;
if (this.triggersSubmenu()) {
// When the menu is a sub-menu, it should always align itself
// to the edges of the trigger, instead of overlapping it.
overlayFallbackX = originX = 'end';
originFallbackX = overlayX = 'start';
offsetX = this.dir === 'rtl' ? -MENU_PANEL_OFFSET_X : MENU_PANEL_OFFSET_X;
offsetY = -MENU_PANEL_TOP_PADDING;
} else {
offsetY = MENU_PANEL_OFFSET_Y;
originY = 'bottom';
originFallbackY = 'top';
}
positionStrategy.withPositions([
{ originX, originY, overlayX, overlayY, offsetX, offsetY },
{
originX: originFallbackX,
originY,
overlayX: overlayFallbackX,
overlayY,
offsetX: -offsetX,
offsetY
},
{
originX,
originY: originFallbackY,
overlayX,
overlayY: overlayFallbackY,
offsetX,
offsetY: -offsetY
},
{
originX: originFallbackX,
originY: originFallbackY,
overlayX: overlayFallbackX,
overlayY: overlayFallbackY,
offsetX: -offsetX,
offsetY: -offsetY
}
] as ConnectedPosition[]);
}
/**
* Returns a stream that emits whenever an action that should close the context menu occurs. */
private _contextMenuClosingActions() {
let backdrop: Observable<MouseEvent>;
let detachments: Observable<void>;
if (this._overlayRef) {
backdrop = this._overlayRef.backdropClick();
detachments = this._overlayRef.detachments();
}
const parentClose = this._parentMenu
? this._parentMenu.closed
: observableOf();
const hover = this._parentMenu
? this._parentMenu._hovered().pipe(
filter(active => active !== this._contextMenuItemInstance),
filter(() => this._contextMenuOpen)
)
: observableOf();
return merge(backdrop!, parentClose, hover, detachments!);
}
/** Handles mouse presses on the trigger. */
_handleMousedown(event: MouseEvent): void {
// Since right or middle button clicks won't trigger the `click` event,
// we shouldn't consider the menu as opened by mouse in those cases.
// this._openedBy = event.button === 0 ? 'mouse' : null;
// Since clicking on the trigger won't close the menu if it opens a sub-menu,
// we should prevent focus from moving onto it via click to avoid the
// highlight from lingering on the menu item.
if (this.triggersSubmenu()) {
event.preventDefault();
}
}
/** Handles key presses on the trigger. */
_handleKeydown(event: KeyboardEvent): void {
const keyCode = event.keyCode;
if (
this.triggersSubmenu() &&
((keyCode === RIGHT_ARROW && this.dir === 'ltr') ||
(keyCode === LEFT_ARROW && this.dir === 'rtl'))
) {
this.openContextMenu();
}
}
/** Handles click events on the trigger. */
_handleClick(event: MouseEvent): void {
if (this.triggersSubmenu()) {
// Stop event propagation to avoid closing the parent menu.
event.stopPropagation();
this.openContextMenu();
} else {
this.toggleContextMenu();
}
}
/* Subscribes to document clicks to close the context menu on clicks on the background. */
private _waitForClose() {
return this._documentClickObservable
.pipe(
map(event => event.target as Node),
filter((target: Node) => !this._element.nativeElement.contains(target)),
takeUntil(this.contextMenu.closed))
.subscribe(() => {
this.closeContextMenu();
});
}
/** Handles the cases where the user hovers over the trigger. */
private _handleHover() {
// Subscribe to changes in the hovered item in order to toggle the panel.
if (!this.triggersSubmenu()) {
return;
}
this._hoverSubscription = this._parentMenu
._hovered()
// Since we might have multiple competing triggers for the same menu (e.g. a sub-menu
// with different data and triggers), we have to delay it by a tick to ensure that
// it won't be closed immediately after it is opened.
.pipe(
filter(active => active === this._contextMenuItemInstance && !active.disabled),
delay(0, asapScheduler)
)
.subscribe(() => {
// If the same menu is used between multiple triggers, it might still be animating
// while the new trigger tries to re-open it. Wait for the animation to finish
// before doing so. Also interrupt if the user moves to another item.
if (this.contextMenu._isAnimating) {
// We need the `delay(0)` here in order to avoid
// 'changed after checked' errors in some cases.
this.contextMenu._animationDone
.pipe(
take(1),
delay(0, asapScheduler),
takeUntil(this._parentMenu._hovered())
)
.subscribe(() => this.openContextMenu());
} else {
this.openContextMenu();
}
});
}
/** Gets the portal that should be attached to the overlay. */
private _getPortal(): TemplatePortal {
// Note that we can avoid this check by keeping the portal on the context menu panel.
// While it would be cleaner, we'd have to introduce another required method on
// `NxContextMenuPanelComponent`, making it harder to consume.
if (!this._portal ||
this._portal.templateRef !== this.contextMenu.templateRef) {
this._portal = new TemplatePortal(
this.contextMenu.templateRef,
this._viewContainerRef
);
}
return this._portal;
}
} | the_stack |
import { assert } from "chai";
import { TabWatcher } from "../src/background/tabWatcher";
import { browserMock } from "./browserMock";
import { ensureNotNull, createSpy, SpyData, booleanContext } from "./testHelpers";
import { quickBeforeRedirectDetails } from "./quickHelpers";
describe("TabWatcher", () => {
beforeEach(() => browserMock.reset());
let listener: {
onDomainEnter: SpyData,
onDomainLeave: SpyData
};
let watcher: TabWatcher | null = null;
function setupWatcher() {
listener = {
onDomainEnter: createSpy(),
onDomainLeave: createSpy()
};
watcher = new TabWatcher(listener);
}
afterEach(() => {
watcher = null;
});
describe("listener", () => {
it("should be called on tab create and remove", () => {
setupWatcher();
const tabId1 = browserMock.tabs.create("http://www.google.com", "firefox-default");
listener.onDomainEnter.assertCalls([["firefox-default", "www.google.com"]]);
const tabId2 = browserMock.tabs.create("http://www.google.de", "firefox-private");
listener.onDomainEnter.assertCalls([["firefox-private", "www.google.de"]]);
browserMock.tabs.remove(tabId1);
listener.onDomainLeave.assertCalls([["firefox-default", "www.google.com"]]);
browserMock.tabs.remove(tabId2);
listener.onDomainLeave.assertCalls([["firefox-private", "www.google.de"]]);
});
it("should be called only for new domains tab create and remove", () => {
setupWatcher();
const tabId1 = browserMock.tabs.create("http://www.google.com", "firefox-default");
listener.onDomainEnter.assertCalls([["firefox-default", "www.google.com"]]);
const tabId1b = browserMock.tabs.create("http://www.google.com", "firefox-default");
listener.onDomainEnter.assertNoCall();
const tabId2 = browserMock.tabs.create("http://www.google.de", "firefox-private");
listener.onDomainEnter.assertCalls([["firefox-private", "www.google.de"]]);
const tabId2b = browserMock.tabs.create("http://www.google.de", "firefox-private");
listener.onDomainEnter.assertNoCall();
browserMock.tabs.remove(tabId1);
listener.onDomainLeave.assertNoCall();
browserMock.tabs.remove(tabId1b);
listener.onDomainLeave.assertCalls([["firefox-default", "www.google.com"]]);
browserMock.tabs.remove(tabId2);
listener.onDomainLeave.assertNoCall();
browserMock.tabs.remove(tabId2b);
listener.onDomainLeave.assertCalls([["firefox-private", "www.google.de"]]);
});
it("should be called after web navigation commit", () => {
setupWatcher();
const tabId1 = browserMock.tabs.create("http://www.google.com", "firefox-default");
listener.onDomainEnter.assertCalls([["firefox-default", "www.google.com"]]);
browserMock.webNavigation.beforeNavigate(tabId1, "http://www.google.de");
listener.onDomainEnter.assertNoCall();
listener.onDomainLeave.assertNoCall();
browserMock.webNavigation.commit(tabId1, "http://www.google.de");
listener.onDomainEnter.assertCalls([["firefox-default", "www.google.de"]]);
listener.onDomainLeave.assertCalls([["firefox-default", "www.google.com"]]);
});
it("should be called when a navigation follows a navigation", () => {
setupWatcher();
const tabId1 = browserMock.tabs.create("http://www.google.com", "firefox-default");
browserMock.tabs.create("http://www.google.co.uk", "firefox-default");
browserMock.webNavigation.beforeNavigate(tabId1, "http://www.google.de");
browserMock.webNavigation.beforeNavigate(tabId1, "http://www.google.jp");
browserMock.webNavigation.beforeNavigate(tabId1, "http://www.google.co.uk");
browserMock.webRequest.onBeforeRedirect.emit(quickBeforeRedirectDetails("http://www.amazon.jp", "http://www.amazon.com", tabId1));
browserMock.webRequest.onBeforeRedirect.emit(quickBeforeRedirectDetails("http://www.amazon.co.uk", "http://www.amazon.de", tabId1));
listener.onDomainLeave.assertCalls([
["firefox-default", "www.google.de"],
["firefox-default", "www.google.jp"],
["firefox-default", "www.amazon.com"]
]);
});
it("should be called if tabs exist before creation", () => {
browserMock.tabs.create("http://www.google.com", "firefox-default");
browserMock.tabs.create("http://www.google.de", "firefox-private");
setupWatcher();
listener.onDomainEnter.assertCalls([
["firefox-default", "www.google.com"],
["firefox-private", "www.google.de"]
]);
});
it("should call scheduleDeadFramesCheck on tab if it exists", () => {
setupWatcher();
const tabId1 = browserMock.tabs.create("http://www.google.com", "firefox-default");
const scheduleDeadFramesCheck = createSpy();
(watcher as any).tabInfos[tabId1] = { scheduleDeadFramesCheck };
browserMock.webNavigation.complete(tabId1, "");
scheduleDeadFramesCheck.assertCalls([[]]);
});
it("should be called for frames", () => {
setupWatcher();
watcher = ensureNotNull(watcher);
const tabId1 = browserMock.tabs.create("http://www.amazon.com", "firefox-default");
listener.onDomainEnter.assertCalls([["firefox-default", "www.amazon.com"]]);
watcher.prepareNavigation(tabId1, 1, "images.google.com");
watcher.prepareNavigation(tabId1, 1, "www.google.com");
listener.onDomainLeave.assertCalls([["firefox-default", "images.google.com"]]);
listener.onDomainEnter.assertNoCall();
watcher.commitNavigation(tabId1, 1, "www.google.com");
listener.onDomainEnter.assertCalls([["firefox-default", "www.google.com"]]);
watcher.commitNavigation(tabId1, 1, "www.google.com");
listener.onDomainEnter.assertNoCall();
watcher.prepareNavigation(tabId1, 1, "");
listener.onDomainLeave.assertNoCall();
watcher.commitNavigation(tabId1, 1, "");
listener.onDomainLeave.assertCalls([["firefox-default", "www.google.com"]]);
listener.onDomainEnter.assertNoCall();
});
});
describe("cookieStoreContainsDomain", () => {
booleanContext((checkNext) => {
it("should work with multiple cookie stores", () => {
setupWatcher();
watcher = ensureNotNull(watcher);
assert.isFalse(watcher.cookieStoreContainsDomain("firefox-default", "www.google.com", checkNext));
assert.isFalse(watcher.cookieStoreContainsDomain("firefox-private", "www.google.com", checkNext));
const tabId1 = browserMock.tabs.create("http://www.google.com", "firefox-default");
assert.isTrue(watcher.cookieStoreContainsDomain("firefox-default", "www.google.com", checkNext));
assert.isFalse(watcher.cookieStoreContainsDomain("firefox-default", "www.google.de", checkNext));
assert.isFalse(watcher.cookieStoreContainsDomain("firefox-private", "www.google.com", checkNext));
const tabId2 = browserMock.tabs.create("http://www.google.com", "firefox-default");
assert.isTrue(watcher.cookieStoreContainsDomain("firefox-default", "www.google.com", checkNext));
browserMock.tabs.remove(tabId1);
assert.isTrue(watcher.cookieStoreContainsDomain("firefox-default", "www.google.com", checkNext));
browserMock.tabs.remove(tabId2);
assert.isFalse(watcher.cookieStoreContainsDomain("firefox-default", "www.google.com", checkNext));
});
});
it("should work during navigation", () => {
setupWatcher();
watcher = ensureNotNull(watcher);
const tabId1 = browserMock.tabs.create("http://www.google.com", "firefox-default");
browserMock.webNavigation.beforeNavigate(tabId1, "http://www.google.de");
assert.isTrue(watcher.cookieStoreContainsDomain("firefox-default", "www.google.com", false));
assert.isFalse(watcher.cookieStoreContainsDomain("firefox-default", "www.google.de", false));
assert.isTrue(watcher.cookieStoreContainsDomain("firefox-default", "www.google.com", true));
assert.isTrue(watcher.cookieStoreContainsDomain("firefox-default", "www.google.de", true));
browserMock.webNavigation.commit(tabId1, "http://www.google.de");
assert.isFalse(watcher.cookieStoreContainsDomain("firefox-default", "www.google.com", false));
assert.isTrue(watcher.cookieStoreContainsDomain("firefox-default", "www.google.de", false));
assert.isFalse(watcher.cookieStoreContainsDomain("firefox-default", "www.google.com", true));
assert.isTrue(watcher.cookieStoreContainsDomain("firefox-default", "www.google.de", true));
});
it("should work with frames", () => {
setupWatcher();
watcher = ensureNotNull(watcher);
const tabId1 = browserMock.tabs.create("", "firefox-default");
watcher.commitNavigation(tabId1, 1, "www.google.com");
watcher.prepareNavigation(tabId1, 1, "www.google.de");
assert.isTrue(watcher.cookieStoreContainsDomain("firefox-default", "www.google.com", false));
assert.isFalse(watcher.cookieStoreContainsDomain("firefox-default", "www.google.de", false));
assert.isTrue(watcher.cookieStoreContainsDomain("firefox-default", "www.google.com", true));
assert.isTrue(watcher.cookieStoreContainsDomain("firefox-default", "www.google.de", true));
watcher.commitNavigation(tabId1, 1, "www.google.de");
assert.isFalse(watcher.cookieStoreContainsDomain("firefox-default", "www.google.com", false));
assert.isTrue(watcher.cookieStoreContainsDomain("firefox-default", "www.google.de", false));
assert.isFalse(watcher.cookieStoreContainsDomain("firefox-default", "www.google.com", true));
assert.isTrue(watcher.cookieStoreContainsDomain("firefox-default", "www.google.de", true));
});
});
describe("containsDomain", () => {
it("should work with multiple cookie stores", () => {
setupWatcher();
watcher = ensureNotNull(watcher);
assert.isFalse(watcher.containsDomain("www.google.com"));
const tabId1 = browserMock.tabs.create("http://www.google.com", "firefox-default");
assert.isTrue(watcher.containsDomain("www.google.com"));
assert.isFalse(watcher.containsDomain("www.google.de"));
const tabId2 = browserMock.tabs.create("http://www.google.com", "firefox-default");
assert.isTrue(watcher.containsDomain("www.google.com"));
browserMock.tabs.remove(tabId1);
assert.isTrue(watcher.containsDomain("www.google.com"));
browserMock.tabs.remove(tabId2);
assert.isFalse(watcher.containsDomain("www.google.com"));
});
it("should work during navigation", () => {
setupWatcher();
watcher = ensureNotNull(watcher);
const tabId1 = browserMock.tabs.create("http://www.google.com", "firefox-default");
browserMock.webNavigation.beforeNavigate(tabId1, "http://www.google.de");
assert.isTrue(watcher.containsDomain("www.google.com"));
assert.isTrue(watcher.containsDomain("www.google.de"));
browserMock.webNavigation.commit(tabId1, "http://www.google.de");
assert.isFalse(watcher.containsDomain("www.google.com"));
assert.isTrue(watcher.containsDomain("www.google.de"));
});
it("should work with frames", () => {
setupWatcher();
watcher = ensureNotNull(watcher);
const tabId1 = browserMock.tabs.create("", "firefox-default");
watcher.commitNavigation(tabId1, 1, "www.google.com");
watcher.prepareNavigation(tabId1, 1, "www.google.de");
assert.isTrue(watcher.containsDomain("www.google.com"));
assert.isTrue(watcher.containsDomain("www.google.de"));
watcher.commitNavigation(tabId1, 1, "www.google.de");
assert.isFalse(watcher.containsDomain("www.google.com"));
assert.isTrue(watcher.containsDomain("www.google.de"));
});
});
describe("isThirdPartyCookieOnTab", () => {
it("should detect if a cookie domain is third-party for a specified tab", () => {
setupWatcher();
watcher = ensureNotNull(watcher);
assert.isFalse(watcher.isThirdPartyCookieOnTab(1, "google.com"));
assert.isFalse(watcher.isThirdPartyCookieOnTab(1, "www.google.com"));
assert.isFalse(watcher.isThirdPartyCookieOnTab(1, "google.de"));
const tabId1 = browserMock.tabs.create("http://www.google.com", "firefox-default");
assert.isFalse(watcher.isThirdPartyCookieOnTab(tabId1, ".google.com"));
assert.isFalse(watcher.isThirdPartyCookieOnTab(tabId1, "google.com"));
assert.isTrue(watcher.isThirdPartyCookieOnTab(tabId1, "google.de"));
assert.isFalse(watcher.isThirdPartyCookieOnTab(tabId1, "www.google.com"));
// A frame should not be detected as first party
watcher.commitNavigation(tabId1, 1, "google.de");
assert.isTrue(watcher.isThirdPartyCookieOnTab(tabId1, "google.de"));
// during navigation both domains are first party
browserMock.webNavigation.beforeNavigate(tabId1, "http://www.google.de");
assert.isFalse(watcher.isThirdPartyCookieOnTab(tabId1, "www.google.com"));
assert.isFalse(watcher.isThirdPartyCookieOnTab(tabId1, "www.google.de"));
assert.isFalse(watcher.isThirdPartyCookieOnTab(tabId1, ".google.de"));
assert.isFalse(watcher.isThirdPartyCookieOnTab(tabId1, ".www.google.de"));
assert.isFalse(watcher.isThirdPartyCookieOnTab(tabId1, "what.www.google.de"));
assert.isFalse(watcher.isThirdPartyCookieOnTab(tabId1, ".what.www.google.de"));
browserMock.webNavigation.commit(tabId1, "http://www.google.de");
assert.isTrue(watcher.isThirdPartyCookieOnTab(tabId1, "www.google.com"));
assert.isFalse(watcher.isThirdPartyCookieOnTab(tabId1, "www.google.de"));
assert.isFalse(watcher.isThirdPartyCookieOnTab(tabId1, ".google.de"));
assert.isFalse(watcher.isThirdPartyCookieOnTab(tabId1, ".www.google.de"));
assert.isFalse(watcher.isThirdPartyCookieOnTab(tabId1, "what.www.google.de"));
assert.isFalse(watcher.isThirdPartyCookieOnTab(tabId1, ".what.www.google.de"));
// Second level tld
browserMock.webNavigation.beforeNavigate(tabId1, "http://michelgagne.blogspot.de");
browserMock.webNavigation.commit(tabId1, "http://michelgagne.blogspot.de");
assert.isTrue(watcher.isThirdPartyCookieOnTab(tabId1, "www.google.com"));
assert.isFalse(watcher.isThirdPartyCookieOnTab(tabId1, "michelgagne.blogspot.de"));
assert.isFalse(watcher.isThirdPartyCookieOnTab(tabId1, "hello.michelgagne.blogspot.de"));
assert.isTrue(watcher.isThirdPartyCookieOnTab(tabId1, "blogspot.de"));
});
});
describe("cookieStoreContainsDomainFP", () => {
booleanContext((deep) => {
it("should detect if a first party domain is opened in a cookie store and if it is not", () => {
setupWatcher();
const cookieStoreId = "firefox-default";
const cookieStoreId2 = "firefox-alternative";
watcher = ensureNotNull(watcher);
assert.isFalse(watcher.cookieStoreContainsDomainFP(cookieStoreId, "google.com", deep));
assert.isFalse(watcher.cookieStoreContainsDomainFP(cookieStoreId, "google.de", deep));
const tabId1 = browserMock.tabs.create("http://www.google.com", cookieStoreId);
assert.isTrue(watcher.cookieStoreContainsDomainFP(cookieStoreId, "google.com", deep));
assert.isFalse(watcher.cookieStoreContainsDomainFP(cookieStoreId, "google.de", deep));
// in another frame
watcher.commitNavigation(tabId1, 1, "www.amazon.com");
assert.equal(watcher.cookieStoreContainsDomainFP(cookieStoreId, "amazon.com", deep), deep);
assert.isFalse(watcher.cookieStoreContainsDomainFP(cookieStoreId, "amazon.de", deep));
// in another store
assert.isFalse(watcher.cookieStoreContainsDomainFP(cookieStoreId2, "google.com", deep));
assert.isFalse(watcher.cookieStoreContainsDomainFP(cookieStoreId2, "google.de", deep));
// if there is a tab open in the other store
browserMock.tabs.create("http://www.google.de", cookieStoreId2);
assert.isFalse(watcher.cookieStoreContainsDomainFP(cookieStoreId2, "google.com", deep));
assert.isTrue(watcher.cookieStoreContainsDomainFP(cookieStoreId2, "google.de", deep));
// during navigation both domains are first party
browserMock.webNavigation.beforeNavigate(tabId1, "http://www.google.de");
assert.isTrue(watcher.cookieStoreContainsDomainFP(cookieStoreId, "google.com", deep));
assert.isTrue(watcher.cookieStoreContainsDomainFP(cookieStoreId, "google.de", deep));
browserMock.webNavigation.commit(tabId1, "http://www.google.de");
assert.isFalse(watcher.cookieStoreContainsDomainFP(cookieStoreId, "google.com", deep));
assert.isTrue(watcher.cookieStoreContainsDomainFP(cookieStoreId, "google.de", deep));
// in another frame
watcher.commitNavigation(tabId1, 1, "www.amazon.com");
watcher.prepareNavigation(tabId1, 1, "www.amazon.de");
assert.equal(watcher.cookieStoreContainsDomainFP(cookieStoreId, "amazon.com", deep), deep);
assert.equal(watcher.cookieStoreContainsDomainFP(cookieStoreId, "amazon.de", deep), deep);
// Second level
browserMock.webNavigation.beforeNavigate(tabId1, "http://michelgagne.blogspot.de");
browserMock.webNavigation.commit(tabId1, "http://michelgagne.blogspot.de");
assert.isFalse(watcher.cookieStoreContainsDomainFP(cookieStoreId, "google.com", deep));
assert.isTrue(watcher.cookieStoreContainsDomainFP(cookieStoreId, "michelgagne.blogspot.de", deep));
assert.isFalse(watcher.cookieStoreContainsDomainFP(cookieStoreId, "blogspot.de", deep));
});
});
});
}); | the_stack |
import { ethers, upgrades, waffle } from "hardhat";
import { Overrides, Signer, BigNumberish, utils, Wallet } from "ethers";
import chai from "chai";
import { solidity } from "ethereum-waffle";
import "@openzeppelin/test-helpers";
import {
AlpacaToken,
AlpacaToken__factory,
FairLaunch,
FairLaunch__factory,
MockERC20,
MockERC20__factory,
} from "../../../typechain";
import { latestBlockNumber } from "../../helpers/time";
chai.use(solidity);
const { expect } = chai;
describe("FairLaunch", () => {
const ALPACA_REWARD_PER_BLOCK = ethers.utils.parseEther("5000");
const ALPACA_BONUS_LOCK_UP_BPS = 7000;
// Contract as Signer
let alpacaTokenAsAlice: AlpacaToken;
let alpacaTokenAsBob: AlpacaToken;
let alpacaTokenAsDev: AlpacaToken;
let stoken0AsDeployer: MockERC20;
let stoken0AsAlice: MockERC20;
let stoken0AsBob: MockERC20;
let stoken0AsDev: MockERC20;
let stoken1AsDeployer: MockERC20;
let stoken1AsAlice: MockERC20;
let stoken1AsBob: MockERC20;
let stoken1AsDev: MockERC20;
let fairLaunchAsDeployer: FairLaunch;
let fairLaunchAsAlice: FairLaunch;
let fairLaunchAsBob: FairLaunch;
let fairLaunchAsDev: FairLaunch;
// Accounts
let deployer: Signer;
let alice: Signer;
let bob: Signer;
let dev: Signer;
let alpacaToken: AlpacaToken;
let fairLaunch: FairLaunch;
let stakingTokens: MockERC20[];
async function fixture() {
[deployer, alice, bob, dev] = await ethers.getSigners();
// Setup FairLaunch contract
// Deploy ALPACAs
const AlpacaToken = (await ethers.getContractFactory("AlpacaToken", deployer)) as AlpacaToken__factory;
alpacaToken = await AlpacaToken.deploy(37, 43);
await alpacaToken.deployed();
const FairLaunch = (await ethers.getContractFactory("FairLaunch", deployer)) as FairLaunch__factory;
fairLaunch = await FairLaunch.deploy(
alpacaToken.address,
await dev.getAddress(),
ALPACA_REWARD_PER_BLOCK,
0,
ALPACA_BONUS_LOCK_UP_BPS,
0
);
await fairLaunch.deployed();
await alpacaToken.transferOwnership(fairLaunch.address);
stakingTokens = new Array();
for (let i = 0; i < 4; i++) {
const MockERC20 = (await ethers.getContractFactory("MockERC20", deployer)) as MockERC20__factory;
const mockERC20 = (await upgrades.deployProxy(MockERC20, [`STOKEN${i}`, `STOKEN${i}`, 18])) as MockERC20;
await mockERC20.deployed();
stakingTokens.push(mockERC20);
}
alpacaTokenAsAlice = AlpacaToken__factory.connect(alpacaToken.address, alice);
alpacaTokenAsBob = AlpacaToken__factory.connect(alpacaToken.address, bob);
alpacaTokenAsDev = AlpacaToken__factory.connect(alpacaToken.address, dev);
stoken0AsDeployer = MockERC20__factory.connect(stakingTokens[0].address, deployer);
stoken0AsAlice = MockERC20__factory.connect(stakingTokens[0].address, alice);
stoken0AsBob = MockERC20__factory.connect(stakingTokens[0].address, bob);
stoken0AsDev = MockERC20__factory.connect(stakingTokens[0].address, dev);
stoken1AsDeployer = MockERC20__factory.connect(stakingTokens[1].address, deployer);
stoken1AsAlice = MockERC20__factory.connect(stakingTokens[1].address, alice);
stoken1AsBob = MockERC20__factory.connect(stakingTokens[1].address, bob);
stoken1AsDev = MockERC20__factory.connect(stakingTokens[1].address, dev);
fairLaunchAsDeployer = FairLaunch__factory.connect(fairLaunch.address, deployer);
fairLaunchAsAlice = FairLaunch__factory.connect(fairLaunch.address, alice);
fairLaunchAsBob = FairLaunch__factory.connect(fairLaunch.address, bob);
fairLaunchAsDev = FairLaunch__factory.connect(fairLaunch.address, dev);
}
beforeEach(async () => {
await waffle.loadFixture(fixture);
});
context("when adjust params", async () => {
it("should add new pool", async () => {
for (let i = 0; i < stakingTokens.length; i++) {
await fairLaunch.addPool(1, stakingTokens[i].address, false, {
from: await deployer.getAddress(),
} as Overrides);
}
expect(await fairLaunch.poolLength()).to.eq(stakingTokens.length);
});
it("should revert when the stakeToken is already added to the pool", async () => {
for (let i = 0; i < stakingTokens.length; i++) {
await fairLaunch.addPool(1, stakingTokens[i].address, false, {
from: await deployer.getAddress(),
} as Overrides);
}
expect(await fairLaunch.poolLength()).to.eq(stakingTokens.length);
await expect(
fairLaunch.addPool(1, stakingTokens[0].address, false, { from: await deployer.getAddress() } as Overrides)
).to.be.revertedWith("add: stakeToken dup");
});
});
context("when use pool", async () => {
it("should revert when there is nothing to be harvested", async () => {
await fairLaunch.addPool(1, stakingTokens[0].address.toString(), false, {
from: await deployer.getAddress(),
} as Overrides);
await expect(fairLaunch.harvest(0, { from: await deployer.getAddress() } as Overrides)).to.be.revertedWith(
"nothing to harvest"
);
});
it("should revert when that pool is not existed", async () => {
await expect(
fairLaunch.deposit(await deployer.getAddress(), 88, ethers.utils.parseEther("100"), {
from: await deployer.getAddress(),
} as Overrides)
).to.be.reverted;
});
it("should revert when withdrawer is not a funder", async () => {
// 1. Mint STOKEN0 for staking
await stoken0AsDeployer.mint(await alice.getAddress(), ethers.utils.parseEther("400"));
// 2. Add STOKEN0 to the fairLaunch pool
await fairLaunchAsDeployer.addPool(1, stakingTokens[0].address, false);
// 3. Deposit STOKEN0 to the STOKEN0 pool
await stoken0AsAlice.approve(fairLaunch.address, ethers.utils.parseEther("100"));
await fairLaunchAsAlice.deposit(await bob.getAddress(), 0, ethers.utils.parseEther("100"));
// 4. Bob try to withdraw from the pool
// Bob shuoldn't do that, he can get yield but not the underlaying
await expect(fairLaunchAsBob.withdrawAll(await bob.getAddress(), 0)).to.be.revertedWith("only funder");
});
it("should revert when 2 accounts try to fund the same user", async () => {
// 1. Mint STOKEN0 for staking
await stoken0AsDeployer.mint(await alice.getAddress(), ethers.utils.parseEther("400"));
await stoken0AsDeployer.mint(await dev.getAddress(), ethers.utils.parseEther("100"));
// 2. Add STOKEN0 to the fairLaunch pool
await fairLaunchAsDeployer.addPool(1, stakingTokens[0].address, false);
// 3. Deposit STOKEN0 to the STOKEN0 pool
await stoken0AsAlice.approve(fairLaunch.address, ethers.utils.parseEther("100"));
await fairLaunchAsAlice.deposit(await bob.getAddress(), 0, ethers.utils.parseEther("100"));
// 4. Dev try to deposit to the pool on the bahalf of Bob
// Dev should get revert tx as this will fuck up the tracking
await stoken0AsDev.approve(fairLaunch.address, ethers.utils.parseEther("100"));
await expect(fairLaunchAsDev.deposit(await bob.getAddress(), 0, ethers.utils.parseEther("1"))).to.be.revertedWith(
"bad sof"
);
});
it("should harvest yield from the position opened by funder", async () => {
// 1. Mint STOKEN0 for staking
await stoken0AsDeployer.mint(await alice.getAddress(), ethers.utils.parseEther("400"));
// 2. Add STOKEN0 to the fairLaunch pool
await fairLaunchAsDeployer.addPool(1, stakingTokens[0].address, false);
// 3. Deposit STOKEN0 to the STOKEN0 pool
await stoken0AsAlice.approve(fairLaunch.address, ethers.utils.parseEther("100"));
await fairLaunchAsAlice.deposit(await bob.getAddress(), 0, ethers.utils.parseEther("100"));
// 4. Move 1 Block so there is some pending
await fairLaunchAsDeployer.massUpdatePools();
expect(await fairLaunchAsBob.pendingAlpaca(0, await bob.getAddress())).to.be.eq(ethers.utils.parseEther("5000"));
// 5. Harvest all yield
await fairLaunchAsBob.harvest(0);
expect(await alpacaToken.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("10000"));
});
it("should distribute rewards according to the alloc point", async () => {
// 1. Mint STOKEN0 and STOKEN1 for staking
await stoken0AsDeployer.mint(await alice.getAddress(), ethers.utils.parseEther("100"));
await stoken1AsDeployer.mint(await alice.getAddress(), ethers.utils.parseEther("50"));
// 2. Add STOKEN0 to the fairLaunch pool
await fairLaunchAsDeployer.addPool(50, stakingTokens[0].address, false);
await fairLaunchAsDeployer.addPool(50, stakingTokens[1].address, false);
// 3. Deposit STOKEN0 to the STOKEN0 pool
await stoken0AsAlice.approve(fairLaunch.address, ethers.utils.parseEther("100"));
await fairLaunchAsAlice.deposit(await alice.getAddress(), 0, ethers.utils.parseEther("100"));
// 4. Deposit STOKEN1 to the STOKEN1 pool
await stoken1AsAlice.approve(fairLaunch.address, ethers.utils.parseEther("50"));
await fairLaunchAsAlice.deposit(await alice.getAddress(), 1, ethers.utils.parseEther("50"));
// 4. Move 1 Block so there is some pending
await fairLaunchAsDeployer.massUpdatePools();
expect(await fairLaunch.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("7500"));
expect(await fairLaunch.pendingAlpaca(1, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("2500"));
// 5. Harvest all yield
await fairLaunchAsAlice.harvest(0);
await fairLaunchAsAlice.harvest(1);
expect(await alpacaToken.balanceOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("17500"));
});
it("should work", async () => {
// 1. Mint STOKEN0 for staking
await stoken0AsDeployer.mint(await alice.getAddress(), ethers.utils.parseEther("400"));
await stoken0AsDeployer.mint(await bob.getAddress(), ethers.utils.parseEther("100"));
// 2. Add STOKEN0 to the fairLaunch pool
await fairLaunchAsDeployer.addPool(1, stakingTokens[0].address, false);
// 3. Deposit STOKEN0 to the STOKEN0 pool
await stoken0AsAlice.approve(fairLaunch.address, ethers.utils.parseEther("100"));
await fairLaunchAsAlice.deposit(await alice.getAddress(), 0, ethers.utils.parseEther("100"));
// 4. Trigger random update pool to make 1 more block mine
await fairLaunchAsAlice.massUpdatePools();
// 5. Check pendingAlpaca for Alice
expect(await fairLaunch.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("5000"));
// 6. Trigger random update pool to make 1 more block mine
await fairLaunchAsAlice.massUpdatePools();
// 7. Check pendingAlpaca for Alice
expect(await fairLaunch.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("10000"));
// 8. Alice should get 15,000 ALPACAs when she harvest
// also check that dev got his tax
await fairLaunchAsAlice.harvest(0);
expect(await alpacaToken.balanceOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("15000"));
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("1500"));
// 9. Bob come in and join the party
// 2 blocks are mined here, hence Alice should get 10,000 ALPACAs more
await stoken0AsBob.approve(fairLaunch.address, ethers.utils.parseEther("100"));
await fairLaunchAsBob.deposit(await bob.getAddress(), 0, ethers.utils.parseEther("100"));
expect(await fairLaunch.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("10000"));
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("2500"));
// 10. Trigger random update pool to make 1 more block mine
await fairLaunch.massUpdatePools();
// 11. Check pendingAlpaca
// Reward per Block must now share amoung Bob and Alice (50-50)
// Alice should has 12,500 ALPACAs (10,000 + 2,500)
// Bob should has 2,500 ALPACAs
// Dev get 10% tax per block (5,000*0.1 = 500/block)
expect(await fairLaunch.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("12500"));
expect(await fairLaunch.pendingAlpaca(0, await bob.getAddress())).to.be.eq(ethers.utils.parseEther("2500"));
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("3000"));
// 12. Trigger random update pool to make 1 more block mine
await fairLaunchAsAlice.massUpdatePools();
// 13. Check pendingAlpaca
// Reward per Block must now share amoung Bob and Alice (50-50)
// Alice should has 15,000 ALPACAs (12,500 + 2,500)
// Bob should has 5,000 ALPACAs (2,500 + 2,500)
// Dev get 10% tax per block (5,000*0.1 = 500/block)
expect(await fairLaunch.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("15000"));
expect(await fairLaunch.pendingAlpaca(0, await bob.getAddress())).to.be.eq(ethers.utils.parseEther("5000"));
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("3500"));
// 14. Bob harvest his yield
// Reward per Block is till (50-50) as Bob is not leaving the pool yet
// Alice should has 17,500 ALPACAs (15,000 + 2,500) in pending
// Bob should has 7,500 ALPACAs (5,000 + 2,500) in his account as he harvest it
// Dev get 10% tax per block (5,000*0.1 = 500/block)
await fairLaunchAsBob.harvest(0);
expect(await fairLaunch.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("17500"));
expect(await fairLaunch.pendingAlpaca(0, await bob.getAddress())).to.be.eq(ethers.utils.parseEther("0"));
expect(await alpacaToken.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("7500"));
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("4000"));
// 15. Alice wants more ALPACAs so she deposit 300 STOKEN0 more
await stoken0AsAlice.approve(fairLaunch.address, ethers.utils.parseEther("300"));
await fairLaunchAsAlice.deposit(await alice.getAddress(), 0, ethers.utils.parseEther("300"));
// Alice deposit to the same pool as she already has some STOKEN0 in it
// Hence, Alice will get auto-harvest
// Alice should get 22,500 ALPACAs (17,500 + 2,500 [B1] + 2,500 [B2]) back to her account
// Hence, Alice should has 15,000 + 22,500 = 37,500 ALPACAs in her account and 0 pending as she harvested
// Bob should has (2,500 [B1] + 2,500 [B2]) = 5,000 ALPACAs in pending
expect(await fairLaunch.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("0"));
expect(await fairLaunch.pendingAlpaca(0, await bob.getAddress())).to.be.eq(ethers.utils.parseEther("5000"));
expect(await alpacaToken.balanceOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("37500"));
expect(await alpacaToken.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("7500"));
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("5000"));
// 16. Trigger random update pool to make 1 more block mine
await fairLaunchAsAlice.massUpdatePools();
// 1 more block is mined, now Alice shold get 80% and Bob should get 20% of rewards
// How many STOKEN0 needed to make Alice get 80%: find n from 100n/(100n+100) = 0.8
// Hence, Alice should get 0 + 4,000 = 4,000 ALPACAs in pending
// Bob should get 5,000 + 1,000 = 6,000 ALPACAs in pending
expect(await fairLaunch.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("4000"));
expect(await fairLaunch.pendingAlpaca(0, await bob.getAddress())).to.be.eq(ethers.utils.parseEther("6000"));
expect(await alpacaToken.balanceOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("37500"));
expect(await alpacaToken.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("7500"));
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("5500"));
// 17. Ayyooo people vote for the bonus period, 1 block executed
// bonus will start to accu. on the next box
await fairLaunchAsDeployer.setBonus(10, (await ethers.provider.getBlockNumber()) + 5, 7000);
// Make block mined 7 times to make it pass bonusEndBlock
for (let i = 0; i < 7; i++) {
await stoken1AsDeployer.mint(await deployer.getAddress(), ethers.utils.parseEther("1"));
}
// Trigger this to mint token for dev, 1 more block mined
await fairLaunchAsDeployer.massUpdatePools();
// Expect pending balances
// Each block during bonus period Alice will get 40,000 ALPACAs in pending
// Bob will get 10,000 ALPACAs in pending
// Total blocks mined = 9 blocks counted from setBonus executed
// However, bonus will start to accu. on the setBonus's block + 1
// Hence, 5 blocks during bonus period and 3 blocks are out of bonus period
// Hence Alice will get 4,000 + (40,000 * 5) + (4,000 * 4) = 220,000 ALPACAs in pending
// Bob will get 6,000 + (10,000*5)+(1,000*4) = 60,000 ALPACAs in pending
// Dev will get 5,500 + (5,000*5*0.3) + (500*4) = 15,000 ALPACAs in account
// Dev will get 0 + (5,000*5*0.7) = 17,500 ALPACAs locked in AlpacaToken contract
expect(await fairLaunch.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("220000"));
expect(await fairLaunch.pendingAlpaca(0, await bob.getAddress())).to.be.eq(ethers.utils.parseEther("60000"));
expect(await alpacaToken.balanceOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("37500"));
expect(await alpacaToken.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("7500"));
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("15000"));
expect(await alpacaToken.lockOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("17500"));
// 18. Alice harvest her pending ALPACAs
// Alice Total Pending is 220,000 ALPACAs
// 50,000 * 5 = 200,000 ALPACAs are from bonus period
// Hence subject to lock 200,000 * 0.7 = 140,000 will be locked
// 200,000 - 140,000 = 60,000 ALPACAs from bonus period should be free float
// Alice should get 37,500 + (220,000-140,000) + 4,000 = 121,500 ALPACAs
// 1 Block is mined, hence Bob pending must be increased
// Bob should get 60,000 + 1,000 = 61,000 ALPACAs
// Dev should get 500 ALPACAs in the account
await fairLaunchAsAlice.harvest(0);
expect(await fairLaunch.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("0"));
expect(await fairLaunch.pendingAlpaca(0, await bob.getAddress())).to.be.eq(ethers.utils.parseEther("61000"));
expect(await alpacaToken.lockOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("140000"));
expect(await alpacaToken.lockOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("0"));
expect(await alpacaToken.balanceOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("121500"));
expect(await alpacaToken.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("7500"));
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("15500"));
expect(await alpacaToken.lockOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("17500"));
// 19. Bob harvest his pending ALPACAs
// Bob Total Pending is 61,000 ALPACAs
// 10,000 * 5 = 50,000 ALPACAs are from bonus period
// Hence subject to lock 50,000 * 0.7 = 35,000 will be locked
// 50,000 - 35,000 = 15,000 ALPACAs from bonus period should be free float
// Bob should get 7,500 + (61,000-35,000) + 1,000 = 34,500 ALPACAs
// 1 Block is mined, hence Bob pending must be increased
// Alice should get 0 + 4,000 = 4,000 ALPACAs in pending
// Dev should get 500 ALPACAs in the account
await fairLaunchAsBob.harvest(0);
expect(await fairLaunch.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("4000"));
expect(await fairLaunch.pendingAlpaca(0, await bob.getAddress())).to.be.eq(ethers.utils.parseEther("0"));
expect(await alpacaToken.lockOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("140000"));
expect(await alpacaToken.lockOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("35000"));
expect(await alpacaToken.balanceOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("121500"));
expect(await alpacaToken.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("34500"));
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("16000"));
expect(await alpacaToken.lockOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("17500"));
// 20. Alice is happy. Now she want to leave the pool.
// 2 Blocks are mined
// Alice pending must be 0 as she harvest and leave the pool.
// Alice should get 121,500 + 4,000 + 4,000 = 129,500 ALPACAs
// Bob pending should be 1,000 ALPACAs
// Dev get another 500 ALPACAs
await fairLaunchAsAlice.withdrawAll(await alice.getAddress(), 0);
expect(await fairLaunch.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("0"));
expect(await fairLaunch.pendingAlpaca(0, await bob.getAddress())).to.be.eq(ethers.utils.parseEther("1000"));
expect(await alpacaToken.lockOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("140000"));
expect(await alpacaToken.lockOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("35000"));
expect(await stakingTokens[0].balanceOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("400"));
expect(await stakingTokens[0].balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("0"));
expect(await alpacaToken.balanceOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("129500"));
expect(await alpacaToken.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("34500"));
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("16500"));
expect(await alpacaToken.lockOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("17500"));
// 21. Bob is happy. Now he want to leave the pool.
// 1 Blocks is mined
// Alice should not move as she left the pool already
// Bob pending should be 0 ALPACAs
// Bob should has 34,500 + 1,000 + 5,000 = 40,500 ALPACAs in his account
// Dev get another 500 ALPACAs
await fairLaunchAsBob.withdrawAll(await bob.getAddress(), 0);
expect(await fairLaunch.pendingAlpaca(0, await alice.getAddress())).to.be.eq(ethers.utils.parseEther("0"));
expect(await fairLaunch.pendingAlpaca(0, await bob.getAddress())).to.be.eq(ethers.utils.parseEther("0"));
expect(await alpacaToken.lockOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("140000"));
expect(await alpacaToken.lockOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("35000"));
expect(await stakingTokens[0].balanceOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("400"));
expect(await stakingTokens[0].balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("100"));
expect(await alpacaToken.balanceOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("129500"));
expect(await alpacaToken.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("40500"));
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("17000"));
expect(await alpacaToken.lockOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("17500"));
// Oh hello! The locked ALPACAs will be released on the next block
// so let's move four block to get all tokens unlocked
for (let i = 0; i < 5; i++) {
// random contract call to make block mined
await stoken0AsDeployer.mint(await deployer.getAddress(), ethers.utils.parseEther("1"));
}
expect(await alpacaToken.canUnlockAmount(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("140000"));
expect(await alpacaToken.canUnlockAmount(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("35000"));
expect(await alpacaToken.canUnlockAmount(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("17500"));
await alpacaTokenAsAlice.unlock();
expect(await alpacaToken.balanceOf(await alice.getAddress())).to.be.eq(ethers.utils.parseEther("269500"));
await alpacaTokenAsBob.unlock();
expect(await alpacaToken.balanceOf(await bob.getAddress())).to.be.eq(ethers.utils.parseEther("75500"));
await alpacaTokenAsDev.unlock();
expect(await alpacaToken.balanceOf(await dev.getAddress())).to.be.eq(ethers.utils.parseEther("34500"));
});
});
}); | the_stack |
import { Trans } from "@lingui/macro";
import { Tooltip } from "reactjs-components";
import * as React from "react";
import { MountService } from "foundation-ui";
import {
Flex,
TextInput,
FormSectionBody,
FieldGroup,
ToggleBox,
SelectInput,
} from "@dcos/ui-kit";
import AddButton from "#SRC/js/components/form/AddButton";
import FieldError from "#SRC/js/components/form/FieldError";
import FieldInput from "#SRC/js/components/form/FieldInput";
import FieldLabel from "#SRC/js/components/form/FieldLabel";
import FieldSelect from "#SRC/js/components/form/FieldSelect";
import FormGroup from "#SRC/js/components/form/FormGroup";
import FormGroupContainer from "#SRC/js/components/form/FormGroupContainer";
import FormGroupHeading from "#SRC/js/components/form/FormGroupHeading";
import FormGroupHeadingContent from "#SRC/js/components/form/FormGroupHeadingContent";
import FormRow from "#SRC/js/components/form/FormRow";
import KVForm from "#SRC/js/components/form/KVForm";
import InfoTooltipIcon from "#SRC/js/components/form/InfoTooltipIcon";
import MetadataStore from "#SRC/js/stores/MetadataStore";
import dcosVersion$ from "#SRC/js/stores/dcos-version";
import ConfigStore from "#SRC/js/stores/ConfigStore";
import ContainerConstants from "../../constants/ContainerConstants";
import { FormReducer as volumes } from "../../reducers/serviceForm/FormReducers/Volumes";
import { VolumeSelect } from "../VolumeSelect";
const { DOCKER } = ContainerConstants.type;
const heading = <FormGroupHeadingContent primary={true} />;
const onInput = (fn) => (e) => {
e.preventDefault();
e.stopPropagation();
fn(e?.currentTarget?.value);
};
export default class VolumesFormSection extends React.Component<{
data: Record<string, unknown>;
errors: Record<string, unknown>;
onAddItem: (e: any) => void;
onChange: (e: any) => void;
onRemoveItem: (e: any) => void;
}> {
static configReducers = { volumes };
state = { showCSI: false };
componentDidMount() {
dcosVersion$.subscribe(({ hasCSI }) => {
this.setState({ showCSI: hasCSI });
});
}
getPersistentVolumeConfig(volume, key) {
const volumeErrors = this.props.errors?.container?.volumes?.[key]?.volumes;
const sizeError = volumeErrors?.persistent?.size;
const containerPathError = volumeErrors?.containerPath;
return (
<FormRow>
<FormGroup className="column-4" showError={Boolean(containerPathError)}>
<FieldLabel>
<FormGroupHeading>
<Trans render={heading}>Container Path</Trans>
<FormGroupHeadingContent>
<Tooltip
content={containerPathTooltip}
interactive={true}
maxWidth={300}
wrapText={true}
>
<InfoTooltipIcon />
</Tooltip>
</FormGroupHeadingContent>
</FormGroupHeading>
</FieldLabel>
<FieldInput
name={`volumes.${key}.containerPath`}
type="text"
value={volume.containerPath}
autoFocus={Boolean(containerPathError)}
/>
<FieldError>{containerPathError}</FieldError>
</FormGroup>
<FormGroup className="column-2" showError={Boolean(sizeError)}>
<FieldLabel className="text-no-transform">
<FormGroupHeading>
<Trans render={heading}>Size (MiB)</Trans>
</FormGroupHeading>
</FieldLabel>
<FieldInput
name={`volumes.${key}.size`}
type="number"
value={volume.size}
/>
<FieldError>{sizeError}</FieldError>
</FormGroup>
</FormRow>
);
}
getHostVolumeConfig(volume, key) {
const errors = this.props.errors?.container?.volumes?.[key];
const hostPathError = errors?.hostPath;
const containerPathError = errors?.containerPath;
const tooltipContent = (
<Trans>
If you are using the Mesos containerizer, this must be a single-level{" "}
path relative to the container.{" "}
<a
href={MetadataStore.buildDocsURI("/storage/external-storage/")}
target="_blank"
>
More information
</a>
.
</Trans>
);
return (
<FormRow>
<FormGroup className="column-4" showError={Boolean(hostPathError)}>
<FieldLabel>
<FormGroupHeading>
<Trans render={heading}>Host Path</Trans>
</FormGroupHeading>
</FieldLabel>
<FieldInput
name={`volumes.${key}.hostPath`}
value={volume.hostPath}
/>
<FieldError>{hostPathError}</FieldError>
</FormGroup>
<FormGroup className="column-4" showError={Boolean(containerPathError)}>
<FieldLabel>
<FormGroupHeading>
<Trans render={heading}>Container Path</Trans>
<FormGroupHeadingContent>
<Tooltip
content={tooltipContent}
interactive={true}
maxWidth={300}
wrapText={true}
>
<InfoTooltipIcon />
</Tooltip>
</FormGroupHeadingContent>
</FormGroupHeading>
</FieldLabel>
<FieldInput
name={`volumes.${key}.containerPath`}
type="text"
value={volume.containerPath}
autoFocus={Boolean(containerPathError)}
/>
<FieldError>{containerPathError}</FieldError>
</FormGroup>
<FormGroup className="column-4" showError={Boolean(errors?.mode)}>
<FieldLabel>
<FormGroupHeading>
<Trans render={heading}>Mode</Trans>
</FormGroupHeading>
</FieldLabel>
<FieldSelect name={`volumes.${key}.mode`} value={volume.mode}>
<Trans render={<option value="RW" />}>Read and Write</Trans>\
<Trans render={<option value="RO" />}>Read Only</Trans>
</FieldSelect>
</FormGroup>
</FormRow>
);
}
getExternalCSIVolumeConfig(volume, key) {
const updateVolume = (v) => {
this.props.onChange({
target: { name: `volumes.${key}`, value: { ...volume, ...v } },
});
};
const updateExternal = (value) =>
updateVolume({ externalCSI: { ...volume.externalCSI, ...value } });
const options = volume?.externalCSI?.options || {};
const updateOptions = (value) =>
updateExternal({ options: { ...options, ...value } });
const updateCapability = (value) =>
updateOptions({ capability: { ...options.capability, ...value } });
// yes, inline styling is not a good practice. but time is short and we want to use ui-kit-components here!
return (
<div style={{ marginTop: "16px" }}>
<FormSectionBody>
<FieldGroup direction="row">
<TextInput
inputLabel="Name"
value={volume.externalCSI.name}
tooltipContent={<Trans>A unique identifier for the volume</Trans>}
onChange={onInput((x) => updateExternal({ name: x }))}
/>
<TextInput
inputLabel="Plugin Name"
value={options?.pluginName}
required={true}
tooltipContent={<Trans>The name of the CSI plugin</Trans>}
onChange={onInput((x) => updateOptions({ pluginName: x }))}
/>
</FieldGroup>
<TextInput
inputLabel="Container Path"
value={volume.containerPath}
tooltipContent={containerPathTooltip}
onChange={onInput((x) => updateVolume({ containerPath: x }))}
/>
<SelectInput
options={accessModes}
inputLabel="Access Mode"
value={options?.capability?.accessMode}
onChange={onInput((x) => updateCapability({ accessMode: x }))}
/>
<Flex direction="column">
<FieldLabel>
<FormGroupHeading>
<Trans id="Access Type" />
</FormGroupHeading>
</FieldLabel>
<FieldGroup direction="row">
<ToggleBox
id="block"
isActive={options?.capability?.accessType === "block"}
onChange={() =>
updateCapability({ accessType: "block", fsType: undefined })
}
>
Block
</ToggleBox>
<ToggleBox
id="mount"
isActive={options?.capability?.accessType === "mount"}
onChange={() => updateCapability({ accessType: "mount" })}
>
Mount
</ToggleBox>
</FieldGroup>
</Flex>
{options?.capability?.accessType === "mount" ? (
<div>
<TextInput
inputLabel="Filesystem Type"
placeholder="xfs"
value={options?.capability?.fsType}
onChange={onInput((x) => updateCapability({ fsType: x }))}
/>
</div>
) : null}
<KVForm
data={options?.nodeStageSecret || {}}
onChange={(x) => updateOptions({ nodeStageSecret: x })}
label={<Trans id="Node Stage Secret" />}
/>
<KVForm
data={options?.nodePublishSecret || {}}
onChange={(x) => updateOptions({ nodePublishSecret: x })}
label={<Trans id="Node Publish Secret" />}
/>
<KVForm
data={options?.volumeContext || {}}
onChange={(x) => updateOptions({ volumeContext: x })}
label={<Trans id="Volume Context" />}
/>
</FormSectionBody>
</div>
);
}
getExternalVolumeConfig(volume, key) {
const volumeErrors = this.props.errors?.container?.volumes?.[key]?.volume;
const nameError = volumeErrors?.external?.name;
const sizeError = volumeErrors?.external?.size;
const containerPathError = volumeErrors?.containerPath;
const tooltipContent = (
<Trans>
Docker Runtime only supports the default size for implicit volumes,
please select Universal Container Runtime (UCR) if you want to modify
the size.
</Trans>
);
let sizeField = (
<Tooltip
content={tooltipContent}
width={300}
wrapperClassName="tooltip-wrapper tooltip-block-wrapper text-align-center"
wrapText={true}
>
<FieldInput
name={`volumes.${key}.size`}
type="number"
disabled={true}
value={""}
/>
</Tooltip>
);
if (this.props.data?.container?.type !== DOCKER) {
sizeField = (
<FieldInput
name={`volumes.${key}.size`}
type="number"
value={volume.size}
autoFocus={Boolean(sizeError)}
/>
);
}
return (
<FormRow>
<FormGroup className="column-4" showError={Boolean(nameError)}>
<FieldLabel>
<FormGroupHeading>
<Trans render={heading} id="Name" />
</FormGroupHeading>
</FieldLabel>
<FieldInput
name={`volumes.${key}.name`}
type="text"
value={volume.name}
/>
<FieldError>{nameError}</FieldError>
</FormGroup>
<FormGroup className="column-4" showError={Boolean(containerPathError)}>
<FieldLabel>
<FormGroupHeading>
<Trans render={heading} id="Container Path" />
</FormGroupHeading>
</FieldLabel>
<FieldInput
name={`volumes.${key}.containerPath`}
type="text"
value={volume.containerPath}
autoFocus={Boolean(containerPathError)}
/>
<FieldError>{containerPathError}</FieldError>
</FormGroup>
<FormGroup className="column-2" showError={Boolean(sizeError)}>
<FieldLabel className="text-no-transform">
<FormGroupHeading>
<Trans render={heading} id="Size (GiB)" />
</FormGroupHeading>
</FieldLabel>
{sizeField}
<FieldError>{sizeError}</FieldError>
</FormGroup>
</FormRow>
);
}
getUnknownVolumeConfig(volume, index) {
const errs = this.props.errors?.container?.volumes?.[index];
const sizeError = errs?.persistent?.size;
const profileNameError = errs?.persistent?.profileName;
const containerPathError = errs?.containerPath;
return (
<div>
<FormRow>
<FormGroup className="column-4" showError={Boolean(profileNameError)}>
<FieldLabel>
<FormGroupHeading>
<Trans render={<FormGroupHeadingContent primary={true} />}>
Profile Name
</Trans>
</FormGroupHeading>
</FieldLabel>
<FieldInput
name={`volumes.${index}.profileName`}
type="text"
value={volume.profileName}
/>
<FieldError>{containerPathError}</FieldError>
</FormGroup>
<FormGroup
className="column-4"
showError={Boolean(containerPathError)}
>
<FieldLabel>
<FormGroupHeading>
<Trans render={<FormGroupHeadingContent primary={true} />}>
Container Path
</Trans>
</FormGroupHeading>
</FieldLabel>
<FieldInput
name={`volumes.${index}.containerPath`}
type="text"
value={volume.containerPath}
/>
<FieldError>{containerPathError}</FieldError>
</FormGroup>
<FormGroup className="column-2" showError={Boolean(sizeError)}>
<FieldLabel className="text-no-transform">
<FormGroupHeading>
<Trans render={<FormGroupHeadingContent primary={true} />}>
Size (MiB)
</Trans>
</FormGroupHeading>
</FieldLabel>
<FieldInput
name={`volumes.${index}.size`}
type="number"
value={volume.size}
/>
<FieldError>{sizeError}</FieldError>
</FormGroup>
</FormRow>
</div>
);
}
getVolumesLines(data) {
return data.map((volume, key) => {
const typeError = this.props.errors?.container?.volumes?.[key]?.type;
const onRemove = () =>
void this.props.onRemoveItem({ value: key, path: "volumes" });
const { plugins } = ConfigStore.get("config").uiConfiguration;
// we used to set DSS visibility via our uiConfig. maybe it makes sense to change that to whether we're on enterprise or not.
const dss = plugins.dss?.enabled ? [] : ["DSS"];
const csi = this.state.showCSI ? [] : ["EXTERNAL_CSI"];
const exclude = ["EPHEMERAL", ...dss, ...csi];
return (
<FormGroupContainer key={key} onRemove={onRemove}>
<FormGroup showError={Boolean(typeError)}>
<FieldLabel>
<FormGroupHeading>
<Trans render={heading}>Volume Type</Trans>
</FormGroupHeading>
</FieldLabel>
<VolumeSelect volume={volume} index={key} exclude={exclude} />
</FormGroup>
{volume.type === "PERSISTENT"
? this.getPersistentVolumeConfig(volume, key)
: volume.type === "HOST"
? this.getHostVolumeConfig(volume, key)
: volume.type === "EXTERNAL"
? this.getExternalVolumeConfig(volume, key)
: volume.type === "EXTERNAL_CSI"
? this.getExternalCSIVolumeConfig(volume, key)
: volume.type === "DSS"
? this.getUnknownVolumeConfig(volume, key)
: null}
</FormGroupContainer>
);
});
}
render() {
return (
<div>
<h1 className="flush-top short-bottom">
<FormGroupHeading>
<Trans render={heading}>Volumes</Trans>
<FormGroupHeadingContent>
<Tooltip
content={storageTooltip}
interactive={true}
maxWidth={300}
wrapText={true}
>
<InfoTooltipIcon />
</Tooltip>
</FormGroupHeadingContent>
</FormGroupHeading>
</h1>
<Trans render="p">
Create a stateful service by configuring a persistent volume.
Persistent volumes enable instances to be restarted without data loss.
</Trans>
{this.getVolumesLines(this.props.data.volumes)}
<div>
<AddButton
onClick={this.props.onAddItem.bind(this, { path: "volumes" })}
>
<Trans>Add Volume</Trans>
</AddButton>
</div>
<MountService.Mount
type="CreateService:SingleContainerVolumes:VolumeConflicts"
data={this.props.data}
/>
</div>
);
}
}
const storageTooltip = (
<Trans>
DC/OS offers several storage options.{" "}
<a href={MetadataStore.buildDocsURI("/storage/")} target="_blank">
More information
</a>
.
</Trans>
);
// prettier-ignore
const accessModes = [
{ value: "SINGLE_NODE_WRITER", label: "SINGLE_NODE_WRITER - Can only be published once as read/write on a single node, at any given time." },
{ value: "SINGLE_NODE_READER_ONLY", label: "SINGLE_NODE_READER_ONLY - Can only be published once as readonly on a single node, at any given time" },
{ value: "MULTI_NODE_READER_ONLY", label: "MULTI_NODE_READER_ONLY - Can be published as readonly at multiple nodes simultaneously" },
{ value: "MULTI_NODE_SINGLE_WRITER", label: "MULTI_NODE_SINGLE_WRITER - Can be published at multiple nodes simultaneously. Only one of the node can be used as read/write. The rest will be readonly" },
{ value: "MULTI_NODE_MULTI_WRITER", label: "MULTI_NODE_MULTI_WRITER - Can be published as read/write at multiple nodes simultaneously" },
];
const containerPathTooltip = (
<Trans>
The path where your application will read and write data. This must be a
single-level path relative to the container.{" "}
<a
href={MetadataStore.buildDocsURI("/storage/persistent-volume/")}
target="_blank"
>
More information
</a>
.
</Trans>
); | the_stack |
declare namespace SqlBricks {
/**
* Statement is an abstract base class for all statements (SELECT, INSERT, UPDATE, DELETE)
* and should never be instantiated directly. It is exposed because it can be used with the
* instanceof operator to easily determine whether something is a SQL Bricks statement: my_var instanceof Statement.
*/
interface Statement {
/**
* Clones a statement so that subsequent modifications do not affect the original statement.
*/
clone(): this
/**
* Returns the non-parameterized SQL for the statement. This is called implicitly by Javascript when using a Statement anywhere that a string is expected (string concatenation, Array.join(), etc).
* While toString() is easy to use, it is not recommended in most cases because:
* It doesn't provide robust protection against SQL injection attacks (it just does basic escaping)
* It doesn't provide as much support for complex data types (objects, arrays, etc, are "stringified" before being passed to your database driver, which then has to interpret them correctly)
* It does not provide the same level of detail in error messages (see this issue)
* For the above reasons, it is usually better to use toParams().
*/
toString(): string
/**
* Returns an object with two properties: a parameterized text string and a values array. The values are populated with anything on the right-hand side
* of a WHERE criteria,as well as any values passed into an insert() or update() (they can be passed explicitly with val() or opted out of with sql())
* @param options A placeholder option of '?%d' can be passed to generate placeholders compatible with node-sqlite3 (%d is replaced with the parameter #):
* @example
* update('person', {'first_name': 'Fred'}).where({'last_name': 'Flintstone'}).toParams({placeholder: '?%d'});
* // {"text": "UPDATE person SET first_name = ?1 WHERE last_name = ?2", "values": ["Fred", "Flintstone"]}
*/
toParams(options?: { placeholder: string }): SqlBricksParam
}
interface SqlBricksParam {
text: string
values: any[]
}
type TableName = string | SelectStatement
interface OnCriteria {
[column: string]: string
}
interface WhereObject {
[column: string]: any
}
interface WhereGroup {
op?: string
expressions: WhereExpression[]
}
interface WhereBinary {
op: string
col: string | SelectStatement
val: any
quantifier: string
}
/**
* When a non-expression object is passed somewhere a whereExpression is expected,
* each key/value pair will be ANDed together:
*/
type WhereExpression = WhereGroup | WhereBinary | WhereObject | string
/**
* A SELECT statement
*/
interface SelectStatement extends Statement {
/**
* Appends additional columns to an existing query.
* @param columns can be passed as multiple arguments, a comma-delimited string or an array.
*/
select(...columns: Array<string | SelectStatement>): SelectStatement
/**
* Appends additional columns to an existing query.
* @param columns can be passed as multiple arguments, a comma-delimited string or an array.
*/
select(columns: string[] | SelectStatement[]): SelectStatement
as(alias: string): SelectStatement
distinct(...columns: Array<string | SelectStatement>): SelectStatement
distinct(columns: string[] | SelectStatement[]): SelectStatement
/**
* Makes the query a SELECT ... INTO query (which creates a new table with the results of the query).
* @alias intoTable
* @param tbl new table to create
*/
into(tbl: TableName): SelectStatement
/**
* Makes the query a SELECT ... INTO query (which creates a new table with the results of the query).
* @alias into
* @param tbl new table to create
*/
intoTable(tbl: TableName): SelectStatement
intoTemp(tbl: TableName): SelectStatement
intoTempTable(tbl: TableName): SelectStatement
/**
* Table names can be passed in as multiple string arguments, a comma-delimited string or an array.
* @param tbls table names
*/
from(...tbls: TableName[]): SelectStatement
/**
* Table names can be passed in as multiple string arguments, a comma-delimited string or an array.
* @param tbls array of table names
*/
from(tbls: TableName[]): SelectStatement
/**
* Adds the specified join to the query.
* @alias innerJoin
* @param tbl can include an alias after a space or after the 'AS' keyword ('my_table my_alias').
* @param onCriteria is optional if a joinCriteria function has been supplied.
*/
join(tbl: string, criteria?: OnCriteria | string[] | WhereExpression): SelectStatement
join(tbl: string, onCol1: string, onCol2: string): SelectStatement
join(firstTbl: string, ...otherTbls: string[]): SelectStatement
leftJoin(tbl: string, criteria?: OnCriteria | string[] | WhereExpression): SelectStatement
leftJoin(tbl: string, onCol1: string, onCol2: string): SelectStatement
leftJoin(firstTbl: string, ...otherTbls: string[]): SelectStatement
rightJoin(tbl: string, criteria?: OnCriteria | string[] | WhereExpression): SelectStatement
rightJoin(tbl: string, onCol1: string, onCol2: string): SelectStatement
rightJoin(firstTbl: string, ...otherTbls: string[]): SelectStatement
fullJoin(tbl: string, criteria?: OnCriteria | string[] | WhereExpression): SelectStatement
fullJoin(tbl: string, onCol1: string, onCol2: string): SelectStatement
fullJoin(firstTbl: string, ...otherTbls: string[]): SelectStatement
crossJoin(tbl: string, criteria?: OnCriteria | string[] | WhereExpression): SelectStatement
crossJoin(tbl: string, onCol1: string, onCol2: string): SelectStatement
crossJoin(firstTbl: string, ...otherTbls: string[]): SelectStatement
innerJoin(tbl: string, criteria?: OnCriteria | string[] | WhereExpression): SelectStatement
innerJoin(tbl: string, onCol1: string, onCol2: string): SelectStatement
innerJoin(firstTbl: string, ...otherTbls: string[]): SelectStatement
leftOuterJoin(tbl: string, criteria?: OnCriteria | string[] | WhereExpression): SelectStatement
leftOuterJoin(tbl: string, onCol1: string, onCol2: string): SelectStatement
leftOuterJoin(firstTbl: string, ...otherTbls: string[]): SelectStatement
rightOuterJoin(tbl: string, criteria?: OnCriteria | string[] | WhereExpression): SelectStatement
rightOuterJoin(tbl: string, onCol1: string, onCol2: string): SelectStatement
rightOuterJoin(firstTbl: string, ...otherTbls: string[]): SelectStatement
fullOuterJoin(tbl: string, criteria?: OnCriteria | string[] | WhereExpression): SelectStatement
fullOuterJoin(tbl: string, onCol1: string, onCol2: string): SelectStatement
fullOuterJoin(firstTbl: string, ...otherTbls: string[]): SelectStatement
on(onCriteria: OnCriteria | WhereExpression): SelectStatement
on(onCol1: string, onCol2: string): SelectStatement
/**
* Joins using USING instead of ON.
* @param columnList columnList can be passed in as one or more string arguments, a comma-delimited string, or an array.
* @example
* select('*').from('person').join('address').using('address_id', 'country_id');
* // SELECT * FROM person INNER JOIN address USING (address_id, country_id)
*/
using(...columnList: string[]): SelectStatement
using(columnList: string[]): SelectStatement
/**
* Adds the specified natural join to the query.
* @param tbl can include an alias after a space or after the 'AS' keyword ('my_table my_alias').
*/
naturalJoin(tbl: string): SelectStatement
naturalLeftJoin(tbl: string): SelectStatement
naturalRightJoin(tbl: string): SelectStatement
naturalFullJoin(tbl: string): SelectStatement
naturalInnerJoin(tbl: string): SelectStatement
naturalLeftOuterJoin(tbl: string): SelectStatement
naturalRightOuterJoin(tbl: string): SelectStatement
naturalFullOuterJoin(tbl: string): SelectStatement
where(column?: string | null, value?: any): SelectStatement
where(...whereExpr: WhereExpression[]): SelectStatement
and(...options: any[]): SelectStatement
/**
* Sets or extends the GROUP BY columns.
* @param columns can take multiple arguments, a single comma-delimited string or an array.
*/
groupBy(...columns: string[]): SelectStatement
groupBy(columns: string[]): SelectStatement
having(column: string, value: string): SelectStatement
having(whereExpr: WhereExpression): SelectStatement
/**
* Sets or extends the list of columns in the ORDER BY clause.
* @param columns can be passed as multiple arguments, a single comma-delimited string or an array.
*/
orderBy(...columns: string[]): SelectStatement
orderBy(columns: string[]): SelectStatement
order(...columns: string[]): SelectStatement
order(columns: string[]): SelectStatement
forUpdate(...tbls: string[]): SelectStatement
of(tlb: string): SelectStatement
noWait(): SelectStatement
union(...stmt: Statement[]): SelectStatement
intersect(...stmt: Statement[]): SelectStatement
minus(...stmt: Statement[]): SelectStatement
except(...stmt: Statement[]): SelectStatement
}
/**
* An INSERT statement
*/
interface InsertStatement extends Statement {
into(tbl: TableName, ...columns: any[]): InsertStatement
intoTable(tbl: TableName, ...columns: any[]): InsertStatement
select(...columns: Array<string | SelectStatement>): InsertStatement
select(columns: string[] | SelectStatement[]): InsertStatement
values(...values: any[]): InsertStatement
}
/**
* An UPDATE statement
*/
interface UpdateStatement extends Statement {
values(...values: any[]): UpdateStatement
set(...values: any[]): UpdateStatement
where(column?: string | null, value?: any): UpdateStatement
where(...whereExpr: WhereExpression[]): UpdateStatement
and(column?: string | null, value?: any): UpdateStatement
and(...whereExpr: WhereExpression[]): UpdateStatement
}
/**
* A DELETE statement
*/
interface DeleteStatement extends Statement {
from(...tbls: string[]): DeleteStatement
using(...columnList: string[]): DeleteStatement
using(columnList: string[]): DeleteStatement
where(column?: string | null, value?: any): DeleteStatement
where(...whereExpr: WhereExpression[]): DeleteStatement
and(column?: string | null, value?: any): DeleteStatement
and(...whereExpr: WhereExpression[]): DeleteStatement
}
}
interface SqlBricksFn {
(...params: any[]): any
/**
* Wraps a value (user-supplied string, number, boolean, etc) so that it can be passed into SQL Bricks
* anywhere that a column is expected (the left-hand side of WHERE criteria and many other SQL Bricks APIs)
* @param value value to be wraped
*/
val(value: any): any
/**
* Returns a new INSERT statement. It can be used with or without the new operator.
* @alias insertInto
* @param tbl table name
* @param values a values object or a columns list. Passing a set of columns (as multiple arguments, a comma-delimited string or an array)
* will put the statement into split keys/values mode, where a matching array of values is expected in values()
* @example
* insert('person', {'first_name': 'Fred', 'last_name': 'Flintstone'});
* // INSERT INTO person (first_name, last_name) VALUES ('Fred', 'Flintstone')
*/
insert(tbl?: string, ...values: any[]): SqlBricks.InsertStatement
/**
* Returns a new INSERT statement. It can be used with or without the new operator.
* @alias insert
* @param tbl table name
* @param values a values object or a columns list. Passing a set of columns (as multiple arguments, a comma-delimited string or an array)
* will put the statement into split keys/values mode, where a matching array of values is expected in values()
* @example
* insert('person', {'first_name': 'Fred', 'last_name': 'Flintstone'});
* // INSERT INTO person (first_name, last_name) VALUES ('Fred', 'Flintstone')
*/
insertInto(tbl?: string, ...values: any[]): SqlBricks.InsertStatement
/**
* Returns a new select statement, seeded with a set of columns. It can be used with or without the new keyword.
* @param columns it can be passed in here (or appended later via sel.select() or sel.distinct()) via multiple arguments
* or a comma-delimited string or an array. If no columns are specified, toString() will default to SELECT *.
*/
select(...columns: Array<string | SqlBricks.SelectStatement>): SqlBricks.SelectStatement
select(columns: string[] | SqlBricks.SelectStatement[]): SqlBricks.SelectStatement
/**
* Returns a new UPDATE statement. It can be used with or without the new operator.
* @param tbl table name
* @param values
*/
update(tbl: string, ...values: any[]): SqlBricks.UpdateStatement
/**
* Returns a new DELETE statement. It can be used with or without the new operator.
* @alias deleteFrom
* @param tbl table name
*/
delete(tbl?: string): SqlBricks.DeleteStatement
/**
* Returns a new DELETE statement. It can be used with or without the new operator.
* @alias delete
* @param tbl table name
*/
deleteFrom(tbl?: string): SqlBricks.DeleteStatement
/**
* Registers a set of frequently-used table aliases with SQL Bricks.
* These table aliases can then be used by themselves in from(), join(), etc
* and SQL Bricks will automatically expand them to include the table name as well as the alias.
* @param expansions
* @example
* sql.aliasExpansions({'psn': 'person', 'addr': 'address', 'zip': 'zipcode', 'usr': 'user'});
* select().from('psn').join('addr', {'psn.addr_id': 'addr.id'});
* // SELECT * FROM person psn INNER JOIN address addr ON psn.addr_id = addr.id
*/
aliasExpansions(expansions: { [tbl: string]: string }): void
/**
* Sets a user-supplied function to automatically generate the .on() criteria for joins whenever it is not supplied explicitly.
* @param func
*/
joinCriteria(func?: (...args: any[]) => SqlBricks.OnCriteria): any
_extension(): any
prop: number
conversions: any
//////////////////////////////////////////
////// Where Expression functions //////
//////////////////////////////////////////
/**
* Joins the passed expressions with AND
* @param whereExprs
*/
and(...whereExprs: SqlBricks.WhereExpression[]): SqlBricks.WhereGroup
/**
* Joins the passed expressions with OR:
* @param whereExprs
*/
or(...whereExprs: SqlBricks.WhereExpression[]): SqlBricks.WhereGroup
/**
* Negates the expression by wrapping it in NOT (...)
* (if it is at the top level, the parentheses are unnecessary and will be omitted)
* @param whereExpr
*/
not(whereExpr: SqlBricks.WhereExpression): SqlBricks.WhereGroup
/**
* Generates a BETWEEN
* @param column
* @param value1
* @param value2
*/
between(column: string, value1: any, value2: any): SqlBricks.WhereExpression
isNull(column: string): SqlBricks.WhereExpression
isNotNull(column: string): SqlBricks.WhereExpression
like(column: string, value: any, escapeStr?: string): SqlBricks.WhereExpression
exists(stmt: any): SqlBricks.WhereExpression
in(column: string, stmt: SqlBricks.SelectStatement): SqlBricks.WhereExpression
in(column: string, ...values: any[]): SqlBricks.WhereExpression
/**
* Generates the appropriate relational operator (=, <>, <, <=, > or >=).
* @param column column name or query result
* @param value column value
*/
eq(column: string | SqlBricks.SelectStatement, value?: any): SqlBricks.WhereBinary
equal(column: string | SqlBricks.SelectStatement, value?: any): SqlBricks.WhereBinary
notEq(column: string | SqlBricks.SelectStatement, value?: any): SqlBricks.WhereBinary
lt(column: string | SqlBricks.SelectStatement, value?: any): SqlBricks.WhereBinary
lte(column: string | SqlBricks.SelectStatement, value?: any): SqlBricks.WhereBinary
gt(column: string | SqlBricks.SelectStatement, value?: any): SqlBricks.WhereBinary
gte(column: string | SqlBricks.SelectStatement, value?: any): SqlBricks.WhereBinary
eqAll(column: string | SqlBricks.SelectStatement, value?: any): SqlBricks.WhereBinary
notEqAll(column: string | SqlBricks.SelectStatement, value?: any): SqlBricks.WhereBinary
ltAll(column: string | SqlBricks.SelectStatement, value?: any): SqlBricks.WhereBinary
lteAll(column: string | SqlBricks.SelectStatement, value?: any): SqlBricks.WhereBinary
gtAll(column: string | SqlBricks.SelectStatement, value?: any): SqlBricks.WhereBinary
gteAll(column: string | SqlBricks.SelectStatement, value?: any): SqlBricks.WhereBinary
eqAny(column: string | SqlBricks.SelectStatement, value?: any): SqlBricks.WhereBinary
notEqAny(column: string | SqlBricks.SelectStatement, value?: any): SqlBricks.WhereBinary
ltAny(column: string | SqlBricks.SelectStatement, value?: any): SqlBricks.WhereBinary
lteAny(column: string | SqlBricks.SelectStatement, value?: any): SqlBricks.WhereBinary
gtAny(column: string | SqlBricks.SelectStatement, value?: any): SqlBricks.WhereBinary
gteAny(column: string | SqlBricks.SelectStatement, value?: any): SqlBricks.WhereBinary
eqSome(column: string | SqlBricks.SelectStatement, value?: any): SqlBricks.WhereBinary
notEqSome(column: string | SqlBricks.SelectStatement, value?: any): SqlBricks.WhereBinary
ltSome(column: string | SqlBricks.SelectStatement, value?: any): SqlBricks.WhereBinary
lteSome(column: string | SqlBricks.SelectStatement, value?: any): SqlBricks.WhereBinary
gtSome(column: string | SqlBricks.SelectStatement, value?: any): SqlBricks.WhereBinary
gteSome(column: string | SqlBricks.SelectStatement, value?: any): SqlBricks.WhereBinary
}
declare const SqlBricks: SqlBricksFn
export = SqlBricks | the_stack |
import { logger, PrefixedLogger } from '../../logger';
import { LocalStorageCryptoStore } from './localStorage-crypto-store';
import { MemoryCryptoStore } from './memory-crypto-store';
import * as IndexedDBCryptoStoreBackend from './indexeddb-crypto-store-backend';
import { InvalidCryptoStoreError } from '../../errors';
import * as IndexedDBHelpers from "../../indexeddb-helpers";
import {
CryptoStore,
IDeviceData,
IProblem,
ISession,
ISessionInfo,
IWithheld,
Mode,
OutgoingRoomKeyRequest,
} from "./base";
import { IRoomKeyRequestBody } from "../index";
import { ICrossSigningKey } from "../../client";
import { IOlmDevice } from "../algorithms/megolm";
import { IRoomEncryption } from "../RoomList";
import { InboundGroupSessionData } from "../OlmDevice";
import { IEncryptedPayload } from "../aes";
/**
* Internal module. indexeddb storage for e2e.
*
* @module
*/
/**
* An implementation of CryptoStore, which is normally backed by an indexeddb,
* but with fallback to MemoryCryptoStore.
*
* @implements {module:crypto/store/base~CryptoStore}
*/
export class IndexedDBCryptoStore implements CryptoStore {
public static STORE_ACCOUNT = 'account';
public static STORE_SESSIONS = 'sessions';
public static STORE_INBOUND_GROUP_SESSIONS = 'inbound_group_sessions';
public static STORE_INBOUND_GROUP_SESSIONS_WITHHELD = 'inbound_group_sessions_withheld';
public static STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS = 'shared_history_inbound_group_sessions';
public static STORE_DEVICE_DATA = 'device_data';
public static STORE_ROOMS = 'rooms';
public static STORE_BACKUP = 'sessions_needing_backup';
public static exists(indexedDB: IDBFactory, dbName: string): Promise<boolean> {
return IndexedDBHelpers.exists(indexedDB, dbName);
}
private backendPromise: Promise<CryptoStore> = null;
private backend: CryptoStore = null;
/**
* Create a new IndexedDBCryptoStore
*
* @param {IDBFactory} indexedDB global indexedDB instance
* @param {string} dbName name of db to connect to
*/
constructor(private readonly indexedDB: IDBFactory, private readonly dbName: string) {}
/**
* Ensure the database exists and is up-to-date, or fall back to
* a local storage or in-memory store.
*
* This must be called before the store can be used.
*
* @return {Promise} resolves to either an IndexedDBCryptoStoreBackend.Backend,
* or a MemoryCryptoStore
*/
public startup(): Promise<CryptoStore> {
if (this.backendPromise) {
return this.backendPromise;
}
this.backendPromise = new Promise<CryptoStore>((resolve, reject) => {
if (!this.indexedDB) {
reject(new Error('no indexeddb support available'));
return;
}
logger.log(`connecting to indexeddb ${this.dbName}`);
const req = this.indexedDB.open(this.dbName, IndexedDBCryptoStoreBackend.VERSION);
req.onupgradeneeded = (ev) => {
const db = req.result;
const oldVersion = ev.oldVersion;
IndexedDBCryptoStoreBackend.upgradeDatabase(db, oldVersion);
};
req.onblocked = () => {
logger.log(
`can't yet open IndexedDBCryptoStore because it is open elsewhere`,
);
};
req.onerror = (ev) => {
logger.log("Error connecting to indexeddb", ev);
reject(req.error);
};
req.onsuccess = () => {
const db = req.result;
logger.log(`connected to indexeddb ${this.dbName}`);
resolve(new IndexedDBCryptoStoreBackend.Backend(db));
};
}).then((backend) => {
// Edge has IndexedDB but doesn't support compund keys which we use fairly extensively.
// Try a dummy query which will fail if the browser doesn't support compund keys, so
// we can fall back to a different backend.
return backend.doTxn(
'readonly',
[
IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,
IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD,
],
(txn) => {
backend.getEndToEndInboundGroupSession('', '', txn, () => {});
}).then(() => backend,
);
}).catch((e) => {
if (e.name === 'VersionError') {
logger.warn("Crypto DB is too new for us to use!", e);
// don't fall back to a different store: the user has crypto data
// in this db so we should use it or nothing at all.
throw new InvalidCryptoStoreError(InvalidCryptoStoreError.TOO_NEW);
}
logger.warn(
`unable to connect to indexeddb ${this.dbName}` +
`: falling back to localStorage store: ${e}`,
);
try {
return new LocalStorageCryptoStore(global.localStorage);
} catch (e) {
logger.warn(
`unable to open localStorage: falling back to in-memory store: ${e}`,
);
return new MemoryCryptoStore();
}
}).then(backend => {
this.backend = backend;
return backend as CryptoStore;
});
return this.backendPromise;
}
/**
* Delete all data from this store.
*
* @returns {Promise} resolves when the store has been cleared.
*/
public deleteAllData(): Promise<void> {
return new Promise<void>((resolve, reject) => {
if (!this.indexedDB) {
reject(new Error('no indexeddb support available'));
return;
}
logger.log(`Removing indexeddb instance: ${this.dbName}`);
const req = this.indexedDB.deleteDatabase(this.dbName);
req.onblocked = () => {
logger.log(
`can't yet delete IndexedDBCryptoStore because it is open elsewhere`,
);
};
req.onerror = (ev) => {
logger.log("Error deleting data from indexeddb", ev);
reject(req.error);
};
req.onsuccess = () => {
logger.log(`Removed indexeddb instance: ${this.dbName}`);
resolve();
};
}).catch((e) => {
// in firefox, with indexedDB disabled, this fails with a
// DOMError. We treat this as non-fatal, so that people can
// still use the app.
logger.warn(`unable to delete IndexedDBCryptoStore: ${e}`);
});
}
/**
* Look for an existing outgoing room key request, and if none is found,
* add a new one
*
* @param {module:crypto/store/base~OutgoingRoomKeyRequest} request
*
* @returns {Promise} resolves to
* {@link module:crypto/store/base~OutgoingRoomKeyRequest}: either the
* same instance as passed in, or the existing one.
*/
public getOrAddOutgoingRoomKeyRequest(request: OutgoingRoomKeyRequest): Promise<OutgoingRoomKeyRequest> {
return this.backend.getOrAddOutgoingRoomKeyRequest(request);
}
/**
* Look for an existing room key request
*
* @param {module:crypto~RoomKeyRequestBody} requestBody
* existing request to look for
*
* @return {Promise} resolves to the matching
* {@link module:crypto/store/base~OutgoingRoomKeyRequest}, or null if
* not found
*/
public getOutgoingRoomKeyRequest(requestBody: IRoomKeyRequestBody): Promise<OutgoingRoomKeyRequest | null> {
return this.backend.getOutgoingRoomKeyRequest(requestBody);
}
/**
* Look for room key requests by state
*
* @param {Array<Number>} wantedStates list of acceptable states
*
* @return {Promise} resolves to the a
* {@link module:crypto/store/base~OutgoingRoomKeyRequest}, or null if
* there are no pending requests in those states. If there are multiple
* requests in those states, an arbitrary one is chosen.
*/
public getOutgoingRoomKeyRequestByState(wantedStates: number[]): Promise<OutgoingRoomKeyRequest | null> {
return this.backend.getOutgoingRoomKeyRequestByState(wantedStates);
}
/**
* Look for room key requests by state –
* unlike above, return a list of all entries in one state.
*
* @param {Number} wantedState
* @return {Promise<Array<*>>} Returns an array of requests in the given state
*/
public getAllOutgoingRoomKeyRequestsByState(wantedState: number): Promise<OutgoingRoomKeyRequest[]> {
return this.backend.getAllOutgoingRoomKeyRequestsByState(wantedState);
}
/**
* Look for room key requests by target device and state
*
* @param {string} userId Target user ID
* @param {string} deviceId Target device ID
* @param {Array<Number>} wantedStates list of acceptable states
*
* @return {Promise} resolves to a list of all the
* {@link module:crypto/store/base~OutgoingRoomKeyRequest}
*/
public getOutgoingRoomKeyRequestsByTarget(
userId: string,
deviceId: string,
wantedStates: number[],
): Promise<OutgoingRoomKeyRequest[]> {
return this.backend.getOutgoingRoomKeyRequestsByTarget(
userId, deviceId, wantedStates,
);
}
/**
* Look for an existing room key request by id and state, and update it if
* found
*
* @param {string} requestId ID of request to update
* @param {number} expectedState state we expect to find the request in
* @param {Object} updates name/value map of updates to apply
*
* @returns {Promise} resolves to
* {@link module:crypto/store/base~OutgoingRoomKeyRequest}
* updated request, or null if no matching row was found
*/
public updateOutgoingRoomKeyRequest(
requestId: string,
expectedState: number,
updates: Partial<OutgoingRoomKeyRequest>,
): Promise<OutgoingRoomKeyRequest | null> {
return this.backend.updateOutgoingRoomKeyRequest(
requestId, expectedState, updates,
);
}
/**
* Look for an existing room key request by id and state, and delete it if
* found
*
* @param {string} requestId ID of request to update
* @param {number} expectedState state we expect to find the request in
*
* @returns {Promise} resolves once the operation is completed
*/
public deleteOutgoingRoomKeyRequest(
requestId: string,
expectedState: number,
): Promise<OutgoingRoomKeyRequest | null> {
return this.backend.deleteOutgoingRoomKeyRequest(requestId, expectedState);
}
// Olm Account
/*
* Get the account pickle from the store.
* This requires an active transaction. See doTxn().
*
* @param {*} txn An active transaction. See doTxn().
* @param {function(string)} func Called with the account pickle
*/
public getAccount(txn: IDBTransaction, func: (accountPickle: string) => void) {
this.backend.getAccount(txn, func);
}
/**
* Write the account pickle to the store.
* This requires an active transaction. See doTxn().
*
* @param {*} txn An active transaction. See doTxn().
* @param {string} accountPickle The new account pickle to store.
*/
public storeAccount(txn: IDBTransaction, accountPickle: string): void {
this.backend.storeAccount(txn, accountPickle);
}
/**
* Get the public part of the cross-signing keys (eg. self-signing key,
* user signing key).
*
* @param {*} txn An active transaction. See doTxn().
* @param {function(string)} func Called with the account keys object:
* { key_type: base64 encoded seed } where key type = user_signing_key_seed or self_signing_key_seed
*/
public getCrossSigningKeys(txn: IDBTransaction, func: (keys: Record<string, ICrossSigningKey>) => void): void {
this.backend.getCrossSigningKeys(txn, func);
}
/**
* @param {*} txn An active transaction. See doTxn().
* @param {function(string)} func Called with the private key
* @param {string} type A key type
*/
public getSecretStorePrivateKey(
txn: IDBTransaction,
func: (key: IEncryptedPayload | null) => void,
type: string,
): void {
this.backend.getSecretStorePrivateKey(txn, func, type);
}
/**
* Write the cross-signing keys back to the store
*
* @param {*} txn An active transaction. See doTxn().
* @param {string} keys keys object as getCrossSigningKeys()
*/
public storeCrossSigningKeys(txn: IDBTransaction, keys: Record<string, ICrossSigningKey>): void {
this.backend.storeCrossSigningKeys(txn, keys);
}
/**
* Write the cross-signing private keys back to the store
*
* @param {*} txn An active transaction. See doTxn().
* @param {string} type The type of cross-signing private key to store
* @param {string} key keys object as getCrossSigningKeys()
*/
public storeSecretStorePrivateKey(txn: IDBTransaction, type: string, key: IEncryptedPayload): void {
this.backend.storeSecretStorePrivateKey(txn, type, key);
}
// Olm sessions
/**
* Returns the number of end-to-end sessions in the store
* @param {*} txn An active transaction. See doTxn().
* @param {function(int)} func Called with the count of sessions
*/
public countEndToEndSessions(txn: IDBTransaction, func: (count: number) => void): void {
this.backend.countEndToEndSessions(txn, func);
}
/**
* Retrieve a specific end-to-end session between the logged-in user
* and another device.
* @param {string} deviceKey The public key of the other device.
* @param {string} sessionId The ID of the session to retrieve
* @param {*} txn An active transaction. See doTxn().
* @param {function(object)} func Called with A map from sessionId
* to session information object with 'session' key being the
* Base64 end-to-end session and lastReceivedMessageTs being the
* timestamp in milliseconds at which the session last received
* a message.
*/
public getEndToEndSession(
deviceKey: string,
sessionId: string,
txn: IDBTransaction,
func: (sessions: { [ sessionId: string ]: ISessionInfo }) => void,
): void {
this.backend.getEndToEndSession(deviceKey, sessionId, txn, func);
}
/**
* Retrieve the end-to-end sessions between the logged-in user and another
* device.
* @param {string} deviceKey The public key of the other device.
* @param {*} txn An active transaction. See doTxn().
* @param {function(object)} func Called with A map from sessionId
* to session information object with 'session' key being the
* Base64 end-to-end session and lastReceivedMessageTs being the
* timestamp in milliseconds at which the session last received
* a message.
*/
public getEndToEndSessions(
deviceKey: string,
txn: IDBTransaction,
func: (sessions: { [sessionId: string]: ISessionInfo }) => void,
): void {
this.backend.getEndToEndSessions(deviceKey, txn, func);
}
/**
* Retrieve all end-to-end sessions
* @param {*} txn An active transaction. See doTxn().
* @param {function(object)} func Called one for each session with
* an object with, deviceKey, lastReceivedMessageTs, sessionId
* and session keys.
*/
public getAllEndToEndSessions(txn: IDBTransaction, func: (session: ISessionInfo) => void): void {
this.backend.getAllEndToEndSessions(txn, func);
}
/**
* Store a session between the logged-in user and another device
* @param {string} deviceKey The public key of the other device.
* @param {string} sessionId The ID for this end-to-end session.
* @param {string} sessionInfo Session information object
* @param {*} txn An active transaction. See doTxn().
*/
public storeEndToEndSession(
deviceKey: string,
sessionId: string,
sessionInfo: ISessionInfo,
txn: IDBTransaction,
): void {
this.backend.storeEndToEndSession(deviceKey, sessionId, sessionInfo, txn);
}
public storeEndToEndSessionProblem(deviceKey: string, type: string, fixed: boolean): Promise<void> {
return this.backend.storeEndToEndSessionProblem(deviceKey, type, fixed);
}
public getEndToEndSessionProblem(deviceKey: string, timestamp: number): Promise<IProblem | null> {
return this.backend.getEndToEndSessionProblem(deviceKey, timestamp);
}
public filterOutNotifiedErrorDevices(devices: IOlmDevice[]): Promise<IOlmDevice[]> {
return this.backend.filterOutNotifiedErrorDevices(devices);
}
// Inbound group sessions
/**
* Retrieve the end-to-end inbound group session for a given
* server key and session ID
* @param {string} senderCurve25519Key The sender's curve 25519 key
* @param {string} sessionId The ID of the session
* @param {*} txn An active transaction. See doTxn().
* @param {function(object)} func Called with A map from sessionId
* to Base64 end-to-end session.
*/
public getEndToEndInboundGroupSession(
senderCurve25519Key: string,
sessionId: string,
txn: IDBTransaction,
func: (groupSession: InboundGroupSessionData | null, groupSessionWithheld: IWithheld | null) => void,
): void {
this.backend.getEndToEndInboundGroupSession(senderCurve25519Key, sessionId, txn, func);
}
/**
* Fetches all inbound group sessions in the store
* @param {*} txn An active transaction. See doTxn().
* @param {function(object)} func Called once for each group session
* in the store with an object having keys {senderKey, sessionId,
* sessionData}, then once with null to indicate the end of the list.
*/
public getAllEndToEndInboundGroupSessions(
txn: IDBTransaction,
func: (session: ISession | null) => void,
): void {
this.backend.getAllEndToEndInboundGroupSessions(txn, func);
}
/**
* Adds an end-to-end inbound group session to the store.
* If there already exists an inbound group session with the same
* senderCurve25519Key and sessionID, the session will not be added.
* @param {string} senderCurve25519Key The sender's curve 25519 key
* @param {string} sessionId The ID of the session
* @param {object} sessionData The session data structure
* @param {*} txn An active transaction. See doTxn().
*/
public addEndToEndInboundGroupSession(
senderCurve25519Key: string,
sessionId: string,
sessionData: InboundGroupSessionData,
txn: IDBTransaction,
): void {
this.backend.addEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn);
}
/**
* Writes an end-to-end inbound group session to the store.
* If there already exists an inbound group session with the same
* senderCurve25519Key and sessionID, it will be overwritten.
* @param {string} senderCurve25519Key The sender's curve 25519 key
* @param {string} sessionId The ID of the session
* @param {object} sessionData The session data structure
* @param {*} txn An active transaction. See doTxn().
*/
public storeEndToEndInboundGroupSession(
senderCurve25519Key: string,
sessionId: string,
sessionData: InboundGroupSessionData,
txn: IDBTransaction,
): void {
this.backend.storeEndToEndInboundGroupSession(senderCurve25519Key, sessionId, sessionData, txn);
}
public storeEndToEndInboundGroupSessionWithheld(
senderCurve25519Key: string,
sessionId: string,
sessionData: IWithheld,
txn: IDBTransaction,
): void {
this.backend.storeEndToEndInboundGroupSessionWithheld(senderCurve25519Key, sessionId, sessionData, txn);
}
// End-to-end device tracking
/**
* Store the state of all tracked devices
* This contains devices for each user, a tracking state for each user
* and a sync token matching the point in time the snapshot represents.
* These all need to be written out in full each time such that the snapshot
* is always consistent, so they are stored in one object.
*
* @param {Object} deviceData
* @param {*} txn An active transaction. See doTxn().
*/
public storeEndToEndDeviceData(deviceData: IDeviceData, txn: IDBTransaction): void {
this.backend.storeEndToEndDeviceData(deviceData, txn);
}
/**
* Get the state of all tracked devices
*
* @param {*} txn An active transaction. See doTxn().
* @param {function(Object)} func Function called with the
* device data
*/
public getEndToEndDeviceData(txn: IDBTransaction, func: (deviceData: IDeviceData | null) => void): void {
this.backend.getEndToEndDeviceData(txn, func);
}
// End to End Rooms
/**
* Store the end-to-end state for a room.
* @param {string} roomId The room's ID.
* @param {object} roomInfo The end-to-end info for the room.
* @param {*} txn An active transaction. See doTxn().
*/
public storeEndToEndRoom(roomId: string, roomInfo: IRoomEncryption, txn: IDBTransaction): void {
this.backend.storeEndToEndRoom(roomId, roomInfo, txn);
}
/**
* Get an object of roomId->roomInfo for all e2e rooms in the store
* @param {*} txn An active transaction. See doTxn().
* @param {function(Object)} func Function called with the end to end encrypted rooms
*/
public getEndToEndRooms(txn: IDBTransaction, func: (rooms: Record<string, IRoomEncryption>) => void): void {
this.backend.getEndToEndRooms(txn, func);
}
// session backups
/**
* Get the inbound group sessions that need to be backed up.
* @param {number} limit The maximum number of sessions to retrieve. 0
* for no limit.
* @returns {Promise} resolves to an array of inbound group sessions
*/
public getSessionsNeedingBackup(limit: number): Promise<ISession[]> {
return this.backend.getSessionsNeedingBackup(limit);
}
/**
* Count the inbound group sessions that need to be backed up.
* @param {*} txn An active transaction. See doTxn(). (optional)
* @returns {Promise} resolves to the number of sessions
*/
public countSessionsNeedingBackup(txn?: IDBTransaction): Promise<number> {
return this.backend.countSessionsNeedingBackup(txn);
}
/**
* Unmark sessions as needing to be backed up.
* @param {Array<object>} sessions The sessions that need to be backed up.
* @param {*} txn An active transaction. See doTxn(). (optional)
* @returns {Promise} resolves when the sessions are unmarked
*/
public unmarkSessionsNeedingBackup(sessions: ISession[], txn?: IDBTransaction): Promise<void> {
return this.backend.unmarkSessionsNeedingBackup(sessions, txn);
}
/**
* Mark sessions as needing to be backed up.
* @param {Array<object>} sessions The sessions that need to be backed up.
* @param {*} txn An active transaction. See doTxn(). (optional)
* @returns {Promise} resolves when the sessions are marked
*/
public markSessionsNeedingBackup(sessions: ISession[], txn?: IDBTransaction): Promise<void> {
return this.backend.markSessionsNeedingBackup(sessions, txn);
}
/**
* Add a shared-history group session for a room.
* @param {string} roomId The room that the key belongs to
* @param {string} senderKey The sender's curve 25519 key
* @param {string} sessionId The ID of the session
* @param {*} txn An active transaction. See doTxn(). (optional)
*/
public addSharedHistoryInboundGroupSession(
roomId: string,
senderKey: string,
sessionId: string,
txn?: IDBTransaction,
): void {
this.backend.addSharedHistoryInboundGroupSession(roomId, senderKey, sessionId, txn);
}
/**
* Get the shared-history group session for a room.
* @param {string} roomId The room that the key belongs to
* @param {*} txn An active transaction. See doTxn(). (optional)
* @returns {Promise} Resolves to an array of [senderKey, sessionId]
*/
public getSharedHistoryInboundGroupSessions(
roomId: string,
txn?: IDBTransaction,
): Promise<[senderKey: string, sessionId: string][]> {
return this.backend.getSharedHistoryInboundGroupSessions(roomId, txn);
}
/**
* Perform a transaction on the crypto store. Any store methods
* that require a transaction (txn) object to be passed in may
* only be called within a callback of either this function or
* one of the store functions operating on the same transaction.
*
* @param {string} mode 'readwrite' if you need to call setter
* functions with this transaction. Otherwise, 'readonly'.
* @param {string[]} stores List IndexedDBCryptoStore.STORE_*
* options representing all types of object that will be
* accessed or written to with this transaction.
* @param {function(*)} func Function called with the
* transaction object: an opaque object that should be passed
* to store functions.
* @param {Logger} [log] A possibly customised log
* @return {Promise} Promise that resolves with the result of the `func`
* when the transaction is complete. If the backend is
* async (ie. the indexeddb backend) any of the callback
* functions throwing an exception will cause this promise to
* reject with that exception. On synchronous backends, the
* exception will propagate to the caller of the getFoo method.
*/
doTxn<T>(mode: Mode, stores: Iterable<string>, func: (txn: IDBTransaction) => T, log?: PrefixedLogger): Promise<T> {
return this.backend.doTxn(mode, stores, func, log);
}
} | the_stack |
// This file was automatically generated by elastic/elastic-client-generator-js
// DO NOT MODIFY IT BY HAND. Instead, modify the source open api file,
// and elastic/elastic-client-generator-js to regenerate this file again.
import {
Transport,
TransportRequestOptions,
TransportRequestOptionsWithMeta,
TransportRequestOptionsWithOutMeta,
TransportResult
} from '@elastic/transport'
import * as T from '../types'
import * as TB from '../typesWithBodyKey'
interface That { transport: Transport }
export default class Rollup {
transport: Transport
constructor (transport: Transport) {
this.transport = transport
}
async deleteJob (this: That, params: T.RollupDeleteJobRequest | TB.RollupDeleteJobRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.RollupDeleteJobResponse>
async deleteJob (this: That, params: T.RollupDeleteJobRequest | TB.RollupDeleteJobRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.RollupDeleteJobResponse, unknown>>
async deleteJob (this: That, params: T.RollupDeleteJobRequest | TB.RollupDeleteJobRequest, options?: TransportRequestOptions): Promise<T.RollupDeleteJobResponse>
async deleteJob (this: That, params: T.RollupDeleteJobRequest | TB.RollupDeleteJobRequest, options?: TransportRequestOptions): Promise<any> {
const acceptedPath: string[] = ['id']
const querystring: Record<string, any> = {}
const body = undefined
for (const key in params) {
if (acceptedPath.includes(key)) {
continue
} else if (key !== 'body') {
// @ts-expect-error
querystring[key] = params[key]
}
}
const method = 'DELETE'
const path = `/_rollup/job/${encodeURIComponent(params.id.toString())}`
return await this.transport.request({ path, method, querystring, body }, options)
}
async getJobs (this: That, params?: T.RollupGetJobsRequest | TB.RollupGetJobsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.RollupGetJobsResponse>
async getJobs (this: That, params?: T.RollupGetJobsRequest | TB.RollupGetJobsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.RollupGetJobsResponse, unknown>>
async getJobs (this: That, params?: T.RollupGetJobsRequest | TB.RollupGetJobsRequest, options?: TransportRequestOptions): Promise<T.RollupGetJobsResponse>
async getJobs (this: That, params?: T.RollupGetJobsRequest | TB.RollupGetJobsRequest, options?: TransportRequestOptions): Promise<any> {
const acceptedPath: string[] = ['id']
const querystring: Record<string, any> = {}
const body = undefined
params = params ?? {}
for (const key in params) {
if (acceptedPath.includes(key)) {
continue
} else if (key !== 'body') {
// @ts-expect-error
querystring[key] = params[key]
}
}
let method = ''
let path = ''
if (params.id != null) {
method = 'GET'
path = `/_rollup/job/${encodeURIComponent(params.id.toString())}`
} else {
method = 'GET'
path = '/_rollup/job/'
}
return await this.transport.request({ path, method, querystring, body }, options)
}
async getRollupCaps (this: That, params?: T.RollupGetRollupCapsRequest | TB.RollupGetRollupCapsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.RollupGetRollupCapsResponse>
async getRollupCaps (this: That, params?: T.RollupGetRollupCapsRequest | TB.RollupGetRollupCapsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.RollupGetRollupCapsResponse, unknown>>
async getRollupCaps (this: That, params?: T.RollupGetRollupCapsRequest | TB.RollupGetRollupCapsRequest, options?: TransportRequestOptions): Promise<T.RollupGetRollupCapsResponse>
async getRollupCaps (this: That, params?: T.RollupGetRollupCapsRequest | TB.RollupGetRollupCapsRequest, options?: TransportRequestOptions): Promise<any> {
const acceptedPath: string[] = ['id']
const querystring: Record<string, any> = {}
const body = undefined
params = params ?? {}
for (const key in params) {
if (acceptedPath.includes(key)) {
continue
} else if (key !== 'body') {
// @ts-expect-error
querystring[key] = params[key]
}
}
let method = ''
let path = ''
if (params.id != null) {
method = 'GET'
path = `/_rollup/data/${encodeURIComponent(params.id.toString())}`
} else {
method = 'GET'
path = '/_rollup/data/'
}
return await this.transport.request({ path, method, querystring, body }, options)
}
async getRollupIndexCaps (this: That, params: T.RollupGetRollupIndexCapsRequest | TB.RollupGetRollupIndexCapsRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.RollupGetRollupIndexCapsResponse>
async getRollupIndexCaps (this: That, params: T.RollupGetRollupIndexCapsRequest | TB.RollupGetRollupIndexCapsRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.RollupGetRollupIndexCapsResponse, unknown>>
async getRollupIndexCaps (this: That, params: T.RollupGetRollupIndexCapsRequest | TB.RollupGetRollupIndexCapsRequest, options?: TransportRequestOptions): Promise<T.RollupGetRollupIndexCapsResponse>
async getRollupIndexCaps (this: That, params: T.RollupGetRollupIndexCapsRequest | TB.RollupGetRollupIndexCapsRequest, options?: TransportRequestOptions): Promise<any> {
const acceptedPath: string[] = ['index']
const querystring: Record<string, any> = {}
const body = undefined
for (const key in params) {
if (acceptedPath.includes(key)) {
continue
} else if (key !== 'body') {
// @ts-expect-error
querystring[key] = params[key]
}
}
const method = 'GET'
const path = `/${encodeURIComponent(params.index.toString())}/_rollup/data`
return await this.transport.request({ path, method, querystring, body }, options)
}
async putJob (this: That, params: T.RollupPutJobRequest | TB.RollupPutJobRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.RollupPutJobResponse>
async putJob (this: That, params: T.RollupPutJobRequest | TB.RollupPutJobRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.RollupPutJobResponse, unknown>>
async putJob (this: That, params: T.RollupPutJobRequest | TB.RollupPutJobRequest, options?: TransportRequestOptions): Promise<T.RollupPutJobResponse>
async putJob (this: That, params: T.RollupPutJobRequest | TB.RollupPutJobRequest, options?: TransportRequestOptions): Promise<any> {
const acceptedPath: string[] = ['id']
const acceptedBody: string[] = ['cron', 'groups', 'index_pattern', 'metrics', 'page_size', 'rollup_index']
const querystring: Record<string, any> = {}
let body: Record<string, any> | string
// @ts-expect-error
if (typeof params?.body === 'string') {
// @ts-expect-error
body = params.body
} else {
// @ts-expect-error
body = params.body != null ? { ...params.body } : undefined
}
for (const key in params) {
if (acceptedBody.includes(key)) {
body = body ?? {}
// @ts-expect-error
body[key] = params[key]
} else if (acceptedPath.includes(key)) {
continue
} else if (key !== 'body') {
// @ts-expect-error
querystring[key] = params[key]
}
}
const method = 'PUT'
const path = `/_rollup/job/${encodeURIComponent(params.id.toString())}`
return await this.transport.request({ path, method, querystring, body }, options)
}
async rollup (this: That, params: T.RollupRollupRequest | TB.RollupRollupRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.RollupRollupResponse>
async rollup (this: That, params: T.RollupRollupRequest | TB.RollupRollupRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.RollupRollupResponse, unknown>>
async rollup (this: That, params: T.RollupRollupRequest | TB.RollupRollupRequest, options?: TransportRequestOptions): Promise<T.RollupRollupResponse>
async rollup (this: That, params: T.RollupRollupRequest | TB.RollupRollupRequest, options?: TransportRequestOptions): Promise<any> {
const acceptedPath: string[] = ['index', 'rollup_index']
const acceptedBody: string[] = ['config']
const querystring: Record<string, any> = {}
// @ts-expect-error
let body: any = params.body ?? undefined
for (const key in params) {
if (acceptedBody.includes(key)) {
// @ts-expect-error
body = params[key]
} else if (acceptedPath.includes(key)) {
continue
} else if (key !== 'body') {
// @ts-expect-error
querystring[key] = params[key]
}
}
const method = 'POST'
const path = `/${encodeURIComponent(params.index.toString())}/_rollup/${encodeURIComponent(params.rollup_index.toString())}`
return await this.transport.request({ path, method, querystring, body }, options)
}
async rollupSearch<TDocument = unknown> (this: That, params: T.RollupRollupSearchRequest | TB.RollupRollupSearchRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.RollupRollupSearchResponse<TDocument>>
async rollupSearch<TDocument = unknown> (this: That, params: T.RollupRollupSearchRequest | TB.RollupRollupSearchRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.RollupRollupSearchResponse<TDocument>, unknown>>
async rollupSearch<TDocument = unknown> (this: That, params: T.RollupRollupSearchRequest | TB.RollupRollupSearchRequest, options?: TransportRequestOptions): Promise<T.RollupRollupSearchResponse<TDocument>>
async rollupSearch<TDocument = unknown> (this: That, params: T.RollupRollupSearchRequest | TB.RollupRollupSearchRequest, options?: TransportRequestOptions): Promise<any> {
const acceptedPath: string[] = ['index', 'type']
const acceptedBody: string[] = ['aggs', 'query', 'size']
const querystring: Record<string, any> = {}
let body: Record<string, any> | string
// @ts-expect-error
if (typeof params?.body === 'string') {
// @ts-expect-error
body = params.body
} else {
// @ts-expect-error
body = params.body != null ? { ...params.body } : undefined
}
for (const key in params) {
if (acceptedBody.includes(key)) {
body = body ?? {}
// @ts-expect-error
body[key] = params[key]
} else if (acceptedPath.includes(key)) {
continue
} else if (key !== 'body') {
// @ts-expect-error
querystring[key] = params[key]
}
}
const method = body != null ? 'POST' : 'GET'
const path = `/${encodeURIComponent(params.index.toString())}/_rollup_search`
return await this.transport.request({ path, method, querystring, body }, options)
}
async startJob (this: That, params: T.RollupStartJobRequest | TB.RollupStartJobRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.RollupStartJobResponse>
async startJob (this: That, params: T.RollupStartJobRequest | TB.RollupStartJobRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.RollupStartJobResponse, unknown>>
async startJob (this: That, params: T.RollupStartJobRequest | TB.RollupStartJobRequest, options?: TransportRequestOptions): Promise<T.RollupStartJobResponse>
async startJob (this: That, params: T.RollupStartJobRequest | TB.RollupStartJobRequest, options?: TransportRequestOptions): Promise<any> {
const acceptedPath: string[] = ['id']
const querystring: Record<string, any> = {}
const body = undefined
for (const key in params) {
if (acceptedPath.includes(key)) {
continue
} else if (key !== 'body') {
// @ts-expect-error
querystring[key] = params[key]
}
}
const method = 'POST'
const path = `/_rollup/job/${encodeURIComponent(params.id.toString())}/_start`
return await this.transport.request({ path, method, querystring, body }, options)
}
async stopJob (this: That, params: T.RollupStopJobRequest | TB.RollupStopJobRequest, options?: TransportRequestOptionsWithOutMeta): Promise<T.RollupStopJobResponse>
async stopJob (this: That, params: T.RollupStopJobRequest | TB.RollupStopJobRequest, options?: TransportRequestOptionsWithMeta): Promise<TransportResult<T.RollupStopJobResponse, unknown>>
async stopJob (this: That, params: T.RollupStopJobRequest | TB.RollupStopJobRequest, options?: TransportRequestOptions): Promise<T.RollupStopJobResponse>
async stopJob (this: That, params: T.RollupStopJobRequest | TB.RollupStopJobRequest, options?: TransportRequestOptions): Promise<any> {
const acceptedPath: string[] = ['id']
const querystring: Record<string, any> = {}
const body = undefined
for (const key in params) {
if (acceptedPath.includes(key)) {
continue
} else if (key !== 'body') {
// @ts-expect-error
querystring[key] = params[key]
}
}
const method = 'POST'
const path = `/_rollup/job/${encodeURIComponent(params.id.toString())}/_stop`
return await this.transport.request({ path, method, querystring, body }, options)
}
} | the_stack |
import {
AlignCenterOutlined,
CaretRightOutlined,
CopyFilled,
MonitorOutlined,
PauseOutlined,
SaveFilled,
SettingFilled,
} from '@ant-design/icons';
import { Divider, Dropdown, Menu, Select, Space, Tooltip } from 'antd';
import { ToolbarButton } from 'app/components';
import { Chronograph } from 'app/components/Chronograph';
import useI18NPrefix from 'app/hooks/useI18NPrefix';
import { CommonFormTypes } from 'globalConstants';
import React, { memo, useCallback, useContext, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useHistory } from 'react-router';
import { format } from 'sql-formatter';
import styled from 'styled-components/macro';
import {
INFO,
LEVEL_1,
SPACE,
SPACE_TIMES,
SPACE_XS,
WARNING,
} from 'styles/StyleConstants';
import { getInsertedNodeIndex } from 'utils/utils';
import { isParentIdEqual } from '../../../../slice/utils';
import { selectSources } from '../../../SourcePage/slice/selectors';
import {
PREVIEW_SIZE_LIST,
ViewStatus,
ViewViewModelStages,
} from '../../constants';
import { EditorContext } from '../../EditorContext';
import { useSaveAsView } from '../../hooks/useSaveAsView';
import { useStartAnalysis } from '../../hooks/useStartAnalysis';
import { SaveFormContext } from '../../SaveFormContext';
import { useViewSlice } from '../../slice';
import {
selectCurrentEditingViewAttr,
selectViews,
} from '../../slice/selectors';
import { saveView } from '../../slice/thunks';
import { isNewView } from '../../utils';
interface ToolbarProps {
allowManage: boolean;
allowEnableViz: boolean | undefined;
}
export const Toolbar = memo(({ allowManage, allowEnableViz }: ToolbarProps) => {
const { actions } = useViewSlice();
const dispatch = useDispatch();
const { onRun, onSave } = useContext(EditorContext);
const { showSaveForm } = useContext(SaveFormContext);
const sources = useSelector(selectSources);
const history = useHistory();
const histState = history.location.state as any;
const viewsData = useSelector(selectViews);
const t = useI18NPrefix('view.editor');
const saveAsView = useSaveAsView();
const startAnalysis = useStartAnalysis();
const id = useSelector(state =>
selectCurrentEditingViewAttr(state, { name: 'id' }),
) as string;
const name = useSelector(state =>
selectCurrentEditingViewAttr(state, { name: 'name' }),
) as string;
const parentId = useSelector(state =>
selectCurrentEditingViewAttr(state, { name: 'parentId' }),
) as string;
const config = useSelector(state =>
selectCurrentEditingViewAttr(state, { name: 'config' }),
) as object;
const sourceId = useSelector(state =>
selectCurrentEditingViewAttr(state, { name: 'sourceId' }),
) as string;
const stage = useSelector(state =>
selectCurrentEditingViewAttr(state, { name: 'stage' }),
) as ViewViewModelStages;
const status = useSelector(state =>
selectCurrentEditingViewAttr(state, { name: 'status' }),
) as ViewStatus;
const script = useSelector(state =>
selectCurrentEditingViewAttr(state, { name: 'script' }),
) as string;
const fragment = useSelector(state =>
selectCurrentEditingViewAttr(state, { name: 'fragment' }),
) as string;
const size = useSelector(state =>
selectCurrentEditingViewAttr(state, { name: 'size' }),
) as number;
const error = useSelector(state =>
selectCurrentEditingViewAttr(state, { name: 'error' }),
) as string;
const ViewIndex = useSelector(state =>
selectCurrentEditingViewAttr(state, { name: 'index' }),
) as number;
const isArchived = status === ViewStatus.Archived;
const formatSQL = useCallback(() => {
dispatch(
actions.changeCurrentEditingView({
script: format(script),
}),
);
}, [dispatch, actions, script]);
const showEdit = useCallback(() => {
showSaveForm({
type: CommonFormTypes.Edit,
visible: true,
initialValues: {
name,
parentId,
config,
},
parentIdLabel: t('folder'),
onSave: (values, onClose) => {
let index = ViewIndex;
if (isParentIdEqual(parentId, values.parentId)) {
index = getInsertedNodeIndex(values, viewsData);
}
dispatch(
actions.changeCurrentEditingView({
...values,
parentId: values.parentId || null,
index,
}),
);
dispatch(saveView({ resolve: onClose }));
},
});
}, [
showSaveForm,
actions,
dispatch,
name,
parentId,
config,
viewsData,
ViewIndex,
t,
]);
const sourceChange = useCallback(
value => {
dispatch(actions.changeCurrentEditingView({ sourceId: value }));
},
[dispatch, actions],
);
const sizeMenuClick = useCallback(
({ key }) => {
dispatch(actions.changeCurrentEditingView({ size: Number(key) }));
},
[dispatch, actions],
);
useEffect(() => {
if (histState?.sourcesId && sources) {
sourceChange(histState.sourcesId);
}
}, [histState?.sourcesId, sourceChange, sources]);
return (
<Container>
<Operates>
<Space split={<Divider type="vertical" className="divider" />}>
{allowManage && (
<Select
placeholder={t('source')}
value={sourceId}
bordered={false}
disabled={isArchived}
onChange={sourceChange}
className="source"
>
{sources.map(({ id, name }) => (
<Select.Option key={id} value={id}>
{name}
</Select.Option>
))}
</Select>
)}
<Space>
<Tooltip
title={
<TipTitle
title={[
`${fragment ? t('runSelection') : t('run')}`,
t('runWinTip'),
t('runMacTip'),
]}
/>
}
placement="bottom"
>
<ToolbarButton
icon={
stage === ViewViewModelStages.Running ? (
<PauseOutlined />
) : (
<CaretRightOutlined />
)
}
color={fragment ? WARNING : INFO}
onClick={onRun}
/>
</Tooltip>
<Tooltip title={t('beautify')} placement="bottom">
<ToolbarButton
icon={<AlignCenterOutlined />}
disabled={isArchived}
onClick={formatSQL}
/>
</Tooltip>
</Space>
<Dropdown
trigger={['click']}
overlay={
<Menu onClick={sizeMenuClick}>
{PREVIEW_SIZE_LIST.map(s => (
<Menu.Item key={s}>{s}</Menu.Item>
))}
</Menu>
}
>
<ToolbarButton size="small">{`Limit: ${size}`}</ToolbarButton>
</Dropdown>
<Chronograph
running={stage === ViewViewModelStages.Running}
status={
error
? 'error'
: stage >= ViewViewModelStages.Running
? stage === ViewViewModelStages.Running
? 'processing'
: 'success'
: 'default'
}
/>
</Space>
</Operates>
<Actions>
<Space>
{allowManage && (
<Tooltip
title={
<TipTitle
title={[t('save'), t('saveWinTip'), t('saveMacTip')]}
/>
}
placement="bottom"
>
<ToolbarButton
icon={<SaveFilled />}
disabled={isArchived || stage !== ViewViewModelStages.Saveable}
color={INFO}
onClick={onSave}
/>
</Tooltip>
)}
{allowManage && (
<Tooltip title={t('info')} placement="bottom">
<ToolbarButton
icon={<SettingFilled />}
disabled={isArchived || isNewView(id)}
color={INFO}
onClick={showEdit}
/>
</Tooltip>
)}
{allowManage && (
<Tooltip title={t('saveAs')} placement="bottom">
<ToolbarButton
icon={<CopyFilled />}
onClick={() => saveAsView(id)}
disabled={isNewView(id)}
color={INFO}
/>
</Tooltip>
)}
{/* <Tooltip title={t('saveFragment')} placement="bottom">
<ToolbarButton icon={<SnippetsFilled />} />
</Tooltip> */}
{allowEnableViz && (
<Tooltip title={t('startAnalysis')} placement="bottom">
<ToolbarButton
disabled={isNewView(id)}
icon={<MonitorOutlined />}
color={INFO}
onClick={() => {
startAnalysis(id);
}}
/>
</Tooltip>
)}
</Space>
</Actions>
</Container>
);
});
const Container = styled.div`
z-index: ${LEVEL_1};
display: flex;
flex-shrink: 0;
align-items: center;
padding: ${SPACE} ${SPACE_XS};
background-color: ${p => p.theme.componentBackground};
border-bottom: 1px solid ${p => p.theme.borderColorSplit};
.source {
width: ${SPACE_TIMES(40)};
}
.size {
width: ${SPACE_TIMES(40)};
}
.divider {
border-color: ${p => p.theme.borderColorBase};
}
`;
const Operates = styled.div`
display: flex;
flex: 1;
`;
const Actions = styled.div`
display: flex;
flex-shrink: 0;
`;
const TipTitle = ({ title }: { title: string[] }) => {
return (
<TipTitleWrapper>
{title.map((s, index) => (
<p key={index}>{s}</p>
))}
</TipTitleWrapper>
);
};
const TipTitleWrapper = styled.div`
display: flex;
flex-direction: column;
`; | the_stack |
describe('Test Jest Syntax', function() {
it('test toBe', () => {
expect({ a: 1 }.a).toBe(1)
expect({ a: 1 }.a).not.toBe(2)
expect(NaN).toBe(NaN)
;[
[1, 2],
[true, false],
[{}, {}],
[{ a: 1 }, { a: 1 }],
[{ a: 1 }, { a: 5 }],
['abc', 'cde'],
['with \ntrailing space', 'without trailing space'],
[[], []],
[null, undefined]
].forEach(([a, b]) => {
expect(a).not.toBe(b)
})
;[false, 1, 'a', undefined, null, {}, []].forEach(v => {
expect(v).toBe(v)
})
})
it('test toBeCloseTo', () => {
;[
[0, 0],
[0, 0.001],
[1.23, 1.229],
[1.23, 1.226],
[1.23, 1.225],
[1.23, 1.234],
[Infinity, Infinity],
[-Infinity, -Infinity]
].forEach(([n1, n2]) => {
expect(n1).toBeCloseTo(n2)
})
;[
[0, 0.01],
[1, 1.23],
[1.23, 1.2249999],
[Infinity, -Infinity],
[Infinity, 1.23],
[-Infinity, -1.23]
].forEach(([n1, n2]) => {
expect(n1).not.toBeCloseTo(n2)
})
})
it('test toBeDefined - toBeUndefined', () => {
;[{}, [], true, 1, 'a', 0.5, new Map(), () => {}, Infinity].forEach(v => {
expect(v).toBeDefined()
expect(v).not.toBeUndefined()
})
expect(undefined).not.toBeDefined()
expect(undefined).toBeUndefined()
})
it('test toBeFalsy - toBeTruthy', () => {
;[{}, [], true, 1, 'a', 0.5, new Map(), () => {}, Infinity].forEach(v => {
expect(v).toBeTruthy()
expect(v).not.toBeFalsy()
})
;[false, null, NaN, 0, '', undefined].forEach(v => {
expect(v).toBeFalsy()
expect(v).not.toBeTruthy()
})
})
it('test toBeGreaterThan - toBeGreaterThanOrEqual - toBeLessThan - toBeLessThanOrEqual', () => {
;[
[1, 2],
[-Infinity, Infinity],
[Number.MIN_VALUE, Number.MAX_VALUE],
[0x11, 0x22],
[0b11, 0b111],
[0o11, 0o22],
[0.1, 0.2]
].forEach(([small, big]) => {
expect(small).toBeLessThan(big)
expect(big).not.toBeLessThan(small)
expect(big).toBeGreaterThan(small)
expect(small).not.toBeGreaterThan(big)
expect(small).toBeLessThanOrEqual(big)
expect(big).not.toBeLessThanOrEqual(small)
expect(big).toBeGreaterThanOrEqual(small)
expect(small).not.toBeGreaterThanOrEqual(big)
})
;[
[1, 1],
[Number.MIN_VALUE, Number.MIN_VALUE],
[Number.MAX_VALUE, Number.MAX_VALUE],
[Infinity, Infinity],
[-Infinity, -Infinity]
].forEach(([n1, n2]) => {
expect(n1).toBeGreaterThanOrEqual(n2)
expect(n1).toBeLessThanOrEqual(n2)
})
})
it('test toBeInstanceOf', () => {
class A {}
class B {}
;[[new Map(), Map], [[], Array], [new A(), A]].forEach(([a, b]) => {
expect(a).toBeInstanceOf(b)
})
;[
['a', String],
[1, Number],
[true, Boolean],
[new A(), B],
[Object.create(null), A],
[undefined, String],
[null, String]
].forEach(([a, b]) => {
expect(a).not.toBeInstanceOf(b)
})
})
it('test toBeNull', () => {
;[{}, [], true, 1, 'a', 0.5, new Map(), () => {}, Infinity].forEach(v => {
expect(v).not.toBeNull()
})
expect(null).toBeNull()
})
it('test toBeNaN', () => {
;[NaN, Math.sqrt(-1), Infinity - Infinity, 0 / 0].forEach(v => {
expect(v).toBeNaN()
})
;[1, '', null, [], 0.2, 0, Infinity, -Infinity].forEach(v => {
expect(v).not.toBeNaN()
})
expect(undefined).not.toBeNaN()
expect({}).not.toBeNaN()
})
it('test toContain - toContainEqual', () => {
const typedArray = new Int8Array(2)
typedArray[0] = 0
typedArray[1] = 1
const iterable = {
*[Symbol.iterator]() {
yield 1
yield 2
yield 3
}
}
expect(iterable).toContain(2)
expect(iterable).toContainEqual(2)
;[
[[1, 2, 3, 4], 1],
[['a', 'b', 'c', 'd'], 'a'],
[[undefined, null], null],
[[undefined, null], undefined],
[[Symbol.for('a')], Symbol.for('a')],
['abcdef', 'abc'],
['11112111', '2'],
[new Set(['abc', 'def']), 'abc'],
[typedArray, 1]
].forEach(([list, v]) => {
expect(list).toContain(v)
})
;[
[[1, 2, 3], 4],
[[null, undefined], 1],
[[{}, []], []],
[[{}, []], {}]
].forEach(([list, v]) => {
expect(list).not.toContain(v)
})
;[
[[1, 2, 3, 4], 1],
[['a', 'b', 'c', 'd'], 'a'],
[[undefined, null], null],
[[undefined, null], undefined],
[[Symbol.for('a')], Symbol.for('a')],
[[{ a: 'b' }, { a: 'c' }], { a: 'b' }],
[new Set([1, 2, 3, 4]), 1],
[typedArray, 1]
].forEach(([list, v]) => {
expect(list).toContainEqual(v)
})
;[[[{ a: 'b' }, { a: 'c' }], { a: 'd' }]].forEach(([list, v]) => {
expect(list).not.toContainEqual(v)
})
})
it('test toEqual', () => {
;[
[true, false],
[1, 2],
[0, -0],
[0, Number.MIN_VALUE],
[Number.MIN_VALUE, 0],
[{ a: 5 }, { b: 6 }],
['banana', 'apple'],
[null, undefined],
[[1], [2]],
[[1, 2], [2, 1]],
[new Map(), new Set()],
[new Set([1, 2]), new Set()],
[new Set([1, 2]), new Set([1, 2, 3])],
[new Set([[1], [2]]), new Set([[1], [2], [3]])],
[new Set([[1], [2]]), new Set([[1], [2], [2]])],
[
new Set([new Set([1]), new Set([2])]),
new Set([new Set([1]), new Set([3])])
],
[new Map([[1, 'one'], [2, 'two']]), new Map([[1, 'one']])],
[new Map([['a', 0]]), new Map([['b', 0]])],
[new Map([['v', 1]]), new Map([['v', 2]])],
[new Map([[['v'], 1]]), new Map([[['v'], 2]])],
[
new Map([[[1], new Map([[[1], 'one']])]]),
new Map([[[1], new Map([[[1], 'two']])]])
],
[{ a: 1, b: 2 }, expect.objectContaining({ a: 2 })],
[false, expect.objectContaining({ a: 2 })],
[[1, 3], expect.arrayContaining([1, 2])],
[1, expect.arrayContaining([1, 2])],
['abd', expect.stringContaining('bc')],
['abd', expect.stringMatching(/bc/i)],
[undefined, expect.anything()],
[undefined, expect.any(Function)],
[
'Eve',
{
asymmetricMatch: function asymmetricMatch(who: string) {
return who === 'Alice' || who === 'Bob'
}
}
],
[
{
target: {
nodeType: 1,
value: 'a'
}
},
{
target: {
nodeType: 1,
value: 'b'
}
}
],
[
{
nodeName: 'div',
nodeType: 1
},
{
nodeName: 'p',
nodeType: 1
}
]
].forEach(([a, b]) => {
expect(a).not.toEqual(b)
})
;[
[true, true],
[1, 1],
[NaN, NaN],
// eslint-disable-next-line no-new-wrappers
[0, new Number(0)],
// eslint-disable-next-line no-new-wrappers
[new Number(0), 0],
['abc', 'abc'],
// eslint-disable-next-line no-new-wrappers
[new String('abc'), 'abc'],
// eslint-disable-next-line no-new-wrappers
['abc', new String('abc')],
[[1], [1]],
[[1, 2], [1, 2]],
[{}, {}],
[{ a: 99 }, { a: 99 }],
[new Set(), new Set()],
[new Set([1, 2]), new Set([1, 2])],
[new Set([1, 2]), new Set([2, 1])],
[new Set([[1], [2]]), new Set([[2], [1]])],
[
new Set([new Set([[1]]), new Set([[2]])]),
new Set([new Set([[2]]), new Set([[1]])])
],
[new Set([[1], [2], [3], [3]]), new Set([[3], [3], [2], [1]])],
[new Set([{ a: 1 }, { b: 2 }]), new Set([{ b: 2 }, { a: 1 }])],
[new Map(), new Map()],
[new Map([[1, 'one'], [2, 'two']]), new Map([[1, 'one'], [2, 'two']])],
[new Map([[1, 'one'], [2, 'two']]), new Map([[2, 'two'], [1, 'one']])],
[
new Map([[[1], 'one'], [[2], 'two'], [[3], 'three'], [[3], 'four']]),
new Map([[[3], 'three'], [[3], 'four'], [[2], 'two'], [[1], 'one']])
],
[
new Map([
[[1], new Map([[[1], 'one']])],
[[2], new Map([[[2], 'two']])]
]),
new Map([
[[2], new Map([[[2], 'two']])],
[[1], new Map([[[1], 'one']])]
])
],
[
new Map([[[1], 'one'], [[2], 'two']]),
new Map([[[2], 'two'], [[1], 'one']])
],
[
new Map([[{ a: 1 }, 'one'], [{ b: 2 }, 'two']]),
new Map([[{ b: 2 }, 'two'], [{ a: 1 }, 'one']])
],
[
new Map([[1, ['one']], [2, ['two']]]),
new Map([[2, ['two']], [1, ['one']]])
],
[{ a: 1, b: 2 }, expect.objectContaining({ a: 1 })],
[[1, 2, 3], expect.arrayContaining([2, 3])],
['abcd', expect.stringContaining('bc')],
['abcd', expect.stringMatching('bc')],
[true, expect.anything()],
[() => {}, expect.any(Function)],
[
{
a: 1,
b: function b() {},
c: true
},
{
a: 1,
b: expect.any(Function),
c: expect.anything()
}
],
[
'Alice',
{
asymmetricMatch: function asymmetricMatch(who: string) {
return who === 'Alice' || who === 'Bob'
}
}
],
[
{
nodeName: 'div',
nodeType: 1
},
{
nodeName: 'div',
nodeType: 1
}
]
].forEach(([a, b]) => {
expect(a).toEqual(b)
})
;(() => {
// symbol based keys in arrays are processed correctly
const mySymbol = Symbol('test')
const actual1: any = []
actual1[mySymbol] = 3
const actual2: any = []
actual2[mySymbol] = 4
const expected: any = []
expected[mySymbol] = 3
expect(actual1).toEqual(expected)
expect(actual2).not.toEqual(expected)
})()
;(() => {
// non-enumerable members should be skipped during equal
const actual3 = {
x: 3
}
Object.defineProperty(actual3, 'test', {
enumerable: false,
value: 5
})
expect(actual3).toEqual({ x: 3 })
})()
;(() => {
// non-enumerable symbolic members should be skipped during equal
const actual4 = {
x: 3
}
const mySymbol2 = Symbol('test')
Object.defineProperty(actual4, mySymbol2, {
enumerable: false,
value: 5
})
expect(actual4).toEqual({ x: 3 })
})()
// cyclic object equality
;(() => {
// properties with the same circularity are equal
const a: any = {}
a.x = a
const b: any = {}
b.x = b
const c: any = {}
c.x = a
const d: any = {}
d.x = b
expect(a).toEqual(b)
expect(b).toEqual(a)
expect(c).toEqual(d)
expect(d).toEqual(c)
})()
;(() => {
// properties with different circularity are not equal
const a: any = {}
a.x = { y: a }
const b: any = {}
const bx: any = {}
b.x = bx
bx.y = bx
const c: any = {}
c.x = a
const d: any = {}
d.x = b
expect(a).not.toEqual(b)
expect(b).not.toEqual(a)
expect(c).not.toEqual(d)
expect(d).not.toEqual(c)
})()
;(() => {
// are not equal if circularity is not on the same property
const a: any = {}
const b: any = {}
a.a = a
b.a = {}
b.a.a = a
const c: any = {}
c.x = { x: c }
const d: any = {}
d.x = d
expect(a).not.toEqual(b)
expect(b).not.toEqual(a)
expect(c).not.toEqual(d)
expect(d).not.toEqual(c)
})()
})
it('test toStrictEqual', () => {
class TestClassA {
a: any
b: any
constructor(a: any, b: any) {
this.a = a
this.b = b
}
}
class TestClassB {
a: any
b: any
constructor(a: any, b: any) {
this.a = a
this.b = b
}
}
/* eslint-disable no-useless-constructor */
const TestClassC = class Child extends TestClassA {
constructor(a: any, b: any) {
super(a, b)
}
}
const TestClassD = class Child extends TestClassB {
constructor(a: any, b: any) {
super(a, b)
}
}
/* eslint-enable */
// does not ignore keys with undefined values
expect({ a: undefined, b: 2 }).not.toStrictEqual({ b: 2 })
// passes when comparing same type
expect({
test: new TestClassA(1, 2)
}).toStrictEqual({ test: new TestClassA(1, 2) })
expect({ test: 2 }).not.toStrictEqual({ test: new TestClassA(1, 2) })
// does not pass for different types
expect({ test: new TestClassA(1, 2) }).not.toStrictEqual({
test: new TestClassB(1, 2)
})
// does not simply compare constructor names
const c = new TestClassC(1, 2)
const d = new TestClassD(1, 2)
expect(c.constructor.name).toEqual(d.constructor.name)
expect({ test: c }).not.toStrictEqual({ test: d })
/* eslint-disable no-sparse-arrays */
// passes for matching sparse arrays
expect([, 1]).toStrictEqual([, 1])
// does not pass when sparseness of arrays do not match
expect([, 1]).not.toStrictEqual([undefined, 1])
expect([undefined, 1]).not.toStrictEqual([, 1])
expect([, , , 1]).not.toStrictEqual([, 1])
// does not pass when equally sparse arrays have different values
expect([, 1]).not.toStrictEqual([, 2])
/* eslint-enable */
})
it('test toHaveLength', () => {
;[[[1, 2], 2], [[], 0], [['a', 'b'], 2], ['abc', 3], ['', 0]].forEach(
([received, length]) => {
expect(received).toHaveLength(length)
}
)
;[[[1, 2], 3], [[], 1], [['a', 'b'], 99], ['abc', 66], ['', 1]].forEach(
([received, length]) => {
expect(received).not.toHaveLength(length)
}
)
})
it('test toMatch', () => {
;[['foo', 'foo'], ['Foo bar', /^foo/i]].forEach(([n1, n2]) => {
expect(n1).toMatch(n2)
})
;[['bar', 'foo'], ['bar', /foo/]].forEach(([n1, n2]) => {
expect(n1).not.toMatch(n2)
})
// escape string
expect('this?: throws').toMatch('this?: throws')
})
it('toMatchObject', () => {
class Foo {
get a() {
return undefined
}
get b() {
return 'b'
}
}
;[
[{ a: 'b', c: 'd' }, { a: 'b' }],
[{ a: 'b', c: 'd' }, { a: 'b', c: 'd' }],
[{ a: 'b', t: { x: { r: 'r' }, z: 'z' } }, { a: 'b', t: { z: 'z' } }],
[{ a: 'b', t: { x: { r: 'r' }, z: 'z' } }, { t: { x: { r: 'r' } } }],
[{ a: [3, 4, 5], b: 'b' }, { a: [3, 4, 5] }],
[{ a: [3, 4, 5, 'v'], b: 'b' }, { a: [3, 4, 5, 'v'] }],
[{ a: 1, c: 2 }, { a: expect.any(Number) }],
[{ a: { x: 'x', y: 'y' } }, { a: { x: expect.any(String) } }],
[new Set([1, 2]), new Set([1, 2])],
[new Set([1, 2]), new Set([2, 1])],
[new Date('2015-11-30'), new Date('2015-11-30')],
[{ a: new Date('2015-11-30'), b: 'b' }, { a: new Date('2015-11-30') }],
[{ a: null, b: 'b' }, { a: null }],
[{ a: undefined, b: 'b' }, { a: undefined }],
[{ a: [{ a: 'a', b: 'b' }] }, { a: [{ a: 'a' }] }],
[[1, 2], [1, 2]],
[{ a: undefined }, { a: undefined }],
[[], []],
[new Error('foo'), new Error('foo')],
[new Error('bar'), { message: 'bar' }],
[new Foo(), { a: undefined, b: 'b' }],
[Object.assign(Object.create(null), { a: 'b' }), { a: 'b' }]
].forEach(([n1, n2]) => {
expect(n1).toMatchObject(n2)
})
;[
[{ a: 'b', c: 'd' }, { e: 'b' }],
[{ a: 'b', c: 'd' }, { a: 'b!', c: 'd' }],
[{ a: 'a', c: 'd' }, { a: expect.any(Number) }],
[{ a: 'b', t: { x: { r: 'r' }, z: 'z' } }, { a: 'b', t: { z: [3] } }],
[{ a: 'b', t: { x: { r: 'r' }, z: 'z' } }, { t: { l: { r: 'r' } } }],
[{ a: [3, 4, 5], b: 'b' }, { a: [3, 4, 5, 6] }],
[{ a: [3, 4, 5], b: 'b' }, { a: [3, 4] }],
[{ a: [3, 4, 'v'], b: 'b' }, { a: ['v'] }],
[{ a: [3, 4, 5], b: 'b' }, { a: { b: 4 } }],
[{ a: [3, 4, 5], b: 'b' }, { a: { b: expect.any(String) } }],
[[1, 2], [1, 3]],
[[0], [-0]],
[new Set([1, 2]), new Set([2])],
[new Date('2015-11-30'), new Date('2015-10-10')],
[{ a: new Date('2015-11-30'), b: 'b' }, { a: new Date('2015-10-10') }],
[{ a: null, b: 'b' }, { a: '4' }],
[{ a: null, b: 'b' }, { a: undefined }],
[{ a: undefined }, { a: null }],
[{ a: [{ a: 'a', b: 'b' }] }, { a: [{ a: 'c' }] }],
[{ a: 1, b: 1, c: 1, d: { e: { f: 555 } } }, { d: { e: { f: 222 } } }],
[{}, { a: undefined }],
[[1, 2, 3], [2, 3, 1]],
[[1, 2, 3], [1, 2, 2]],
[new Error('foo'), new Error('bar')],
[Object.assign(Object.create(null), { a: 'b' }), { c: 'd' }]
].forEach(([n1, n2]) => {
expect(n1).not.toMatchObject(n2)
})
})
it('test toHaveProperty', () => {
class Foo {
val: any
get a() {
return undefined
}
get b() {
return 'b'
}
set setter(val: any) {
this.val = val
}
}
class Foo2 extends Foo {
get c() {
return 'c'
}
}
const foo2 = new Foo2()
foo2.setter = true
function E(this: any, nodeName: any) {
this.nodeName = nodeName.toUpperCase()
}
E.prototype.nodeType = 1
const memoized: any = function() {}
memoized.memo = []
;[
[{ a: { b: { c: { d: 1 } } } }, 'a.b.c.d', 1],
[{ a: { b: { c: { d: 1 } } } }, ['a', 'b', 'c', 'd'], 1],
[{ 'a.b.c.d': 1 }, ['a.b.c.d'], 1],
[{ a: { b: [1, 2, 3] } }, ['a', 'b', 1], 2],
[{ a: 0 }, 'a', 0],
[{ a: { b: undefined } }, 'a.b', undefined],
[{ a: { b: { c: 5 } } }, 'a.b', { c: 5 }],
[Object.assign(Object.create(null), { property: 1 }), 'property', 1],
[new Foo(), 'a', undefined],
[new Foo(), 'b', 'b'],
[new Foo(), 'setter', undefined],
[foo2, 'a', undefined],
[foo2, 'c', 'c'],
[foo2, 'val', true],
['', 'length', 0],
[memoized, 'memo', []]
].forEach(([obj, keyPath, value]) => {
expect(obj).toHaveProperty(keyPath, value)
})
;[
[{ a: { b: { c: { d: 1 } } } }, 'a.b.ttt.d', 1],
[{ a: { b: { c: { d: 1 } } } }, 'a.b.c.d', 2],
[{ 'a.b.c.d': 1 }, 'a.b.c.d', 2],
[{ 'a.b.c.d': 1 }, ['a.b.c.d'], 2],
[{ a: { b: { c: { d: 1 } } } }, ['a', 'b', 'c', 'd'], 2],
[{ a: { b: { c: {} } } }, 'a.b.c.d', 1],
[{ a: 1 }, 'a.b.c.d', 5],
[{}, 'a', 'test'],
[{ a: { b: 3 } }, 'a.b', undefined],
[1, 'a.b.c', 'test'],
['abc', 'a.b.c', { a: 5 }],
[{ a: { b: { c: 5 } } }, 'a.b', { c: 4 }],
[new Foo(), 'a', 'a'],
[new Foo(), 'b', undefined]
].forEach(([obj, keyPath, value]) => {
expect(obj).not.toHaveProperty(keyPath, value)
})
;[
[{ a: { b: { c: { d: 1 } } } }, 'a.b.c.d'],
[{ a: { b: { c: { d: 1 } } } }, ['a', 'b', 'c', 'd']],
[{ 'a.b.c.d': 1 }, ['a.b.c.d']],
[{ a: { b: [1, 2, 3] } }, ['a', 'b', 1]],
[{ a: 0 }, 'a'],
[{ a: { b: undefined } }, 'a.b']
].forEach(([obj, keyPath]) => {
expect(obj).toHaveProperty(keyPath)
})
;[
[{ a: { b: { c: {} } } }, 'a.b.c.d'],
[{ a: 1 }, 'a.b.c.d'],
[{}, 'a'],
[1, 'a.b.c'],
['abc', 'a.b.c'],
[false, 'key'],
[0, 'key'],
['', 'key'],
// eslint-disable-next-line symbol-description
[Symbol(), 'key'],
[Object.assign(Object.create(null), { key: 1 }), 'not']
].forEach(([obj, keyPath]) => {
expect(obj).not.toHaveProperty(keyPath)
})
})
it('test toThrow', () => {
expect(() => {
throw new TypeError('error')
}).toThrow('error')
expect(() => {
throw new TypeError('error')
}).toThrow(/error/)
expect(() => {
throw new TypeError('error')
}).toThrow(TypeError)
expect(() => {
throw new TypeError('error')
}).toThrow(Error)
expect(() => {
throw new TypeError('error')
}).toThrow(new TypeError('error'))
})
it('Listing jest stub and spy syntax here', () => {
const spy = cy.spy((...args) => args)
const fn = (spy: any) => {
spy('abc')
}
const fn2 = (spy: any) => {
spy('def', 123)
}
fn(spy)
expect(spy).toHaveBeenCalled()
fn(spy) // 2nd call
expect(spy).toHaveBeenCalledTimes(2)
fn(spy)
expect(spy).toHaveBeenCalledWith('abc')
fn2(spy) // 4th call
expect(spy).toHaveBeenLastCalledWith('def', 123)
expect(spy).toHaveBeenNthCalledWith(2, 'abc') // check 2nd call
expect(spy).toHaveBeenNthCalledWith(4, 'def', 123) // check 4th call
expect(spy).toHaveReturned()
expect(spy).toHaveReturnedTimes(4)
fn(spy) // 5th call
expect(spy).toHaveReturnedWith(['abc'])
fn2(spy) // 6th call
expect(spy).toHaveLastReturnedWith(['def', 123])
expect(spy).toHaveNthReturnedWith(5, ['abc']) // 5th call
})
it('Extends expect', () => {
const spy = cy.spy((...args) => args)
const fn = (spy: any) => {
spy('abc')
}
fn(spy)
expect(spy).toHaveBeenCalledWith(expect.anything())
expect(spy).toHaveBeenCalledWith(expect.any(String))
expect('abc').toEqual(expect.anything())
expect('abc').toEqual(expect.any(String))
const expected = ['Alice', 'Bob']
expect(['Alice', 'Bob', 'Eve']).toEqual(expect.arrayContaining(expected))
expect(['Bob', 'Eve']).not.toEqual(expect.arrayContaining(expected))
expect({ x: 3, y: 5 }).toEqual(
expect.objectContaining({
x: expect.any(Number),
y: expect.any(Number)
})
)
expect('qwerty').toEqual(expect.stringContaining('ty'))
expect('qwerty').not.toEqual(expect.stringContaining('abc'))
const expected2 = [
expect.stringMatching(/^Alic/),
expect.stringMatching(/^[BR]ob/)
]
expect(['Alicia', 'Roberto', 'Evelina']).toEqual(
expect.arrayContaining(expected2)
)
expect(['Roberto', 'Evelina']).not.toEqual(
expect.arrayContaining(expected2)
)
expect('abc').toEqual(expect.not.stringMatching(/dev/))
expect([{ foo: 'bar' }, { baz: 1 }]).toMatchObject([
expect.objectContaining({ foo: 'bar' }),
expect.objectContaining({ baz: 1 })
])
})
it('resolves', async () => {
await expect(Promise.resolve('abc')).resolves.toEqual('abc')
await expect(Promise.resolve('lemon')).resolves.not.toBe('octopus')
})
it('rejects', async () => {
await expect(Promise.reject(new Error('abc'))).rejects.toThrow('abc')
await expect(Promise.reject(new Error('abc'))).rejects.not.toEqual(
new Error('abcd')
)
})
}) | the_stack |
import React from 'react';
import createClass from 'create-react-class';
import { LineChart, Legend, chartConstants, formatters } from './../../index';
import _ from 'lodash';
import Resizer from '../Resizer/Resizer';
import Button from '../Button/Button';
export default {
title: 'Visualizations/LineChart',
component: LineChart,
parameters: {
docs: {
description: {
component: (LineChart as any).peek.description,
},
},
},
};
/* Default */
export const Default = () => {
const data = [
{ x: new Date('2015-01-01T00:00:00-08:00'), y: 1 },
{ x: new Date('2015-01-02T00:00:00-08:00'), y: 0 },
{ x: new Date('2015-01-03T00:00:00-08:00'), y: 3 },
{ x: new Date('2015-01-04T00:00:00-08:00'), y: 5 },
];
const style = {
paddingTop: '4rem',
};
const Component = createClass({
render() {
return (
<div style={style}>
<LineChart data={data} width={800} />
</div>
);
},
});
return <Component />;
};
Default.storyName = 'Default';
/* Responsive */
export const Responsive = () => {
const data = [
{ x: new Date('2015-01-01T00:00:00-08:00'), y: 1 },
{ x: new Date('2015-01-02T00:00:00-08:00'), y: 2 },
{ x: new Date('2015-01-03T00:00:00-08:00'), y: 3 },
{ x: new Date('2015-01-04T00:00:00-08:00'), y: 5 },
];
const style = {
paddingTop: '4rem',
};
const Component = createClass({
render() {
return (
<div style={style}>
<Resizer>
{(width /*, height */) => (
<LineChart width={width} height={width * 0.3} data={data} />
)}
</Resizer>
</div>
);
},
});
return <Component />;
};
Responsive.storyName = 'Responsive';
/* Multi */
export const Multi = () => {
const data = [
{
x: new Date('2015-01-01T00:00:00-08:00'),
apples: 184,
oranges: 142,
pears: 117,
},
{
x: new Date('2015-01-02T00:00:00-08:00'),
apples: 191,
oranges: 145,
pears: 118,
},
{
x: new Date('2015-01-03T00:00:00-08:00'),
apples: 114,
oranges: 107,
pears: 103,
},
{
x: new Date('2015-01-04T00:00:00-08:00'),
apples: 24,
oranges: 62,
pears: 85,
},
{
x: new Date('2015-01-05T00:00:00-08:00'),
apples: 4,
oranges: 52,
pears: 81,
},
{
x: new Date('2015-01-06T00:00:00-08:00'),
apples: 72,
oranges: 86,
pears: 94,
},
{
x: new Date('2015-01-07T00:00:00-08:00'),
apples: 166,
oranges: 133,
pears: 113,
},
{
x: new Date('2015-01-08T00:00:00-08:00'),
apples: 199,
oranges: 149,
pears: 120,
},
{
x: new Date('2015-01-09T00:00:00-08:00'),
apples: 141,
oranges: 121,
pears: 108,
},
{
x: new Date('2015-01-10T00:00:00-08:00'),
apples: 46,
oranges: 73,
pears: 89,
},
{
x: new Date('2015-01-11T00:00:00-08:00'),
apples: 0,
oranges: 50,
pears: 80,
},
{
x: new Date('2015-01-12T00:00:00-08:00'),
apples: 46,
oranges: 73,
pears: 89,
},
{
x: new Date('2015-01-13T00:00:00-08:00'),
apples: 142,
oranges: 121,
pears: 108,
},
{
x: new Date('2015-01-14T00:00:00-08:00'),
apples: 199,
oranges: 150,
pears: 120,
},
{
x: new Date('2015-01-15T00:00:00-08:00'),
apples: 165,
oranges: 133,
pears: 113,
},
{
x: new Date('2015-01-16T00:00:00-08:00'),
apples: 71,
oranges: 86,
pears: 94,
},
{
x: new Date('2015-01-17T00:00:00-08:00'),
apples: 4,
oranges: 52,
pears: 81,
},
{
x: new Date('2015-01-18T00:00:00-08:00'),
apples: 25,
oranges: 62,
pears: 85,
},
{
x: new Date('2015-01-19T00:00:00-08:00'),
apples: 115,
oranges: 107,
pears: 103,
},
{
x: new Date('2015-01-20T00:00:00-08:00'),
apples: 191,
oranges: 146,
pears: 118,
},
{
x: new Date('2015-01-21T00:00:00-08:00'),
apples: 184,
oranges: 142,
pears: 117,
},
{
x: new Date('2015-01-22T00:00:00-08:00'),
apples: 99,
oranges: 100,
pears: 100,
},
{
x: new Date('2015-01-23T00:00:00-08:00'),
apples: 15,
oranges: 58,
pears: 83,
},
{
x: new Date('2015-01-24T00:00:00-08:00'),
apples: 9,
oranges: 55,
pears: 82,
},
{
x: new Date('2015-01-25T00:00:00-08:00'),
apples: 87,
oranges: 93,
pears: 97,
},
{
x: new Date('2015-01-26T00:00:00-08:00'),
apples: 176,
oranges: 138,
pears: 115,
},
{
x: new Date('2015-01-27T00:00:00-08:00'),
apples: 196,
oranges: 148,
pears: 119,
},
{
x: new Date('2015-01-28T00:00:00-08:00'),
apples: 127,
oranges: 114,
pears: 105,
},
{
x: new Date('2015-01-29T00:00:00-08:00'),
apples: 3,
oranges: 67,
pears: 87,
},
];
const style = {
paddingTop: '8rem',
};
const Component = createClass({
render() {
return (
<div style={style}>
<LineChart
data={data}
yAxisFields={['apples', 'oranges', 'pears']}
yAxisTitle='Fruit Count'
width={800}
/>
</div>
);
},
});
return <Component />;
};
Multi.storyName = 'Multi';
/* Multi With Legend */
export const MultiWithLegend = () => {
const data = [
{
x: new Date('2015-01-01T00:00:00-08:00'),
apples: 2,
oranges: 3,
pears: 1,
},
{
x: new Date('2015-01-02T00:00:00-08:00'),
apples: 2,
oranges: 5,
pears: 6,
},
{
x: new Date('2015-01-03T00:00:00-08:00'),
apples: 3,
oranges: 2,
pears: 4,
},
{
x: new Date('2015-01-04T00:00:00-08:00'),
apples: 5,
oranges: 6,
pears: 1,
},
];
const yAxisFields = ['apples', 'oranges', 'pears'];
const palette = chartConstants.PALETTE_MONOCHROME_2_5;
const style = {
paddingTop: '8rem',
};
const Component = createClass({
render() {
return (
<div style={style}>
<LineChart
data={data}
yAxisFields={yAxisFields}
yAxisTitle='Fruit Count'
palette={palette}
width={800}
/>
<Legend style={{ verticalAlign: 'top' }}>
{_.map(yAxisFields, (field, i) => (
<Legend.Item
key={field}
hasPoint
hasLine
color={palette[i % palette.length]}
pointKind={i}
>
{field}
</Legend.Item>
))}
</Legend>
</div>
);
},
});
return <Component />;
};
MultiWithLegend.storyName = 'MultiWithLegend';
/* Stacked */
export const Stacked = () => {
const data = [
{
x: new Date('2015-01-01T00:00:00-08:00'),
apples: 2,
oranges: 3,
pears: 1,
bananas: 7,
kiwis: 5,
cherries: 3,
},
{
x: new Date('2015-01-02T00:00:00-08:00'),
apples: 2,
oranges: 5,
pears: 6,
bananas: 7,
kiwis: 5,
cherries: 5,
},
{
x: new Date('2015-01-03T00:00:00-08:00'),
apples: 3,
oranges: 2,
pears: 4,
bananas: 7,
kiwis: 5,
cherries: 2,
},
{
x: new Date('2015-01-04T00:00:00-08:00'),
apples: 5,
oranges: 6,
pears: 1,
bananas: 7,
kiwis: 5,
cherries: 1,
},
{
x: new Date('2015-01-05T00:00:00-08:00'),
apples: 4,
oranges: 3,
pears: 2,
bananas: 7,
kiwis: 5,
cherries: 3,
},
{
x: new Date('2015-01-06T00:00:00-08:00'),
apples: 3,
oranges: 4,
pears: 4,
bananas: 7,
kiwis: 5,
cherries: 5,
},
];
const style = {
paddingTop: '11rem',
};
const Component = createClass({
render() {
return (
<div style={style}>
<LineChart
data={data}
yAxisFields={[
'apples',
'oranges',
'pears',
'bananas',
'kiwis',
'cherries',
]}
yAxisIsStacked={true}
yAxisTitle='Fruit Count'
width={800}
/>
</div>
);
},
});
return <Component />;
};
Stacked.storyName = 'Stacked';
/* Dual Axis */
export const DualAxis = () => {
const data = [
{ x: new Date('2015-01-01T00:00:00-08:00'), bananas: 2, cherries: 8 },
{ x: new Date('2015-03-02T00:00:00-08:00'), bananas: 2, cherries: 5 },
{ x: new Date('2015-05-03T00:00:00-08:00'), bananas: 3, cherries: 5 },
{ x: new Date('2015-07-04T00:00:00-08:00'), bananas: 5, cherries: 6 },
];
const style = {
paddingTop: '5rem',
};
const Component = createClass({
render() {
return (
<div style={style}>
<LineChart
data={data}
margin={{
right: 80,
}}
width={800}
colorMap={{
bananas: chartConstants.COLOR_4,
cherries: chartConstants.COLOR_2,
}}
yAxisFields={['bananas']}
yAxisTitle='Number of Bananas'
yAxisTitleColor={chartConstants.COLOR_4}
y2AxisFields={['cherries']}
y2AxisTitle='Number of Cherries'
y2AxisTitleColor={chartConstants.COLOR_2}
/>
</div>
);
},
});
return <Component />;
};
DualAxis.storyName = 'DualAxis';
/* All The Things */
export const AllTheThings = () => {
const data = [
{
date: new Date('2015-01-01T00:00:00-08:00'),
blueberries: 2000,
oranges: 3000,
},
{
date: new Date('2015-01-02T00:00:00-08:00'),
blueberries: 2000,
oranges: 5000,
},
{
date: new Date('2015-01-03T00:00:00-08:00'),
blueberries: 3000,
oranges: 2000,
},
{ date: new Date('2015-01-04T00:00:00-08:00'), blueberries: 5000 },
{
date: new Date('2015-01-05T00:00:00-08:00'),
blueberries: 2500,
oranges: 6300,
},
{
date: new Date('2015-01-06T00:00:00-08:00'),
blueberries: 1500,
oranges: 6100,
},
];
const yFormatter = (d: number) => `${d / 1000}k`;
const xFormatter = (d: Date) => `${d.getMonth() + 1}-${d.getDate()}`;
const style = {
paddingTop: '5rem',
};
const Component = createClass({
render() {
return (
<div style={style}>
<LineChart
margin={{
right: 80,
}}
width={800}
data={data}
colorMap={{
blueberries: chartConstants.COLOR_0,
oranges: chartConstants.COLOR_1,
}}
xAxisField='date'
xAxisFormatter={xFormatter}
xAxisMin={new Date('2014-12-31T00:00-08:00')}
xAxisMax={new Date('2015-01-07T00:00-08:00')}
xAxisTickCount={5}
xAxisTitle='Date'
yAxisFields={['blueberries']}
yAxisFormatter={yFormatter}
yAxisTickCount={5}
yAxisTitle='Number of Blueberries'
yAxisTitleColor={chartConstants.COLOR_0}
y2AxisFields={['oranges']}
y2AxisFormatter={yFormatter}
y2AxisTickCount={5}
y2AxisTitle='Number of Oranges'
y2AxisHasPoints={false}
y2AxisTitleColor={chartConstants.COLOR_1}
/>
</div>
);
},
});
return <Component />;
};
AllTheThings.storyName = 'AllTheThings';
/* Stacked Single Series With Formatters */
export const StackedSingleSeriesWithFormatters = () => {
const data = [
{ x: new Date('2015-01-01T00:00:00-08:00'), y: 1.55 },
{ x: new Date('2015-01-02T00:00:00-08:00'), y: 2.67 },
{ x: new Date('2015-01-03T00:00:00-08:00'), y: 3.31 },
{ x: new Date('2015-01-04T00:00:00-08:00'), y: 5.99 },
];
const style = {
paddingTop: '4rem',
};
const Component = createClass({
render() {
return (
<div style={style}>
<LineChart
yAxisIsStacked
yAxisFormatter={(yValue) => `$ ${yValue}`}
yAxisTooltipFormatter={(yField, yValueFormatted) => yValueFormatted}
data={data}
width={800}
/>
</div>
);
},
});
return <Component />;
};
StackedSingleSeriesWithFormatters.storyName =
'StackedSingleSeriesWithFormatters';
/* Stacked Monochrome No Shapes */
export const StackedMonochromeNoShapes = () => {
const data = [
{
x: new Date('2015-01-01T00:00:00-08:00'),
apples: 2,
oranges: 3,
pears: 1,
bananas: 7,
kiwis: 5,
},
{
x: new Date('2015-01-02T00:00:00-08:00'),
apples: 2,
oranges: 5,
pears: 6,
bananas: 7,
kiwis: 5,
},
{
x: new Date('2015-01-03T00:00:00-08:00'),
apples: 3,
oranges: 2,
pears: 4,
bananas: 7,
kiwis: 5,
},
{
x: new Date('2015-01-04T00:00:00-08:00'),
apples: 5,
oranges: 6,
pears: 1,
bananas: 7,
kiwis: 5,
},
{
x: new Date('2015-01-05T00:00:00-08:00'),
apples: 4,
oranges: 3,
pears: 2,
bananas: 7,
kiwis: 5,
},
{
x: new Date('2015-01-06T00:00:00-08:00'),
apples: 3,
oranges: 4,
pears: 4,
bananas: 7,
kiwis: 5,
},
];
const style = {
paddingTop: '10rem',
};
const Component = createClass({
render() {
return (
<div style={style}>
<LineChart
data={data}
width={800}
yAxisFields={['apples', 'oranges', 'pears', 'bananas', 'kiwis']}
yAxisIsStacked={true}
yAxisHasPoints={false}
yAxisTitle='Fruit Count'
palette={chartConstants.PALETTE_MONOCHROME_0_5}
/>
</div>
);
},
});
return <Component />;
};
StackedMonochromeNoShapes.storyName = 'StackedMonochromeNoShapes';
/* Abbreviated Numbers */
export const AbbreviatedNumbers = () => {
const data = [
{ x: new Date('2015-01-07T00:00:00-08:00'), blueberries: 1030872156 },
{ x: new Date('2015-01-08T00:00:00-08:00'), blueberries: 4002156 },
{ x: new Date('2015-01-09T00:00:00-08:00'), blueberries: 214872156 },
{ x: new Date('2015-01-10T00:00:00-08:00'), blueberries: 42872156 },
{ x: new Date('2015-01-11T00:00:00-08:00'), blueberries: 4230872156 },
];
const style = {
paddingTop: '4rem',
};
const Component = createClass({
render() {
return (
<div style={style}>
<LineChart
data={data}
width={800}
yAxisFields={['blueberries']}
yAxisFormatter={formatters.formatAbbreviatedNumber}
yAxisTooltipDataFormatter={formatters.formatThousands}
/>
</div>
);
},
});
return <Component />;
};
AbbreviatedNumbers.storyName = 'AbbreviatedNumbers';
/* Color Offset */
export const ColorOffset = () => {
const data = [
{ x: new Date('2015-01-01T00:00:00-08:00'), apples: 184, pears: 117 },
{ x: new Date('2015-01-02T00:00:00-08:00'), apples: 191, pears: 118 },
{ x: new Date('2015-01-03T00:00:00-08:00'), apples: 114, pears: 103 },
{ x: new Date('2015-01-04T00:00:00-08:00'), apples: 24, pears: 85 },
{ x: new Date('2015-01-05T00:00:00-08:00'), apples: 4, pears: 81 },
{ x: new Date('2015-01-06T00:00:00-08:00'), apples: 72, pears: 94 },
{ x: new Date('2015-01-07T00:00:00-08:00'), apples: 166, pears: 113 },
{ x: new Date('2015-01-08T00:00:00-08:00'), apples: 199, pears: 120 },
{ x: new Date('2015-01-09T00:00:00-08:00'), apples: 141, pears: 108 },
{ x: new Date('2015-01-10T00:00:00-08:00'), apples: 46, pears: 89 },
{ x: new Date('2015-01-11T00:00:00-08:00'), apples: 0, pears: 80 },
{ x: new Date('2015-01-12T00:00:00-08:00'), apples: 46, pears: 89 },
{ x: new Date('2015-01-13T00:00:00-08:00'), apples: 142, pears: 108 },
{ x: new Date('2015-01-14T00:00:00-08:00'), apples: 199, pears: 120 },
{ x: new Date('2015-01-15T00:00:00-08:00'), apples: 165, pears: 113 },
];
const style = {
paddingTop: '5rem',
};
const Component = createClass({
render() {
return (
<div style={style}>
<LineChart
data={data}
margin={{
right: 80,
}}
width={800}
hasLegend
yAxisFields={['apples']}
yAxisColorOffset={3}
y2AxisFields={['pears']}
y2AxisColorOffset={4}
/>
</div>
);
},
});
return <Component />;
};
ColorOffset.storyName = 'ColorOffset';
/* Empty */
export const Empty = () => {
const Component = createClass({
render() {
return <LineChart data={[]} yAxisFields={['blueberries']} width={800} />;
},
});
return <Component />;
};
Empty.storyName = 'Empty';
/* Empty With Custom Title And Body */
export const EmptyWithCustomTitleAndBody = () => {
const {
EmptyStateWrapper,
EmptyStateWrapper: { Title, Body },
} = LineChart;
const Component = createClass({
render() {
return (
<LineChart data={[]} yAxisFields={['blueberries']} width={800}>
<EmptyStateWrapper>
<Title>Something went wrong.</Title>
<Body
style={{
fontSize: '12px',
}}
>
Echo park poutine esse tempor squid do. Lo-fi ramps XOXO
chicharrones laboris, portland fugiat locavore. Fap four dollar
toast keytar, cronut kogi fingerstache distillery microdosing
everyday carry austin DIY dreamcatcher. Distillery flexitarian
meditation laboris roof party. Cred raclette gastropub tilde
PBR&B. Shoreditch poke adipisicing, reprehenderit lumbersexual
succulents mustache officia franzen vinyl nostrud af. Hashtag
bitters organic, before they sold out butcher cronut sapiente.
</Body>
</EmptyStateWrapper>
</LineChart>
);
},
});
return <Component />;
};
EmptyWithCustomTitleAndBody.storyName = 'EmptyWithCustomTitleAndBody';
/* Empty With Button */
export const EmptyWithButton = () => {
const {
EmptyStateWrapper,
EmptyStateWrapper: { Title, Body },
} = LineChart;
const Component = createClass({
render() {
return (
<LineChart data={[]} yAxisFields={['blueberries']} width={800}>
<EmptyStateWrapper>
<Title>Something went wrong.</Title>
<Body
style={{
fontSize: '12px',
}}
>
<Button>Action</Button>
</Body>
</EmptyStateWrapper>
</LineChart>
);
},
});
return <Component />;
};
EmptyWithButton.storyName = 'EmptyWithButton';
/* Loading */
export const Loading = () => {
const Component = createClass({
render() {
return <LineChart data={[]} width={800} isLoading />;
},
});
return <Component />;
};
Loading.storyName = 'Loading';
/* Fine Grained Ticks */
export const FineGrainedTicks = () => {
const data = [
{ x: new Date('2018-01-01T00:00:00-0800'), y: 1 },
{ x: new Date('2018-01-02T00:00:00-0800'), y: 2 },
{ x: new Date('2018-01-03T00:00:00-0800'), y: 3 },
];
const style = {
paddingTop: '5rem',
};
const Component = createClass({
render() {
return (
<div style={style}>
<LineChart
data={data}
width={800}
xAxisTicks={_.map(data, 'x')}
xAxisFormatter={(date) => date.toLocaleDateString()}
/>
</div>
);
},
});
return <Component />;
};
FineGrainedTicks.storyName = 'FineGrainedTicks'; | the_stack |
import Conditions from '../../../../../resources/conditions';
import NetRegexes from '../../../../../resources/netregexes';
import Outputs from '../../../../../resources/outputs';
import { Responses } from '../../../../../resources/responses';
import ZoneId from '../../../../../resources/zone_id';
import { RaidbossData } from '../../../../../types/data';
import { TriggerSet } from '../../../../../types/trigger';
// TODO: Does Mustard Bomb cleave? Should it be tankCleave() instead?
export interface Data extends RaidbossData {
lastBoss: boolean;
}
const limitCutNumberMap: { [id: string]: number } = {
'004F': 1,
'0050': 2,
'0051': 3,
'0052': 4,
};
const triggerSet: TriggerSet<Data> = {
zoneId: ZoneId.TheStigmaDreamscape,
timelineFile: 'stigma_dreamscape.txt',
initData: () => {
return {
lastBoss: false,
};
},
triggers: [
{
id: 'Dreamscape Side Cannons Left',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '6320', source: 'Proto-Omega', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '6320', source: 'Proto-Omega', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '6320', source: 'Proto-Oméga', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '6320', source: 'プロトオメガ', capture: false }),
response: Responses.goLeft(),
},
{
id: 'Dreamscape Side Cannons Right',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '6321', source: 'Proto-Omega', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '6321', source: 'Proto-Omega', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '6321', source: 'Proto-Oméga', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '6321', source: 'プロトオメガ', capture: false }),
response: Responses.goRight(),
},
{
id: 'Dreamscape Forward Interceptors',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '6322', source: 'Proto-Omega', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '6322', source: 'Proto-Omega', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '6322', source: 'Proto-Oméga', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '6322', source: 'プロトオメガ', capture: false }),
response: Responses.getBehind(),
},
{
id: 'Dreamscape Rear Interceptors',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '6324', source: 'Proto-Omega', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '6324', source: 'Proto-Omega', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '6324', source: 'Proto-Oméga', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '6324', source: 'プロトオメガ', capture: false }),
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Go front of boss',
de: 'Geh vor den Boss',
fr: 'Allez devant le boss',
ko: '보스 앞으로',
},
},
},
{
id: 'Dreamscape Chemical Missile',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '008B' }),
condition: Conditions.targetIsYou(),
response: Responses.spread(),
},
{
id: 'Dreamscape Electric Slide',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: '0121' }),
infoText: (data, matches, output) => {
if (data.me === matches.target)
return output.target!();
return output.allies!({ target: matches.target });
},
outputStrings: {
target: {
en: 'Stack + Knockback on YOU!',
de: 'Sammeln + Rückstoß auf DIR!',
fr: 'Package + Poussée sur VOUS !',
ko: '나에게 쉐어 + 넉백!',
},
allies: {
en: 'Stack + knockback on ${target}',
de: 'Sammeln + Rückstoß auf ${target}',
fr: 'Package + Poussée sur ${target}',
ko: '${target} 쉐어 + 넉백',
},
},
},
{
id: 'Dreamscape Guided Missile',
type: 'Tether',
netRegex: NetRegexes.tether({ id: '0011' }),
condition: Conditions.targetIsYou(),
alertText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Guided Missile on YOU',
de: 'Geführte Rakete auf DIR',
fr: 'Missile guidé sur VOUS',
ko: '나에게 유도 미사일',
},
},
},
{
id: 'Dreamscape Mustard Bomb',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '632B', source: 'Proto-Omega' }),
netRegexDe: NetRegexes.startsUsing({ id: '632B', source: 'Proto-Omega' }),
netRegexFr: NetRegexes.startsUsing({ id: '632B', source: 'Proto-Oméga' }),
netRegexJa: NetRegexes.startsUsing({ id: '632B', source: 'プロトオメガ' }),
response: Responses.tankBuster(),
},
{
id: 'Dreamscape Assault Cannon',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '63AB', source: 'Arch-Lambda', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '63AB', source: 'Erz-Lambda', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '63AB', source: 'Arch-Lambda', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '63AB', source: 'アーチラムダ', capture: false }),
alertText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Get to wall at last dash',
de: 'Geh zur Wand des letzten Ansturms',
fr: 'Allez vers le mur après la dernière ruée',
ko: '마지막 돌진지점 쪽 벽 끝으로',
},
},
},
{
id: 'Dreamscape Sniper Cannon',
type: 'HeadMarker',
netRegex: NetRegexes.headMarker({ id: ['004F', '0050', '0051', '0052'] }),
condition: Conditions.targetIsYou(),
alertText: (_data, matches, output) => {
const limitCutNumber = limitCutNumberMap[matches.id];
return output.text!({ num: limitCutNumber });
},
outputStrings: {
text: {
en: '#${num} laser on YOU!',
de: '#${num} Laser auf DIR!',
fr: '#${num} Laser sur VOUS !',
ko: '나에게 ${num}번 레이저!',
},
},
},
{
id: 'Dreamscape Wheel',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '63B5', source: 'Arch-Lambda' }),
netRegexDe: NetRegexes.startsUsing({ id: '63B5', source: 'Erz-Lambda' }),
netRegexFr: NetRegexes.startsUsing({ id: '63B5', source: 'Arch-Lambda' }),
netRegexJa: NetRegexes.startsUsing({ id: '63B5', source: 'アーチラムダ' }),
response: Responses.tankBuster(),
},
{
// Dragons spawn outside the last boss, but those ones don't matter.
// Ensure that we don't say anything until the player has engaged the last boss.
// 6435 is Plasmafodder, Stigma-4's auto-attack.
id: 'Dreamscape Last Boss',
type: 'Ability',
netRegex: NetRegexes.ability({ id: '6435', source: 'Stigma-4', capture: false }),
netRegexDe: NetRegexes.ability({ id: '6435', source: 'Stigma-4', capture: false }),
netRegexFr: NetRegexes.ability({ id: '6435', source: 'Stigma-4', capture: false }),
netRegexJa: NetRegexes.ability({ id: '6435', source: 'スティグマ・フォー', capture: false }),
run: (data) => data.lastBoss = true,
},
{
id: 'Dreamscape Atomic Flame',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '63B4', source: 'Arch-Lambda', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '63B4', source: 'Erz-Lambda', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '63B4', source: 'Arch-Lambda', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '63B4', source: 'アーチラムダ', capture: false }),
response: Responses.aoe(),
},
{
// The Hybrid Dragon add uses Touchdown after spawning,
// then immediately begins casting Fire Breath in a cone across the arena.
// If the player is not already in motion by the time Fire Breath begins,
// they are likely to be hit.
id: 'Dreamscape Touchdown',
type: 'AddedCombatant',
netRegex: NetRegexes.addedCombatantFull({ name: 'Hybrid Dragon' }),
netRegexDe: NetRegexes.addedCombatantFull({ name: 'Hybrid-Drache' }),
netRegexFr: NetRegexes.addedCombatantFull({ name: 'Dragon Hybride' }),
netRegexJa: NetRegexes.addedCombatantFull({ name: 'ハイブリッドドラゴン' }),
condition: (data) => data.lastBoss,
infoText: (_data, matches, output) => {
// The arena is a 50x50 square, with (0,0) in the exact center.
const isEast = parseFloat(matches.x) > 0;
if (isEast)
return output.east!();
return output.west!();
},
outputStrings: {
east: Outputs.east,
west: Outputs.west,
},
},
{
id: 'Dreamscape Rush',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '642D', source: 'Proto-rocket Punch', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '642D', source: 'Proto-Raketenschlag', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '642D', source: 'Proto-Astéropoing', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '642D', source: 'プロトロケットパンチ', capture: false }),
suppressSeconds: 5, // All five Punches use it at the same time
alertText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Avoid side dashes',
de: 'Weiche den Anstürmen von der Seite aus',
fr: 'Évitez les ruées sur les côtés',
ko: '옆쪽의 주먹 피하기',
},
},
},
{
id: 'Dreamscape Electromagnetic Release Circle',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '6434', source: 'Stigma-4' }),
netRegexDe: NetRegexes.startsUsing({ id: '6434', source: 'Stigma-4' }),
netRegexFr: NetRegexes.startsUsing({ id: '6434', source: 'Stigma-4' }),
netRegexJa: NetRegexes.startsUsing({ id: '6434', source: 'スティグマ・フォー' }),
delaySeconds: (_data, matches) => parseFloat(matches.castTime) - 4, // Full cast is 9.7s.
response: Responses.getOut(),
},
{
id: 'Dreamscape Electromagnetic Release Donut',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '6432', source: 'Stigma-4' }),
netRegexDe: NetRegexes.startsUsing({ id: '6432', source: 'Stigma-4' }),
netRegexFr: NetRegexes.startsUsing({ id: '6432', source: 'Stigma-4' }),
netRegexJa: NetRegexes.startsUsing({ id: '6432', source: 'スティグマ・フォー' }),
delaySeconds: (_data, matches) => parseFloat(matches.castTime) - 4, // Full cast is 9.7s.
response: Responses.getIn(),
},
{
id: 'Dreamscape Proto-wave Cannons Left',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '642A', source: 'Omega Frame', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '642A', source: 'Omega-Chassis', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '642A', source: 'Châssis Expérimental Oméga', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '642A', source: 'オメガフレーム', capture: false }),
response: Responses.goLeft(),
},
{
id: 'Dreamscape Proto-wave Cannons Right',
type: 'StartsUsing',
netRegex: NetRegexes.startsUsing({ id: '642B', source: 'Omega Frame', capture: false }),
netRegexDe: NetRegexes.startsUsing({ id: '642B', source: 'Omega-Chassis', capture: false }),
netRegexFr: NetRegexes.startsUsing({ id: '642B', source: 'Châssis Expérimental Oméga', capture: false }),
netRegexJa: NetRegexes.startsUsing({ id: '642B', source: 'オメガフレーム', capture: false }),
response: Responses.goRight(),
},
{
id: 'Dreamscape Forward March',
type: 'GainsEffect',
netRegex: NetRegexes.gainsEffect({ effectId: '7A6' }),
condition: Conditions.targetIsYou(),
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Mindhack: Forward',
de: 'Geistlenkung: Vorwärts',
fr: 'Piratage mental : Avant',
ko: '강제이동: 앞',
},
},
},
{
id: 'Dreamscape About Face',
type: 'GainsEffect',
netRegex: NetRegexes.gainsEffect({ effectId: '7A7' }),
condition: Conditions.targetIsYou(),
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Mindhack: Back',
de: 'Geistlenkung: Rückwärts',
fr: 'Piratage mental : Arrière',
ko: '강제이동: 뒤',
},
},
},
{
id: 'Dreamscape Left Face',
type: 'GainsEffect',
netRegex: NetRegexes.gainsEffect({ effectId: '7A8' }),
condition: Conditions.targetIsYou(),
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Mindhack: Left',
de: 'Geistlenkung: Links',
fr: 'Piratage mental : Gauche',
ko: '강제이동: 왼쪽',
},
},
},
{
id: 'Dreamscape Right Face',
type: 'GainsEffect',
netRegex: NetRegexes.gainsEffect({ effectId: '7A9' }),
condition: Conditions.targetIsYou(),
infoText: (_data, _matches, output) => output.text!(),
outputStrings: {
text: {
en: 'Mindhack: Right',
de: 'Geistlenkung: Rechts',
fr: 'Piratage mental : Droite',
ko: '강제이동: 오른쪽',
},
},
},
],
timelineReplace: [
{
'locale': 'de',
'replaceSync': {
'A-4 Command': 'Kommando A4',
'A-4 Conquest': 'Operation A4',
'A-4 Headquarters': 'Hauptquartier A4',
'Arch-Lambda': 'Erz-Lambda',
'Hybrid Dragon': 'Hybrid-Drache',
'Mark II Guided Missile': 'Lenkrakete II',
'Omega Frame': 'Omega-Chassis',
'Proto-Omega': 'Proto-Omega',
'Proto-rocket Punch': 'Proto-Raketenschlag',
'Stigma-4': 'Stigma-4',
},
'replaceText': {
'(?<!Multi-)AI Takeover': 'Plan B',
'Atomic Flame': 'Atomare Flamme',
'Atomic Ray': 'Atomstrahlung',
'Auto-mobile Assault Cannon': 'Wellengeschütz „Sturm”',
'Auto-mobile Sniper Cannon': 'Wellengeschütz „Pfeil”',
'Burn': 'Verbrennung',
'Chemical Missile': 'Napalmrakete',
'Electric Slide': 'Elektrosturz',
'Electromagnetic Release': 'Elektromagnetische Entladung',
'Entrench': 'Manöver „Sturm”',
'Fire Breath': 'Feueratem',
'Forward Interceptors': 'Frontale Abfangrakete',
'Guided Missile': 'Lenkraketen',
'Iron Kiss': 'Eiserner Kuss',
'Mindhack': 'Hirnsonde',
'Multi-AI Takeover': 'Gebündelte Kräfte',
'Mustard Bomb': 'Senfbombe',
'Proto-wave Cannon': 'Experimentelles Wellengeschütz',
'Rear Interceptors': 'Rückwärtige Abfangrakete',
'Rush': 'Stürmen',
'Self-Destruct': 'Selbstzerstörung',
'Side Cannons': 'Seitliche Maschinenkanone',
'Touchdown': 'Aufsetzer',
'Tread': 'Angriffsmanöver Alpha',
'(?<!Proto-)Wave Cannon': 'Wellengeschütz',
'Wheel': 'Rad',
},
},
{
'locale': 'fr',
'replaceSync': {
'A-4 Command': 'Poste de commandement A-4',
'A-4 Conquest': 'Conquête A-4',
'A-4 Headquarters': 'Quartier général A-4',
'Arch-Lambda': 'Arch-Lambda',
'Hybrid Dragon': 'dragon hybride',
'Mark II Guided Missile': 'missile autoguidé v2',
'Omega Frame': 'châssis expérimental Oméga',
'Proto-Omega': 'Proto-Oméga',
'Proto-rocket Punch': 'proto-astéropoing',
'Stigma-4': 'Stigma-4',
},
'replaceText': {
'\\?': ' ?',
'(?<!Multi-)AI Takeover': 'Appel de renforts',
'Atomic Flame': 'Flammes atomiques',
'Atomic Ray': 'Rayon atomique',
'Auto-mobile Assault Cannon': 'Assaut plasmique',
'Auto-mobile Sniper Cannon': 'Canon plasma longue portée',
'Burn': 'Combustion',
'Chemical Missile': 'Missile au napalm',
'Electric Slide': 'Glissement Oméga',
'Electromagnetic Release': 'Décharge électromagnétique',
'Entrench': 'Manœuvre d\'assaut violent',
'Fire Breath': 'Souffle enflammé',
'Forward Interceptors': 'Contre-salve avant',
'Guided Missile': 'Missile à tête chercheuse',
'Iron Kiss': 'Impact de missile',
'Mindhack': 'Piratage mental',
'Multi-AI Takeover': 'Appel de renforts polyvalents',
'Mustard Bomb': 'Obus d\'ypérite',
'Proto-wave Cannon': 'Canon plasma expérimental',
'Rear Interceptors': 'Contre-salve arrière',
'Rush': 'Ruée',
'Self-Destruct': 'Auto-destruction',
'Side Cannons': 'Salve d\'obus latérale',
'Touchdown': 'Atterrissage',
'Tread': 'Manœuvre d\'assaut',
'(?<!Proto-)Wave Cannon': 'Canon plasma',
'Wheel': 'Roue',
},
},
{
'locale': 'ja',
'replaceSync': {
'A-4 Command': 'コマンドA4',
'A-4 Conquest': 'コンクエストA4',
'A-4 Headquarters': 'ヘッドクォーターA4',
'Arch-Lambda': 'アーチラムダ',
'Hybrid Dragon': 'ハイブリッドドラゴン',
'Mark II Guided Missile': 'ガイデッドミサイルII',
'Omega Frame': 'オメガフレーム',
'Proto-Omega': 'プロトオメガ',
'Proto-rocket Punch': 'プロトロケットパンチ',
'Stigma-4': 'スティグマ・フォー',
},
'replaceText': {
'(?<!Multi-)AI Takeover': '支援要請',
'Atomic Flame': 'アトミックフレイム',
'Atomic Ray': 'アトミックレイ',
'Auto-mobile Assault Cannon': '強襲式波動砲',
'Auto-mobile Sniper Cannon': '狙撃式波動砲',
'Burn': '燃焼',
'Chemical Missile': 'ナパームミサイル',
'Electric Slide': 'オメガスライド',
'Electromagnetic Release': '電磁放射',
'Entrench': '強襲機動',
'Fire Breath': 'ファイアブレス',
'Forward Interceptors': '前方迎撃ロケット',
'Guided Missile': '誘導ミサイル',
'Iron Kiss': '着弾',
'Mindhack': 'ブレインハック',
'Multi-AI Takeover': '複合支援要請',
'Mustard Bomb': 'マスタードボム',
'Proto-wave Cannon': '試作型波動砲',
'Rear Interceptors': '後方迎撃ロケット',
'Rush': '突進',
'Self-Destruct': '自爆',
'Side Cannons': '側面機関砲',
'Touchdown': 'タッチダウン',
'Tread': '突撃機動',
'(?<!Proto-)Wave Cannon': '波動砲',
'Wheel': 'ホイール',
},
},
],
};
export default triggerSet; | the_stack |
import { Kind } from './Kind'
import {
HVal,
NOT_SUPPORTED_IN_FILTER_MSG,
CANNOT_CHANGE_READONLY_VALUE,
valueInspect,
valueIsKind,
valueMatches,
} from './HVal'
import { HaysonDateTime } from './hayson'
import { Node } from '../filter/Node'
import { HGrid } from './HGrid'
import { HList } from './HList'
import { HDict } from './HDict'
import { HDate } from './HDate'
import { HTime } from './HTime'
import { EvalContext } from '../filter/EvalContext'
export interface PartialHaysonDateTime {
_kind?: Kind
val: string
tz?: string
}
/** Accepted types for making a `HDateTime` from */
type DateTimeBaseType = string | Date | HaysonDateTime | HDateTime
/**
* Prefixes for IANA timezone names.
*/
const TIMEZONE_PREFIXES = [
'Africa',
'America',
'Asia',
'Atlantic',
'Australia',
'Brazil',
'Canada',
'Chile',
'Etc',
'Europe',
'Indian',
'Mexico',
'Pacific',
'US',
]
/**
* The default method for checking whether a timezone is valid or not.
*
* This implementation attempts to use the environment's Intl API. This may
* not work in all environments (Deno) but this is the best attempt at something generic.
*
* This approach was discovered after examining the source code for Luxon.
*
* @param timezone The timezone.
* @returns True if the timezone is supported.
*/
export function defaultIsValidTimeZone(timezone: string): boolean {
try {
new Intl.DateTimeFormat('en-US', { timeZone: timezone }).format()
return true
} catch (err) {
return false
}
}
/**
* Haystack date time.
*/
export class HDateTime implements HVal {
/**
* An internal cached date string value in an ISO 8601 format.
*/
readonly #iso: string
/**
* Internal implementation.
*/
readonly #value: string
/**
* Internal timezone.
*/
readonly #timezone: string
/**
* Constructs a new haystack date time.
*
* @param value The date time as a string, a JS Date or Hayson date object.
*/
private constructor(value: string | Date | HaysonDateTime) {
let val = ''
let tz = ''
if (value) {
if (typeof value === 'string') {
val = value
} else if (value instanceof Date) {
val = (value as Date).toISOString()
} else {
const obj = value as HaysonDateTime
val = obj.val
if (obj.tz) {
tz = obj.tz
}
}
}
if (!val) {
throw new Error('Invalid date')
}
// Parse the ISO formatted string, the offset and any timezone.
const result =
/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:[.]\d+)?)(Z|(?:[-+]\d{2}:\d{2}))(?: (.+))?$/.exec(
val
) ?? []
let [, , offset, timezone] = result
const [, dateTime] = result
if (!dateTime || !offset) {
throw new Error('Invalid date format')
}
if (tz) {
timezone = tz
}
if (!timezone) {
// Calculate the GMT offset if there is no timezone specified.
timezone = HDateTime.fromGmtOffset(offset)
if (timezone === 'UTC') {
offset = 'Z'
}
}
this.#iso = `${dateTime}${offset}`
this.#value = `${dateTime}${offset}${
offset === 'Z' ? '' : ` ${timezone}`
}`
this.#timezone = timezone || 'UTC'
}
/**
* Calculate the GMT offset to use as a fallback timezone.
*
* @param offset The string encoded offset (-/+HH:MM) or Z.
* @returns The calculated GMT offset.
*/
private static fromGmtOffset(offset: string): string {
if (offset === 'Z') {
return 'UTC'
}
const negative = offset[0] === '-'
const hours = Number(offset.substring(1, 3))
return hours ? `GMT${negative ? '+' : '-'}${hours}` : 'UTC'
}
/**
* Factory method for a haystack date time.
*
* @param value The date time as a string, a JS Date or Hayson date object.
* @returns A haystack date time.
*/
public static make(value: DateTimeBaseType): HDateTime {
if (valueIsKind<HDateTime>(value, Kind.DateTime)) {
return value
} else {
return Object.freeze(
new HDateTime(value as string | Date | HaysonDateTime)
) as HDateTime
}
}
/**
* @returns The date time value.
*/
public get value(): string {
return this.#value
}
public set value(value: string) {
throw new Error(CANNOT_CHANGE_READONLY_VALUE)
}
/**
* @returns The date time in an ISO 8601 format.
*/
public get iso(): string {
return this.#iso
}
/**
* @returns The timezone.
*/
public get timezone(): string {
return this.#timezone
}
/**
* @returns The date time object as a JavaScript date.
*/
public get date(): Date {
return new Date(this.iso)
}
/**
* @returns The value's kind.
*/
public getKind(): Kind {
return Kind.DateTime
}
/**
* Compares the value's kind.
*
* @param kind The kind to compare against.
* @returns True if the kind matches.
*/
public isKind(kind: Kind): boolean {
return valueIsKind<HDateTime>(this, kind)
}
/**
* Returns true if the haystack filter matches the value.
*
* @param filter The filter to test.
* @param cx Optional haystack filter evaluation context.
* @returns True if the filter matches ok.
*/
public matches(filter: string | Node, cx?: Partial<EvalContext>): boolean {
return valueMatches(this, filter, cx)
}
/**
* Dump the value to the local console output.
*
* @param message An optional message to display before the value.
* @returns The value instance.
*/
public inspect(message?: string): this {
return valueInspect(this, message)
}
/**
* @returns Now as a date time object.
*/
public static now(): HDateTime {
return HDateTime.make(new Date())
}
/**
* @returns A string representation of the value.
*/
public toString(): string {
return (
this.date.toLocaleString() +
(this.timezone ? ` ${this.timezone}` : '')
)
}
/**
* @returns The encoded date time value.
*/
public valueOf(): string {
return this.value
}
/**
* Encodes to an encoding zinc value.
*
* @returns The encoded zinc string.
*/
public toZinc(): string {
return this.value
}
/**
* Value equality check.
*
* @param value The value to test.
* @returns True if the value is the same.
*/
public equals(value: unknown): boolean {
return (
valueIsKind<HDateTime>(value, Kind.DateTime) &&
value.value === this.value
)
}
/**
* Compares two date times.
*
* @param value The value value to compare against.
* @returns The sort order as negative, 0, or positive
*/
public compareTo(value: unknown): number {
if (!valueIsKind<HDateTime>(value, Kind.DateTime)) {
return -1
}
// Always compare the ISO 8601 date time values as this naturally
// can be sorted as strings.
if (this.iso < value.iso) {
return -1
}
if (this.iso === value.iso) {
return 0
}
return 1
}
/**
* Encodes to an encoded zinc value that can be used
* in a haystack filter string.
*
* A dict isn't supported in filter so throw an error.
*
* @returns The encoded value that can be used in a haystack filter.
*/
public toFilter(): string {
throw new Error(NOT_SUPPORTED_IN_FILTER_MSG)
}
/**
* @returns A JSON reprentation of the object.
*/
public toJSON(): HaysonDateTime {
const json: HaysonDateTime = {
_kind: this.getKind(),
val: this.iso,
}
const tz = this.timezone
if (tz !== 'UTC') {
json.tz = tz
}
return json
}
/**
* @returns An Axon encoded string of the value.
*/
public toAxon(): string {
const date = this.date
return `dateTime(${HDate.make(date).toAxon()},${HTime.make(
date
).toAxon()})`
}
/**
* @returns Returns the value instance.
*/
public newCopy(): HDateTime {
return this
}
/**
* @returns The value as a grid.
*/
public toGrid(): HGrid {
return HGrid.make(this)
}
/**
* @returns The value as a list.
*/
public toList(): HList<HDateTime> {
return HList.make(this)
}
/**
* @returns The value as a dict.
*/
public toDict(): HDict {
return HDict.make(this)
}
/**
* Return the full IANA timezone name or an empty string if it can't be found.
*
* @param isValidTimeZone An optional callback invoked to see if the timezone is valid.
* @returns The IANA timezone name or an empty string if the timezone name isn't valid.
*/
public getIANATimeZone(
isValidTimeZone: (timezone: string) => boolean = defaultIsValidTimeZone
): string {
return HDateTime.getIANATimeZone(this.#timezone, isValidTimeZone)
}
/**
* Return the full IANA timezone name or an empty string if it can't be found.
*
* The timezone name can be a full existing timezone or an alias.
*
* Since a vanilla JavaScript environment doesn't have support for querying the IANA database,
* a callback function needs to be passed in to query the local database implementation.
*
* Here's an example that uses [Luxon](https://moment.github.io/luxon/index.html)...
* ```typescript
* import { DateTime } from 'luxon'
* ...
* const isValidTimeZone = (timezone: string): boolean =>
* !!DateTime.now().setZone(timezone).isValid
*
* const tz = getIANATimeZone('New_York', isValidTimeZone) // Returns 'America/New_York'.
* ...
* ```
*
* Here's an example that uses [Moment with timezones](https://momentjs.com/timezone/docs/)...
* ```typescript
* import * as moment from 'moment-timezone'
* ...
* const isValidTimeZone = (timezone: string): boolean =>
* !!moment.tz.zone(timezone)
*
* const tz = getIANATimeZone('New_York', isValidTimeZone) // Returns 'America/New_York'.
* ```
*
* @see defaultIsValidTimeZone
* @link [IANA timezone database](https://www.iana.org/time-zones)
* @link [Fantom's DateTime with alias explanation](https://fantom.org/doc/docLang/DateTime)
*
* @param timezone A full timezone name or alias.
* @param isValidTimeZone An optional callback invoked to see if the timezone is valid.
* @returns The IANA timezone name or an empty string if the timezone name isn't valid.
*/
public static getIANATimeZone(
timezone: string,
isValidTimeZone: (timezone: string) => boolean = defaultIsValidTimeZone
): string {
if (isValidTimeZone(timezone)) {
return timezone
}
for (const prefix of TIMEZONE_PREFIXES) {
const tz = `${prefix}/${timezone}`
if (isValidTimeZone(tz)) {
return tz
}
}
return ''
}
} | the_stack |
import React, { useCallback, useEffect, useRef, useState } from 'react';
import {
Alert,
ImageStyle,
KeyboardAvoidingView,
Platform,
ScrollView,
StyleProp,
TouchableOpacity,
View,
} from 'react-native';
// import DateTimePicker, {
// Event,
// AndroidEvent,
// } from '@react-native-community/datetimepicker';
import { useRoute } from '@react-navigation/native';
import { Controller, useForm } from 'react-hook-form';
import * as ImagePicker from 'expo-image-picker';
import { CustomHeader, ShowImageModal } from '../components';
import {
ActivityIndicator,
Avatar,
AvatarProps,
Text,
TextInput,
TextInputType,
} from '../core-ui';
import { UploadTypeEnum } from '../generated/server/globalTypes';
// import { formatDateTime } from '../helpers/formatDateTime';
import {
createReactNativeFile,
errorHandlerAlert,
formatExtensions,
getFormat,
getImage,
getTextInputRules,
useStorage,
} from '../helpers';
// import { formatDateTime } from '../helpers/formatDateTime';
import {
useEditProfile,
useLazyProfile,
useSiteSettings,
useStatelessUpload,
} from '../hooks';
import { makeStyles } from '../theme';
import { StackRouteProp } from '../types';
type ProfileProps = Pick<AvatarProps, 'size'> & {
image: string;
imageStyle?: StyleProp<ImageStyle>;
};
type ProfileForm = {
username: string;
name: string;
website: string;
bio: string;
location: string;
dateOfBirth: string;
};
export default function EditProfile(props: ProfileProps) {
const styles = useStyles();
const { imageStyle } = props;
const {
params: { user: selectedUser },
} = useRoute<StackRouteProp<'EditProfile'>>();
const storage = useStorage();
const username = storage.getItem('user')?.username || '';
const {
authorizedExtensions,
maxUsernameLength,
minUsernameLength,
minPasswordLength,
fullNameRequired,
} = useSiteSettings();
const extensions = authorizedExtensions?.split('|');
const normalizedExtensions = formatExtensions(extensions);
const { control, handleSubmit, errors, setValue, getValues } = useForm<
ProfileForm
>({
mode: 'onChange',
});
const [show, setShow] = useState(false);
const [currentUserData, setCurrentUserData] = useState(selectedUser);
const [userImage, setUserImage] = useState('');
const [oldUsername, setOldUsername] = useState('');
const [avatarId, setAvatarId] = useState(0);
const [noChanges, setNoChanges] = useState(true);
const mounted = useRef(false);
const nameInputRef = useRef<TextInputType>(null);
const bioInputRef = useRef<TextInputType>(null);
const websiteInputRef = useRef<TextInputType>(null);
const locationInputRef = useRef<TextInputType>(null);
let setForm = useCallback(
(user: ProfileForm & { avatar: string }) => {
setUserImage(getImage(user.avatar));
setOldUsername(user.username);
setValue('username', user.username);
setValue('name', user.name || '');
setValue('website', user.website);
setValue('bio', user.bio);
setValue('location', user.location);
// setValue(
// 'dateOfBirth',
// formatDateTime(user.dateOfBirth || '', 'medium', false, 'en-US'),
// );
},
[setOldUsername, setUserImage, setValue],
);
const { usernameInputRules, nameInputRules } = getTextInputRules({
maxUsernameLength,
minUsernameLength,
minPasswordLength,
fullNameRequired,
});
useEffect(() => {
mounted.current = true;
return () => {
mounted.current = false;
};
}, []);
useEffect(() => {
if (selectedUser) {
let { avatar, username } = selectedUser;
setUserImage(getImage(avatar, 'xl'));
setOldUsername(username);
}
}, [selectedUser, setOldUsername, setUserImage]);
const { getProfile } = useLazyProfile(
{
variables: { username },
},
'HIDE_ALERT',
);
const { editProfile, loading: editProfileLoading } = useEditProfile({
onCompleted: ({ editProfile: result }) => {
if (result) {
const {
id,
avatar,
bioRaw: bio,
websiteName: website,
dateOfBirth,
username,
name,
location,
} = result;
storage.setItem('user', {
id,
username,
name: name || '',
avatar,
});
setForm({
username,
name: name || '',
avatar,
bio: bio || '',
website: website || '',
dateOfBirth: dateOfBirth || '',
location: location || '',
});
setCurrentUserData({
...currentUserData,
username,
name,
avatar,
websiteName: website,
bioRaw: bio,
location,
dateOfBirth,
});
getProfile({ variables: { username } });
Alert.alert(
t('Success!'),
t('Profile has been updated!'),
[{ text: t('Got it') }],
{ cancelable: false },
);
}
},
onError: (error) => {
errorHandlerAlert(error);
},
});
const { upload, loading: uploadLoading } = useStatelessUpload({
onCompleted: ({ upload: result }) => {
if (result && mounted.current) {
setUserImage(result.url);
setAvatarId(result.id);
}
},
onError: (error) => {
errorHandlerAlert(error);
},
});
// const onChangeDate = (
// event: Event | AndroidEvent,
// selectedDate: Date | undefined,
// ) => {
// const currentDate = selectedDate
// ? new Date(selectedDate).toISOString()
// : date;
// const currentSelectedDate = formatDateTime(
// selectedUser.dateOfBirth ? selectedUser.dateOfBirth : '',
// 'medium',
// false,
// 'en-US',
// );
// if (
// currentSelectedDate ===
// formatDateTime(currentDate, 'medium', false, 'en-US')
// ) {
// setNoChanges(true);
// } else {
// setNoChanges(false);
// }
// setShow(Platform.OS === 'ios');
// setDate(currentDate);
// setValue(
// 'dateOfBirth',
// formatDateTime(currentDate, 'medium', false, 'en-US'),
// );
// };
// const showMode = () => {
// setShow(!show);
// };
// const toggleDatepicker = () => {
// showMode();
// };
const onPressCancel = () => {
if (!show) {
setShow(true);
}
setTimeout(() => setShow(false), 50);
};
const pickImage = async () => {
let stringifyExtensions = normalizedExtensions.toString();
let user = storage.getItem('user');
if (user) {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [1, 1],
quality: 1,
});
if (!result.cancelled) {
let format = getFormat(result.uri);
if (normalizedExtensions.includes(format)) {
const reactNativeFile = createReactNativeFile(result.uri);
upload({
variables: {
file: reactNativeFile,
userId: user?.id,
type: UploadTypeEnum.avatar,
},
});
setNoChanges(false);
} else {
Alert.alert(
t('Failed!'),
t(`Please upload image with {stringifyExtensions} format`, {
stringifyExtensions,
}),
[{ text: t('Got it') }],
);
}
}
return;
}
};
const onPressRight = handleSubmit(() => {
let dateOfBirth = new Date(getValues('dateOfBirth'));
dateOfBirth.setDate(dateOfBirth.getDate() + 1);
let newUsername = getValues('username');
let newName = getValues('name');
let newWebsite = getValues('website');
let newBio = getValues('bio');
let newLocation = getValues('location');
editProfile({
variables: {
newUsername: oldUsername !== newUsername ? newUsername : undefined,
username: oldUsername,
editProfileInput: {
name: newName,
website: newWebsite,
bioRaw: newBio,
location: newLocation,
dateOfBirth: dateOfBirth.toJSON(),
},
uploadId: avatarId,
},
});
setNoChanges(true);
});
const scrollViewRef = useRef<ScrollView>(null);
return (
<KeyboardAvoidingView
style={{ flex: 1 }}
contentContainerStyle={styles.container}
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
enabled
keyboardVerticalOffset={90}
>
<ScrollView
ref={scrollViewRef}
// onContentSizeChange={() => {
// if (scrollViewRef.current && show) {
// scrollViewRef.current.scrollToEnd({ animated: true });
// }
// }}
>
<CustomHeader
title=""
rightTitle="Save"
onPressRight={onPressRight}
noShadow
isLoading={editProfileLoading}
disabled={noChanges || uploadLoading}
/>
<View style={styles.pictureContainer}>
{!uploadLoading ? (
<Avatar
src={userImage}
size="l"
style={[styles.image, imageStyle]}
onPress={() => {
setShow(true);
}}
/>
) : (
<ActivityIndicator size="large" style={styles.avatarLoading} />
)}
<TouchableOpacity
onPress={pickImage}
style={styles.changePictureContainer}
disabled={uploadLoading || editProfileLoading}
>
<Text color={!uploadLoading ? 'primary' : 'textLighter'}>
{t('Change Picture')}
</Text>
</TouchableOpacity>
</View>
{!editProfileLoading && selectedUser && currentUserData && (
<View style={styles.inputContainer}>
<Controller
name="username"
defaultValue={currentUserData.username}
rules={usernameInputRules}
control={control}
render={({ onChange, value }) => (
<TextInput
label={t('Username')}
error={errors.username != null}
errorMsg={errors.username?.message}
value={value}
editable={
currentUserData.canEditUsername || currentUserData.admin
}
onChangeText={(text) => {
if (currentUserData.username === text) {
setNoChanges(true);
} else {
setNoChanges(false);
}
onChange(text);
}}
onSubmitEditing={() => nameInputRef.current?.focus()}
returnKeyType="next"
autoCapitalize="none"
style={styles.spacingBottom}
/>
)}
/>
<Controller
name="name"
defaultValue={currentUserData.name}
rules={nameInputRules}
control={control}
render={({ onChange, value }) => (
<TextInput
inputRef={nameInputRef}
label={t('Name')}
error={errors.name != null}
value={value}
onChangeText={(text) => {
if (currentUserData.name === text) {
setNoChanges(true);
} else {
setNoChanges(false);
}
onChange(text);
}}
onSubmitEditing={() => websiteInputRef.current?.focus()}
returnKeyType="next"
autoCapitalize="words"
style={styles.spacingBottom}
/>
)}
/>
<Controller
name="website"
defaultValue={currentUserData.websiteName}
control={control}
render={({ onChange, value }) => (
<TextInput
inputRef={websiteInputRef}
label={t('Website')}
placeholder={t('Insert your website')}
error={errors.website != null}
value={value}
onChangeText={(text) => {
if (currentUserData.websiteName === text) {
setNoChanges(true);
} else {
setNoChanges(false);
}
onChange(text);
}}
onSubmitEditing={() => bioInputRef.current?.focus()}
returnKeyType="next"
autoCapitalize="none"
style={styles.spacingBottom}
/>
)}
/>
<Controller
name="bio"
defaultValue={currentUserData.bioRaw}
control={control}
render={({ onChange, value }) => (
<TextInput
inputRef={bioInputRef}
label={t('Bio')}
placeholder={t('Insert your bio')}
error={errors.bio != null}
value={value}
onChangeText={(text) => {
if (currentUserData.bioRaw === text) {
setNoChanges(true);
} else {
setNoChanges(false);
}
onChange(text);
}}
autoCapitalize="none"
style={styles.spacingBottom}
multiline
maxLength={120}
/>
)}
/>
<Controller
name="location"
defaultValue={currentUserData.location}
control={control}
render={({ onChange, value }) => (
<TextInput
inputRef={locationInputRef}
label={t('Location')}
placeholder={t('Insert your location')}
error={errors.location != null}
value={value}
onChangeText={(text) => {
if (currentUserData.location === text) {
setNoChanges(true);
} else {
setNoChanges(false);
}
onChange(text);
}}
returnKeyType="done"
autoCapitalize="none"
style={styles.spacingBottom}
/>
)}
/>
{/*
// Commented out because normal discourse doesn't have DoB (Need plugins)
<Controller
name="dateOfBirth"
defaultValue={formatDateTime(
selectedUser.dateOfBirth || '',
'medium',
false,
'en-US',
)}
control={control}
render={({ value }) => (
<View>
<TextInput
label={t('Date of Birth')}
placeholder={t('Insert your date of birth')}
editable={false}
value={value}
style={styles.spacingBottom}
rightIcon="Event"
onPressIcon={toggleDatepicker}
onTouchStart={toggleDatepicker}
/>
{show && (
<DateTimePicker
testID="dateTimePicker"
value={new Date(date)}
mode={t('date')}
display="default"
onChange={onChangeDate}
/>
)}
</View>
)}
/> */}
{show && (
<ShowImageModal
show={show}
userImage={{ uri: userImage }}
onPressCancel={onPressCancel}
/>
)}
</View>
)}
</ScrollView>
</KeyboardAvoidingView>
);
}
const useStyles = makeStyles(({ colors, spacing }) => ({
container: {
flexGrow: 1,
backgroundColor: colors.backgroundDarker,
flex: 1,
},
inputContainer: {
paddingHorizontal: spacing.xxl,
backgroundColor: colors.background,
marginTop: spacing.m,
paddingTop: spacing.l,
},
spacingBottom: {
paddingBottom: spacing.xxl,
paddingVertical: spacing.l,
},
image: {
alignItems: 'center',
},
pictureContainer: {
alignItems: 'center',
backgroundColor: colors.background,
paddingBottom: spacing.xl,
},
changePictureContainer: {
paddingVertical: spacing.xl,
},
avatarLoading: {
marginTop: 40,
marginBottom: 20,
},
})); | the_stack |
import { nanoid } from "nanoid"
import { AST } from "@/parser"
import { RenderNode, RenderConnect, Size, LayoutChildren, Box } from "./types"
import {
CHART_PADDING_HORIZONTAL,
CHART_PADDING_VERTICAL,
MINIMUM_CHART_PADDING_HORIZONTAL,
MINIMUM_CHART_PADDING_VERTICAL,
NODE_PADDING_HORIZONTAL,
NODE_PADDING_VERTICAL,
NODE_MARGIN_VERTICAL,
NODE_MARGIN_HORIZONTAL,
NODE_TEXT_FONTSIZE,
ROOT_RADIUS,
QUANTIFIER_HEIGHT,
NAME_HEIGHT,
BRANCH_PADDING_HORIZONTAL,
TEXT_PADDING_VERTICAL,
QUANTIFIER_TEXT_FONTSIZE,
QUANTIFIER_ICON_WIDTH,
QUANTIFIER_ICON_MARGIN_RIGHT,
NAME_TEXT_FONTSIZE,
} from "./constants"
import { getQuantifierText } from "@/parser"
import { getTextsWithBacktick, getName } from "./utils"
const fontFamily = `-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji`
type TextSize = { width: number; height: number }
const textSizeMap = new Map<string, TextSize>()
const sizeWeakMap = new WeakMap<AST.Node, Size>()
class RenderEngine {
private canvas: HTMLCanvasElement
private context: CanvasRenderingContext2D | null
private renderNodes: RenderNode[] = []
private renderConnects: RenderConnect[] = []
private layoutChildrenList: LayoutChildren[] = []
constructor() {
// the `measureText` method use canvas.measureText
if (process.env.EXPORT) {
const { createCanvas } = require("canvas")
this.canvas = createCanvas()
} else {
this.canvas = document.createElement("canvas")
}
this.context = this.canvas.getContext("2d")
}
public render(ast: AST.Regex, minimum = false) {
this.renderNodes = []
this.renderConnects = []
this.layoutChildrenList = []
const { body } = ast
let { width, height } = this.calcNodesSize(body)
const paddingHorizontal = minimum
? MINIMUM_CHART_PADDING_HORIZONTAL
: CHART_PADDING_HORIZONTAL
const paddingVertical = minimum
? MINIMUM_CHART_PADDING_VERTICAL
: CHART_PADDING_VERTICAL
this.renderChildren(body, {
parentWidth: width,
parentHeight: height,
initialX: paddingHorizontal,
initialY: paddingVertical,
})
return {
width: width + 2 * paddingHorizontal,
height: height + 2 * paddingHorizontal,
nodes: this.renderNodes,
connects: this.renderConnects,
}
}
// name
// -------------
// | texts |
// -------------
// quantifier
private calcNodeSize(node: AST.Node): Size {
if (sizeWeakMap.has(node)) {
return sizeWeakMap.get(node)!
}
let width = 0
let height = 0
let offsetWidth = 0
let offsetHeight = 0
let paddingTop = 0
let paddingBottom = 0
const texts = getTextsWithBacktick(node)
if (node.type === "choice") {
node.branches.forEach((nodes) => {
let { width: branchWidth, height: branchHeight } =
this.calcNodesSize(nodes)
height += branchHeight
height += NODE_MARGIN_VERTICAL
branchWidth +=
NODE_MARGIN_HORIZONTAL * 2 + BRANCH_PADDING_HORIZONTAL * 2
width = Math.max(width, branchWidth)
})
} else if (node.type === "group" || node.type === "lookAroundAssertion") {
;({ width, height } = this.calcNodesSize(node.children))
height += 2 * NODE_MARGIN_VERTICAL
width += NODE_MARGIN_HORIZONTAL * 2
} else if (texts) {
const size = this.measureTexts(texts, NODE_TEXT_FONTSIZE)
width = size.width + 2 * NODE_PADDING_HORIZONTAL
height = size.height + 2 * NODE_PADDING_VERTICAL
} else if (node.type === "root") {
width = ROOT_RADIUS
height = ROOT_RADIUS
} else {
// empty node
width = 2 * NODE_PADDING_HORIZONTAL
height = NODE_TEXT_FONTSIZE + 2 * NODE_PADDING_VERTICAL
}
// quantifier times text
if (
(node.type === "character" || node.type === "group") &&
node.quantifier
) {
const { quantifier } = node
paddingBottom += QUANTIFIER_HEIGHT
const text = getQuantifierText(quantifier)
if (text) {
const quantifierWidth =
this.measureText(text, QUANTIFIER_TEXT_FONTSIZE).width +
QUANTIFIER_ICON_WIDTH +
QUANTIFIER_ICON_MARGIN_RIGHT
offsetWidth = Math.max(quantifierWidth, width, offsetWidth)
}
}
// name
const name = getName(node)
if (name) {
const nameWidth =
this.measureText(name, NAME_TEXT_FONTSIZE).width +
NODE_PADDING_VERTICAL * 2
offsetWidth = Math.max(width, nameWidth, offsetWidth)
paddingTop += NAME_HEIGHT
}
offsetHeight = height + Math.max(paddingTop, paddingBottom) * 2
offsetWidth = Math.max(offsetWidth, width)
const size: Size = {
width,
height,
offsetWidth,
offsetHeight,
}
sizeWeakMap.set(node, size)
return size
}
private calcNodesSize(nodes: AST.Node[]) {
let height = 0
let width = 0
nodes.forEach((node) => {
const size = this.calcNodeSize(node)
height = Math.max(height, size.offsetHeight)
width += size.offsetWidth
})
width += NODE_MARGIN_HORIZONTAL * (nodes.length - 1)
return { width, height }
}
renderChildren(
nodes: AST.Node[],
{
parentWidth,
parentHeight,
initialX,
initialY,
}: {
parentWidth: number
parentHeight: number
initialX: number
initialY: number
}
) {
if (nodes.length === 0) {
return
}
const { width } = this.calcNodesSize(nodes)
const deltaX = (parentWidth - width) / 2
const connectY = initialY + parentHeight / 2
let x = initialX
const layoutChildren: LayoutChildren = []
this.layoutChildrenList.push(layoutChildren)
const head = nodes[0]
const tail = nodes[nodes.length - 1]
let paddingLeft = 0
let paddingRight = 0
if (head.type !== "root") {
const headSize = this.calcNodeSize(head)
paddingLeft = (headSize.offsetWidth - headSize.width) / 2
this.renderConnects.push({
kind: "straight",
id: nanoid(),
start: { x, y: connectY },
end: { x: (x += deltaX + paddingLeft), y: connectY },
})
}
nodes.forEach((node, index) => {
const size = this.calcNodeSize(node)
paddingLeft = (size.offsetWidth - size.width) / 2
if (index !== 0) {
this.renderConnects.push({
kind: "straight",
id: nanoid(),
start: { x, y: connectY },
end: {
x: (x += NODE_MARGIN_HORIZONTAL + paddingLeft + paddingRight),
y: connectY,
},
})
}
this.renderSingleNode(node, {
initialX: x,
initialY: initialY + (parentHeight - size.height) / 2,
width: size.width,
height: size.height,
layoutChildren,
})
x += size.width
paddingRight = paddingLeft
})
if (tail.type !== "root") {
this.renderConnects.push({
kind: "straight",
id: nanoid(),
start: { x, y: connectY },
end: { x: (x += deltaX + paddingRight), y: connectY },
})
}
}
private renderSingleNode(
node: AST.Node,
{
initialX,
initialY,
width,
height,
layoutChildren,
}: {
initialX: number
initialY: number
width: number
height: number
layoutChildren: LayoutChildren
}
) {
const renderNode: RenderNode = {
id: node.id,
x: initialX,
y: initialY,
width,
height,
target: node,
}
this.renderNodes.push(renderNode)
layoutChildren.push({
id: node.id,
x: initialX,
y: initialY,
width,
height,
})
if (node.type === "group" || node.type === "lookAroundAssertion") {
this.renderChildren(node.children, {
parentWidth: width,
parentHeight: height,
initialX,
initialY,
})
} else if (node.type === "choice") {
const { branches } = node
let x = initialX
let y = initialY
const padding = NODE_MARGIN_HORIZONTAL + BRANCH_PADDING_HORIZONTAL
branches.forEach((branch) => {
const branchHeight =
this.calcNodesSize(branch).height + NODE_MARGIN_VERTICAL
this.renderConnects.push({
id: nanoid(),
kind: "split",
start: { x, y: initialY + height / 2 },
end: {
x: x + padding,
y: y + branchHeight / 2,
},
})
this.renderConnects.push({
id: nanoid(),
kind: "combine",
start: { x: x + width - padding, y: y + branchHeight / 2 },
end: { x: x + width, y: initialY + height / 2 },
})
this.renderChildren(branch, {
initialX: x + padding,
initialY: y,
parentWidth: width - 2 * padding,
parentHeight: branchHeight,
})
y += branchHeight
})
}
}
public measureText(text: string, fontSize: number = 16) {
const context = this.context
if (!context) {
return { width: 0, height: 0 }
}
const textFont = fontSize + "px " + fontFamily
const key = textFont + "-" + text
if (textSizeMap.has(key)) {
return textSizeMap.get(key) as TextSize
}
context.font = textFont
const metrics = context.measureText(text)
const size = { width: metrics.width, height: fontSize }
textSizeMap.set(key, size)
return size
}
public measureTexts(texts: string[] | string, fontSize: number = 16) {
if (typeof texts === "string") {
return this.measureText(texts, fontSize)
}
return texts
.map((text) => this.measureText(text, fontSize))
.reduce(
({ width: prevWidth, height: prevHeight }, { width, height }) => ({
width: Math.max(width, prevWidth),
height: height + prevHeight + TEXT_PADDING_VERTICAL,
}),
{ width: 0, height: -TEXT_PADDING_VERTICAL }
)
}
public selectByBound(box: Box) {
let selected = false
const selectedIds = []
for (let i = 0; this.layoutChildrenList.length; i++) {
const layoutChildren = this.layoutChildrenList[i]
for (let j = 0; j < layoutChildren.length; j++) {
const nodeLayout = layoutChildren[j]
const { id, x, y, width, height } = nodeLayout
const overlapX = box.x < x && box.x + box.width > x + width
const overlapY = box.y < y && box.y + box.height > y + height
if (overlapX && overlapY) {
selected = true
selectedIds.push(id)
} else if (selected) {
return selectedIds
}
}
}
return selectedIds
}
}
const renderEngine = new RenderEngine()
export default renderEngine | the_stack |
import { IFacetOptions } from '../Facet/Facet';
import { FacetValue } from '../Facet/FacetValue';
import { Facet } from '../Facet/Facet';
import { ComponentOptions } from '../Base/ComponentOptions';
import { HierarchicalFacetValuesList } from './HierarchicalFacetValuesList';
import { HierarchicalFacetQueryController } from '../../controllers/HierarchicalFacetQueryController';
import { IComponentBindings } from '../Base/ComponentBindings';
import { IIndexFieldValue } from '../../rest/FieldValue';
import { Utils } from '../../utils/Utils';
import { $$ } from '../../utils/Dom';
import { Defer } from '../../misc/Defer';
import { HierarchicalFacetSearchValuesList } from './HierarchicalFacetSearchValuesList';
import { HierarchicalFacetSearch } from './HierarchicalFacetSearch';
import { HierarchicalBreadcrumbValuesList } from './HierarchicalBreadcrumbValuesList';
import { IQuerySuccessEventArgs } from '../../events/QueryEvents';
import { Assert } from '../../misc/Assert';
import { IPopulateBreadcrumbEventArgs } from '../../events/BreadcrumbEvents';
import { IPopulateOmniboxEventArgs } from '../../events/OmniboxEvents';
import { OmniboxHierarchicalValuesList } from './OmniboxHierarchicalValuesList';
import { HierarchicalFacetValueElement } from './HierarchicalFacetValueElement';
import { Initialization } from '../Base/Initialization';
import { ISearchAlertsPopulateMessageEventArgs } from '../../events/SearchAlertEvents';
import * as _ from 'underscore';
import { exportGlobally } from '../../GlobalExports';
import 'styling/_HierarchicalFacet';
import { SVGIcons } from '../../utils/SVGIcons';
import { SVGDom } from '../../utils/SVGDom';
import { ResponsiveFacetOptions } from '../ResponsiveComponents/ResponsiveFacetOptions';
export interface IHierarchicalFacetOptions extends IFacetOptions {
delimitingCharacter?: string;
levelStart?: number;
levelEnd?: number;
marginByLevel?: number;
}
export interface IValueHierarchy {
childs?: IValueHierarchy[];
parent?: IValueHierarchy;
originalPosition?: number;
facetValue: FacetValue;
level: number;
keepOpened: boolean;
hasChildSelected: boolean;
allChildShouldBeSelected: boolean;
}
interface IFlatHierarchy {
facetValue: FacetValue;
level: number;
parent: string;
self: string;
}
/**
* @deprecated This component is exposed for legacy reasons. Instead, use the {@link CategoryFacet} component, which is more performant and easier to use.
*
* The `HierarchicalFacet` component inherits all of its options and behaviors from the [`Facet`]{@link Facet}
* component, but is meant to be used to render hierarchical values.
*
* **Note:**
* > The `HierarchicalFacet` component does not support the [`customSort`]{@link Facet.options.customSort}
* > `Facet` option.
*
* The `HierarchicalFacet` component can be used to display files in a file system, or categories for items in a
* hierarchy.
*
* This facet requires a group by field with a special format to work correctly.
*
* **Example:**
*
* You have the following files indexed on a file system:
* ```
* c:\
* folder1\
* text1.txt
* folder2\
* folder3\
* text2.txt
* ```
* The `text1.txt` item would have a field with the following format:
* `c; c|folder1;`
*
* The `text2.txt` item would have a field with the following format:
* `c; c|folder2; c|folder2|folder3;`
*
* By default, the `|` character determines the hierarchy (`folder3` inside `folder2` inside `c`).
*
* Since both items contain the `c` value, selecting it value in the facet would return both items.
*
* Selecting the `folder3` value in the facet would only return the `text2.txt` item.
*
* @notSupportedIn salesforcefree
*
* @deprecatedSince [January 2019 Release (v2.5395.12)](https://docs.coveo.com/en/2763/)
*/
export class HierarchicalFacet extends Facet implements IComponentBindings {
static ID = 'HierarchicalFacet';
static doExport = () => {
exportGlobally({
HierarchicalFacet: HierarchicalFacet
});
};
/**
* The options for the component
* @componentOptions
*/
static options: IHierarchicalFacetOptions = {
/**
* The character that allows to specify the hierarchical dependency.
*
* **Example:**
*
* If your field has the following values:
*
* `@field: c; c>folder2; c>folder2>folder3;`
*
* The delimiting character is `>`.
*
* Default value is `|`.
*/
delimitingCharacter: ComponentOptions.buildStringOption({ defaultValue: '|' }),
/**
* Specifies at which level (0-based index) of the hierarchy the `HierarchicalFacet` should start displaying its
* values.
*
* **Example:**
*
* If you have the following files indexed on a file system:
* ```
* c:\
* folder1\
* text1.txt
* folder2\
* folder3\
* text2.txt
* ```
* Setting `levelStart` to `1` displays `folder1` and `folder2` in the `HierarchicalFacet`, but omits `c:`.
*
* Default (and minimum) value is `0`.
*/
levelStart: ComponentOptions.buildNumberOption({ defaultValue: 0, min: 0 }),
/**
* Specifies at which level (0-based index) of the hierarchy the `HierarchicalFacet` should stop displaying its
* values.
*
* Default value is `undefined`, which means the `HierarchicalFacet` component renders all hierarchical levels.
* Minimum value is `0`.
*/
levelEnd: ComponentOptions.buildNumberOption({ min: 0 }),
/**
* Specifies the margin (in pixels) to display between each hierarchical level when expanding.
*
* Default value is `10`.
*/
marginByLevel: ComponentOptions.buildNumberOption({ defaultValue: 10, min: 0 }),
...ResponsiveFacetOptions
};
static parent = Facet;
public options: IHierarchicalFacetOptions;
public facetValuesList: HierarchicalFacetValuesList;
public numberOfValuesToShow: number;
public facetQueryController: HierarchicalFacetQueryController;
public topLevelHierarchy: IValueHierarchy[];
public shouldReshuffleFacetValuesClientSide = false;
private valueHierarchy: { [facetValue: string]: IValueHierarchy };
private originalNumberOfValuesToShow: number;
private correctLevels: IFlatHierarchy[] = [];
/**
* Creates a new `HierarchicalFacet` component.
* @param element The HTMLElement on which to instantiate the component.
* @param options The options for the `HierarchicalFacet` component.
* @param bindings The bindings that the component requires to function normally. If not set, these will be
* automatically resolved (with a slower execution time).
*/
public constructor(public element: HTMLElement, options: IHierarchicalFacetOptions, public bindings: IComponentBindings) {
super(element, options, bindings, HierarchicalFacet.ID);
this.options = ComponentOptions.initComponentOptions(element, HierarchicalFacet, this.options);
this.numberOfValuesToShow = this.originalNumberOfValuesToShow = this.options.numberOfValues || 5;
this.numberOfValues = Math.max(this.options.numberOfValues, 10000);
this.options.injectionDepth = Math.max(this.options.injectionDepth, 10000);
this.logger.info('Hierarchy facet: Set number of values very high in order to build hierarchy', this.numberOfValues, this);
this.logger.info('Hierarchy facet: Set injection depth very high in order to build hierarchy', this.options.injectionDepth);
}
/**
* Selects a single value.
* @param value The value to select.
* @param selectChildren Specifies whether to also select all child values (if any). Default value is the opposite of
* the [`useAnd`]{@link Facet.options.useAnd} option value set for this `HierarchicalFacet`.
*/
public selectValue(value: FacetValue | string, selectChildren = !this.options.useAnd) {
this.ensureDom();
this.ensureValueHierarchyExists([value]);
let valueHierarchy = this.getValueFromHierarchy(value);
if (selectChildren) {
this.selectChilds(valueHierarchy, valueHierarchy.childs);
}
this.flagParentForSelection(valueHierarchy);
super.selectValue(value);
}
/**
* Selects multiple values
* @param values The array of values to select.
* @param selectChildren Specifies whether to also select all child values (if any). Default value is the opposite of
* the [`useAnd`]{@link Facet.options.useAnd} option value set for this `HierarchicalFacet`.
*/
public selectMultipleValues(values: FacetValue[] | string[], selectChildren = !this.options.useAnd): void {
this.ensureDom();
this.ensureValueHierarchyExists(values);
_.each(values as FacetValue[], value => {
let valueHierarchy = this.getValueFromHierarchy(value);
this.flagParentForSelection(valueHierarchy);
if (selectChildren) {
_.each(valueHierarchy.childs, child => {
this.selectValue(child.facetValue);
});
}
});
super.selectMultipleValues(values);
}
/**
* Deselects a single value
* @param value The value to deselect.
* @param deselectChildren Specifies whether to also deselect all child values (if any). Default value is `true`.
*/
public deselectValue(value: FacetValue | string, deselectChildren = true) {
this.ensureDom();
this.ensureValueHierarchyExists([value]);
let valueHierarchy = this.getValueFromHierarchy(value);
if (deselectChildren) {
let hasChilds = valueHierarchy.childs != undefined;
if (hasChilds) {
let activeChilds = _.filter<IValueHierarchy>(valueHierarchy.childs, child => {
let valueToCompare = this.getFacetValueFromHierarchy(child.facetValue);
return valueToCompare.selected || valueToCompare.excluded;
});
valueHierarchy.hasChildSelected = false;
if (activeChilds.length == valueHierarchy.childs.length) {
this.deselectChilds(valueHierarchy, valueHierarchy.childs);
}
}
}
this.deselectParent(valueHierarchy.parent);
this.unflagParentForSelection(valueHierarchy);
super.deselectValue(value);
}
/**
* Excludes a single value.
* @param value The value to exclude.
* @param excludeChildren Specifies whether to also exclude all child values (if any). Default value is the opposite
* of the [`useAnd`]{@link Facet.options.useAnd} option value set for this `HierarchicalFacet`.
*/
public excludeValue(value: FacetValue | string, excludeChildren = !this.options.useAnd): void {
this.ensureDom();
this.ensureValueHierarchyExists([value]);
let valueHierarchy = this.getValueFromHierarchy(value);
if (excludeChildren) {
this.excludeChilds(valueHierarchy.childs);
} else {
this.deselectChilds(valueHierarchy, valueHierarchy.childs);
this.close(valueHierarchy);
}
this.flagParentForSelection(valueHierarchy);
super.excludeValue(value);
}
/**
* Un-excludes a single value.
* @param value The value to un-exclude.
* @param unexludeChildren Specifies whether to also un-exclude all child values (if any). Default value is the
* opposite of the [`useAnd`]{@link Facet.options.useAnd} option value set for this `HierarchicalFacet`.
*/
public unexcludeValue(value: FacetValue | string, unexludeChildren = !this.options.useAnd): void {
this.ensureDom();
this.ensureValueHierarchyExists([value]);
let valueHierarchy = this.getValueFromHierarchy(value);
if (unexludeChildren) {
this.unexcludeChilds(valueHierarchy.childs);
}
this.unflagParentForSelection(valueHierarchy);
super.unexcludeValue(value);
}
/**
* Deselects multiple values.
* @param values The array of values to deselect.
* @param deselectChildren Specifies whether to also deselect all child values (if any). Default value is the opposite
* of the [`useAnd`]{@link Facet.options.useAnd} option value set for this `HierarchicalFacet`.
*/
public deselectMultipleValues(values: FacetValue[] | string[], deselectChildren = !this.options.useAnd): void {
this.ensureDom();
this.ensureValueHierarchyExists(values);
_.each(values as FacetValue[], value => {
let valueHierarchy = this.getValueFromHierarchy(value);
valueHierarchy.hasChildSelected = false;
this.unflagParentForSelection(valueHierarchy);
if (deselectChildren) {
_.each(valueHierarchy.childs, child => {
let childInHierarchy = this.getValueFromHierarchy(child.facetValue);
childInHierarchy.hasChildSelected = false;
this.deselectValue(child.facetValue);
});
}
});
super.deselectMultipleValues(values);
}
/**
* Toggles the selection of a single value (selects value if not selected; deselects value if selected).
* @param value The value to select or deselect.
*/
public toggleSelectValue(value: FacetValue | string): void {
this.ensureDom();
this.ensureValueHierarchyExists([value]);
if (this.getFacetValueFromHierarchy(value).selected == false) {
this.selectValue(value);
} else {
this.deselectValue(value);
}
}
/**
* Toggles the exclusion of a single value (excludes value if not excluded; un-excludes value if excluded).
* @param value The value to exclude or un-exclude.
*/
public toggleExcludeValue(value: FacetValue | string): void {
this.ensureDom();
this.ensureValueHierarchyExists([value]);
if (this.getFacetValueFromHierarchy(value).excluded == false) {
this.excludeValue(value);
} else {
this.unexcludeValue(value);
}
}
/**
* Gets the caption of a single value.
* @param facetValue The value whose caption the method should return.
* @returns {string} The caption of the value.
*/
public getValueCaption(facetValue: IIndexFieldValue | FacetValue): string {
let stringValue = this.getSelf(facetValue as FacetValue);
let ret = stringValue;
if (Utils.exists(this.options.valueCaption)) {
if (typeof this.options.valueCaption == 'object') {
ret = this.options.valueCaption[stringValue] || ret;
}
if (typeof this.options.valueCaption == 'function') {
ret = this.options.valueCaption.call(this, facetValue);
}
}
return ret;
}
/**
* Gets the values that the `HierarchicalFacet` is currently displaying.
* @returns {any[]} An array containing all the values that the `HierarchicalFacet` is currently displaying.
*/
public getDisplayedValues(): string[] {
let displayed = _.filter(this.values.getAll(), v => {
let valFromHierarchy = this.getValueFromHierarchy(v);
if (valFromHierarchy) {
let elem = this.getElementFromFacetValueList(v);
return !$$(elem).hasClass('coveo-inactive');
}
return false;
});
return _.pluck(displayed, 'value');
}
/**
* Updates the sort criteria for the `HierarchicalFacet`.
*
* See the [`sortCriteria`]{@link IGroupByRequest.sortCriteria} property of the [`IGroupByRequest`] interface for the
* list and description of possible values.
*
* @param criteria The new sort criteria.
*/
public updateSort(criteria: string) {
super.updateSort(criteria);
}
/**
* Opens (expands) a single value and shows all its children.
* @param value The value to open.
*/
public open(value: FacetValue | IValueHierarchy | string) {
let getter;
if (_.isString(value)) {
getter = this.getValueHierarchy(value);
} else if (value instanceof FacetValue) {
getter = this.getValueHierarchy(value.value);
} else {
getter = value;
}
if (getter != undefined) {
$$(this.getElementFromFacetValueList(getter.facetValue.value)).addClass('coveo-open');
this.showChilds(getter.childs);
if (getter.parent != undefined) {
this.open(this.getValueHierarchy(getter.facetValue.value).parent);
}
this.getValueHierarchy(getter.facetValue.value).keepOpened = true;
}
}
/**
* Closes (collapses) a single value and hides all its children.
* @param value The value to close.
*/
public close(value: FacetValue | IValueHierarchy | string) {
let getter;
if (_.isString(value)) {
getter = this.getValueHierarchy(value);
} else if (value instanceof FacetValue) {
getter = this.getValueHierarchy(value.value);
} else {
getter = value;
}
if (getter != undefined) {
$$(this.getElementFromFacetValueList(getter.facetValue)).removeClass('coveo-open');
this.hideChilds(getter.childs);
_.each(getter.childs, (child: IValueHierarchy) => {
this.close(this.getValueHierarchy(child.facetValue.value));
});
this.getValueHierarchy(getter.facetValue.value).keepOpened = false;
}
}
/**
* Resets the `HierarchicalFacet` state.
*/
public reset() {
_.each(this.getAllValueHierarchy(), valueHierarchy => {
valueHierarchy.hasChildSelected = false;
valueHierarchy.allChildShouldBeSelected = false;
});
// Need to close all values, otherwise we might end up with orphan(s)
// if a parent value, after reset, is no longer visible.
_.each(this.getAllValueHierarchy(), valueHierarchy => {
this.close(valueHierarchy);
});
super.reset();
}
public processFacetSearchAllResultsSelected(facetValues: FacetValue[]): void {
this.selectMultipleValues(facetValues);
this.triggerNewQuery();
}
protected triggerUpdateDeltaQuery(facetValues: FacetValue[]) {
this.shouldReshuffleFacetValuesClientSide = this.keepDisplayedValuesNextTime;
super.triggerUpdateDeltaQuery(facetValues);
}
protected updateSearchElement(moreValuesAvailable = true) {
// We always want to show search for hierarchical facet :
// It's useful since child values are folded under their parent most of the time
super.updateSearchElement(true);
}
protected facetValueHasChanged() {
this.updateQueryStateModel();
Defer.defer(() => {
this.updateAppearanceDependingOnState();
});
}
protected initFacetQueryController() {
this.facetQueryController = new HierarchicalFacetQueryController(this);
}
protected initFacetSearch() {
this.facetSearch = new HierarchicalFacetSearch(this, HierarchicalFacetSearchValuesList, this.root);
this.element.appendChild(this.facetSearch.build());
}
protected handleDeferredQuerySuccess(data: IQuerySuccessEventArgs) {
this.updateAppearanceDependingOnState();
super.handleDeferredQuerySuccess(data);
}
protected handlePopulateSearchAlerts(args: ISearchAlertsPopulateMessageEventArgs) {
if (this.values.hasSelectedOrExcludedValues()) {
args.text.push(
new HierarchicalBreadcrumbValuesList(
this,
this.values.getSelected().concat(this.values.getExcluded()),
this.getAllValueHierarchy()
).buildAsString()
);
}
}
protected handlePopulateBreadcrumb(args: IPopulateBreadcrumbEventArgs) {
Assert.exists(args);
if (this.values.hasSelectedOrExcludedValues()) {
let element = new HierarchicalBreadcrumbValuesList(
this,
this.values.getSelected().concat(this.values.getExcluded()),
this.getAllValueHierarchy()
).build();
args.breadcrumbs.push({
element: element
});
}
}
protected handleOmniboxWithStaticValue(eventArg: IPopulateOmniboxEventArgs) {
let regex = eventArg.completeQueryExpression.regex;
let match = _.first(
_.filter<IValueHierarchy>(this.getAllValueHierarchy(), existingValue => {
return regex.test(this.getValueCaption(existingValue.facetValue));
}),
this.options.numberOfValuesInOmnibox
);
let facetValues = _.compact(
_.map(match, gotAMatch => {
let fromList = this.getFromFacetValueList(gotAMatch.facetValue);
return fromList ? fromList.facetValue : undefined;
})
);
let element = new OmniboxHierarchicalValuesList(this, facetValues, eventArg).build();
eventArg.rows.push({
element: element,
zIndex: this.omniboxZIndex
});
}
protected rebuildValueElements() {
this.shouldReshuffleFacetValuesClientSide = this.shouldReshuffleFacetValuesClientSide || this.keepDisplayedValuesNextTime;
this.numberOfValues = Math.max(this.numberOfValues, 10000);
this.processHierarchy();
this.setValueListContent();
super.rebuildValueElements();
this.buildParentChildRelationship();
this.checkForOrphans();
this.checkForNewUnselectedChild();
this.crop();
this.shouldReshuffleFacetValuesClientSide = false;
}
protected initFacetValuesList() {
this.facetValuesList = new HierarchicalFacetValuesList(this, HierarchicalFacetValueElement);
this.element.appendChild(this.facetValuesList.build());
}
protected updateMoreLess() {
let moreValuesAvailable = this.numberOfValuesToShow < this.topLevelHierarchy.length;
let lessIsShown = this.numberOfValuesToShow > this.originalNumberOfValuesToShow;
super.updateMoreLess(lessIsShown, moreValuesAvailable);
}
protected handleClickMore(): void {
this.numberOfValuesToShow += this.originalNumberOfValuesToShow;
this.numberOfValuesToShow = Math.min(this.numberOfValuesToShow, this.values.size());
this.crop();
this.updateMoreLess();
}
protected handleClickLess() {
this.numberOfValuesToShow = this.originalNumberOfValuesToShow;
this.crop();
this.updateMoreLess();
}
protected updateNumberOfValues() {
this.numberOfValues = Math.max(this.numberOfValues, 10000);
}
private ensureValueHierarchyExists(facetValues: any) {
if (facetValues[0] && typeof facetValues[0] == 'string') {
facetValues = _.map(facetValues, (value: string) => {
return FacetValue.createFromValue(value);
});
}
let atLeastOneDoesNotExists = false;
_.each(facetValues, (facetValue: FacetValue) => {
if (this.getValueHierarchy(facetValue.value) == undefined) {
atLeastOneDoesNotExists = true;
}
});
if (atLeastOneDoesNotExists) {
this.processHierarchy(facetValues);
}
}
private crop() {
// Partition the top level or the facet to only operate on the values that are not selected or excluded
let partition = _.partition(this.topLevelHierarchy, (hierarchy: IValueHierarchy) => {
return hierarchy.facetValue.selected || hierarchy.facetValue.excluded || hierarchy.hasChildSelected;
});
// Hide and show the partitionned top level values, depending on the numberOfValuesToShow
let numberOfValuesLeft = this.numberOfValuesToShow - partition[0].length;
_.each(_.last(partition[1], partition[1].length - numberOfValuesLeft), (toHide: IValueHierarchy) => {
this.hideFacetValue(toHide);
this.hideChilds(toHide.childs);
});
_.each(_.first(partition[1], numberOfValuesLeft), (toShow: IValueHierarchy) => {
this.showFacetValue(toShow);
});
}
private placeChildsUnderTheirParent(hierarchy: IValueHierarchy, hierarchyElement: HTMLElement) {
let toIterateOver = hierarchy.childs;
if (toIterateOver) {
let toIterateOverSorted = this.facetValuesList.sortFacetValues(_.pluck(toIterateOver, 'facetValue')).reverse();
_.each(toIterateOverSorted, child => {
let childFromHierarchy = this.getValueFromHierarchy(child);
if (childFromHierarchy) {
let childElement = this.getElementFromFacetValueList(child);
$$(childElement).insertAfter(hierarchyElement);
if (childFromHierarchy.childs && childFromHierarchy.childs.length != 0) {
this.placeChildsUnderTheirParent(childFromHierarchy, childElement);
}
}
});
}
if (hierarchy.keepOpened) {
this.open(hierarchy);
this.showChilds(hierarchy.childs);
} else {
this.hideChilds(hierarchy.childs);
}
}
private addCssClassToParentAndChilds(hierarchy: IValueHierarchy, hierarchyElement: HTMLElement) {
$$(hierarchyElement).addClass('coveo-has-childs');
if (hierarchy.hasChildSelected) {
$$(hierarchyElement).addClass('coveo-has-childs-selected');
}
const expandChilds = $$('span', { className: 'coveo-hierarchical-facet-expand' }, SVGIcons.icons.facetExpand);
const collapseChilds = $$('span', { className: 'coveo-hierarchical-facet-collapse' }, SVGIcons.icons.facetCollapse);
SVGDom.addClassToSVGInContainer(expandChilds.el, 'coveo-hierarchical-facet-expand-svg');
SVGDom.addClassToSVGInContainer(collapseChilds.el, 'coveo-hierarchical-facet-collapse-svg');
let openAndCloseChilds = $$(
'div',
{
className: 'coveo-has-childs-toggle'
},
expandChilds.el,
collapseChilds.el
).el;
$$(openAndCloseChilds).on('click', () => {
$$(hierarchyElement).hasClass('coveo-open') ? this.close(hierarchy) : this.open(hierarchy);
});
$$(hierarchyElement).prepend(openAndCloseChilds);
}
private buildParentChildRelationship() {
let fragment = document.createDocumentFragment();
fragment.appendChild(this.facetValuesList.valueContainer);
let sorted = _.map(this.facetValuesList.sortFacetValues(), (facetValue: FacetValue) => {
return this.getValueFromHierarchy(facetValue);
});
_.each(sorted, (hierarchy: IValueHierarchy) => {
let hierarchyElement = this.getElementFromFacetValueList(hierarchy.facetValue);
if (Utils.isNonEmptyArray(hierarchy.childs)) {
this.placeChildsUnderTheirParent(hierarchy, hierarchyElement);
this.addCssClassToParentAndChilds(hierarchy, hierarchyElement);
} else {
$$(hierarchyElement).addClass('coveo-no-childs');
}
hierarchyElement.style.marginLeft = this.options.marginByLevel * (hierarchy.level - this.options.levelStart) + 'px';
});
$$(<any>fragment).insertAfter(this.headerElement);
}
private setValueListContent() {
this.facetValuesList.hierarchyFacetValues = _.map(this.correctLevels, hierarchy => {
if (!this.values.contains(hierarchy.facetValue.value)) {
hierarchy.facetValue.occurrences = 0;
this.values.add(hierarchy.facetValue);
}
return hierarchy.facetValue;
});
}
private createHierarchy(valuesToBuildWith: FacetValue[]) {
let flatHierarchy = _.map(valuesToBuildWith, (value: FacetValue) => {
let parent = this.getParent(value);
let self = value.lookupValue || value.value;
return {
facetValue: value,
level: this.getLevel(value),
parent: parent,
self: self
};
});
this.setInHierarchy(flatHierarchy);
_.each(this.getAllValueHierarchy(), valueHierarchy => {
if (valueHierarchy.facetValue.selected) {
this.flagParentForSelection(valueHierarchy);
}
});
return flatHierarchy;
}
private processHierarchy(facetValues = this.values.getAll()) {
_.each(this.getAllValueHierarchy(), (hierarchy: IValueHierarchy) => {
if (this.values.get(hierarchy.facetValue.value) == undefined) {
this.deleteValueHierarchy(this.getLookupOrValue(hierarchy.facetValue));
}
});
this.createHierarchy(facetValues);
}
private setInHierarchy(flatHierarchy: IFlatHierarchy[]) {
this.correctLevels = _.filter<IFlatHierarchy>(flatHierarchy, hierarchy => {
let isCorrectMinimumLevel = this.options.levelStart == undefined || hierarchy.level >= this.options.levelStart;
let isCorrectMaximumLevel = this.options.levelEnd == undefined || hierarchy.level < this.options.levelEnd;
return isCorrectMinimumLevel && isCorrectMaximumLevel;
});
_.each(this.correctLevels, (hierarchy: IFlatHierarchy) => {
let childs = _.map(
_.filter<IFlatHierarchy>(this.correctLevels, (possibleChild: IFlatHierarchy) => {
return possibleChild.parent != null && possibleChild.parent.toLowerCase() == hierarchy.self.toLowerCase();
}),
(child): IValueHierarchy => {
return {
facetValue: child.facetValue,
level: child.level,
keepOpened: false,
hasChildSelected: false,
allChildShouldBeSelected: false
};
}
);
let parent =
hierarchy.parent != null
? _.find<IFlatHierarchy>(this.correctLevels, possibleParent => {
return possibleParent.self.toLowerCase() == hierarchy.parent.toLowerCase();
})
: null;
let hierarchyThatAlreadyExists = this.getValueHierarchy(hierarchy.facetValue.value);
if (hierarchyThatAlreadyExists && hierarchyThatAlreadyExists.childs.length != childs.length) {
hierarchyThatAlreadyExists.childs = childs;
}
let hierarchyThatAlreadyExistsAtParent;
if (parent) {
hierarchyThatAlreadyExistsAtParent = this.getValueHierarchy(parent.facetValue.value);
}
this.setValueHierarchy(hierarchy.facetValue.value, {
childs: childs,
parent:
parent == undefined
? undefined
: {
facetValue: parent.facetValue,
level: parent.level,
keepOpened: hierarchyThatAlreadyExistsAtParent ? hierarchyThatAlreadyExistsAtParent.keepOpened : false,
hasChildSelected: hierarchyThatAlreadyExistsAtParent ? hierarchyThatAlreadyExistsAtParent.hasChildSelected : false,
originalPosition: hierarchyThatAlreadyExistsAtParent ? hierarchyThatAlreadyExistsAtParent.originalPosition : undefined,
allChildShouldBeSelected: hierarchyThatAlreadyExistsAtParent
? hierarchyThatAlreadyExistsAtParent.allChildShouldBeSelected
: false
},
facetValue: hierarchy.facetValue,
level: hierarchy.level,
keepOpened: hierarchyThatAlreadyExists ? hierarchyThatAlreadyExists.keepOpened : false,
hasChildSelected: hierarchyThatAlreadyExists ? hierarchyThatAlreadyExists.hasChildSelected : false,
originalPosition: hierarchyThatAlreadyExists ? hierarchyThatAlreadyExists.originalPosition : undefined,
allChildShouldBeSelected: hierarchyThatAlreadyExists ? hierarchyThatAlreadyExists.allChildShouldBeSelected : false
});
});
this.topLevelHierarchy = _.chain(this.values.getAll())
.filter((value: FacetValue) => {
let fromHierarchy = this.getValueFromHierarchy(value);
if (fromHierarchy) {
return fromHierarchy.level == (this.options.levelStart || 0);
} else {
return false;
}
})
.map((value: FacetValue) => {
return this.getValueFromHierarchy(value);
})
.value();
}
private getParent(value: FacetValue) {
let lastIndexOfDelimiting = this.getLookupOrValue(value).lastIndexOf(this.options.delimitingCharacter);
if (lastIndexOfDelimiting != -1) {
return this.getLookupOrValue(value).substring(0, lastIndexOfDelimiting);
}
return undefined;
}
private getSelf(value: FacetValue) {
let parent = this.getParent(value);
if (parent == undefined) {
return this.getLookupOrValue(value);
} else {
let indexOfParent = this.getLookupOrValue(value).indexOf(parent);
return this.getLookupOrValue(value).substring(indexOfParent + parent.length + 1);
}
}
private showFacetValue(value: IValueHierarchy) {
$$(this.getElementFromFacetValueList(value.facetValue.value)).removeClass('coveo-inactive');
}
private hideFacetValue(value: IValueHierarchy) {
$$(this.getElementFromFacetValueList(value.facetValue.value)).addClass('coveo-inactive');
}
private hideChilds(children: IValueHierarchy[]) {
_.each(children, child => {
this.hideFacetValue(child);
});
}
private showChilds(children: IValueHierarchy[]) {
_.each(children, child => {
this.showFacetValue(child);
});
}
private selectChilds(parent: IValueHierarchy, children: IValueHierarchy[]) {
this.flagParentForSelection(parent);
parent.allChildShouldBeSelected = true;
this.selectMultipleValues(
_.map(children, child => {
return child.facetValue;
})
);
}
private deselectChilds(parent: IValueHierarchy, children: IValueHierarchy[]) {
parent.hasChildSelected = false;
parent.allChildShouldBeSelected = false;
this.deselectMultipleValues(
_.map(children, child => {
return child.facetValue;
})
);
}
private excludeChilds(children: IValueHierarchy[]) {
this.excludeMultipleValues(
_.map(children, child => {
return child.facetValue;
})
);
}
private unexcludeChilds(children: IValueHierarchy[]) {
this.unexcludeMultipleValues(
_.map(children, child => {
return child.facetValue;
})
);
}
private deselectParent(parent: IValueHierarchy) {
if (parent != undefined) {
this.deselectValue(parent.facetValue, false);
}
}
private flagParentForSelection(valueHierarchy: IValueHierarchy) {
let parent = valueHierarchy.parent;
let current = valueHierarchy;
while (parent) {
let parentInHierarchy = this.getValueHierarchy(parent.facetValue.value);
parentInHierarchy.hasChildSelected = true;
let found = _.find(parentInHierarchy.childs, (child: IValueHierarchy) => {
return child.facetValue.value.toLowerCase() == current.facetValue.value.toLowerCase();
});
if (found) {
if (this.getValueHierarchy(found.facetValue.value).hasChildSelected) {
found.hasChildSelected = true;
}
}
parent = parentInHierarchy.parent;
current = parentInHierarchy;
}
}
private unflagParentForSelection(valueHierarchy: IValueHierarchy) {
let parent = valueHierarchy.parent;
while (parent) {
let parentInHierarchy = this.getValueHierarchy(parent.facetValue.value);
let otherSelectedChilds = _.filter<IValueHierarchy>(parentInHierarchy.childs, child => {
let childInHierarchy = this.getValueHierarchy(child.facetValue.value);
if (childInHierarchy != undefined) {
return (
childInHierarchy.facetValue.value != valueHierarchy.facetValue.value &&
(childInHierarchy.facetValue.selected || childInHierarchy.facetValue.excluded || childInHierarchy.hasChildSelected)
);
}
});
if (otherSelectedChilds.length == 0) {
parentInHierarchy.hasChildSelected = false;
}
parentInHierarchy.allChildShouldBeSelected = false;
parent = parentInHierarchy.parent;
}
}
public getValueFromHierarchy(value: any): IValueHierarchy {
let getter = value instanceof FacetValue ? value.value : value;
return this.getValueHierarchy(getter);
}
private getFacetValueFromHierarchy(value: any): FacetValue {
return this.getValueFromHierarchy(value).facetValue;
}
private getLookupOrValue(value: FacetValue) {
return value.lookupValue || value.value;
}
private getElementFromFacetValueList(value: any) {
let ret = this.getFromFacetValueList(value);
if (ret) {
return ret.renderer.listItem;
} else {
return $$('div').el;
}
}
private getFromFacetValueList(value: any) {
let fromHierarchy = this.getValueFromHierarchy(value);
if (fromHierarchy != undefined) {
return this.facetValuesList.get(value);
} else {
return undefined;
}
}
private getLevel(value: FacetValue) {
return value.value.split(this.options.delimitingCharacter).length - 1;
}
public getAllValueHierarchy(): { [facetValue: string]: IValueHierarchy } {
if (this.valueHierarchy == null) {
this.valueHierarchy = {};
}
return this.valueHierarchy;
}
private deleteValueHierarchy(key: string) {
if (this.valueHierarchy != null) {
delete this.valueHierarchy[key.toLowerCase()];
}
}
private getValueHierarchy(key: string): IValueHierarchy {
if (this.valueHierarchy == null) {
return undefined;
}
return this.valueHierarchy[key.toLowerCase()];
}
private setValueHierarchy(key: string, value: IValueHierarchy) {
if (this.valueHierarchy == null) {
this.valueHierarchy = {};
}
this.valueHierarchy[key.toLowerCase()] = value;
}
private checkForOrphans() {
_.each(this.valueHierarchy, (v: IValueHierarchy) => {
if (this.getLevel(v.facetValue) != this.options.levelStart) {
if (this.getValueHierarchy(this.getParent(v.facetValue)) == undefined) {
this.logger.error(
`Orphan value found in HierarchicalFacet : ${v.facetValue.value}`,
`Needed : ${this.getParent(v.facetValue)} but not found`
);
this.logger.warn(`Removing incoherent facet value : ${v.facetValue.value}`);
this.hideFacetValue(v);
}
}
});
}
private checkForNewUnselectedChild() {
// It's possible that after checking a facet value, the index returns new facet values (because of injection depth);
_.each(this.valueHierarchy, (v: IValueHierarchy) => {
if (v.allChildShouldBeSelected) {
let notAlreadySelected = _.find(v.childs, (child: IValueHierarchy) => {
return child.facetValue.selected != true;
});
if (notAlreadySelected) {
this.selectValue(v.facetValue, true);
this.logger.info('Re-executing query with new facet values returned by index');
this.queryController.deferExecuteQuery();
}
}
});
}
}
Initialization.registerAutoCreateComponent(HierarchicalFacet); | the_stack |
export interface XY { x: number, y: number; }
export interface XYZ extends XY { z: number; }
export interface XYZW extends XYZ { w: number; }
export interface RGB { r: number; g: number; b: number; }
export interface RGBA extends RGB { a: number; }
import * as Bind from "bind-imgui";
export { Bind };
let bind: Bind.Module;
export default async function(value?: Partial<Bind.Module>): Promise<void> {
return new Promise<void>((resolve: () => void) => {
Bind.default(value).then((value: Bind.Module): void => {
bind = value;
resolve();
});
});
}
export { bind };
function import_Scalar(sca: XY | XYZ | XYZW | Bind.ImAccess<number> | Bind.ImScalar<number> | Bind.ImTuple2<number> | Bind.ImTuple3<number> | Bind.ImTuple4<number> | Bind.interface_ImVec4): Bind.ImScalar<number> {
if (Array.isArray(sca)) { return [ sca[0] ]; }
if (typeof sca === "function") { return [ sca() ]; }
return [ sca.x ];
}
function export_Scalar(tuple: Bind.ImScalar<number>, sca: XY | XYZ | XYZW | Bind.ImAccess<number> | Bind.ImScalar<number> | Bind.ImTuple2<number> | Bind.ImTuple3<number> | Bind.ImTuple4<number> | Bind.interface_ImVec4): void {
if (Array.isArray(sca)) { sca[0] = tuple[0]; return; }
if (typeof sca === "function") { sca(tuple[0]); return; }
sca.x = tuple[0];
}
function import_Vector2(vec: XY | XYZ | XYZW | Bind.ImTuple2<number> | Bind.ImTuple3<number> | Bind.ImTuple4<number> | Bind.interface_ImVec4): Bind.ImTuple2<number> {
if (Array.isArray(vec)) { return [ vec[0], vec[1] ]; }
return [ vec.x, vec.y ];
}
function export_Vector2(tuple: Bind.ImTuple2<number>, vec: XY | XYZ | XYZW | Bind.ImTuple2<number> | Bind.ImTuple3<number> | Bind.ImTuple4<number> | Bind.interface_ImVec4): void {
if (Array.isArray(vec)) { vec[0] = tuple[0]; vec[1] = tuple[1]; return; }
vec.x = tuple[0]; vec.y = tuple[1];
}
function import_Vector3(vec: XYZ | XYZW | Bind.ImTuple3<number> | Bind.ImTuple4<number> | Bind.interface_ImVec4): Bind.ImTuple3<number> {
if (Array.isArray(vec)) { return [ vec[0], vec[1], vec[2] ]; }
return [ vec.x, vec.y, vec.z ];
}
function export_Vector3(tuple: Bind.ImTuple3<number>, vec: XYZ | XYZW | Bind.ImTuple3<number> | Bind.ImTuple4<number> | Bind.interface_ImVec4): void {
if (Array.isArray(vec)) { vec[0] = tuple[0]; vec[1] = tuple[1]; vec[2] = tuple[2]; return; }
vec.x = tuple[0]; vec.y = tuple[1]; vec.z = tuple[2];
}
function import_Vector4(vec: XYZW | Bind.ImTuple3<number> | Bind.ImTuple4<number> | Bind.interface_ImVec4): Bind.ImTuple4<number> {
if (Array.isArray(vec)) { return [ vec[0], vec[1], vec[2], vec[3] || 0 ]; }
return [ vec.x, vec.y, vec.z, vec.w ];
}
function export_Vector4(tuple: Bind.ImTuple4<number>, vec: XYZW | Bind.ImTuple3<number> | Bind.ImTuple4<number> | Bind.interface_ImVec4): void {
if (Array.isArray(vec)) { vec[0] = tuple[0]; vec[1] = tuple[1]; vec[2] = tuple[2]; vec[3] = tuple[3]; return; }
vec.x = tuple[0]; vec.y = tuple[1]; vec.z = tuple[2]; vec.w = tuple[3];
}
function import_Color3(col: RGB | RGBA | Bind.ImTuple3<number> | Bind.ImTuple4<number> | Bind.interface_ImVec4): Bind.ImTuple3<number> {
if (Array.isArray(col)) { return [ col[0], col[1], col[2] ]; }
if ("r" in col) { return [ col.r, col.g, col.b ]; }
return [ col.x, col.y, col.z ];
}
function export_Color3(tuple: Bind.ImTuple3<number>, col: RGB | RGBA | Bind.ImTuple3<number> | Bind.ImTuple4<number> | Bind.interface_ImVec4): void {
if (Array.isArray(col)) { col[0] = tuple[0]; col[1] = tuple[1]; col[2] = tuple[2]; return; }
if ("r" in col) { col.r = tuple[0]; col.g = tuple[1]; col.b = tuple[2]; return; }
col.x = tuple[0]; col.y = tuple[1]; col.z = tuple[2];
}
function import_Color4(col: RGBA | Bind.ImTuple4<number> | Bind.interface_ImVec4 | RGBA): Bind.ImTuple4<number> {
if (Array.isArray(col)) { return [ col[0], col[1], col[2], col[3] ]; }
if ("r" in col) { return [ col.r, col.g, col.b, col.a ]; }
return [ col.x, col.y, col.z, col.w ];
}
function export_Color4(tuple: Bind.ImTuple4<number>, col: RGBA | Bind.ImTuple4<number> | Bind.interface_ImVec4 | RGBA): void {
if (Array.isArray(col)) { col[0] = tuple[0]; col[1] = tuple[1]; col[2] = tuple[2]; col[3] = tuple[3]; return; }
if ("r" in col) { col.r = tuple[0]; col.g = tuple[1]; col.b = tuple[2]; col.a = tuple[3]; return; }
col.x = tuple[0]; col.y = tuple[1]; col.z = tuple[2]; col.w = tuple[3];
}
import * as config from "./imconfig.js";
export { IMGUI_VERSION as VERSION }
export const IMGUI_VERSION: string = "1.80"; // bind.IMGUI_VERSION;
export { IMGUI_VERSION_NUM as VERSION_NUM }
export const IMGUI_VERSION_NUM: number = 18000; // bind.IMGUI_VERSION_NUM;
// #define IMGUI_CHECKVERSION() ImGui::DebugCheckVersionAndDataLayout(IMGUI_VERSION, sizeof(ImGuiIO), sizeof(ImGuiStyle), sizeof(ImVec2), sizeof(ImVec4), sizeof(ImDrawVert))
export { IMGUI_CHECKVERSION as CHECKVERSION }
export function IMGUI_CHECKVERSION(): boolean { return DebugCheckVersionAndDataLayout(IMGUI_VERSION, bind.ImGuiIOSize, bind.ImGuiStyleSize, bind.ImVec2Size, bind.ImVec4Size, bind.ImDrawVertSize, bind.ImDrawIdxSize); }
export const IMGUI_HAS_TABLE: boolean = true;
export function ASSERT(c: any): asserts c { if (!c) { throw new Error(); } }
export function IM_ASSERT(c: any): asserts c { if (!c) { throw new Error(); } }
export { IM_ARRAYSIZE as ARRAYSIZE }
export function IM_ARRAYSIZE(_ARR: ArrayLike<any> | ImStringBuffer): number {
if (_ARR instanceof ImStringBuffer) {
return _ARR.size;
} else {
return _ARR.length;
}
}
export { ImStringBuffer as StringBuffer }
export class ImStringBuffer {
constructor(public size: number, public buffer: string = "") {}
}
export type ImAccess<T> = Bind.ImAccess<T>; export { ImAccess as Access }
export type ImScalar<T> = Bind.ImScalar<T>; export { ImScalar as Scalar }
export type ImTuple2<T> = Bind.ImTuple2<T>; export { ImTuple2 as Tuple2 }
export type ImTuple3<T> = Bind.ImTuple3<T>; export { ImTuple3 as Tuple3 }
export type ImTuple4<T> = Bind.ImTuple4<T>; export { ImTuple4 as Tuple4 }
export { ImTextureID as TextureID }
export type ImTextureID = WebGLTexture;
export { ImGuiID as ID }
export type ImGuiID = Bind.ImGuiID;
// Flags for ImGui::Begin()
export { ImGuiWindowFlags as WindowFlags };
export enum ImGuiWindowFlags {
None = 0,
NoTitleBar = 1 << 0, // Disable title-bar
NoResize = 1 << 1, // Disable user resizing with the lower-right grip
NoMove = 1 << 2, // Disable user moving the window
NoScrollbar = 1 << 3, // Disable scrollbars (window can still scroll with mouse or programatically)
NoScrollWithMouse = 1 << 4, // Disable user vertically scrolling with mouse wheel. On child window, mouse wheel will be forwarded to the parent unless NoScrollbar is also set.
NoCollapse = 1 << 5, // Disable user collapsing window by double-clicking on it
AlwaysAutoResize = 1 << 6, // Resize every window to its content every frame
NoBackground = 1 << 7, // Disable drawing background color (WindowBg, etc.) and outside border. Similar as using SetNextWindowBgAlpha(0.0f).
NoSavedSettings = 1 << 8, // Never load/save settings in .ini file
NoMouseInputs = 1 << 9, // Disable catching mouse or keyboard inputs, hovering test with pass through.
MenuBar = 1 << 10, // Has a menu-bar
HorizontalScrollbar = 1 << 11, // Allow horizontal scrollbar to appear (off by default). You may use SetNextWindowContentSize(ImVec2(width,0.0f)); prior to calling Begin() to specify width. Read code in imgui_demo in the "Horizontal Scrolling" section.
NoFocusOnAppearing = 1 << 12, // Disable taking focus when transitioning from hidden to visible state
NoBringToFrontOnFocus = 1 << 13, // Disable bringing window to front when taking focus (e.g. clicking on it or programatically giving it focus)
AlwaysVerticalScrollbar= 1 << 14, // Always show vertical scrollbar (even if ContentSize.y < Size.y)
AlwaysHorizontalScrollbar= 1 << 15, // Always show horizontal scrollbar (even if ContentSize.x < Size.x)
AlwaysUseWindowPadding = 1 << 16, // Ensure child windows without border uses style.WindowPadding (ignored by default for non-bordered child windows, because more convenient)
NoNavInputs = 1 << 18, // No gamepad/keyboard navigation within the window
NoNavFocus = 1 << 19, // No focusing toward this window with gamepad/keyboard navigation (e.g. skipped by CTRL+TAB)
UnsavedDocument = 1 << 20, // Append '*' to title without affecting the ID, as a convenience to avoid using the ### operator. When used in a tab/docking context, tab is selected on closure and closure is deferred by one frame to allow code to cancel the closure (with a confirmation popup, etc.) without flicker.
NoNav = NoNavInputs | NoNavFocus,
NoDecoration = NoTitleBar | NoResize | NoScrollbar | NoCollapse,
NoInputs = NoMouseInputs | NoNavInputs | NoNavFocus,
// [Internal]
NavFlattened = 1 << 23, // (WIP) Allow gamepad/keyboard navigation to cross over parent border to this child (only use on child that have no scrolling!)
ChildWindow = 1 << 24, // Don't use! For internal use by BeginChild()
Tooltip = 1 << 25, // Don't use! For internal use by BeginTooltip()
Popup = 1 << 26, // Don't use! For internal use by BeginPopup()
Modal = 1 << 27, // Don't use! For internal use by BeginPopupModal()
ChildMenu = 1 << 28, // Don't use! For internal use by BeginMenu()
}
// Flags for ImGui::InputText()
export { ImGuiInputTextFlags as InputTextFlags };
export enum ImGuiInputTextFlags {
None = 0,
CharsDecimal = 1 << 0, // Allow 0123456789.+-*/
CharsHexadecimal = 1 << 1, // Allow 0123456789ABCDEFabcdef
CharsUppercase = 1 << 2, // Turn a..z into A..Z
CharsNoBlank = 1 << 3, // Filter out spaces, tabs
AutoSelectAll = 1 << 4, // Select entire text when first taking mouse focus
EnterReturnsTrue = 1 << 5, // Return 'true' when Enter is pressed (as opposed to when the value was modified)
CallbackCompletion = 1 << 6, // Call user function on pressing TAB (for completion handling)
CallbackHistory = 1 << 7, // Call user function on pressing Up/Down arrows (for history handling)
CallbackAlways = 1 << 8, // Call user function every time. User code may query cursor position, modify text buffer.
CallbackCharFilter = 1 << 9, // Call user function to filter character. Modify data->EventChar to replace/filter input, or return 1 to discard character.
AllowTabInput = 1 << 10, // Pressing TAB input a '\t' character into the text field
CtrlEnterForNewLine = 1 << 11, // In multi-line mode, unfocus with Enter, add new line with Ctrl+Enter (default is opposite: unfocus with Ctrl+Enter, add line with Enter).
NoHorizontalScroll = 1 << 12, // Disable following the cursor horizontally
AlwaysInsertMode = 1 << 13, // Insert mode
ReadOnly = 1 << 14, // Read-only mode
Password = 1 << 15, // Password mode, display all characters as '*'
NoUndoRedo = 1 << 16, // Disable undo/redo. Note that input text owns the text data while active, if you want to provide your own undo/redo stack you need e.g. to call ClearActiveID().
CharsScientific = 1 << 17, // Allow 0123456789.+-*/eE (Scientific notation input)
CallbackResize = 1 << 18, // Allow buffer capacity resize + notify when the string wants to be resized (for string types which hold a cache of their Size) (see misc/stl/imgui_stl.h for an example of using this)
CallbackEdit = 1 << 19, // Callback on any edit (note that InputText() already returns true on edit, the callback is useful mainly to manipulate the underlying buffer while focus is active)
// [Internal]
Multiline = 1 << 20, // For internal use by InputTextMultiline()
NoMarkEdited = 1 << 21, // For internal use by functions using InputText() before reformatting data
}
// Flags for ImGui::TreeNodeEx(), ImGui::CollapsingHeader*()
export { ImGuiTreeNodeFlags as TreeNodeFlags };
export enum ImGuiTreeNodeFlags {
None = 0,
Selected = 1 << 0, // Draw as selected
Framed = 1 << 1, // Full colored frame (e.g. for CollapsingHeader)
AllowItemOverlap = 1 << 2, // Hit testing to allow subsequent widgets to overlap this one
NoTreePushOnOpen = 1 << 3, // Don't do a TreePush() when open (e.g. for CollapsingHeader) = no extra indent nor pushing on ID stack
NoAutoOpenOnLog = 1 << 4, // Don't automatically and temporarily open node when Logging is active (by default logging will automatically open tree nodes)
DefaultOpen = 1 << 5, // Default node to be open
OpenOnDoubleClick = 1 << 6, // Need double-click to open node
OpenOnArrow = 1 << 7, // Only open when clicking on the arrow part. If OpenOnDoubleClick is also set, single-click arrow or double-click all box to open.
Leaf = 1 << 8, // No collapsing, no arrow (use as a convenience for leaf nodes).
Bullet = 1 << 9, // Display a bullet instead of arrow
FramePadding = 1 << 10, // Use FramePadding (even for an unframed text node) to vertically align text baseline to regular widget height. Equivalent to calling AlignTextToFramePadding().
SpanAvailWidth = 1 << 11, // Extend hit box to the right-most edge, even if not framed. This is not the default in order to allow adding other items on the same line. In the future we may refactor the hit system to be front-to-back, allowing natural overlaps and then this can become the default.
SpanFullWidth = 1 << 12, // Extend hit box to the left-most and right-most edges (bypass the indented area).
NavLeftJumpsBackHere = 1 << 13, // (WIP) Nav: left direction may move to this TreeNode() from any of its child (items submitted between TreeNode and TreePop)
CollapsingHeader = Framed | NoTreePushOnOpen | NoAutoOpenOnLog,
}
export { ImGuiPopupFlags as PopupFlags };
export enum ImGuiPopupFlags {
None = 0,
MouseButtonLeft = 0, // For BeginPopupContext*(): open on Left Mouse release. Guaranteed to always be == 0 (same as ImGuiMouseButton_Left)
MouseButtonRight = 1, // For BeginPopupContext*(): open on Right Mouse release. Guaranteed to always be == 1 (same as ImGuiMouseButton_Right)
MouseButtonMiddle = 2, // For BeginPopupContext*(): open on Middle Mouse release. Guaranteed to always be == 2 (same as ImGuiMouseButton_Middle)
MouseButtonMask_ = 0x1F,
MouseButtonDefault_ = 1,
NoOpenOverExistingPopup = 1 << 5, // For OpenPopup*(), BeginPopupContext*(): don't open if there's already a popup at the same level of the popup stack
NoOpenOverItems = 1 << 6, // For BeginPopupContextWindow(): don't return true when hovering items, only when hovering empty space
AnyPopupId = 1 << 7, // For IsPopupOpen(): ignore the ImGuiID parameter and test for any popup.
AnyPopupLevel = 1 << 8, // For IsPopupOpen(): search/test at any level of the popup stack (default test in the current level)
AnyPopup = AnyPopupId | AnyPopupLevel
}
// Flags for ImGui::Selectable()
export { ImGuiSelectableFlags as SelectableFlags };
export enum ImGuiSelectableFlags {
None = 0,
DontClosePopups = 1 << 0, // Clicking this don't close parent popup window
SpanAllColumns = 1 << 1, // Selectable frame can span all columns (text will still fit in current column)
AllowDoubleClick = 1 << 2, // Generate press events on double clicks too
Disabled = 1 << 3, // Cannot be selected, display greyed out text
AllowItemOverlap = 1 << 4 // (WIP) Hit testing to allow subsequent widgets to overlap this one
}
// Flags for ImGui::BeginCombo()
export { ImGuiComboFlags as ComboFlags };
export enum ImGuiComboFlags {
None = 0,
PopupAlignLeft = 1 << 0, // Align the popup toward the left by default
HeightSmall = 1 << 1, // Max ~4 items visible. Tip: If you want your combo popup to be a specific size you can use SetNextWindowSizeConstraints() prior to calling BeginCombo()
HeightRegular = 1 << 2, // Max ~8 items visible (default)
HeightLarge = 1 << 3, // Max ~20 items visible
HeightLargest = 1 << 4, // As many fitting items as possible
NoArrowButton = 1 << 5, // Display on the preview box without the square arrow button
NoPreview = 1 << 6, // Display only a square arrow button
HeightMask_ = HeightSmall | HeightRegular | HeightLarge | HeightLargest,
}
// Flags for ImGui::BeginTabBar()
export { ImGuiTabBarFlags as TabBarFlags };
export enum ImGuiTabBarFlags {
None = 0,
Reorderable = 1 << 0, // Allow manually dragging tabs to re-order them + New tabs are appended at the end of list
AutoSelectNewTabs = 1 << 1, // Automatically select new tabs when they appear
TabListPopupButton = 1 << 2,
NoCloseWithMiddleMouseButton = 1 << 3, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You can still repro this behavior on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false.
NoTabListScrollingButtons = 1 << 4,
NoTooltip = 1 << 5, // Disable tooltips when hovering a tab
FittingPolicyResizeDown = 1 << 6, // Resize tabs when they don't fit
FittingPolicyScroll = 1 << 7, // Add scroll buttons when tabs don't fit
FittingPolicyMask_ = FittingPolicyResizeDown | FittingPolicyScroll,
FittingPolicyDefault_ = FittingPolicyResizeDown
};
// Flags for ImGui::BeginTabItem()
export { ImGuiTabItemFlags as TabItemFlags };
export enum ImGuiTabItemFlags {
None = 0,
UnsavedDocument = 1 << 0, // Append '*' to title without affecting the ID, as a convenience to avoid using the ### operator. Also: tab is selected on closure and closure is deferred by one frame to allow code to undo it without flicker.
SetSelected = 1 << 1, // Trigger flag to programatically make the tab selected when calling BeginTabItem()
NoCloseWithMiddleMouseButton = 1 << 2, // Disable behavior of closing tabs (that are submitted with p_open != NULL) with middle mouse button. You can still repro this behavior on user's side with if (IsItemHovered() && IsMouseClicked(2)) *p_open = false.
NoPushId = 1 << 3, // Don't call PushID(tab->ID)/PopID() on BeginTabItem()/EndTabItem()
NoTooltip = 1 << 4, // Disable tooltip for the given tab
NoReorder = 1 << 5, // Disable reordering this tab or having another tab cross over this tab
Leading = 1 << 6, // Enforce the tab position to the left of the tab bar (after the tab list popup button)
Trailing = 1 << 7 // Enforce the tab position to the right of the tab bar (before the scrolling buttons)
}
export { ImGuiTableFlags as TableFlags };
export enum ImGuiTableFlags {
// Features
None = 0,
Resizable = 1 << 0, // Enable resizing columns.
Reorderable = 1 << 1, // Enable reordering columns in header row (need calling TableSetupColumn() + TableHeadersRow() to display headers)
Hideable = 1 << 2, // Enable hiding/disabling columns in context menu.
Sortable = 1 << 3, // Enable sorting. Call TableGetSortSpecs() to obtain sort specs. Also see ImGuiTableFlags_SortMulti and ImGuiTableFlags_SortTristate.
NoSavedSettings = 1 << 4, // Disable persisting columns order, width and sort settings in the .ini file.
ContextMenuInBody = 1 << 5, // Right-click on columns body/contents will display table context menu. By default it is available in TableHeadersRow().
// Decorations
RowBg = 1 << 6, // Set each RowBg color with ImGuiCol_TableRowBg or ImGuiCol_TableRowBgAlt (equivalent of calling TableSetBgColor with ImGuiTableBgFlags_RowBg0 on each row manually)
BordersInnerH = 1 << 7, // Draw horizontal borders between rows.
BordersOuterH = 1 << 8, // Draw horizontal borders at the top and bottom.
BordersInnerV = 1 << 9, // Draw vertical borders between columns.
BordersOuterV = 1 << 10, // Draw vertical borders on the left and right sides.
BordersH = BordersInnerH | BordersOuterH, // Draw horizontal borders.
BordersV = BordersInnerV | BordersOuterV, // Draw vertical borders.
BordersInner = BordersInnerV | BordersInnerH, // Draw inner borders.
BordersOuter = BordersOuterV | BordersOuterH, // Draw outer borders.
Borders = BordersInner | BordersOuter, // Draw all borders.
NoBordersInBody = 1 << 11, // [ALPHA] Disable vertical borders in columns Body (borders will always appears in Headers). -> May move to style
NoBordersInBodyUntilResize = 1 << 12, // [ALPHA] Disable vertical borders in columns Body until hovered for resize (borders will always appears in Headers). -> May move to style
// Sizing Policy (read above for defaults)
SizingFixedFit = 1 << 13, // Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching contents width.
SizingFixedSame = 2 << 13, // Columns default to _WidthFixed or _WidthAuto (if resizable or not resizable), matching the maximum contents width of all columns. Implicitly enable ImGuiTableFlags_NoKeepColumnsVisible.
SizingStretchProp = 3 << 13, // Columns default to _WidthStretch with default weights proportional to each columns contents widths.
SizingStretchSame = 4 << 13, // Columns default to _WidthStretch with default weights all equal, unless overriden by TableSetupColumn().
// Sizing Extra Options
NoHostExtendX = 1 << 16, // Make outer width auto-fit to columns, overriding outer_size.x value. Only available when ScrollX/ScrollY are disabled and Stretch columns are not used.
NoHostExtendY = 1 << 17, // Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY are disabled. Data below the limit will be clipped and not visible.
NoKeepColumnsVisible = 1 << 18, // Disable keeping column always minimally visible when ScrollX is off and table gets too small. Not recommended if columns are resizable.
PreciseWidths = 1 << 19, // Disable distributing remainder width to stretched columns (width allocation on a 100-wide table with 3 columns: Without this flag: 33,33,34. With this flag: 33,33,33). With larger number of columns, resizing will appear to be less smooth.
// Clipping
NoClip = 1 << 20, // Disable clipping rectangle for every individual columns (reduce draw command count, items will be able to overflow into other columns). Generally incompatible with TableSetupScrollFreeze().
// Padding
PadOuterX = 1 << 21, // Default if BordersOuterV is on. Enable outer-most padding. Generally desirable if you have headers.
NoPadOuterX = 1 << 22, // Default if BordersOuterV is off. Disable outer-most padding.
NoPadInnerX = 1 << 23, // Disable inner padding between columns (double inner padding if BordersOuterV is on, single inner padding if BordersOuterV is off).
// Scrolling
ScrollX = 1 << 24, // Enable horizontal scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size. Changes default sizing policy. Because this create a child window, ScrollY is currently generally recommended when using ScrollX.
ScrollY = 1 << 25, // Enable vertical scrolling. Require 'outer_size' parameter of BeginTable() to specify the container size.
// Sorting
SortMulti = 1 << 26, // Hold shift when clicking headers to sort on multiple column. TableGetSortSpecs() may return specs where (SpecsCount > 1).
SortTristate = 1 << 27, // Allow no sorting, disable default sorting. TableGetSortSpecs() may return specs where (SpecsCount == 0).
// [Internal] Combinations and masks
SizingMask_ = SizingFixedFit | SizingFixedSame | SizingStretchProp | SizingStretchSame
}
// Flags for ImGui::TableSetupColumn()
export { ImGuiTableColumnFlags as TableColumnFlags };
export enum ImGuiTableColumnFlags {
// Input configuration flags
None = 0,
DefaultHide = 1 << 0, // Default as a hidden/disabled column.
DefaultSort = 1 << 1, // Default as a sorting column.
WidthStretch = 1 << 2, // Column will stretch. Preferable with horizontal scrolling disabled (default if table sizing policy is _SizingStretchSame or _SizingStretchProp).
WidthFixed = 1 << 3, // Column will not stretch. Preferable with horizontal scrolling enabled (default if table sizing policy is _SizingFixedFit and table is resizable).
NoResize = 1 << 4, // Disable manual resizing.
NoReorder = 1 << 5, // Disable manual reordering this column, this will also prevent other columns from crossing over this column.
NoHide = 1 << 6, // Disable ability to hide/disable this column.
NoClip = 1 << 7, // Disable clipping for this column (all NoClip columns will render in a same draw command).
NoSort = 1 << 8, // Disable ability to sort on this field (even if ImGuiTableFlags_Sortable is set on the table).
NoSortAscending = 1 << 9, // Disable ability to sort in the ascending direction.
NoSortDescending = 1 << 10, // Disable ability to sort in the descending direction.
NoHeaderWidth = 1 << 11, // Disable header text width contribution to automatic column width.
PreferSortAscending = 1 << 12, // Make the initial sort direction Ascending when first sorting on this column (default).
PreferSortDescending = 1 << 13, // Make the initial sort direction Descending when first sorting on this column.
IndentEnable = 1 << 14, // Use current Indent value when entering cell (default for column 0).
IndentDisable = 1 << 15, // Ignore current Indent value when entering cell (default for columns > 0). Indentation changes _within_ the cell will still be honored.
// Output status flags, read-only via TableGetColumnFlags()
IsEnabled = 1 << 20, // Status: is enabled == not hidden by user/api (referred to as "Hide" in _DefaultHide and _NoHide) flags.
IsVisible = 1 << 21, // Status: is visible == is enabled AND not clipped by scrolling.
IsSorted = 1 << 22, // Status: is currently part of the sort specs
IsHovered = 1 << 23, // Status: is hovered by mouse
// [Internal] Combinations and masks
WidthMask_ = WidthStretch | WidthFixed,
IndentMask_ = IndentEnable | IndentDisable,
StatusMask_ = IsEnabled | IsVisible | IsSorted | IsHovered,
NoDirectResize_ = 1 << 30 // [Internal] Disable user resizing this column directly (it may however we resized indirectly from its left edge)
}
// Flags for ImGui::TableNextRow()
export { ImGuiTableRowFlags as TableRowFlags };
export enum ImGuiTableRowFlags {
None = 0,
Headers = 1 << 0 // Identify header row (set default background color + width of its contents accounted different for auto column width)
}
// Enum for ImGui::TableSetBgColor()
// Background colors are rendering in 3 layers:
// - Layer 0: draw with RowBg0 color if set, otherwise draw with ColumnBg0 if set.
// - Layer 1: draw with RowBg1 color if set, otherwise draw with ColumnBg1 if set.
// - Layer 2: draw with CellBg color if set.
// The purpose of the two row/columns layers is to let you decide if a background color changes should override or blend with the existing color.
// When using ImGuiTableFlags_RowBg on the table, each row has the RowBg0 color automatically set for odd/even rows.
// If you set the color of RowBg0 target, your color will override the existing RowBg0 color.
// If you set the color of RowBg1 or ColumnBg1 target, your color will blend over the RowBg0 color.
export { ImGuiTableBgTarget as TableBgTarget };
export enum ImGuiTableBgTarget {
None = 0,
RowBg0 = 1, // Set row background color 0 (generally used for background, automatically set when ImGuiTableFlags_RowBg is used)
RowBg1 = 2, // Set row background color 1 (generally used for selection marking)
CellBg = 3 // Set cell background color (top-most color)
}
// Flags for ImGui::IsWindowFocused()
export { ImGuiFocusedFlags as FocusedFlags };
export enum ImGuiFocusedFlags {
None = 0,
ChildWindows = 1 << 0, // IsWindowFocused(): Return true if any children of the window is focused
RootWindow = 1 << 1, // IsWindowFocused(): Test from root window (top most parent of the current hierarchy)
AnyWindow = 1 << 2, // IsWindowFocused(): Return true if any window is focused
RootAndChildWindows = RootWindow | ChildWindows,
}
// Flags for ImGui::IsItemHovered(), ImGui::IsWindowHovered()
export { ImGuiHoveredFlags as HoveredFlags };
export enum ImGuiHoveredFlags {
None = 0, // Return true if directly over the item/window, not obstructed by another window, not obstructed by an active popup or modal blocking inputs under them.
ChildWindows = 1 << 0, // IsWindowHovered() only: Return true if any children of the window is hovered
RootWindow = 1 << 1, // IsWindowHovered() only: Test from root window (top most parent of the current hierarchy)
AnyWindow = 1 << 2, // IsWindowHovered() only: Return true if any window is hovered
AllowWhenBlockedByPopup = 1 << 3, // Return true even if a popup window is normally blocking access to this item/window
//AllowWhenBlockedByModal = 1 << 4, // Return true even if a modal popup window is normally blocking access to this item/window. FIXME-TODO: Unavailable yet.
AllowWhenBlockedByActiveItem = 1 << 5, // Return true even if an active item is blocking access to this item/window. Useful for Drag and Drop patterns.
AllowWhenOverlapped = 1 << 6, // Return true even if the position is overlapped by another window
AllowWhenDisabled = 1 << 7, // Return true even if the item is disabled
RectOnly = AllowWhenBlockedByPopup | AllowWhenBlockedByActiveItem | AllowWhenOverlapped,
RootAndChildWindows = RootWindow | ChildWindows,
}
// Flags for ImGui::BeginDragDropSource(), ImGui::AcceptDragDropPayload()
export { ImGuiDragDropFlags as DragDropFlags };
export enum ImGuiDragDropFlags {
// BeginDragDropSource() flags
None = 0,
SourceNoPreviewTooltip = 1 << 0, // By default, a successful call to BeginDragDropSource opens a tooltip so you can display a preview or description of the source contents. This flag disable this behavior.
SourceNoDisableHover = 1 << 1, // By default, when dragging we clear data so that IsItemHovered() will return true, to avoid subsequent user code submitting tooltips. This flag disable this behavior so you can still call IsItemHovered() on the source item.
SourceNoHoldToOpenOthers = 1 << 2, // Disable the behavior that allows to open tree nodes and collapsing header by holding over them while dragging a source item.
SourceAllowNullID = 1 << 3, // Allow items such as Text(), Image() that have no unique identifier to be used as drag source, by manufacturing a temporary identifier based on their window-relative position. This is extremely unusual within the dear imgui ecosystem and so we made it explicit.
SourceExtern = 1 << 4, // External source (from outside of imgui), won't attempt to read current item/window info. Will always return true. Only one Extern source can be active simultaneously.
SourceAutoExpirePayload = 1 << 5, // Automatically expire the payload if the source cease to be submitted (otherwise payloads are persisting while being dragged)
// AcceptDragDropPayload() flags
AcceptBeforeDelivery = 1 << 10, // AcceptDragDropPayload() will returns true even before the mouse button is released. You can then call IsDelivery() to test if the payload needs to be delivered.
AcceptNoDrawDefaultRect = 1 << 11, // Do not draw the default highlight rectangle when hovering over target.
AcceptNoPreviewTooltip = 1 << 12, // Request hiding the BeginDragDropSource tooltip from the BeginDragDropTarget site.
AcceptPeekOnly = AcceptBeforeDelivery | AcceptNoDrawDefaultRect, // For peeking ahead and inspecting the payload before delivery.
}
// Standard Drag and Drop payload types. You can define you own payload types using 12-characters long strings. Types starting with '_' are defined by Dear ImGui.
export const IMGUI_PAYLOAD_TYPE_COLOR_3F: string = "_COL3F"; // float[3] // Standard type for colors, without alpha. User code may use this type.
export const IMGUI_PAYLOAD_TYPE_COLOR_4F: string = "_COL4F"; // float[4] // Standard type for colors. User code may use this type.
// A primary data type
export { ImGuiDataType as DataType };
export enum ImGuiDataType {
S8, // char
U8, // unsigned char
S16, // short
U16, // unsigned short
S32, // int
U32, // unsigned int
S64, // long long, __int64
U64, // unsigned long long, unsigned __int64
Float, // float
Double, // double
COUNT
}
// A cardinal direction
export { ImGuiDir as Dir };
export enum ImGuiDir {
None = -1,
Left = 0,
Right = 1,
Up = 2,
Down = 3,
COUNT
}
// A sorting direction
export { ImGuiSortDirection as SortDirection };
export enum ImGuiSortDirection {
None = 0,
Ascending = 1, // Ascending = 0->9, A->Z etc.
Descending = 2 // Descending = 9->0, Z->A etc.
}
// User fill ImGuiIO.KeyMap[] array with indices into the ImGuiIO.KeysDown[512] array
export { ImGuiKey as Key };
export enum ImGuiKey {
Tab,
LeftArrow,
RightArrow,
UpArrow,
DownArrow,
PageUp,
PageDown,
Home,
End,
Insert,
Delete,
Backspace,
Space,
Enter,
Escape,
KeyPadEnter,
A, // for text edit CTRL+A: select all
C, // for text edit CTRL+C: copy
V, // for text edit CTRL+V: paste
X, // for text edit CTRL+X: cut
Y, // for text edit CTRL+Y: redo
Z, // for text edit CTRL+Z: undo
COUNT,
}
// To test io.KeyMods (which is a combination of individual fields io.KeyCtrl, io.KeyShift, io.KeyAlt set by user/backend)
export { ImGuiKeyModFlags as KeyModFlags };
export enum ImGuiKeyModFlags {
None = 0,
Ctrl = 1 << 0,
Shift = 1 << 1,
Alt = 1 << 2,
Super = 1 << 3
}
// [BETA] Gamepad/Keyboard directional navigation
// Keyboard: Set io.ConfigFlags |= EnableKeyboard to enable. NewFrame() will automatically fill io.NavInputs[] based on your io.KeyDown[] + io.KeyMap[] arrays.
// Gamepad: Set io.ConfigFlags |= EnableGamepad to enable. Fill the io.NavInputs[] fields before calling NewFrame(). Note that io.NavInputs[] is cleared by EndFrame().
// Read instructions in imgui.cpp for more details.
export { ImGuiNavInput as NavInput };
export enum ImGuiNavInput
{
// Gamepad Mapping
Activate, // activate / open / toggle / tweak value // e.g. Circle (PS4), A (Xbox), B (Switch), Space (Keyboard)
Cancel, // cancel / close / exit // e.g. Cross (PS4), B (Xbox), A (Switch), Escape (Keyboard)
Input, // text input / on-screen keyboard // e.g. Triang.(PS4), Y (Xbox), X (Switch), Return (Keyboard)
Menu, // tap: toggle menu / hold: focus, move, resize // e.g. Square (PS4), X (Xbox), Y (Switch), Alt (Keyboard)
DpadLeft, // move / tweak / resize window (w/ PadMenu) // e.g. D-pad Left/Right/Up/Down (Gamepads), Arrow keys (Keyboard)
DpadRight, //
DpadUp, //
DpadDown, //
LStickLeft, // scroll / move window (w/ PadMenu) // e.g. Left Analog Stick Left/Right/Up/Down
LStickRight, //
LStickUp, //
LStickDown, //
FocusPrev, // next window (w/ PadMenu) // e.g. L1 or L2 (PS4), LB or LT (Xbox), L or ZL (Switch)
FocusNext, // prev window (w/ PadMenu) // e.g. R1 or R2 (PS4), RB or RT (Xbox), R or ZL (Switch)
TweakSlow, // slower tweaks // e.g. L1 or L2 (PS4), LB or LT (Xbox), L or ZL (Switch)
TweakFast, // faster tweaks // e.g. R1 or R2 (PS4), RB or RT (Xbox), R or ZL (Switch)
// [Internal] Don't use directly! This is used internally to differentiate keyboard from gamepad inputs for behaviors that require to differentiate them.
// Keyboard behavior that have no corresponding gamepad mapping (e.g. CTRL+TAB) may be directly reading from io.KeyDown[] instead of io.NavInputs[].
KeyMenu_, // toggle menu // = io.KeyAlt
KeyLeft_, // move left // = Arrow keys
KeyRight_, // move right
KeyUp_, // move up
KeyDown_, // move down
COUNT,
InternalStart_ = KeyMenu_,
}
// [BETA] Gamepad/Keyboard directional navigation flags, stored in io.ConfigFlags
export { ImGuiConfigFlags as ConfigFlags };
export enum ImGuiConfigFlags
{
None = 0,
NavEnableKeyboard = 1 << 0, // Master keyboard navigation enable flag. NewFrame() will automatically fill io.NavInputs[] based on io.KeyDown[].
NavEnableGamepad = 1 << 1, // Master gamepad navigation enable flag. This is mostly to instruct your imgui back-end to fill io.NavInputs[].
NavEnableSetMousePos = 1 << 2, // Request navigation to allow moving the mouse cursor. May be useful on TV/console systems where moving a virtual mouse is awkward. Will update io.MousePos and set io.WantMoveMouse=true. If enabled you MUST honor io.WantMoveMouse requests in your binding, otherwise ImGui will react as if the mouse is jumping around back and forth.
NavNoCaptureKeyboard = 1 << 3, // Do not set the io.WantCaptureKeyboard flag with io.NavActive is set.
NoMouse = 1 << 4, // Instruct imgui to clear mouse position/buttons in NewFrame(). This allows ignoring the mouse information back-end
NoMouseCursorChange = 1 << 5, // Instruct back-end to not alter mouse cursor shape and visibility.
IsSRGB = 1 << 20, // Application is SRGB-aware.
IsTouchScreen = 1 << 21 // Application is using a touch screen instead of a mouse.
}
// Enumeration for PushStyleColor() / PopStyleColor()
export { ImGuiCol as Col };
export enum ImGuiCol {
Text,
TextDisabled,
WindowBg, // Background of normal windows
ChildBg, // Background of child windows
PopupBg, // Background of popups, menus, tooltips windows
Border,
BorderShadow,
FrameBg, // Background of checkbox, radio button, plot, slider, text input
FrameBgHovered,
FrameBgActive,
TitleBg,
TitleBgActive,
TitleBgCollapsed,
MenuBarBg,
ScrollbarBg,
ScrollbarGrab,
ScrollbarGrabHovered,
ScrollbarGrabActive,
CheckMark,
SliderGrab,
SliderGrabActive,
Button,
ButtonHovered,
ButtonActive,
Header,
HeaderHovered,
HeaderActive,
Separator,
SeparatorHovered,
SeparatorActive,
ResizeGrip,
ResizeGripHovered,
ResizeGripActive,
Tab,
TabHovered,
TabActive,
TabUnfocused,
TabUnfocusedActive,
PlotLines,
PlotLinesHovered,
PlotHistogram,
PlotHistogramHovered,
TableHeaderBg, // Table header background
TableBorderStrong, // Table outer and header borders (prefer using Alpha=1.0 here)
TableBorderLight, // Table inner borders (prefer using Alpha=1.0 here)
TableRowBg, // Table row background (even rows)
TableRowBgAlt, // Table row background (odd rows)
TextSelectedBg,
DragDropTarget,
NavHighlight, // Gamepad/keyboard: current highlighted item
NavWindowingHighlight, // Highlight window when using CTRL+TAB
NavWindowingDimBg, // Darken/colorize entire screen behind the CTRL+TAB window list, when active
ModalWindowDimBg, // Darken/colorize entire screen behind a modal window, when one is active
COUNT,
}
// Enumeration for PushStyleVar() / PopStyleVar() to temporarily modify the ImGuiStyle structure.
// NB: the enum only refers to fields of ImGuiStyle which makes sense to be pushed/popped inside UI code. During initialization, feel free to just poke into ImGuiStyle directly.
// NB: if changing this enum, you need to update the associated internal table GStyleVarInfo[] accordingly. This is where we link enum values to members offset/type.
export { ImGuiStyleVar as StyleVar };
export enum ImGuiStyleVar {
// Enum name --------------------- // Member in ImGuiStyle structure (see ImGuiStyle for descriptions)
Alpha, // float Alpha
WindowPadding, // ImVec2 WindowPadding
WindowRounding, // float WindowRounding
WindowBorderSize, // float WindowBorderSize
WindowMinSize, // ImVec2 WindowMinSize
WindowTitleAlign, // ImVec2 WindowTitleAlign
ChildRounding, // float ChildRounding
ChildBorderSize, // float ChildBorderSize
PopupRounding, // float PopupRounding
PopupBorderSize, // float PopupBorderSize
FramePadding, // ImVec2 FramePadding
FrameRounding, // float FrameRounding
FrameBorderSize, // float FrameBorderSize
ItemSpacing, // ImVec2 ItemSpacing
ItemInnerSpacing, // ImVec2 ItemInnerSpacing
IndentSpacing, // float IndentSpacing
CellPadding, // ImVec2 CellPadding
ScrollbarSize, // float ScrollbarSize
ScrollbarRounding, // float ScrollbarRounding
GrabMinSize, // float GrabMinSize
GrabRounding, // float GrabRounding
TabRounding, // float TabRounding
ButtonTextAlign, // ImVec2 ButtonTextAlign
SelectableTextAlign, // ImVec2 SelectableTextAlign
COUNT
}
// Back-end capabilities flags stored in io.BackendFlags. Set by imgui_impl_xxx or custom back-end.
export { ImGuiBackendFlags as BackendFlags };
export enum ImGuiBackendFlags {
None = 0,
HasGamepad = 1 << 0, // Back-end has a connected gamepad.
HasMouseCursors = 1 << 1, // Back-end can honor GetMouseCursor() values and change the OS cursor shape.
HasSetMousePos = 1 << 2, // Back-end can honor io.WantSetMousePos and reposition the mouse (only used if ImGuiConfigFlags_NavEnableSetMousePos is set).
RendererHasVtxOffset = 1 << 3, // Back-end Renderer supports ImDrawCmd::VtxOffset. This enables output of large meshes (64K+ vertices) while still using 16-bits indices.
}
// Flags for InvisibleButton() [extended in imgui_internal.h]
export { ImGuiButtonFlags as ButtonFlags };
export enum ImGuiButtonFlags {
None = 0,
MouseButtonLeft = 1 << 0, // React on left mouse button (default)
MouseButtonRight = 1 << 1, // React on right mouse button
MouseButtonMiddle = 1 << 2, // React on center mouse button
// [Internal]
MouseButtonMask_ = MouseButtonLeft | MouseButtonRight | MouseButtonMiddle,
MouseButtonDefault_ = MouseButtonLeft
}
// Enumeration for ColorEdit3() / ColorEdit4() / ColorPicker3() / ColorPicker4() / ColorButton()
export { ImGuiColorEditFlags as ColorEditFlags };
export enum ImGuiColorEditFlags {
None = 0,
NoAlpha = 1 << 1, // // ColorEdit, ColorPicker, ColorButton: ignore Alpha component (read 3 components from the input pointer).
NoPicker = 1 << 2, // // ColorEdit: disable picker when clicking on colored square.
NoOptions = 1 << 3, // // ColorEdit: disable toggling options menu when right-clicking on inputs/small preview.
NoSmallPreview = 1 << 4, // // ColorEdit, ColorPicker: disable colored square preview next to the inputs. (e.g. to show only the inputs)
NoInputs = 1 << 5, // // ColorEdit, ColorPicker: disable inputs sliders/text widgets (e.g. to show only the small preview colored square).
NoTooltip = 1 << 6, // // ColorEdit, ColorPicker, ColorButton: disable tooltip when hovering the preview.
NoLabel = 1 << 7, // // ColorEdit, ColorPicker: disable display of inline text label (the label is still forwarded to the tooltip and picker).
NoSidePreview = 1 << 8, // // ColorPicker: disable bigger color preview on right side of the picker, use small colored square preview instead.
NoDragDrop = 1 << 9, // // ColorEdit: disable drag and drop target. ColorButton: disable drag and drop source.
NoBorder = 1 << 10, // // ColorButton: disable border (which is enforced by default)
// User Options (right-click on widget to change some of them). You can set application defaults using SetColorEditOptions(). The idea is that you probably don't want to override them in most of your calls, let the user choose and/or call SetColorEditOptions() during startup.
AlphaBar = 1 << 16, // // ColorEdit, ColorPicker: show vertical alpha bar/gradient in picker.
AlphaPreview = 1 << 17, // // ColorEdit, ColorPicker, ColorButton: display preview as a transparent color over a checkerboard, instead of opaque.
AlphaPreviewHalf= 1 << 18, // // ColorEdit, ColorPicker, ColorButton: display half opaque / half checkerboard, instead of opaque.
HDR = 1 << 19, // // (WIP) ColorEdit: Currently only disable 0.0f..1.0f limits in RGBA edition (note: you probably want to use Float flag as well).
DisplayRGB = 1 << 20, // [Inputs] // ColorEdit: choose one among RGB/HSV/HEX. ColorPicker: choose any combination using RGB/HSV/HEX.
DisplayHSV = 1 << 21, // [Inputs] // "
DisplayHex = 1 << 22, // [Inputs] // "
Uint8 = 1 << 23, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0..255.
Float = 1 << 24, // [DataType] // ColorEdit, ColorPicker, ColorButton: _display_ values formatted as 0.0f..1.0f floats instead of 0..255 integers. No round-trip of value via integers.
PickerHueBar = 1 << 25, // [PickerMode] // ColorPicker: bar for Hue, rectangle for Sat/Value.
PickerHueWheel = 1 << 26, // [PickerMode] // ColorPicker: wheel for Hue, triangle for Sat/Value.
InputRGB = 1 << 27, // [Input] // ColorEdit, ColorPicker: input and output data in RGB format.
InputHSV = 1 << 28, // [Input] // ColorEdit, ColorPicker: input and output data in HSV format.
// Defaults Options. You can set application defaults using SetColorEditOptions(). The intent is that you probably don't want to
// override them in most of your calls. Let the user choose via the option menu and/or call SetColorEditOptions() once during startup.
_OptionsDefault = Uint8|DisplayRGB|InputRGB|PickerHueBar,
// [Internal] Masks
_DisplayMask = DisplayRGB|DisplayHSV|DisplayHex,
_DataTypeMask = Uint8|Float,
_PickerMask = PickerHueWheel|PickerHueBar,
_InputMask = InputRGB|InputHSV,
}
// Flags for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc.
// We use the same sets of flags for DragXXX() and SliderXXX() functions as the features are the same and it makes it easier to swap them.
export { ImGuiSliderFlags as SliderFlags };
export enum ImGuiSliderFlags {
None = 0,
AlwaysClamp = 1 << 4, // Clamp value to min/max bounds when input manually with CTRL+Click. By default CTRL+Click allows going out of bounds.
Logarithmic = 1 << 5, // Make the widget logarithmic (linear otherwise). Consider using ImGuiSliderFlags_NoRoundToFormat with this if using a format-string with small amount of digits.
NoRoundToFormat = 1 << 6, // Disable rounding underlying value to match precision of the display format string (e.g. %.3f values are rounded to those 3 digits)
NoInput = 1 << 7, // Disable CTRL+Click or Enter key allowing to input text directly into the widget
InvalidMask_ = 0x7000000F // [Internal] We treat using those bits as being potentially a 'float power' argument from the previous API that has got miscast to this enum, and will trigger an assert if needed.
}
// Identify a mouse button.
// Those values are guaranteed to be stable and we frequently use 0/1 directly. Named enums provided for convenience.
export { ImGuiMouseButton as MouseButton };
export enum ImGuiMouseButton {
Left = 0,
Right = 1,
Middle = 2,
COUNT = 5
}
// Enumeration for GetMouseCursor()
export { ImGuiMouseCursor as MouseCursor };
export enum ImGuiMouseCursor {
None = -1,
Arrow = 0,
TextInput, // When hovering over InputText, etc.
ResizeAll, // (Unused by imgui functions)
ResizeNS, // When hovering over an horizontal border
ResizeEW, // When hovering over a vertical border or a column
ResizeNESW, // When hovering over the bottom-left corner of a window
ResizeNWSE, // When hovering over the bottom-right corner of a window
Hand, // (Unused by imgui functions. Use for e.g. hyperlinks)
NotAllowed, // When hovering something with disallowed interaction. Usually a crossed circle.
COUNT,
}
// Condition for ImGui::SetWindow***(), SetNextWindow***(), SetNextTreeNode***() functions
// All those functions treat 0 as a shortcut to Always. From the point of view of the user use this as an enum (don't combine multiple values into flags).
export { ImGuiCond as Cond };
export enum ImGuiCond {
None = 0, // No condition (always set the variable), same as _Always
Always = 1 << 0, // Set the variable
Once = 1 << 1, // Set the variable once per runtime session (only the first call with succeed)
FirstUseEver = 1 << 2, // Set the variable if the window has no saved data (if doesn't exist in the .ini file)
Appearing = 1 << 3, // Set the variable if the window is appearing after being hidden/inactive (or the first time)
}
export { ImDrawCornerFlags as DrawCornerFlags };
export enum ImDrawCornerFlags
{
None = 0,
TopLeft = 1 << 0, // 0x1
TopRight = 1 << 1, // 0x2
BotLeft = 1 << 2, // 0x4
BotRight = 1 << 3, // 0x8
Top = TopLeft | TopRight, // 0x3
Bot = BotLeft | BotRight, // 0xC
Left = TopLeft | BotLeft, // 0x5
Right = TopRight | BotRight, // 0xA
All = 0xF, // In your function calls you may use ~0 (= all bits sets) instead of All, as a convenience
}
export { ImDrawListFlags as wListFlags };
export enum ImDrawListFlags
{
None = 0,
AntiAliasedLines = 1 << 0,
AntiAliasedLinesUseTex = 1 << 1, // Enable anti-aliased lines/borders using textures when possible. Require backend to render with bilinear filtering.
AntiAliasedFill = 1 << 2, // Enable anti-aliased edge around filled shapes (rounded rectangles, circles).
AllowVtxOffset = 1 << 3 // Can emit 'VtxOffset > 0' to allow large meshes. Set when 'ImGuiBackendFlags_RendererHasVtxOffset' is enabled.
}
export { ImU32 as U32 }
export type ImU32 = Bind.ImU32;
export { interface_ImVec2 } from "bind-imgui";
export { reference_ImVec2 } from "bind-imgui";
export { ImVec2 as Vec2 }
export class ImVec2 implements Bind.interface_ImVec2 {
public static readonly ZERO: Readonly<ImVec2> = new ImVec2(0.0, 0.0);
public static readonly UNIT: Readonly<ImVec2> = new ImVec2(1.0, 1.0);
public static readonly UNIT_X: Readonly<ImVec2> = new ImVec2(1.0, 0.0);
public static readonly UNIT_Y: Readonly<ImVec2> = new ImVec2(0.0, 1.0);
constructor(public x: number = 0.0, public y: number = 0.0) {}
public Set(x: number, y: number): this {
this.x = x;
this.y = y;
return this;
}
public Copy(other: Readonly<Bind.interface_ImVec2>): this {
this.x = other.x;
this.y = other.y;
return this;
}
public Equals(other: Readonly<Bind.interface_ImVec2>): boolean {
if (this.x !== other.x) { return false; }
if (this.y !== other.y) { return false; }
return true;
}
}
export { interface_ImVec4 } from "bind-imgui";
export { reference_ImVec4 } from "bind-imgui";
export { ImVec4 as Vec4 }
export class ImVec4 implements Bind.interface_ImVec4 {
public static readonly ZERO: Readonly<ImVec4> = new ImVec4(0.0, 0.0, 0.0, 0.0);
public static readonly UNIT: Readonly<ImVec4> = new ImVec4(1.0, 1.0, 1.0, 1.0);
public static readonly UNIT_X: Readonly<ImVec4> = new ImVec4(1.0, 0.0, 0.0, 0.0);
public static readonly UNIT_Y: Readonly<ImVec4> = new ImVec4(0.0, 1.0, 0.0, 0.0);
public static readonly UNIT_Z: Readonly<ImVec4> = new ImVec4(0.0, 0.0, 1.0, 0.0);
public static readonly UNIT_W: Readonly<ImVec4> = new ImVec4(0.0, 0.0, 0.0, 1.0);
public static readonly BLACK: Readonly<ImVec4> = new ImVec4(0.0, 0.0, 0.0, 1.0);
public static readonly WHITE: Readonly<ImVec4> = new ImVec4(1.0, 1.0, 1.0, 1.0);
constructor(public x: number = 0.0, public y: number = 0.0, public z: number = 0.0, public w: number = 1.0) {}
public Set(x: number, y: number, z: number, w: number): this {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
return this;
}
public Copy(other: Readonly<Bind.interface_ImVec4>): this {
this.x = other.x;
this.y = other.y;
this.z = other.z;
this.w = other.w;
return this;
}
public Equals(other: Readonly<Bind.interface_ImVec4>): boolean {
if (this.x !== other.x) { return false; }
if (this.y !== other.y) { return false; }
if (this.z !== other.z) { return false; }
if (this.w !== other.w) { return false; }
return true;
}
}
//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------
// Lightweight std::vector<> like class to avoid dragging dependencies (also: windows implementation of STL with debug enabled is absurdly slow, so let's bypass it so our code runs fast in debug).
// Our implementation does NOT call C++ constructors/destructors. This is intentional and we do not require it. Do not use this class as a straight std::vector replacement in your code!
export { ImVector as Vector }
export class ImVector<T> extends Array<T>
{
public get Size(): number { return this.length; }
public Data: T[] = this;
public empty(): boolean { return this.length === 0; }
public clear(): void { this.length = 0; }
public pop_back(): T | undefined { return this.pop(); }
public push_back(value: T): void { this.push(value); }
public front(): T { IM_ASSERT(this.Size > 0); return this.Data[0]; }
public back(): T { IM_ASSERT(this.Size > 0); return this.Data[this.Size - 1]; }
public size(): number { return this.Size; }
public resize(new_size: number, v?: (index: number) => T): void {
if (v) {
for (let index = this.length; index < new_size; ++index) {
this[index] = v(index);
}
}
else {
this.length = new_size;
}
}
public contains(value: T): boolean {
return this.includes(value);
}
public find_erase_unsorted(value: T): void {
const index = this.indexOf(value);
if (index !== -1) {
this.splice(index, 1);
}
}
// public:
// int Size;
// int Capacity;
// T* Data;
// typedef T value_type;
// typedef value_type* iterator;
// typedef const value_type* const_iterator;
// inline ImVector() { Size = Capacity = 0; Data = NULL; }
// inline ~ImVector() { if (Data) ImGui::MemFree(Data); }
// inline bool empty() const { return Size == 0; }
// inline int size() const { return Size; }
// inline int capacity() const { return Capacity; }
// inline value_type& operator[](int i) { IM_ASSERT(i < Size); return Data[i]; }
// inline const value_type& operator[](int i) const { IM_ASSERT(i < Size); return Data[i]; }
// inline void clear() { if (Data) { Size = Capacity = 0; ImGui::MemFree(Data); Data = NULL; } }
// inline iterator begin() { return Data; }
// inline const_iterator begin() const { return Data; }
// inline iterator end() { return Data + Size; }
// inline const_iterator end() const { return Data + Size; }
// inline value_type& front() { IM_ASSERT(Size > 0); return Data[0]; }
// inline const value_type& front() const { IM_ASSERT(Size > 0); return Data[0]; }
// inline value_type& back() { IM_ASSERT(Size > 0); return Data[Size - 1]; }
// inline const value_type& back() const { IM_ASSERT(Size > 0); return Data[Size - 1]; }
// inline void swap(ImVector<T>& rhs) { int rhs_size = rhs.Size; rhs.Size = Size; Size = rhs_size; int rhs_cap = rhs.Capacity; rhs.Capacity = Capacity; Capacity = rhs_cap; value_type* rhs_data = rhs.Data; rhs.Data = Data; Data = rhs_data; }
// inline int _grow_capacity(int size) const { int new_capacity = Capacity ? (Capacity + Capacity/2) : 8; return new_capacity > size ? new_capacity : size; }
// inline void resize(int new_size) { if (new_size > Capacity) reserve(_grow_capacity(new_size)); Size = new_size; }
// inline void resize(int new_size, const T& v){ if (new_size > Capacity) reserve(_grow_capacity(new_size)); if (new_size > Size) for (int n = Size; n < new_size; n++) Data[n] = v; Size = new_size; }
// inline void reserve(int new_capacity)
// {
// if (new_capacity <= Capacity)
// return;
// T* new_data = (value_type*)ImGui::MemAlloc((size_t)new_capacity * sizeof(T));
// if (Data)
// memcpy(new_data, Data, (size_t)Size * sizeof(T));
// ImGui::MemFree(Data);
// Data = new_data;
// Capacity = new_capacity;
// }
// inline void push_back(const value_type& v) { if (Size == Capacity) reserve(_grow_capacity(Size + 1)); Data[Size++] = v; }
// inline void pop_back() { IM_ASSERT(Size > 0); Size--; }
// inline void push_front(const value_type& v) { if (Size == 0) push_back(v); else insert(Data, v); }
// inline iterator erase(const_iterator it) { IM_ASSERT(it >= Data && it < Data+Size); const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + 1, ((size_t)Size - (size_t)off - 1) * sizeof(value_type)); Size--; return Data + off; }
// inline iterator erase(const_iterator it, const_iterator it_last){ IM_ASSERT(it >= Data && it < Data+Size && it_last > it && it_last <= Data+Size); const ptrdiff_t count = it_last - it; const ptrdiff_t off = it - Data; memmove(Data + off, Data + off + count, ((size_t)Size - (size_t)off - count) * sizeof(value_type)); Size -= (int)count; return Data + off; }
// inline iterator erase_unsorted(const_iterator it) { IM_ASSERT(it >= Data && it < Data+Size); const ptrdiff_t off = it - Data; if (it < Data+Size-1) memcpy(Data + off, Data + Size - 1, sizeof(value_type)); Size--; return Data + off; }
// inline iterator insert(const_iterator it, const value_type& v) { IM_ASSERT(it >= Data && it <= Data+Size); const ptrdiff_t off = it - Data; if (Size == Capacity) reserve(_grow_capacity(Size + 1)); if (off < (int)Size) memmove(Data + off + 1, Data + off, ((size_t)Size - (size_t)off) * sizeof(value_type)); Data[off] = v; Size++; return Data + off; }
// inline bool contains(const value_type& v) const { const T* data = Data; const T* data_end = Data + Size; while (data < data_end) if (*data++ == v) return true; return false; }
}
// Helper: Unicode defines
// #define IM_UNICODE_CODEPOINT_INVALID 0xFFFD // Invalid Unicode code point (standard value).
// #ifdef IMGUI_USE_WCHAR32
// #define IM_UNICODE_CODEPOINT_MAX 0x10FFFF // Maximum Unicode code point supported by this build.
// #else
// #define IM_UNICODE_CODEPOINT_MAX 0xFFFF // Maximum Unicode code point supported by this build.
// #endif
export { IM_UNICODE_CODEPOINT_MAX as UNICODE_CODEPOINT_MAX }
export const IM_UNICODE_CODEPOINT_MAX: number = 0xFFFF; // Maximum Unicode code point supported by this build.
// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
export { ImGuiTextFilter as TextFilter }
export class ImGuiTextFilter
{
// IMGUI_API ImGuiTextFilter(const char* default_filter = "");
constructor(default_filter: string = "") {
if (default_filter)
{
// ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
this.InputBuf.buffer = default_filter;
this.Build();
}
else
{
// InputBuf[0] = 0;
this.InputBuf.buffer = "";
this.CountGrep = 0;
}
}
// IMGUI_API bool Draw(const char* label = "Filter (inc,-exc)", float width = 0.0f); // Helper calling InputText+Build
public Draw(label: string = "Filter (inc,-exc)", width: number = 0.0): boolean {
if (width !== 0.0)
bind.PushItemWidth(width);
const value_changed: boolean = InputText(label, this.InputBuf, IM_ARRAYSIZE(this.InputBuf));
if (width !== 0.0)
bind.PopItemWidth();
if (value_changed)
this.Build();
return value_changed;
}
// IMGUI_API bool PassFilter(const char* text, const char* text_end = NULL) const;
public PassFilter(text: string, text_end: number | null = null): boolean {
// if (Filters.empty())
// return true;
// if (text == NULL)
// text = "";
// for (int i = 0; i != Filters.Size; i++)
// {
// const TextRange& f = Filters[i];
// if (f.empty())
// continue;
// if (f.front() == '-')
// {
// // Subtract
// if (ImStristr(text, text_end, f.begin()+1, f.end()) != NULL)
// return false;
// }
// else
// {
// // Grep
// if (ImStristr(text, text_end, f.begin(), f.end()) != NULL)
// return true;
// }
// }
// Implicit * grep
if (this.CountGrep === 0)
return true;
return false;
}
// IMGUI_API void Build();
public Build(): void {
// Filters.resize(0);
// TextRange input_range(InputBuf, InputBuf+strlen(InputBuf));
// input_range.split(',', Filters);
this.CountGrep = 0;
// for (int i = 0; i != Filters.Size; i++)
// {
// Filters[i].trim_blanks();
// if (Filters[i].empty())
// continue;
// if (Filters[i].front() != '-')
// CountGrep += 1;
// }
}
// void Clear() { InputBuf[0] = 0; Build(); }
public Clear(): void { this.InputBuf.buffer = ""; this.Build(); }
// bool IsActive() const { return !Filters.empty(); }
public IsActive(): boolean { return false; }
// [Internal]
// struct TextRange
// {
// const char* b;
// const char* e;
// TextRange() { b = e = NULL; }
// TextRange(const char* _b, const char* _e) { b = _b; e = _e; }
// const char* begin() const { return b; }
// const char* end() const { return e; }
// bool empty() const { return b == e; }
// char front() const { return *b; }
// static bool is_blank(char c) { return c == ' ' || c == '\t'; }
// void trim_blanks() { while (b < e && is_blank(*b)) b++; while (e > b && is_blank(*(e-1))) e--; }
// IMGUI_API void split(char separator, ImVector<TextRange>& out);
// };
// char InputBuf[256];
public InputBuf: ImStringBuffer = new ImStringBuffer(256);
// ImVector<TextRange> Filters;
// int CountGrep;
public CountGrep: number = 0;
}
// Helper: Text buffer for logging/accumulating text
export { ImGuiTextBuffer as TextBuffer }
export class ImGuiTextBuffer
{
// ImVector<char> Buf;
public Buf: string = "";
public begin(): string { return this.Buf; }
public size(): number { return this.Buf.length; }
public clear(): void { this.Buf = ""; }
public append(text: string): void { this.Buf += text; }
// ImGuiTextBuffer() { Buf.push_back(0); }
// inline char operator[](int i) { return Buf.Data[i]; }
// const char* begin() const { return &Buf.front(); }
// const char* end() const { return &Buf.back(); } // Buf is zero-terminated, so end() will point on the zero-terminator
// int size() const { return Buf.Size - 1; }
// bool empty() { return Buf.Size <= 1; }
// void clear() { Buf.clear(); Buf.push_back(0); }
// void reserve(int capacity) { Buf.reserve(capacity); }
// const char* c_str() const { return Buf.Data; }
// IMGUI_API void appendf(const char* fmt, ...) IM_FMTARGS(2);
// IMGUI_API void appendfv(const char* fmt, va_list args) IM_FMTLIST(2);
}
// Helper: Simple Key->value storage
// Typically you don't have to worry about this since a storage is held within each Window.
// We use it to e.g. store collapse state for a tree (Int 0/1), store color edit options.
// This is optimized for efficient reading (dichotomy into a contiguous buffer), rare writing (typically tied to user interactions)
// You can use it as custom user storage for temporary values. Declare your own storage if, for example:
// - You want to manipulate the open/close state of a particular sub-tree in your interface (tree node uses Int 0/1 to store their state).
// - You want to store custom debug data easily without adding or editing structures in your code (probably not efficient, but convenient)
// Types are NOT stored, so it is up to you to make sure your Key don't collide with different types.
export class ImGuiStorage
{
// struct Pair
// {
// ImGuiID key;
// union { int val_i; float val_f; void* val_p; };
// Pair(ImGuiID _key, int _val_i) { key = _key; val_i = _val_i; }
// Pair(ImGuiID _key, float _val_f) { key = _key; val_f = _val_f; }
// Pair(ImGuiID _key, void* _val_p) { key = _key; val_p = _val_p; }
// };
// ImVector<Pair> Data;
// - Get***() functions find pair, never add/allocate. Pairs are sorted so a query is O(log N)
// - Set***() functions find pair, insertion on demand if missing.
// - Sorted insertion is costly, paid once. A typical frame shouldn't need to insert any new pair.
// void Clear() { Data.clear(); }
// IMGUI_API int GetInt(ImGuiID key, int default_val = 0) const;
// IMGUI_API void SetInt(ImGuiID key, int val);
// IMGUI_API bool GetBool(ImGuiID key, bool default_val = false) const;
// IMGUI_API void SetBool(ImGuiID key, bool val);
// IMGUI_API float GetFloat(ImGuiID key, float default_val = 0.0f) const;
// IMGUI_API void SetFloat(ImGuiID key, float val);
// IMGUI_API void* GetVoidPtr(ImGuiID key) const; // default_val is NULL
// IMGUI_API void SetVoidPtr(ImGuiID key, void* val);
// - Get***Ref() functions finds pair, insert on demand if missing, return pointer. Useful if you intend to do Get+Set.
// - References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
// - A typical use case where this is convenient for quick hacking (e.g. add storage during a live Edit&Continue session if you can't modify existing struct)
// float* pvar = ImGui::GetFloatRef(key); ImGui::SliderFloat("var", pvar, 0, 100.0f); some_var += *pvar;
// IMGUI_API int* GetIntRef(ImGuiID key, int default_val = 0);
// IMGUI_API bool* GetBoolRef(ImGuiID key, bool default_val = false);
// IMGUI_API float* GetFloatRef(ImGuiID key, float default_val = 0.0f);
// IMGUI_API void** GetVoidPtrRef(ImGuiID key, void* default_val = NULL);
// Use on your own storage if you know only integer are being stored (open/close all tree nodes)
// IMGUI_API void SetAllInt(int val);
// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
// IMGUI_API void BuildSortByKey();
}
// Data payload for Drag and Drop operations
export { ImGuiPayload as Payload }
export interface ImGuiPayload<T>
{
// Members
// void* Data; // Data (copied and owned by dear imgui)
Data: T;
// int DataSize; // Data size
// [Internal]
// ImGuiID SourceId; // Source item id
// ImGuiID SourceParentId; // Source parent id (if available)
// int DataFrameCount; // Data timestamp
// char DataType[12 + 1]; // Data type tag (short user-supplied string, 12 characters max)
// bool Preview; // Set when AcceptDragDropPayload() was called and mouse has been hovering the target item (nb: handle overlapping drag targets)
// bool Delivery; // Set when AcceptDragDropPayload() was called and mouse button is released over the target item.
// ImGuiPayload() { Clear(); }
// void Clear() { SourceId = SourceParentId = 0; Data = NULL; DataSize = 0; memset(DataType, 0, sizeof(DataType)); DataFrameCount = -1; Preview = Delivery = false; }
// bool IsDataType(const char* type) const { return DataFrameCount != -1 && strcmp(type, DataType) == 0; }
// bool IsPreview() const { return Preview; }
// bool IsDelivery() const { return Delivery; }
}
// Helpers macros to generate 32-bits encoded colors
export const IM_COL32_R_SHIFT: number = config.IMGUI_USE_BGRA_PACKED_COLOR ? 16 : 0;
export const IM_COL32_G_SHIFT: number = 8;
export const IM_COL32_B_SHIFT: number = config.IMGUI_USE_BGRA_PACKED_COLOR ? 0 : 16;
export const IM_COL32_A_SHIFT: number = 24;
export const IM_COL32_A_MASK: number = 0xFF000000;
export { IM_COL32 as COL32 }
export function IM_COL32(R: number, G: number, B: number, A: number = 255): number {
return ((A << IM_COL32_A_SHIFT) | (B << IM_COL32_B_SHIFT) | (G << IM_COL32_G_SHIFT) | (R << IM_COL32_R_SHIFT)) >>> 0;
}
export const IM_COL32_WHITE: number = IM_COL32(255, 255, 255, 255); export { IM_COL32_WHITE as COL32_WHITE } // Opaque white = 0xFFFFFFFF
export const IM_COL32_BLACK: number = IM_COL32(0, 0, 0, 255); export { IM_COL32_BLACK as COL32_BLACK } // Opaque black
export const IM_COL32_BLACK_TRANS: number = IM_COL32(0, 0, 0, 0); export { IM_COL32_BLACK_TRANS as COL32_BLACK_TRANS } // Transparent black = 0x00000000
// ImColor() helper to implicity converts colors to either ImU32 (packed 4x1 byte) or ImVec4 (4x1 float)
// Prefer using IM_COL32() macros if you want a guaranteed compile-time ImU32 for usage with ImDrawList API.
// **Avoid storing ImColor! Store either u32 of ImVec4. This is not a full-featured color class. MAY OBSOLETE.
// **None of the ImGui API are using ImColor directly but you can use it as a convenience to pass colors in either ImU32 or ImVec4 formats. Explicitly cast to ImU32 or ImVec4 if needed.
export { ImColor as Color }
export class ImColor
{
// ImVec4 Value;
public Value: ImVec4 = new ImVec4();
// ImColor() { Value.x = Value.y = Value.z = Value.w = 0.0f; }
// ImColor(int r, int g, int b, int a = 255) { float sc = 1.0f/255.0f; Value.x = (float)r * sc; Value.y = (float)g * sc; Value.z = (float)b * sc; Value.w = (float)a * sc; }
// ImColor(ImU32 rgba) { float sc = 1.0f/255.0f; Value.x = (float)((rgba>>IM_COL32_R_SHIFT)&0xFF) * sc; Value.y = (float)((rgba>>IM_COL32_G_SHIFT)&0xFF) * sc; Value.z = (float)((rgba>>IM_COL32_B_SHIFT)&0xFF) * sc; Value.w = (float)((rgba>>IM_COL32_A_SHIFT)&0xFF) * sc; }
// ImColor(float r, float g, float b, float a = 1.0f) { Value.x = r; Value.y = g; Value.z = b; Value.w = a; }
// ImColor(const ImVec4& col) { Value = col; }
constructor();
constructor(r: number, g: number, b: number);
constructor(r: number, g: number, b: number, a: number);
constructor(rgba: Bind.ImU32);
constructor(col: Readonly<Bind.interface_ImVec4>);
constructor(r: number | Bind.ImU32 | Readonly<Bind.interface_ImVec4> = 0.0, g: number = 0.0, b: number = 0.0, a: number = 1.0) {
if (typeof(r) === "number") {
if (r > 255 && g === 0.0 && b === 0.0 && a === 1.0) {
this.Value.x = Math.max(0.0, Math.min(1.0, ((r >> IM_COL32_R_SHIFT) & 0xFF) / 255));
this.Value.y = Math.max(0.0, Math.min(1.0, ((r >> IM_COL32_G_SHIFT) & 0xFF) / 255));
this.Value.z = Math.max(0.0, Math.min(1.0, ((r >> IM_COL32_B_SHIFT) & 0xFF) / 255));
this.Value.w = Math.max(0.0, Math.min(1.0, ((r >> IM_COL32_A_SHIFT) & 0xFF) / 255));
} else if (r <= 1.0 && g <= 1.0 && b <= 1.0 && a <= 1.0) {
this.Value.x = Math.max(0.0, r);
this.Value.y = Math.max(0.0, g);
this.Value.z = Math.max(0.0, b);
this.Value.w = Math.max(0.0, a);
} else {
this.Value.x = Math.max(0.0, Math.min(1.0, r / 255));
this.Value.y = Math.max(0.0, Math.min(1.0, g / 255));
this.Value.z = Math.max(0.0, Math.min(1.0, b / 255));
if (a <= 1.0) {
this.Value.w = Math.max(0.0, a);
} else {
this.Value.w = Math.max(0.0, Math.min(1.0, a / 255));
}
}
} else {
this.Value.Copy(r);
}
}
// inline operator ImU32() const { return ImGui::ColorConvertFloat4ToU32(Value); }
public toImU32(): Bind.ImU32 { return ColorConvertFloat4ToU32(this.Value); }
// inline operator ImVec4() const { return Value; }
public toImVec4(): ImVec4 { return this.Value; }
// FIXME-OBSOLETE: May need to obsolete/cleanup those helpers.
// inline void SetHSV(float h, float s, float v, float a = 1.0f){ ImGui::ColorConvertHSVtoRGB(h, s, v, Value.x, Value.y, Value.z); Value.w = a; }
public SetHSV(h: number, s: number, v: number, a: number = 1.0): void {
const ref_r: Bind.ImScalar<number> = [ this.Value.x ];
const ref_g: Bind.ImScalar<number> = [ this.Value.y ];
const ref_b: Bind.ImScalar<number> = [ this.Value.z ];
ColorConvertHSVtoRGB(h, s, v, ref_r, ref_g, ref_b);
this.Value.x = ref_r[0];
this.Value.y = ref_g[0];
this.Value.z = ref_b[0];
this.Value.w = a;
}
// static ImColor HSV(float h, float s, float v, float a = 1.0f) { float r,g,b; ImGui::ColorConvertHSVtoRGB(h, s, v, r, g, b); return ImColor(r,g,b,a); }
public static HSV(h: number, s: number, v: number, a: number = 1.0): ImColor {
const color = new ImColor();
color.SetHSV(h, s, v, a);
return color;
}
}
export { ImGuiInputTextDefaultSize as InputTextDefaultSize }
export const ImGuiInputTextDefaultSize: number = 128;
export { ImGuiInputTextCallback as InputTextCallback }
export type ImGuiInputTextCallback<T> = (data: ImGuiInputTextCallbackData<T>) => number;
// Shared state of InputText(), passed to callback when a ImGuiInputTextFlags_Callback* flag is used and the corresponding callback is triggered.
export { ImGuiInputTextCallbackData as InputTextCallbackData }
export class ImGuiInputTextCallbackData<T> {
constructor(public readonly native: Bind.reference_ImGuiInputTextCallbackData, public readonly UserData: T | null = null) {}
// ImGuiInputTextFlags EventFlag; // One of ImGuiInputTextFlags_Callback* // Read-only
public get EventFlag(): ImGuiInputTextFlags { return this.native.EventFlag; }
// ImGuiInputTextFlags Flags; // What user passed to InputText() // Read-only
public get Flags(): ImGuiInputTextFlags { return this.native.Flags; }
// void* UserData; // What user passed to InputText() // Read-only
// public get UserData(): any { return this.native.UserData; }
// CharFilter event:
// ImWchar EventChar; // Character input // Read-write (replace character or set to zero)
public get EventChar(): Bind.ImWchar { return this.native.EventChar; }
public set EventChar(value: Bind.ImWchar) { this.native.EventChar = value; }
// Completion,History,Always events:
// If you modify the buffer contents make sure you update 'BufTextLen' and set 'BufDirty' to true.
// ImGuiKey EventKey; // Key pressed (Up/Down/TAB) // Read-only
public get EventKey(): ImGuiKey { return this.native.EventKey; }
// char* Buf; // Current text buffer // Read-write (pointed data only, can't replace the actual pointer)
public get Buf(): string { return this.native.Buf; }
public set Buf(value: string) { this.native.Buf = value; }
// int BufTextLen; // Current text length in bytes // Read-write
public get BufTextLen(): number { return this.native.BufTextLen; }
public set BufTextLen(value: number) { this.native.BufTextLen = value; }
// int BufSize; // Maximum text length in bytes // Read-only
public get BufSize(): number { return this.native.BufSize; }
// bool BufDirty; // Set if you modify Buf/BufTextLen!! // Write
public set BufDirty(value: boolean) { this.native.BufDirty = value; }
// int CursorPos; // // Read-write
public get CursorPos(): number { return this.native.CursorPos; }
public set CursorPos(value: number) { this.native.CursorPos = value; }
// int SelectionStart; // // Read-write (== to SelectionEnd when no selection)
public get SelectionStart(): number { return this.native.SelectionStart; }
public set SelectionStart(value: number) { this.native.SelectionStart = value; }
// int SelectionEnd; // // Read-write
public get SelectionEnd(): number { return this.native.SelectionEnd; }
public set SelectionEnd(value: number) { this.native.SelectionEnd = value; }
// NB: Helper functions for text manipulation. Calling those function loses selection.
// IMGUI_API void DeleteChars(int pos, int bytes_count);
public DeleteChars(pos: number, bytes_count: number): void { return this.native.DeleteChars(pos, bytes_count); }
// IMGUI_API void InsertChars(int pos, const char* text, const char* text_end = NULL);
public InsertChars(pos: number, text: string, text_end: number | null = null): void { return this.native.InsertChars(pos, text_end !== null ? text.substring(0, text_end) : text); }
// void SelectAll() { SelectionStart = 0; SelectionEnd = BufTextLen; }
public SelectAll(): void { this.native.SelectAll(); }
// void ClearSelection() { SelectionStart = SelectionEnd = BufTextLen; }
public ClearSelection(): void { this.native.ClearSelection(); }
// bool HasSelection() const { return SelectionStart != SelectionEnd; }
public HasSelection(): boolean { return this.native.HasSelection(); }
}
export { ImGuiSizeCallback as SizeCallback }
export type ImGuiSizeCallback<T> = (data: ImGuiSizeCallbackData<T>) => void;
// Resizing callback data to apply custom constraint. As enabled by SetNextWindowSizeConstraints(). Callback is called during the next Begin().
// NB: For basic min/max size constraint on each axis you don't need to use the callback! The SetNextWindowSizeConstraints() parameters are enough.
export { ImGuiSizeCallbackData as SizeCallbackData }
export class ImGuiSizeCallbackData<T> {
constructor(public readonly native: Bind.reference_ImGuiSizeCallbackData, public readonly UserData: T) {}
get Pos(): Readonly<Bind.interface_ImVec2> { return this.native.Pos; }
get CurrentSize(): Readonly<Bind.interface_ImVec2> { return this.native.CurrentSize; }
get DesiredSize(): Bind.interface_ImVec2 { return this.native.DesiredSize; }
}
// Sorting specification for one column of a table (sizeof == 12 bytes)
export { ImGuiTableColumnSortSpecs as TableColumnSortSpecs }
export class ImGuiTableColumnSortSpecs
{
constructor(public readonly native: Bind.reference_ImGuiTableColumnSortSpecs) {}
get ColumnUserID(): ImGuiID { return this.native.ColumnUserID; }
get ColumnIndex(): Bind.ImS16 { return this.native.ColumnIndex; }
get SortOrder(): Bind.ImS16 { return this.native.SortOrder; }
get SortDirection(): ImGuiSortDirection { return this.native.SortDirection; }
}
// Sorting specifications for a table (often handling sort specs for a single column, occasionally more)
// Obtained by calling TableGetSortSpecs().
// When 'SpecsDirty == true' you can sort your data. It will be true with sorting specs have changed since last call, or the first time.
// Make sure to set 'SpecsDirty = false' after sorting, else you may wastefully sort your data every frame!
export { ImGuiTableSortSpecs as TableSortSpecs }
export class ImGuiTableSortSpecs
{
constructor(public readonly native: Bind.reference_ImGuiTableSortSpecs) {
this._Specs = Array.from({length: this.SpecsCount}).map((_, i) => {
return new ImGuiTableColumnSortSpecs(this.native.GetSpec(i));
})
}
private _Specs: Readonly<ImGuiTableColumnSortSpecs[]>;
get Specs(): Readonly<ImGuiTableColumnSortSpecs[]> { return this._Specs; }
get SpecsCount(): number { return this.native.SpecsCount; }
get SpecsDirty(): boolean { return this.native.SpecsDirty; }
set SpecsDirty(value: boolean) { this.native.SpecsDirty = value; }
}
export { ImGuiListClipper as ListClipper }
export class ImGuiListClipper
{
private _native: Bind.ImGuiListClipper | null = null;
private get native(): Bind.ImGuiListClipper {
return this._native || (this._native = new bind.ImGuiListClipper());
}
public get DisplayStart(): number { return this.native.DisplayStart; }
public get DisplayEnd(): number { return this.native.DisplayEnd; }
public get ItemsCount(): number { return this.native.ItemsCount; }
public get StepNo(): number { return this.native.StepNo; }
public get ItemsFrozen(): number { return this.native.ItemsFrozen; }
public get ItemsHeight(): number { return this.native.ItemsHeight; }
public get StartPosY(): number { return this.native.StartPosY; }
// items_count: Use -1 to ignore (you can call Begin later). Use INT_MAX if you don't know how many items you have (in which case the cursor won't be advanced in the final step).
// items_height: Use -1.0f to be calculated automatically on first step. Otherwise pass in the distance between your items, typically GetTextLineHeightWithSpacing() or GetFrameHeightWithSpacing().
// If you don't specify an items_height, you NEED to call Step(). If you specify items_height you may call the old Begin()/End() api directly, but prefer calling Step().
// ImGuiListClipper(int items_count = -1, float items_height = -1.0f) { Begin(items_count, items_height); } // NB: Begin() initialize every fields (as we allow user to call Begin/End multiple times on a same instance if they want).
// ~ImGuiListClipper() { IM_ASSERT(ItemsCount == -1); } // Assert if user forgot to call End() or Step() until false.
public delete(): void {
if (this._native !== null) {
this._native.delete();
this._native = null;
}
}
// IMGUI_API void Begin(int items_count, float items_height = -1.0f); // Automatically called by constructor if you passed 'items_count' or by Step() in Step 1.
public Begin(items_count: number, items_height: number = -1.0): void {
this.native.Begin(items_count, items_height);
}
// IMGUI_API void End(); // Automatically called on the last call of Step() that returns false.
public End(): void {
this.native.End();
this.delete();
}
// IMGUI_API bool Step(); // Call until it returns false. The DisplayStart/DisplayEnd fields will be set and you can process/draw those items.
public Step(): boolean {
const busy: boolean = this.native.Step();
if (!busy) {
this.delete();
}
return busy;
}
}
//-----------------------------------------------------------------------------
// Draw List
// Hold a series of drawing commands. The user provides a renderer for ImDrawData which essentially contains an array of ImDrawList.
//-----------------------------------------------------------------------------
// The maximum line width to bake anti-aliased textures for. Build atlas with ImFontAtlasFlags_NoBakedLines to disable baking.
export const IM_DRAWLIST_TEX_LINES_WIDTH_MAX: number = 63;
// Draw callbacks for advanced uses.
// NB- You most likely do NOT need to use draw callbacks just to create your own widget or customized UI rendering (you can poke into the draw list for that)
// Draw callback may be useful for example, A) Change your GPU render state, B) render a complex 3D scene inside a UI element (without an intermediate texture/render target), etc.
// The expected behavior from your rendering function is 'if (cmd.UserCallback != NULL) cmd.UserCallback(parent_list, cmd); else RenderTriangles()'
// typedef void (*ImDrawCallback)(const ImDrawList* parent_list, const ImDrawCmd* cmd);
export type ImDrawCallback = (parent_list: Readonly<ImDrawList>, cmd: Readonly<ImDrawCmd>) => void;
// Special Draw callback value to request renderer back-end to reset the graphics/render state.
// The renderer back-end needs to handle this special value, otherwise it will crash trying to call a function at this address.
// This is useful for example if you submitted callbacks which you know have altered the render state and you want it to be restored.
// It is not done by default because they are many perfectly useful way of altering render state for imgui contents (e.g. changing shader/blending settings before an Image call).
export const ImDrawCallback_ResetRenderState = -1;
// Typically, 1 command = 1 GPU draw call (unless command is a callback)
// Pre 1.71 back-ends will typically ignore the VtxOffset/IdxOffset fields. When 'io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset'
// is enabled, those fields allow us to render meshes larger than 64K vertices while keeping 16-bits indices.
export { ImDrawCmd as DrawCmd }
export class ImDrawCmd
{
constructor(public readonly native: Bind.reference_ImDrawCmd) {}
// unsigned int ElemCount; // Number of indices (multiple of 3) to be rendered as triangles. Vertices are stored in the callee ImDrawList's vtx_buffer[] array, indices in idx_buffer[].
get ElemCount(): number { return this.native.ElemCount; }
// ImVec4 ClipRect; // Clipping rectangle (x1, y1, x2, y2)
get ClipRect(): Readonly<Bind.reference_ImVec4> { return this.native.ClipRect; }
// ImTextureID TextureId; // User-provided texture ID. Set by user in ImfontAtlas::SetTexID() for fonts or passed to Image*() functions. Ignore if never using images or multiple fonts atlas.
get TextureId(): ImTextureID | null {
return ImGuiContext.getTexture(this.native.TextureId);
}
// unsigned int VtxOffset; // Start offset in vertex buffer. Pre-1.71 or without ImGuiBackendFlags_RendererHasVtxOffset: always 0. With ImGuiBackendFlags_RendererHasVtxOffset: may be >0 to support meshes larger than 64K vertices with 16-bits indices.
get VtxOffset(): number { return this.native.VtxOffset; }
// unsigned int IdxOffset; // Start offset in index buffer. Always equal to sum of ElemCount drawn so far.
get IdxOffset(): number { return this.native.IdxOffset; }
// ImDrawCallback UserCallback; // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally.
public readonly UserCallback: ImDrawCallback | null = null; // TODO
// void* UserCallbackData; // The draw callback code can access this.
public readonly UserCallbackData: any = null; // TODO
// ImDrawCmd() { ElemCount = 0; ClipRect.x = ClipRect.y = ClipRect.z = ClipRect.w = 0.0f; TextureId = NULL; UserCallback = NULL; UserCallbackData = NULL; }
}
// Vertex index
// (to allow large meshes with 16-bits indices: set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset' and handle ImDrawCmd::VtxOffset in the renderer back-end)
// (to use 32-bits indices: override with '#define ImDrawIdx unsigned int' in imconfig.h)
// #ifndef ImDrawIdx
// typedef unsigned short ImDrawIdx;
// #endif
export { ImDrawIdxSize as DrawIdxSize }
export const ImDrawIdxSize: number = 2; // bind.ImDrawIdxSize;
export { ImDrawIdx as DrawIdx }
export type ImDrawIdx = number;
// Vertex layout
// #ifndef IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT
export { ImDrawVertSize as DrawVertSize }
export const ImDrawVertSize: number = 20; // bind.ImDrawVertSize;
export { ImDrawVertPosOffset as DrawVertPosOffset }
export const ImDrawVertPosOffset: number = 0; // bind.ImDrawVertPosOffset;
export { ImDrawVertUVOffset as DrawVertUVOffset }
export const ImDrawVertUVOffset: number = 8; // bind.ImDrawVertUVOffset;
export { ImDrawVertColOffset as DrawVertColOffset }
export const ImDrawVertColOffset: number = 16; // bind.ImDrawVertColOffset;
export { ImDrawVert as DrawVert }
export class ImDrawVert
{
// ImVec2 pos;
public pos: Float32Array;
// ImVec2 uv;
public uv: Float32Array;
// ImU32 col;
public col: Uint32Array;
constructor(buffer: ArrayBuffer, byteOffset: number = 0) {
this.pos = new Float32Array(buffer, byteOffset + bind.ImDrawVertPosOffset, 2);
this.uv = new Float32Array(buffer, byteOffset + bind.ImDrawVertUVOffset, 2);
this.col = new Uint32Array(buffer, byteOffset + bind.ImDrawVertColOffset, 1);
}
}
// #else
// You can override the vertex format layout by defining IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT in imconfig.h
// The code expect ImVec2 pos (8 bytes), ImVec2 uv (8 bytes), ImU32 col (4 bytes), but you can re-order them or add other fields as needed to simplify integration in your engine.
// The type has to be described within the macro (you can either declare the struct or use a typedef)
// NOTE: IMGUI DOESN'T CLEAR THE STRUCTURE AND DOESN'T CALL A CONSTRUCTOR SO ANY CUSTOM FIELD WILL BE UNINITIALIZED. IF YOU ADD EXTRA FIELDS (SUCH AS A 'Z' COORDINATES) YOU WILL NEED TO CLEAR THEM DURING RENDER OR TO IGNORE THEM.
// IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT;
// #endif
// [Internal] For use by ImDrawList
export class ImDrawCmdHeader
{
// ImVec4 ClipRect;
// ImTextureID TextureId;
// unsigned int VtxOffset;
}
// Draw channels are used by the Columns API to "split" the render list into different channels while building, so items of each column can be batched together.
// You can also use them to simulate drawing layers and submit primitives in a different order than how they will be rendered.
export class ImDrawChannel
{
// ImVector<ImDrawCmd> CmdBuffer;
// ImVector<ImDrawIdx> IdxBuffer;
}
export class ImDrawListSharedData
{
constructor(public readonly native: Bind.reference_ImDrawListSharedData) {}
}
// Draw command list
// This is the low-level list of polygons that ImGui functions are filling. At the end of the frame, all command lists are passed to your ImGuiIO::RenderDrawListFn function for rendering.
// Each ImGui window contains its own ImDrawList. You can use ImGui::GetWindowDrawList() to access the current window draw list and draw custom primitives.
// You can interleave normal ImGui:: calls and adding primitives to the current draw list.
// All positions are generally in pixel coordinates (top-left at (0,0), bottom-right at io.DisplaySize), however you are totally free to apply whatever transformation matrix to want to the data (if you apply such transformation you'll want to apply it to ClipRect as well)
// Important: Primitives are always added to the list and not culled (culling is done at higher-level by ImGui:: functions), if you use this API a lot consider coarse culling your drawn objects.
export { ImDrawList as DrawList }
export class ImDrawList
{
constructor(public readonly native: Bind.reference_ImDrawList) {}
public IterateDrawCmds(callback: (draw_cmd: ImDrawCmd, ElemStart: number) => void): void {
this.native.IterateDrawCmds((draw_cmd: Bind.reference_ImDrawCmd, ElemStart: number): void => {
callback(new ImDrawCmd(draw_cmd), ElemStart);
});
}
// This is what you have to render
// ImVector<ImDrawCmd> CmdBuffer; // Draw commands. Typically 1 command = 1 GPU draw call, unless the command is a callback.
// ImVector<ImDrawIdx> IdxBuffer; // Index buffer. Each command consume ImDrawCmd::ElemCount of those
get IdxBuffer(): Uint8Array { return this.native.IdxBuffer; }
// ImVector<ImDrawVert> VtxBuffer; // Vertex buffer.
get VtxBuffer(): Uint8Array { return this.native.VtxBuffer; }
// ImDrawListFlags Flags; // Flags, you may poke into these to adjust anti-aliasing settings per-primitive.
get Flags(): ImDrawListFlags { return this.native.Flags; }
set Flags(value: ImDrawListFlags) { this.native.Flags = value; }
// [Internal, used while building lists]
// unsigned int _VtxCurrentIdx; // [Internal] == VtxBuffer.Size
// const ImDrawListSharedData* _Data; // Pointer to shared draw data (you can use ImGui::GetDrawListSharedData() to get the one from current ImGui context)
// const char* _OwnerName; // Pointer to owner window's name for debugging
// ImDrawVert* _VtxWritePtr; // [Internal] point within VtxBuffer.Data after each add command (to avoid using the ImVector<> operators too much)
// ImDrawIdx* _IdxWritePtr; // [Internal] point within IdxBuffer.Data after each add command (to avoid using the ImVector<> operators too much)
// ImVector<ImVec4> _ClipRectStack; // [Internal]
// ImVector<ImTextureID> _TextureIdStack; // [Internal]
// ImVector<ImVec2> _Path; // [Internal] current path building
// int _ChannelsCurrent; // [Internal] current channel number (0)
// int _ChannelsCount; // [Internal] number of active channels (1+)
// ImVector<ImDrawChannel> _Channels; // [Internal] draw channels for columns API (not resized down so _ChannelsCount may be smaller than _Channels.Size)
// ImDrawList(const ImDrawListSharedData* shared_data) { _Data = shared_data; _OwnerName = NULL; Clear(); }
// ~ImDrawList() { ClearFreeMemory(); }
// IMGUI_API void PushClipRect(ImVec2 clip_rect_min, ImVec2 clip_rect_max, bool intersect_with_current_clip_rect = false); // Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling)
public PushClipRect(clip_rect_min: Readonly<Bind.interface_ImVec2>, clip_rect_max: Readonly<Bind.interface_ImVec2>, intersect_with_current_clip_rect: boolean = false): void {
this.native.PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
}
// IMGUI_API void PushClipRectFullScreen();
public PushClipRectFullScreen(): void { this.native.PushClipRectFullScreen(); }
// IMGUI_API void PopClipRect();
public PopClipRect(): void { this.native.PopClipRect(); }
// IMGUI_API void PushTextureID(ImTextureID texture_id);
public PushTextureID(texture_id: ImTextureID): void {
this.native.PushTextureID(ImGuiContext.setTexture(texture_id));
}
// IMGUI_API void PopTextureID();
public PopTextureID(): void { this.native.PopTextureID(); }
// inline ImVec2 GetClipRectMin() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.x, cr.y); }
public GetClipRectMin(out: Bind.interface_ImVec2 = new ImVec2()): Bind.interface_ImVec2 {
return this.native.GetClipRectMin(out);
}
// inline ImVec2 GetClipRectMax() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.z, cr.w); }
public GetClipRectMax(out: Bind.interface_ImVec2 = new ImVec2()): Bind.interface_ImVec2 {
return this.native.GetClipRectMax(out);
}
// Primitives
// IMGUI_API void AddLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness = 1.0f);
public AddLine(a: Readonly<Bind.interface_ImVec2>, b: Readonly<Bind.interface_ImVec2>, col: Bind.ImU32, thickness: number = 1.0): void {
this.native.AddLine(a, b, col, thickness);
}
// IMGUI_API void AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners_flags = ImDrawCornerFlags_All, float thickness = 1.0f); // a: upper-left, b: lower-right, rounding_corners_flags: 4-bits corresponding to which corner to round
public AddRect(a: Readonly<Bind.interface_ImVec2>, b: Readonly<Bind.interface_ImVec2>, col: Bind.ImU32, rounding: number = 0.0, rounding_corners_flags: ImDrawCornerFlags = ImDrawCornerFlags.All, thickness: number = 1.0): void {
this.native.AddRect(a, b, col, rounding, rounding_corners_flags, thickness);
}
// IMGUI_API void AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners_flags = ImDrawCornerFlags_All); // a: upper-left, b: lower-right
public AddRectFilled(a: Readonly<Bind.interface_ImVec2>, b: Readonly<Bind.interface_ImVec2>, col: Bind.ImU32, rounding: number = 0.0, rounding_corners_flags: ImDrawCornerFlags = ImDrawCornerFlags.All): void {
this.native.AddRectFilled(a, b, col, rounding, rounding_corners_flags);
}
// IMGUI_API void AddRectFilledMultiColor(const ImVec2& a, const ImVec2& b, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left);
public AddRectFilledMultiColor(a: Readonly<Bind.interface_ImVec2>, b: Readonly<Bind.interface_ImVec2>, col_upr_left: Bind.ImU32, col_upr_right: Bind.ImU32, col_bot_right: Bind.ImU32, col_bot_left: Bind.ImU32): void {
this.native.AddRectFilledMultiColor(a, b, col_upr_left, col_upr_right, col_bot_right, col_bot_left);
}
// IMGUI_API void AddQuad(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col, float thickness = 1.0f);
public AddQuad(a: Readonly<Bind.interface_ImVec2>, b: Readonly<Bind.interface_ImVec2>, c: Readonly<Bind.interface_ImVec2>, d: Readonly<Bind.interface_ImVec2>, col: Bind.ImU32, thickness: number = 1.0): void {
this.native.AddQuad(a, b, c, d, col, thickness);
}
// IMGUI_API void AddQuadFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col);
public AddQuadFilled(a: Readonly<Bind.interface_ImVec2>, b: Readonly<Bind.interface_ImVec2>, c: Readonly<Bind.interface_ImVec2>, d: Readonly<Bind.interface_ImVec2>, col: Bind.ImU32): void {
this.native.AddQuadFilled(a, b, c, d, col);
}
// IMGUI_API void AddTriangle(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col, float thickness = 1.0f);
public AddTriangle(a: Readonly<Bind.interface_ImVec2>, b: Readonly<Bind.interface_ImVec2>, c: Readonly<Bind.interface_ImVec2>, col: Bind.ImU32, thickness: number = 1.0): void {
this.native.AddTriangle(a, b, c, col, thickness);
}
// IMGUI_API void AddTriangleFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col);
public AddTriangleFilled(a: Readonly<Bind.interface_ImVec2>, b: Readonly<Bind.interface_ImVec2>, c: Readonly<Bind.interface_ImVec2>, col: Bind.ImU32): void {
this.native.AddTriangleFilled(a, b, c, col);
}
// IMGUI_API void AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12, float thickness = 1.0f);
public AddCircle(centre: Readonly<Bind.interface_ImVec2>, radius: number, col: Bind.ImU32, num_segments: number = 12, thickness: number = 1.0): void {
this.native.AddCircle(centre, radius, col, num_segments, thickness);
}
// IMGUI_API void AddCircleFilled(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12);
public AddCircleFilled(centre: Readonly<Bind.interface_ImVec2>, radius: number, col: Bind.ImU32, num_segments: number = 12): void {
this.native.AddCircleFilled(centre, radius, col, num_segments);
}
// IMGUI_API void AddNgon(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness = 1.0f);
public AddNgon(centre: Readonly<Bind.interface_ImVec2>, radius: number, col: Bind.ImU32, num_segments: number, thickness: number = 1.0): void {
this.native.AddNgon(centre, radius, col, num_segments, thickness);
}
// IMGUI_API void AddNgonFilled(const ImVec2& center, float radius, ImU32 col, int num_segments);
public AddNgonFilled(centre: Readonly<Bind.interface_ImVec2>, radius: number, col: Bind.ImU32, num_segments: number): void {
this.native.AddNgonFilled(centre, radius, col, num_segments);
}
// IMGUI_API void AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL);
// IMGUI_API void AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL, float wrap_width = 0.0f, const ImVec4* cpu_fine_clip_rect = NULL);
public AddText(pos: Readonly<Bind.interface_ImVec2>, col: Bind.ImU32, text_begin: string, text_end?: number | null): void;
public AddText(font: ImFont, font_size: number, pos: Readonly<Bind.interface_ImVec2>, col: Bind.ImU32, text_begin: string, text_end?: number | null, wrap_width?: number, cpu_fine_clip_rect?: Readonly<Bind.interface_ImVec4> | null): void;
public AddText(...args: any[]): void {
if (args[0] instanceof ImFont) {
const font: ImFont = args[0];
const font_size: number = args[1];
const pos: Readonly<Bind.interface_ImVec2> = args[2];
const col: Bind.ImU32 = args[3];
const text_begin: string = args[4];
const text_end: number | null = args[5] || null;
const wrap_width: number = args[6] = 0.0;
const cpu_fine_clip_rect: Readonly<Bind.interface_ImVec4> | null = args[7] || null;
this.native.AddText_B(font.native, font_size, pos, col, text_end !== null ? text_begin.substring(0, text_end) : text_begin, wrap_width, cpu_fine_clip_rect);
} else {
const pos: Readonly<Bind.interface_ImVec2> = args[0];
const col: Bind.ImU32 = args[1];
const text_begin: string = args[2];
const text_end: number | null = args[3] || null;
this.native.AddText_A(pos, col, text_end !== null ? text_begin.substring(0, text_end) : text_begin);
}
}
// IMGUI_API void AddPolyline(const ImVec2* points, const int num_points, ImU32 col, bool closed, float thickness);
public AddPolyline(points: Array<Readonly<Bind.interface_ImVec2>>, num_points: number, col: Bind.ImU32, closed: boolean, thickness: number): void {
this.native.AddPolyline(points, num_points, col, closed, thickness);
}
// IMGUI_API void AddConvexPolyFilled(const ImVec2* points, const int num_points, ImU32 col);
public AddConvexPolyFilled(points: Array<Readonly<Bind.interface_ImVec2>>, num_points: number, col: Bind.ImU32): void {
this.native.AddConvexPolyFilled(points, num_points, col);
}
// IMGUI_API void AddBezierCubic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments = 0); // Cubic Bezier (4 control points)
public AddBezierCubic(p1: Readonly<Bind.interface_ImVec2>, p2: Readonly<Bind.interface_ImVec2>, p3: Readonly<Bind.interface_ImVec2>, p4: Readonly<Bind.interface_ImVec2>, col: Bind.ImU32, thickness: number = 1.0, num_segments: number = 0): void {
this.native.AddBezierCubic(p1, p2, p3, p4, col, thickness, num_segments);
}
// IMGUI_API void AddBezierQuadratic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness, int num_segments = 0); // Quadratic Bezier (3 control points)
public AddBezierQuadratic(p1: Readonly<Bind.interface_ImVec2>, p2: Readonly<Bind.interface_ImVec2>, p3: Readonly<Bind.interface_ImVec2>, col: Bind.ImU32, thickness: number = 1.0, num_segments: number = 0): void {
this.native.AddBezierQuadratic(p1, p2, p3, col, thickness, num_segments);
}
// IMGUI_API void AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a = ImVec2(0,0), const ImVec2& uv_b = ImVec2(1,1), ImU32 col = 0xFFFFFFFF);
public AddImage(user_texture_id: ImTextureID | null, a: Readonly<Bind.interface_ImVec2>, b: Readonly<Bind.interface_ImVec2>, uv_a: Readonly<Bind.interface_ImVec2> = ImVec2.ZERO, uv_b: Readonly<Bind.interface_ImVec2> = ImVec2.UNIT, col: Bind.ImU32 = 0xFFFFFFFF): void {
this.native.AddImage(ImGuiContext.setTexture(user_texture_id), a, b, uv_a, uv_b, col);
}
// IMGUI_API void AddImageQuad(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a = ImVec2(0,0), const ImVec2& uv_b = ImVec2(1,0), const ImVec2& uv_c = ImVec2(1,1), const ImVec2& uv_d = ImVec2(0,1), ImU32 col = 0xFFFFFFFF);
public AddImageQuad(user_texture_id: ImTextureID | null, a: Readonly<Bind.interface_ImVec2>, b: Readonly<Bind.interface_ImVec2>, c: Readonly<Bind.interface_ImVec2>, d: Readonly<Bind.interface_ImVec2>, uv_a: Readonly<Bind.interface_ImVec2> = ImVec2.ZERO, uv_b: Readonly<Bind.interface_ImVec2> = ImVec2.UNIT_X, uv_c: Readonly<Bind.interface_ImVec2> = ImVec2.UNIT, uv_d: Readonly<Bind.interface_ImVec2> = ImVec2.UNIT_Y, col: Bind.ImU32 = 0xFFFFFFFF): void {
this.native.AddImageQuad(ImGuiContext.setTexture(user_texture_id), a, b, c, d, uv_a, uv_b, uv_c, uv_d, col);
}
// IMGUI_API void AddImageRounded(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col, float rounding, int rounding_corners = ImDrawCornerFlags_All);
public AddImageRounded(user_texture_id: ImTextureID | null, a: Readonly<Bind.interface_ImVec2>, b: Readonly<Bind.interface_ImVec2>, uv_a: Readonly<Bind.interface_ImVec2>, uv_b: Readonly<Bind.interface_ImVec2>, col: Bind.ImU32, rounding: number, rounding_corners: ImDrawCornerFlags = ImDrawCornerFlags.All): void {
this.native.AddImageRounded(ImGuiContext.setTexture(user_texture_id), a, b, uv_a, uv_b, col, rounding, rounding_corners);
}
// Stateful path API, add points then finish with PathFill() or PathStroke()
// inline void PathClear() { _Path.resize(0); }
public PathClear(): void { this.native.PathClear(); }
// inline void PathLineTo(const ImVec2& pos) { _Path.push_back(pos); }
public PathLineTo(pos: Readonly<Bind.interface_ImVec2>): void { this.native.PathLineTo(pos); }
// inline void PathLineToMergeDuplicate(const ImVec2& pos) { if (_Path.Size == 0 || memcmp(&_Path[_Path.Size-1], &pos, 8) != 0) _Path.push_back(pos); }
public PathLineToMergeDuplicate(pos: Readonly<Bind.interface_ImVec2>): void { this.native.PathLineToMergeDuplicate(pos); }
// inline void PathFillConvex(ImU32 col) { AddConvexPolyFilled(_Path.Data, _Path.Size, col); PathClear(); }
public PathFillConvex(col: Bind.ImU32): void { this.native.PathFillConvex(col); }
// inline void PathStroke(ImU32 col, bool closed, float thickness = 1.0f) { AddPolyline(_Path.Data, _Path.Size, col, closed, thickness); PathClear(); }
public PathStroke(col: Bind.ImU32, closed: boolean, thickness: number = 1.0): void { this.native.PathStroke(col, closed, thickness); }
// IMGUI_API void PathArcTo(const ImVec2& centre, float radius, float a_min, float a_max, int num_segments = 10);
public PathArcTo(centre: Readonly<Bind.interface_ImVec2>, radius: number, a_min: number, a_max: number, num_segments: number = 10): void { this.native.PathArcTo(centre, radius, a_min, a_max, num_segments); }
// IMGUI_API void PathArcToFast(const ImVec2& centre, float radius, int a_min_of_12, int a_max_of_12); // Use precomputed angles for a 12 steps circle
public PathArcToFast(centre: Readonly<Bind.interface_ImVec2>, radius: number, a_min_of_12: number, a_max_of_12: number): void { this.native.PathArcToFast(centre, radius, a_min_of_12, a_max_of_12); }
// IMGUI_API void PathBezierCubicCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments = 0); // Cubic Bezier (4 control points)
public PathBezierCubicCurveTo(p2: Readonly<Bind.interface_ImVec2>, p3: Readonly<Bind.interface_ImVec2>, p4: Readonly<Bind.interface_ImVec2>, num_segments: number = 0): void { this.native.PathBezierCubicCurveTo(p2, p3, p4, num_segments); }
// IMGUI_API void PathBezierQuadraticCurveTo(const ImVec2& p2, const ImVec2& p3, int num_segments = 0); // Quadratic Bezier (3 control points)
public PathBezierQuadraticCurveTo(p2: Readonly<Bind.interface_ImVec2>, p3: Readonly<Bind.interface_ImVec2>, num_segments: number = 0): void { this.native.PathBezierQuadraticCurveTo(p2, p3, num_segments); }
// IMGUI_API void PathRect(const ImVec2& rect_min, const ImVec2& rect_max, float rounding = 0.0f, int rounding_corners_flags = ImDrawCornerFlags_All);
public PathRect(rect_min: Readonly<Bind.interface_ImVec2>, rect_max: Readonly<Bind.interface_ImVec2>, rounding: number = 0.0, rounding_corners_flags: ImDrawCornerFlags = ImDrawCornerFlags.All): void { this.native.PathRect(rect_min, rect_max, rounding, rounding_corners_flags); }
// Channels
// - Use to simulate layers. By switching channels to can render out-of-order (e.g. submit foreground primitives before background primitives)
// - Use to minimize draw calls (e.g. if going back-and-forth between multiple non-overlapping clipping rectangles, prefer to append into separate channels then merge at the end)
// IMGUI_API void ChannelsSplit(int channels_count);
public ChannelsSplit(channels_count: number): void { this.native.ChannelsSplit(channels_count); }
// IMGUI_API void ChannelsMerge();
public ChannelsMerge(): void { this.native.ChannelsMerge(); }
// IMGUI_API void ChannelsSetCurrent(int channel_index);
public ChannelsSetCurrent(channel_index: number): void { this.native.ChannelsSetCurrent(channel_index); }
// Advanced
// IMGUI_API void AddCallback(ImDrawCallback callback, void* callback_data); // Your rendering function must check for 'UserCallback' in ImDrawCmd and call the function instead of rendering triangles.
public AddCallback(callback: ImDrawCallback, callback_data: any): void {
const _callback: Bind.ImDrawCallback = (parent_list: Readonly<Bind.reference_ImDrawList>, draw_cmd: Readonly<Bind.reference_ImDrawCmd>): void => {
callback(new ImDrawList(parent_list), new ImDrawCmd(draw_cmd));
};
this.native.AddCallback(_callback, callback_data);
}
// IMGUI_API void AddDrawCmd(); // This is useful if you need to forcefully create a new draw call (to allow for dependent rendering / blending). Otherwise primitives are merged into the same draw-call as much as possible
public AddDrawCmd(): void { this.native.AddDrawCmd(); }
// Internal helpers
// NB: all primitives needs to be reserved via PrimReserve() beforehand!
// IMGUI_API void PrimReserve(int idx_count, int vtx_count);
public PrimReserve(idx_count: number, vtx_count: number): void { this.native.PrimReserve(idx_count, vtx_count); }
// IMGUI_API void PrimUnreserve(int idx_count, int vtx_count);
public PrimUnreserve(idx_count: number, vtx_count: number): void { this.native.PrimUnreserve(idx_count, vtx_count); }
// IMGUI_API void PrimRect(const ImVec2& a, const ImVec2& b, ImU32 col); // Axis aligned rectangle (composed of two triangles)
public PrimRect(a: Readonly<Bind.interface_ImVec2>, b: Readonly<Bind.interface_ImVec2>, col: Bind.ImU32): void { this.native.PrimRect(a, b, col); }
// IMGUI_API void PrimRectUV(const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col);
public PrimRectUV(a: Readonly<Bind.interface_ImVec2>, b: Readonly<Bind.interface_ImVec2>, uv_a: Readonly<Bind.interface_ImVec2>, uv_b: Readonly<Bind.interface_ImVec2>, col: Bind.ImU32): void { this.native.PrimRectUV(a, b, uv_a, uv_b, col); }
// IMGUI_API void PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col);
public PrimQuadUV(a: Readonly<Bind.interface_ImVec2>, b: Readonly<Bind.interface_ImVec2>, c: Readonly<Bind.interface_ImVec2>, d: Readonly<Bind.interface_ImVec2>, uv_a: Readonly<Bind.interface_ImVec2>, uv_b: Readonly<Bind.interface_ImVec2>, uv_c: Readonly<Bind.interface_ImVec2>, uv_d: Readonly<Bind.interface_ImVec2>, col: Bind.ImU32): void { this.native.PrimQuadUV(a, b, c, d, uv_a, uv_b, uv_c, uv_d, col); }
// inline void PrimWriteVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col){ _VtxWritePtr->pos = pos; _VtxWritePtr->uv = uv; _VtxWritePtr->col = col; _VtxWritePtr++; _VtxCurrentIdx++; }
public PrimWriteVtx(pos: Readonly<Bind.interface_ImVec2>, uv: Readonly<Bind.interface_ImVec2>, col: Bind.ImU32): void { this.native.PrimWriteVtx(pos, uv, col); }
// inline void PrimWriteIdx(ImDrawIdx idx) { *_IdxWritePtr = idx; _IdxWritePtr++; }
public PrimWriteIdx(idx: ImDrawIdx): void { this.native.PrimWriteIdx(idx); }
// inline void PrimVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { PrimWriteIdx((ImDrawIdx)_VtxCurrentIdx); PrimWriteVtx(pos, uv, col); }
public PrimVtx(pos: Readonly<Bind.interface_ImVec2>, uv: Readonly<Bind.interface_ImVec2>, col: Bind.ImU32): void { this.native.PrimVtx(pos, uv, col); }
}
// All draw data to render an ImGui frame
export { ImDrawData as DrawData }
export class ImDrawData
{
constructor(public readonly native: Bind.reference_ImDrawData) {}
public IterateDrawLists(callback: (draw_list: ImDrawList) => void): void {
this.native.IterateDrawLists((draw_list: Bind.reference_ImDrawList): void => {
callback(new ImDrawList(draw_list));
});
}
// bool Valid; // Only valid after Render() is called and before the next NewFrame() is called.
get Valid(): boolean { return this.native.Valid; }
// ImDrawList** CmdLists;
// int CmdListsCount;
get CmdListsCount(): number { return this.native.CmdListsCount; }
// int TotalIdxCount; // For convenience, sum of all cmd_lists idx_buffer.Size
get TotalIdxCount(): number { return this.native.TotalIdxCount; }
// int TotalVtxCount; // For convenience, sum of all cmd_lists vtx_buffer.Size
get TotalVtxCount(): number { return this.native.TotalVtxCount; }
// ImVec2 DisplayPos; // Upper-left position of the viewport to render (== upper-left of the orthogonal projection matrix to use)
get DisplayPos(): Readonly<Bind.reference_ImVec2> { return this.native.DisplayPos; }
// ImVec2 DisplaySize; // Size of the viewport to render (== io.DisplaySize for the main viewport) (DisplayPos + DisplaySize == lower-right of the orthogonal projection matrix to use)
get DisplaySize(): Readonly<Bind.reference_ImVec2> { return this.native.DisplaySize; }
// ImVec2 FramebufferScale; // Amount of pixels for each unit of DisplaySize. Based on io.DisplayFramebufferScale. Generally (1,1) on normal display, (2,2) on OSX with Retina display.
get FramebufferScale(): Readonly<Bind.reference_ImVec2> { return this.native.FramebufferScale; }
// Functions
// ImDrawData() { Valid = false; CmdLists = NULL; CmdListsCount = TotalVtxCount = TotalIdxCount = 0; }
// IMGUI_API void DeIndexAllBuffers(); // For backward compatibility or convenience: convert all buffers from indexed to de-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering!
public DeIndexAllBuffers(): void { this.native.DeIndexAllBuffers(); }
// IMGUI_API void ScaleClipRects(const ImVec2& fb_scale); // Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than ImGui expects, or if there is a difference between your window resolution and framebuffer resolution.
public ScaleClipRects(fb_scale: Readonly<Bind.interface_ImVec2>): void {
this.native.ScaleClipRects(fb_scale);
}
}
export class script_ImFontConfig implements Bind.interface_ImFontConfig
{
// void* FontData; // // TTF/OTF data
// int FontDataSize; // // TTF/OTF data size
FontData: DataView | null = null;
// bool FontDataOwnedByAtlas; // true // TTF/OTF data ownership taken by the container ImFontAtlas (will delete memory itself).
FontDataOwnedByAtlas: boolean = true;
// int FontNo; // 0 // Index of font within TTF/OTF file
FontNo: number = 0;
// float SizePixels; // // Size in pixels for rasterizer.
SizePixels: number = 0;
// int OversampleH, OversampleV; // 3, 1 // Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on the Y axis.
OversampleH: number = 3;
OversampleV: number = 1;
// bool PixelSnapH; // false // Align every glyph to pixel boundary. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1.
PixelSnapH: boolean = false;
// ImVec2 GlyphExtraSpacing; // 0, 0 // Extra spacing (in pixels) between glyphs. Only X axis is supported for now.
GlyphExtraSpacing: ImVec2 = new ImVec2(0, 0);
// ImVec2 GlyphOffset; // 0, 0 // Offset all glyphs from this font input.
GlyphOffset: ImVec2 = new ImVec2(0, 0);
// const ImWchar* GlyphRanges; // NULL // Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE.
GlyphRanges: number | null = null;
// float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font
GlyphMinAdvanceX: number = 0;
// float GlyphMaxAdvanceX; // FLT_MAX // Maximum AdvanceX for glyphs
GlyphMaxAdvanceX: number = Number.MAX_VALUE;
// bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights.
MergeMode: boolean = false;
// unsigned int RasterizerFlags; // 0x00 // Settings for custom font rasterizer (e.g. ImGuiFreeType). Leave as zero if you aren't using one.
RasterizerFlags: number = 0;
// float RasterizerMultiply; // 1.0f // Brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable.
RasterizerMultiply: number = 1.0;
// ImWchar EllipsisChar; // -1 // Explicitly specify unicode codepoint of ellipsis character. When fonts are being merged first specified ellipsis will be used.
EllipsisChar: number = -1;
// [Internal]
// char Name[32]; // Name (strictly to ease debugging)
Name: string = "";
// ImFont* DstFont;
DstFont: Bind.reference_ImFont | null = null;
// IMGUI_API ImFontConfig();
}
export { ImFontConfig as FontConfig }
export class ImFontConfig {
constructor(public readonly internal: Bind.interface_ImFontConfig = new script_ImFontConfig()) {}
// void* FontData; // // TTF/OTF data
// int FontDataSize; // // TTF/OTF data size
get FontData(): DataView | null { return this.internal.FontData; }
// bool FontDataOwnedByAtlas; // true // TTF/OTF data ownership taken by the container ImFontAtlas (will delete memory itself).
get FontDataOwnedByAtlas(): boolean { return this.internal.FontDataOwnedByAtlas; }
// int FontNo; // 0 // Index of font within TTF/OTF file
get FontNo(): number { return this.internal.FontNo; }
// float SizePixels; // // Size in pixels for rasterizer.
get SizePixels(): number { return this.internal.SizePixels; }
// int OversampleH, OversampleV; // 3, 1 // Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on the Y axis.
get OversampleH(): number { return this.internal.OversampleH; }
get OversampleV(): number { return this.internal.OversampleV; }
// bool PixelSnapH; // false // Align every glyph to pixel boundary. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1.
get PixelSnapH(): boolean { return this.internal.PixelSnapH; }
// ImVec2 GlyphExtraSpacing; // 0, 0 // Extra spacing (in pixels) between glyphs. Only X axis is supported for now.
get GlyphExtraSpacing(): ImVec2 { return this.internal.GlyphExtraSpacing; }
// ImVec2 GlyphOffset; // 0, 0 // Offset all glyphs from this font input.
get GlyphOffset(): ImVec2 { return this.internal.GlyphOffset; }
// const ImWchar* GlyphRanges; // NULL // Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE.
get GlyphRanges(): number | null { return this.internal.GlyphRanges; }
// float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font
get GlyphMinAdvanceX(): number { return this.internal.GlyphMinAdvanceX; }
// float GlyphMaxAdvanceX; // FLT_MAX // Maximum AdvanceX for glyphs
get GlyphMaxAdvanceX(): number { return this.internal.GlyphMaxAdvanceX; }
// bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights.
get MergeMode(): boolean { return this.internal.MergeMode; }
// unsigned int RasterizerFlags; // 0x00 // Settings for custom font rasterizer (e.g. ImGuiFreeType). Leave as zero if you aren't using one.
get RasterizerFlags(): number { return this.internal.RasterizerFlags; }
// float RasterizerMultiply; // 1.0f // Brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable.
get RasterizerMultiply(): number { return this.internal.RasterizerMultiply; }
// [Internal]
// char Name[32]; // Name (strictly to ease debugging)
get Name(): string { return this.internal.Name; }
set Name(value: string) { this.internal.Name = value; }
// ImFont* DstFont;
get DstFont(): ImFont | null {
const font = this.internal.DstFont;
return font && new ImFont(font);
}
// IMGUI_API ImFontConfig();
}
// struct ImFontGlyph
export class script_ImFontGlyph implements Bind.interface_ImFontGlyph
{
// unsigned int Codepoint : 31; // 0x0000..0xFFFF
Codepoint: number = 0;
// unsigned int Visible : 1; // Flag to allow early out when rendering
Visible: boolean = false;
// float AdvanceX; // Distance to next character (= data from font + ImFontConfig::GlyphExtraSpacing.x baked in)
AdvanceX: number = 0.0;
// float X0, Y0, X1, Y1; // Glyph corners
X0: number = 0.0;
Y0: number = 0.0;
X1: number = 1.0;
Y1: number = 1.0;
// float U0, V0, U1, V1; // Texture coordinates
U0: number = 0.0;
V0: number = 0.0;
U1: number = 1.0;
V1: number = 1.0;
}
export { ImFontGlyph as FontGlyph }
export class ImFontGlyph implements Bind.interface_ImFontGlyph {
constructor(public readonly internal: Bind.interface_ImFontGlyph = new script_ImFontGlyph()) {}
// unsigned int Codepoint : 31; // 0x0000..0xFFFF
get Codepoint(): number { return this.internal.Codepoint; }
// unsigned int Visible : 1; // Flag to allow early out when rendering
get Visible(): boolean { return this.internal.Visible; }
// float AdvanceX; // Distance to next character (= data from font + ImFontConfig::GlyphExtraSpacing.x baked in)
get AdvanceX(): number { return this.internal.AdvanceX; };
// float X0, Y0, X1, Y1; // Glyph corners
get X0(): number { return this.internal.X0; };
get Y0(): number { return this.internal.Y0; };
get X1(): number { return this.internal.X1; };
get Y1(): number { return this.internal.Y1; };
// float U0, V0, U1, V1; // Texture coordinates
get U0(): number { return this.internal.U0; };
get V0(): number { return this.internal.V0; };
get U1(): number { return this.internal.U1; };
get V1(): number { return this.internal.V1; };
}
// See ImFontAtlas::AddCustomRectXXX functions.
export class ImFontAtlasCustomRect
{
// unsigned short Width, Height; // Input // Desired rectangle dimension
// unsigned short X, Y; // Output // Packed position in Atlas
// unsigned int GlyphID; // Input // For custom font glyphs only (ID < 0x110000)
// float GlyphAdvanceX; // Input // For custom font glyphs only: glyph xadvance
// ImVec2 GlyphOffset; // Input // For custom font glyphs only: glyph display offset
// ImFont* Font; // Input // For custom font glyphs only: target font
// ImFontAtlasCustomRect() { Width = Height = 0; X = Y = 0xFFFF; GlyphID = 0; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0, 0); Font = NULL; }
// bool IsPacked() const { return X != 0xFFFF; }
}
export { ImFontAtlasFlags as FontAtlasFlags }
export enum ImFontAtlasFlags
{
None = 0,
NoPowerOfTwoHeight = 1 << 0, // Don't round the height to next power of two
NoMouseCursors = 1 << 1, // Don't build software mouse cursors into the atlas
NoBakedLines = 1 << 2, // Don't build thick line textures into the atlas (save a little texture memory). The AntiAliasedLinesUseTex features uses them, otherwise they will be rendered using polygons (more expensive for CPU/GPU).
}
// Load and rasterize multiple TTF/OTF fonts into a same texture.
// Sharing a texture for multiple fonts allows us to reduce the number of draw calls during rendering.
// We also add custom graphic data into the texture that serves for ImGui.
// 1. (Optional) Call AddFont*** functions. If you don't call any, the default font will be loaded for you.
// 2. Call GetTexDataAsAlpha8() or GetTexDataAsRGBA32() to build and retrieve pixels data.
// 3. Upload the pixels data into a texture within your graphics system.
// 4. Call SetTexID(my_tex_id); and pass the pointer/identifier to your texture. This value will be passed back to you during rendering to identify the texture.
// IMPORTANT: If you pass a 'glyph_ranges' array to AddFont*** functions, you need to make sure that your array persist up until the ImFont is build (when calling GetTextData*** or Build()). We only copy the pointer, not the data.
export { ImFontAtlas as FontAtlas }
export class ImFontAtlas
{
constructor(public readonly native: Bind.reference_ImFontAtlas) {}
// IMGUI_API ImFontAtlas();
// IMGUI_API ~ImFontAtlas();
// IMGUI_API ImFont* AddFont(const ImFontConfig* font_cfg);
// IMGUI_API ImFont* AddFontDefault(const ImFontConfig* font_cfg = NULL);
public AddFontDefault(font_cfg: Bind.interface_ImFontConfig | null = null): ImFont {
return new ImFont(this.native.AddFontDefault(font_cfg));
}
// IMGUI_API ImFont* AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL);
// IMGUI_API ImFont* AddFontFromMemoryTTF(void* font_data, int font_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // Note: Transfer ownership of 'ttf_data' to ImFontAtlas! Will be deleted after Build(). Set font_cfg->FontDataOwnedByAtlas to false to keep ownership.
public AddFontFromMemoryTTF(data: ArrayBuffer, size_pixels: number, font_cfg: ImFontConfig | null = null, glyph_ranges: number | null = null): ImFont {
return new ImFont(this.native.AddFontFromMemoryTTF(new Uint8Array(data), size_pixels, font_cfg && font_cfg.internal, glyph_ranges));
}
// IMGUI_API ImFont* AddFontFromMemoryCompressedTTF(const void* compressed_font_data, int compressed_font_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data' still owned by caller. Compress with binary_to_compressed_c.cpp.
// IMGUI_API ImFont* AddFontFromMemoryCompressedBase85TTF(const char* compressed_font_data_base85, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data_base85' still owned by caller. Compress with binary_to_compressed_c.cpp with -base85 parameter.
// IMGUI_API void ClearTexData(); // Clear the CPU-side texture data. Saves RAM once the texture has been copied to graphics memory.
public ClearTexData(): void { this.native.ClearTexData(); }
// IMGUI_API void ClearInputData(); // Clear the input TTF data (inc sizes, glyph ranges)
public ClearInputData(): void { this.native.ClearInputData(); }
// IMGUI_API void ClearFonts(); // Clear the ImGui-side font data (glyphs storage, UV coordinates)
public ClearFonts(): void { this.native.ClearFonts(); }
// IMGUI_API void Clear(); // Clear all
public Clear(): void { this.native.Clear(); }
// Build atlas, retrieve pixel data.
// User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine). Then store your texture handle with SetTexID().
// RGBA32 format is provided for convenience and compatibility, but note that unless you use CustomRect to draw color data, the RGB pixels emitted from Fonts will all be white (~75% of waste).
// Pitch = Width * BytesPerPixels
// IMGUI_API bool Build(); // Build pixels data. This is called automatically for you by the GetTexData*** functions.
public Build(): boolean { return this.native.Build(); }
// IMGUI_API bool IsBuilt() { return Fonts.Size > 0 && (TexPixelsAlpha8 != NULL || TexPixelsRGBA32 != NULL); }
public IsBuilt(): boolean { return this.native.IsBuilt(); }
// IMGUI_API void GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 1 byte per-pixel
public GetTexDataAsAlpha8(): { pixels: Uint8ClampedArray, width: number, height: number, bytes_per_pixel: number } {
return this.native.GetTexDataAsAlpha8();
}
// IMGUI_API void GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 4 bytes-per-pixel
public GetTexDataAsRGBA32(): { pixels: Uint8ClampedArray, width: number, height: number, bytes_per_pixel: number } {
return this.native.GetTexDataAsRGBA32();
}
// void SetTexID(ImTextureID id) { TexID = id; }
public SetTexID(id: ImTextureID | null): void { this.TexID = id; }
//-------------------------------------------
// Glyph Ranges
//-------------------------------------------
// Helpers to retrieve list of common Unicode ranges (2 value per range, values are inclusive, zero-terminated list)
// NB: Make sure that your string are UTF-8 and NOT in your local code page. In C++11, you can create UTF-8 string literal using the u8"Hello world" syntax. See FAQ for details.
// IMGUI_API const ImWchar* GetGlyphRangesDefault(); // Basic Latin, Extended Latin
GetGlyphRangesDefault(): number { return this.native.GetGlyphRangesDefault(); }
// IMGUI_API const ImWchar* GetGlyphRangesKorean(); // Default + Korean characters
GetGlyphRangesKorean(): number { return this.native.GetGlyphRangesKorean(); }
// IMGUI_API const ImWchar* GetGlyphRangesJapanese(); // Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs
GetGlyphRangesJapanese(): number { return this.native.GetGlyphRangesJapanese(); }
// IMGUI_API const ImWchar* GetGlyphRangesChineseFull(); // Default + Half-Width + Japanese Hiragana/Katakana + full set of about 21000 CJK Unified Ideographs
GetGlyphRangesChineseFull(): number { return this.native.GetGlyphRangesChineseFull(); }
// IMGUI_API const ImWchar* GetGlyphRangesChineseSimplifiedCommon();// Default + Half-Width + Japanese Hiragana/Katakana + set of 2500 CJK Unified Ideographs for common simplified Chinese
GetGlyphRangesChineseSimplifiedCommon(): number { return this.native.GetGlyphRangesChineseSimplifiedCommon(); }
// IMGUI_API const ImWchar* GetGlyphRangesCyrillic(); // Default + about 400 Cyrillic characters
GetGlyphRangesCyrillic(): number { return this.native.GetGlyphRangesCyrillic(); }
// IMGUI_API const ImWchar* GetGlyphRangesThai(); // Default + Thai characters
GetGlyphRangesThai(): number { return this.native.GetGlyphRangesThai(); }
// IMGUI_API const ImWchar* GetGlyphRangesVietnamese(); // Default + Vietnamese characters
GetGlyphRangesVietnamese(): number { return this.native.GetGlyphRangesVietnamese(); }
// Helpers to build glyph ranges from text data. Feed your application strings/characters to it then call BuildRanges().
// struct GlyphRangesBuilder
// {
// ImVector<unsigned char> UsedChars; // Store 1-bit per Unicode code point (0=unused, 1=used)
// GlyphRangesBuilder() { UsedChars.resize(0x10000 / 8); memset(UsedChars.Data, 0, 0x10000 / 8); }
// bool GetBit(int n) const { return (UsedChars[n >> 3] & (1 << (n & 7))) != 0; }
// void SetBit(int n) { UsedChars[n >> 3] |= 1 << (n & 7); } // Set bit 'c' in the array
// void AddChar(ImWchar c) { SetBit(c); } // Add character
// IMGUI_API void AddText(const char* text, const char* text_end = NULL); // Add string (each character of the UTF-8 string are added)
// IMGUI_API void AddRanges(const ImWchar* ranges); // Add ranges, e.g. builder.AddRanges(ImFontAtlas::GetGlyphRangesDefault) to force add all of ASCII/Latin+Ext
// IMGUI_API void BuildRanges(ImVector<ImWchar>* out_ranges); // Output new ranges
// };
//-------------------------------------------
// Custom Rectangles/Glyphs API
//-------------------------------------------
// You can request arbitrary rectangles to be packed into the atlas, for your own purposes. After calling Build(), you can query the rectangle position and render your pixels.
// You can also request your rectangles to be mapped as font glyph (given a font + Unicode point), so you can render e.g. custom colorful icons and use them as regular glyphs.
// struct CustomRect
// {
// unsigned int ID; // Input // User ID. Use <0x10000 to map into a font glyph, >=0x10000 for other/internal/custom texture data.
// unsigned short Width, Height; // Input // Desired rectangle dimension
// unsigned short X, Y; // Output // Packed position in Atlas
// float GlyphAdvanceX; // Input // For custom font glyphs only (ID<0x10000): glyph xadvance
// ImVec2 GlyphOffset; // Input // For custom font glyphs only (ID<0x10000): glyph display offset
// ImFont* Font; // Input // For custom font glyphs only (ID<0x10000): target font
// CustomRect() { ID = 0xFFFFFFFF; Width = Height = 0; X = Y = 0xFFFF; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0,0); Font = NULL; }
// bool IsPacked() const { return X != 0xFFFF; }
// };
// IMGUI_API int AddCustomRectRegular(unsigned int id, int width, int height); // Id needs to be >= 0x10000. Id >= 0x80000000 are reserved for ImGui and ImDrawList
// IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0,0)); // Id needs to be < 0x10000 to register a rectangle to map into a specific font.
// IMGUI_API void CalcCustomRectUV(const CustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max);
// const CustomRect* GetCustomRectByIndex(int index) const { if (index < 0) return NULL; return &CustomRects[index]; }
//-------------------------------------------
// Members
//-------------------------------------------
// bool Locked; // Marked as Locked by ImGui::NewFrame() so attempt to modify the atlas will assert.
get Locked(): boolean { return this.native.Locked; }
set Locked(value: boolean) { this.native.Locked = value; }
// ImFontAtlasFlags Flags; // Build flags (see ImFontAtlasFlags_)
get Flags(): ImFontAtlasFlags { return this.native.Flags; }
set Flags(value: ImFontAtlasFlags) { this.native.Flags = value; }
// ImTextureID TexID; // User data to refer to the texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure.
get TexID(): ImTextureID | null {
return ImGuiContext.getTexture(this.native.TexID);
}
set TexID(value: ImTextureID | null) {
this.native.TexID = ImGuiContext.setTexture(value);
}
// int TexDesiredWidth; // Texture width desired by user before Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height.
get TexDesiredWidth(): number { return this.native.TexDesiredWidth; }
set TexDesiredWidth(value: number) { this.native.TexDesiredWidth = value; }
// int TexGlyphPadding; // Padding between glyphs within texture in pixels. Defaults to 1.
get TexGlyphPadding(): number { return this.native.TexGlyphPadding; }
set TexGlyphPadding(value: number) { this.native.TexGlyphPadding = value; }
// [Internal]
// NB: Access texture data via GetTexData*() calls! Which will setup a default font for you.
// unsigned char* TexPixelsAlpha8; // 1 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight
// unsigned int* TexPixelsRGBA32; // 4 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight * 4
// int TexWidth; // Texture width calculated during Build().
get TexWidth(): number { return this.native.TexWidth; }
// int TexHeight; // Texture height calculated during Build().
get TexHeight(): number { return this.native.TexHeight; }
// ImVec2 TexUvScale; // = (1.0f/TexWidth, 1.0f/TexHeight)
get TexUvScale(): Readonly<Bind.reference_ImVec2> { return this.native.TexUvScale; }
// ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel
get TexUvWhitePixel(): Readonly<Bind.reference_ImVec2> { return this.native.TexUvWhitePixel; }
// ImVector<ImFont*> Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font.
get Fonts(): ImVector<ImFont> {
const fonts: ImVector<ImFont> = new ImVector<ImFont>();
this.native.IterateFonts((font: Bind.reference_ImFont) => {
fonts.push(new ImFont(font));
});
return fonts;
}
// ImVector<CustomRect> CustomRects; // Rectangles for packing custom texture data into the atlas.
// ImVector<ImFontConfig> ConfigData; // Internal data
// int CustomRectIds[1]; // Identifiers of custom texture rectangle used by ImFontAtlas/ImDrawList
}
// Font runtime data and rendering
// ImFontAtlas automatically loads a default embedded font for you when you call GetTexDataAsAlpha8() or GetTexDataAsRGBA32().
export { ImFont as Font }
export class ImFont
{
constructor(public readonly native: Bind.reference_ImFont) {}
// Members: Hot ~62/78 bytes
// float FontSize; // <user set> // Height of characters, set during loading (don't change after loading)
get FontSize(): number { return this.native.FontSize; }
// float Scale; // = 1.f // Base font scale, multiplied by the per-window font scale which you can adjust with SetFontScale()
get Scale(): number { return this.native.Scale; }
set Scale(value: number) { this.native.Scale = value; }
// ImVector<ImFontGlyph> Glyphs; // // All glyphs.
get Glyphs(): ImVector<ImFontGlyph> {
const glyphs = new ImVector<ImFontGlyph>();
this.native.IterateGlyphs((glyph: Bind.reference_ImFontGlyph): void => {
glyphs.push(new ImFontGlyph(glyph)); // TODO: wrap native
});
return glyphs;
}
// ImVector<float> IndexAdvanceX; // // Sparse. Glyphs->AdvanceX in a directly indexable way (more cache-friendly, for CalcTextSize functions which are often bottleneck in large UI).
// get IndexAdvanceX(): any { return this.native.IndexAdvanceX; }
// ImVector<unsigned short> IndexLookup; // // Sparse. Index glyphs by Unicode code-point.
// get IndexLookup(): any { return this.native.IndexLookup; }
// const ImFontGlyph* FallbackGlyph; // == FindGlyph(FontFallbackChar)
get FallbackGlyph(): ImFontGlyph | null {
const glyph = this.native.FallbackGlyph;
return glyph && new ImFontGlyph(glyph);
}
set FallbackGlyph(value: ImFontGlyph | null) {
this.native.FallbackGlyph = value && value.internal as Bind.reference_ImFontGlyph;
}
// float FallbackAdvanceX; // == FallbackGlyph->AdvanceX
get FallbackAdvanceX(): number { return this.native.FallbackAdvanceX; }
// ImWchar FallbackChar; // = '?' // Replacement glyph if one isn't found. Only set via SetFallbackChar()
get FallbackChar(): number { return this.native.FallbackChar; }
// ImWchar EllipsisChar; // 2 // out // = -1 // Character used for ellipsis rendering.
get EllipsisChar(): number { return this.native.EllipsisChar; }
// Members: Cold ~18/26 bytes
// short ConfigDataCount; // ~ 1 // Number of ImFontConfig involved in creating this font. Bigger than 1 when merging multiple font sources into one ImFont.
get ConfigDataCount(): number { return this.ConfigData.length; }
// ImFontConfig* ConfigData; // // Pointer within ContainerAtlas->ConfigData
get ConfigData(): ImFontConfig[] {
const cfg_data: ImFontConfig[] = [];
this.native.IterateConfigData((cfg: Bind.interface_ImFontConfig): void => {
cfg_data.push(new ImFontConfig(cfg));
});
return cfg_data;
}
// ImFontAtlas* ContainerAtlas; // // What we has been loaded into
get ContainerAtlas(): ImFontAtlas | null { return null; }
// float Ascent, Descent; // // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize]
get Ascent(): number { return this.native.Ascent; }
get Descent(): number { return this.native.Descent; }
// int MetricsTotalSurface;// // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs)
get MetricsTotalSurface(): number { return this.native.MetricsTotalSurface; }
// Methods
// IMGUI_API ImFont();
// IMGUI_API ~ImFont();
// IMGUI_API void ClearOutputData();
public ClearOutputData(): void { return this.native.ClearOutputData(); }
// IMGUI_API void BuildLookupTable();
public BuildLookupTable(): void { return this.native.BuildLookupTable(); }
// IMGUI_API const ImFontGlyph*FindGlyph(ImWchar c) const;
public FindGlyph(c: number): Readonly<ImFontGlyph> | null {
const glyph: Readonly<Bind.reference_ImFontGlyph> | null = this.native.FindGlyph(c);
return glyph && new ImFontGlyph(glyph);
}
// IMGUI_API const ImFontGlyph*FindGlyphNoFallback(ImWchar c) const;
public FindGlyphNoFallback(c: number): ImFontGlyph | null {
const glyph: Readonly<Bind.reference_ImFontGlyph> | null = this.native.FindGlyphNoFallback(c);
return glyph && new ImFontGlyph(glyph);
}
// IMGUI_API void SetFallbackChar(ImWchar c);
public SetFallbackChar(c: number): void { return this.native.SetFallbackChar(c); }
// float GetCharAdvance(ImWchar c) const { return ((int)c < IndexAdvanceX.Size) ? IndexAdvanceX[(int)c] : FallbackAdvanceX; }
public GetCharAdvance(c: number): number { return this.native.GetCharAdvance(c); }
// bool IsLoaded() const { return ContainerAtlas != NULL; }
public IsLoaded(): boolean { return this.native.IsLoaded(); }
// const char* GetDebugName() const { return ConfigData ? ConfigData->Name : "<unknown>"; }
public GetDebugName(): string { return this.native.GetDebugName(); }
// 'max_width' stops rendering after a certain width (could be turned into a 2d size). FLT_MAX to disable.
// 'wrap_width' enable automatic word-wrapping across multiple lines to fit into given width. 0.0f to disable.
// IMGUI_API ImVec2 CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end = NULL, const char** remaining = NULL) const; // utf8
public CalcTextSizeA(size: number, max_width: number, wrap_width: number, text_begin: string, text_end: number | null = null, remaining: Bind.ImScalar<number> | null = null): Bind.interface_ImVec2 {
return this.native.CalcTextSizeA(size, max_width, wrap_width, text_end !== null ? text_begin.substring(0, text_end) : text_begin, remaining, new ImVec2());
}
// IMGUI_API const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const;
public CalcWordWrapPositionA(scale: number, text: string, text_end: number | null = null, wrap_width: number): number {
return this.native.CalcWordWrapPositionA(scale, text_end !== null ? text.substring(0, text_end) : text, wrap_width);
}
// IMGUI_API void RenderChar(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, unsigned short c) const;
public RenderChar(draw_list: ImDrawList, size: number, pos: Readonly<Bind.interface_ImVec2>, col: Bind.ImU32, c: Bind.ImWchar): void {
this.native.RenderChar(draw_list.native, size, pos, col, c);
}
// IMGUI_API void RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width = 0.0f, bool cpu_fine_clip = false) const;
public RenderText(draw_list: ImDrawList, size: number, pos: Readonly<Bind.interface_ImVec2>, col: Bind.ImU32, clip_rect: Readonly<Bind.interface_ImVec4>, text_begin: string, text_end: number | null = null, wrap_width: number = 0.0, cpu_fine_clip: boolean = false): void {}
// [Internal]
// IMGUI_API void GrowIndex(int new_size);
// IMGUI_API void AddGlyph(ImWchar c, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x);
// IMGUI_API void AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst = true); // Makes 'dst' character/glyph points to 'src' character/glyph. Currently needs to be called AFTER fonts have been built.
// #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
// typedef ImFontGlyph Glyph; // OBSOLETE 1.52+
// #endif
// IMGUI_API bool IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last);
public IsGlyphRangeUnused(c_begin: number, c_last: number): boolean { return false; } // TODO
}
// a script version of Bind.ImGuiStyle with matching interface
class script_ImGuiStyle implements Bind.interface_ImGuiStyle {
public Alpha: number = 1.0;
public WindowPadding: ImVec2 = new ImVec2(8, 8);
public WindowRounding: number = 7.0;
public WindowBorderSize: number = 0.0;
public WindowMinSize: ImVec2 = new ImVec2(32, 32);
public WindowTitleAlign: ImVec2 = new ImVec2(0.0, 0.5);
public WindowMenuButtonPosition: ImGuiDir = ImGuiDir.Left;
public ChildRounding: number = 0.0;
public ChildBorderSize: number = 1.0;
public PopupRounding: number = 0.0;
public PopupBorderSize: number = 1.0;
public FramePadding: ImVec2 = new ImVec2(4, 3);
public FrameRounding: number = 0.0;
public FrameBorderSize: number = 0.0;
public ItemSpacing: ImVec2 = new ImVec2(8, 4);
public ItemInnerSpacing: ImVec2 = new ImVec2(4, 4);
public CellPadding: ImVec2 = new ImVec2(4, 2);
public TouchExtraPadding: ImVec2 = new ImVec2(0, 0);
public IndentSpacing: number = 21.0;
public ColumnsMinSpacing: number = 6.0;
public ScrollbarSize: number = 16.0;
public ScrollbarRounding: number = 9.0;
public GrabMinSize: number = 10.0;
public GrabRounding: number = 0.0;
public LogSliderDeadzone: number = 4.0;
public TabRounding: number = 0.0;
public TabBorderSize: number = 0.0;
public TabMinWidthForCloseButton: number = 0.0;
public ColorButtonPosition: ImGuiDir = ImGuiDir.Right;
public ButtonTextAlign: ImVec2 = new ImVec2(0.5, 0.5);
public SelectableTextAlign: ImVec2 = new ImVec2(0.0, 0.0);
public DisplayWindowPadding: ImVec2 = new ImVec2(22, 22);
public DisplaySafeAreaPadding: ImVec2 = new ImVec2(4, 4);
public MouseCursorScale: number = 1;
public AntiAliasedLines: boolean = true;
public AntiAliasedLinesUseTex: boolean = true;
public AntiAliasedFill: boolean = true;
public CurveTessellationTol: number = 1.25;
public CircleSegmentMaxError: number = 1.60;
private Colors: ImVec4[] = [];
public _getAt_Colors(index: number): Bind.interface_ImVec4 { return this.Colors[index]; }
public _setAt_Colors(index: number, color: Readonly<Bind.interface_ImVec4>): boolean { this.Colors[index].Copy(color); return true; }
constructor() {
for (let i = 0; i < ImGuiCol.COUNT; ++i) {
this.Colors[i] = new ImVec4();
}
const _this = new ImGuiStyle(this);
const native = new bind.ImGuiStyle();
const _that = new ImGuiStyle(native);
_that.Copy(_this);
bind.StyleColorsClassic(native);
_this.Copy(_that);
native.delete();
}
public ScaleAllSizes(scale_factor: number): void {
const _this = new ImGuiStyle(this);
const native = new bind.ImGuiStyle();
const _that = new ImGuiStyle(native);
_that.Copy(_this);
native.ScaleAllSizes(scale_factor);
_this.Copy(_that);
native.delete();
}
}
export { ImGuiStyle as Style }
export class ImGuiStyle
{
constructor(public readonly internal: Bind.interface_ImGuiStyle = new script_ImGuiStyle()) {}
get Alpha(): number { return this.internal.Alpha; } set Alpha(value: number) { this.internal.Alpha = value; }
get WindowPadding(): Bind.interface_ImVec2 { return this.internal.WindowPadding; }
get WindowRounding(): number { return this.internal.WindowRounding; } set WindowRounding(value: number) { this.internal.WindowRounding = value; }
get WindowBorderSize(): number { return this.internal.WindowBorderSize; } set WindowBorderSize(value: number) { this.internal.WindowBorderSize = value; }
get WindowMinSize(): Bind.interface_ImVec2 { return this.internal.WindowMinSize; }
get WindowTitleAlign(): Bind.interface_ImVec2 { return this.internal.WindowTitleAlign; }
get WindowMenuButtonPosition(): ImGuiDir { return this.internal.WindowMenuButtonPosition; } set WindowMenuButtonPosition(value: ImGuiDir) { this.internal.WindowMenuButtonPosition = value; }
get ChildRounding(): number { return this.internal.ChildRounding; } set ChildRounding(value: number) { this.internal.ChildRounding = value; }
get ChildBorderSize(): number { return this.internal.ChildBorderSize; } set ChildBorderSize(value: number) { this.internal.ChildBorderSize = value; }
get PopupRounding(): number { return this.internal.PopupRounding; } set PopupRounding(value: number) { this.internal.PopupRounding = value; }
get PopupBorderSize(): number { return this.internal.PopupBorderSize; } set PopupBorderSize(value: number) { this.internal.PopupBorderSize = value; }
get FramePadding(): Bind.interface_ImVec2 { return this.internal.FramePadding; }
get FrameRounding(): number { return this.internal.FrameRounding; } set FrameRounding(value: number) { this.internal.FrameRounding = value; }
get FrameBorderSize(): number { return this.internal.FrameBorderSize; } set FrameBorderSize(value: number) { this.internal.FrameBorderSize = value; }
get ItemSpacing(): Bind.interface_ImVec2 { return this.internal.ItemSpacing; }
get ItemInnerSpacing(): Bind.interface_ImVec2 { return this.internal.ItemInnerSpacing; }
get CellPadding(): Bind.interface_ImVec2 { return this.internal.CellPadding; }
get TouchExtraPadding(): Bind.interface_ImVec2 { return this.internal.TouchExtraPadding; }
get IndentSpacing(): number { return this.internal.IndentSpacing; } set IndentSpacing(value: number) { this.internal.IndentSpacing = value; }
get ColumnsMinSpacing(): number { return this.internal.ColumnsMinSpacing; } set ColumnsMinSpacing(value: number) { this.internal.ColumnsMinSpacing = value; }
get ScrollbarSize(): number { return this.internal.ScrollbarSize; } set ScrollbarSize(value: number) { this.internal.ScrollbarSize = value; }
get ScrollbarRounding(): number { return this.internal.ScrollbarRounding; } set ScrollbarRounding(value: number) { this.internal.ScrollbarRounding = value; }
get GrabMinSize(): number { return this.internal.GrabMinSize; } set GrabMinSize(value: number) { this.internal.GrabMinSize = value; }
get GrabRounding(): number { return this.internal.GrabRounding; } set GrabRounding(value: number) { this.internal.GrabRounding = value; }
get LogSliderDeadzone(): number { return this.internal.LogSliderDeadzone; } set LogSliderDeadzone(value: number) { this.internal.LogSliderDeadzone = value; }
get TabRounding(): number { return this.internal.TabRounding; } set TabRounding(value: number) { this.internal.TabRounding = value; }
get TabBorderSize(): number { return this.internal.TabBorderSize; } set TabBorderSize(value: number) { this.internal.TabBorderSize = value; }
get TabMinWidthForCloseButton(): number { return this.internal.TabMinWidthForCloseButton; } set TabMinWidthForCloseButton(value: number) { this.internal.TabMinWidthForCloseButton = value; }
get ColorButtonPosition(): number { return this.internal.ColorButtonPosition; } set ColorButtonPosition(value: number) { this.internal.ColorButtonPosition = value; }
get ButtonTextAlign(): Bind.interface_ImVec2 { return this.internal.ButtonTextAlign; }
get SelectableTextAlign(): Bind.interface_ImVec2 { return this.internal.SelectableTextAlign; }
get DisplayWindowPadding(): Bind.interface_ImVec2 { return this.internal.DisplayWindowPadding; }
get DisplaySafeAreaPadding(): Bind.interface_ImVec2 { return this.internal.DisplaySafeAreaPadding; }
get MouseCursorScale(): number { return this.internal.MouseCursorScale; } set MouseCursorScale(value: number) { this.internal.MouseCursorScale = value; }
get AntiAliasedLines(): boolean { return this.internal.AntiAliasedLines; } set AntiAliasedLines(value: boolean) { this.internal.AntiAliasedLines = value; }
get AntiAliasedLinesUseTex(): boolean { return this.internal.AntiAliasedLinesUseTex; } set AntiAliasedLinesUseTex(value: boolean) { this.internal.AntiAliasedLinesUseTex = value; }
get AntiAliasedFill(): boolean { return this.internal.AntiAliasedFill; } set AntiAliasedFill(value: boolean) { this.internal.AntiAliasedFill = value; }
get CurveTessellationTol(): number { return this.internal.CurveTessellationTol; } set CurveTessellationTol(value: number) { this.internal.CurveTessellationTol = value; }
get CircleSegmentMaxError(): number { return this.internal.CircleSegmentMaxError; } set CircleSegmentMaxError(value: number) { this.internal.CircleSegmentMaxError = value; }
public Colors: Bind.interface_ImVec4[] = new Proxy([], {
get: (target: Bind.interface_ImVec4[], key: PropertyKey): number | Bind.interface_ImVec4 => {
if (key === "length") { return ImGuiCol.COUNT; }
return this.internal._getAt_Colors(Number(key));
},
set: (target: Bind.interface_ImVec4[], key: PropertyKey, value: Readonly<Bind.interface_ImVec4>): boolean => {
return this.internal._setAt_Colors(Number(key), value);
},
});
public Copy(other: Readonly<ImGuiStyle>): this {
this.Alpha = other.Alpha;
this.WindowPadding.Copy(other.WindowPadding);
this.WindowRounding = other.WindowRounding;
this.WindowBorderSize = other.WindowBorderSize;
this.WindowMinSize.Copy(other.WindowMinSize);
this.WindowTitleAlign.Copy(other.WindowTitleAlign);
this.WindowMenuButtonPosition = other.WindowMenuButtonPosition;
this.ChildRounding = other.ChildRounding;
this.ChildBorderSize = other.ChildBorderSize;
this.PopupRounding = other.PopupRounding;
this.PopupBorderSize = other.PopupBorderSize;
this.FramePadding.Copy(other.FramePadding);
this.FrameRounding = other.FrameRounding;
this.FrameBorderSize = other.FrameBorderSize;
this.ItemSpacing.Copy(other.ItemSpacing);
this.ItemInnerSpacing.Copy(other.ItemInnerSpacing);
this.CellPadding.Copy(other.CellPadding);
this.TouchExtraPadding.Copy(other.TouchExtraPadding);
this.IndentSpacing = other.IndentSpacing;
this.ColumnsMinSpacing = other.ColumnsMinSpacing;
this.ScrollbarSize = other.ScrollbarSize;
this.ScrollbarRounding = other.ScrollbarRounding;
this.GrabMinSize = other.GrabMinSize;
this.GrabRounding = other.GrabRounding;
this.LogSliderDeadzone = other.LogSliderDeadzone;
this.TabRounding = other.TabRounding;
this.TabBorderSize = other.TabBorderSize;
this.TabMinWidthForCloseButton = other.TabMinWidthForCloseButton;
this.ColorButtonPosition = other.ColorButtonPosition;
this.ButtonTextAlign.Copy(other.ButtonTextAlign);
this.DisplayWindowPadding.Copy(other.DisplayWindowPadding);
this.DisplaySafeAreaPadding.Copy(other.DisplaySafeAreaPadding);
this.MouseCursorScale = other.MouseCursorScale;
this.AntiAliasedLines = other.AntiAliasedLines;
this.AntiAliasedLinesUseTex = other.AntiAliasedLinesUseTex;
this.AntiAliasedFill = other.AntiAliasedFill;
this.CurveTessellationTol = other.CurveTessellationTol;
this.CircleSegmentMaxError = other.CircleSegmentMaxError;
for (let i = 0; i < ImGuiCol.COUNT; ++i) {
this.Colors[i].Copy(other.Colors[i]);
}
return this;
}
public ScaleAllSizes(scale_factor: number): void { this.internal.ScaleAllSizes(scale_factor); }
}
// This is where your app communicate with Dear ImGui. Access via ImGui::GetIO().
// Read 'Programmer guide' section in .cpp file for general usage.
export { ImGuiIO as IO }
export class ImGuiIO
{
constructor(public readonly native: Bind.reference_ImGuiIO) {}
//------------------------------------------------------------------
// Settings (fill once) // Default value:
//------------------------------------------------------------------
// ImGuiConfigFlags ConfigFlags; // = 0 // See ImGuiConfigFlags_ enum. Set by user/application. Gamepad/keyboard navigation options, etc.
get ConfigFlags(): ImGuiConfigFlags { return this.native.ConfigFlags; }
set ConfigFlags(value: ImGuiConfigFlags) { this.native.ConfigFlags = value; }
// ImGuiBackendFlags BackendFlags; // = 0 // Set ImGuiBackendFlags_ enum. Set by imgui_impl_xxx files or custom back-end to communicate features supported by the back-end.
get BackendFlags(): ImGuiBackendFlags { return this.native.BackendFlags; }
set BackendFlags(value: ImGuiBackendFlags) { this.native.BackendFlags = value; }
// ImVec2 DisplaySize; // <unset> // Display size, in pixels. For clamping windows positions.
get DisplaySize(): Bind.reference_ImVec2 { return this.native.DisplaySize; }
// float DeltaTime; // = 1.0f/60.0f // Time elapsed since last frame, in seconds.
get DeltaTime(): number { return this.native.DeltaTime; }
set DeltaTime(value: number) { this.native.DeltaTime = value; }
// float IniSavingRate; // = 5.0f // Maximum time between saving positions/sizes to .ini file, in seconds.
get IniSavingRate(): number { return this.native.IniSavingRate; }
set IniSavingRate(value: number) { this.native.IniSavingRate = value; }
// const char* IniFilename; // = "imgui.ini" // Path to .ini file. NULL to disable .ini saving.
get IniFilename(): string { return this.native.IniFilename; }
set IniFilename(value: string) { this.native.IniFilename = value; }
// const char* LogFilename; // = "imgui_log.txt" // Path to .log file (default parameter to ImGui::LogToFile when no file is specified).
get LogFilename(): string { return this.native.LogFilename; }
set LogFilename(value: string) { this.native.LogFilename = value; }
// float MouseDoubleClickTime; // = 0.30f // Time for a double-click, in seconds.
get MouseDoubleClickTime(): number { return this.native.MouseDoubleClickTime; }
set MouseDoubleClickTime(value: number) { this.native.MouseDoubleClickTime = value; }
// float MouseDoubleClickMaxDist; // = 6.0f // Distance threshold to stay in to validate a double-click, in pixels.
get MouseDoubleClickMaxDist(): number { return this.native.MouseDoubleClickMaxDist; }
set MouseDoubleClickMaxDist(value: number) { this.native.MouseDoubleClickMaxDist = value; }
// float MouseDragThreshold; // = 6.0f // Distance threshold before considering we are dragging
get MouseDragThreshold(): number { return this.native.MouseDragThreshold; }
set MouseDragThreshold(value: number) { this.native.MouseDragThreshold = value; }
// int KeyMap[ImGuiKey_COUNT]; // <unset> // Map of indices into the KeysDown[512] entries array
public KeyMap: number[] = new Proxy([], {
get: (target: number[], key: PropertyKey): number => {
if (key === "length") { return ImGuiKey.COUNT; }
return this.native._getAt_KeyMap(Number(key));
},
set: (target: number[], key: PropertyKey, value: number): boolean => {
return this.native._setAt_KeyMap(Number(key), value);
},
});
// float KeyRepeatDelay; // = 0.250f // When holding a key/button, time before it starts repeating, in seconds (for buttons in Repeat mode, etc.).
get KeyRepeatDelay(): number { return this.native.KeyRepeatDelay; }
set KeyRepeatDelay(value: number) { this.native.KeyRepeatDelay = value; }
// float KeyRepeatRate; // = 0.050f // When holding a key/button, rate at which it repeats, in seconds.
get KeyRepeatRate(): number { return this.native.KeyRepeatRate; }
set KeyRepeatRate(value: number) { this.native.KeyRepeatRate = value; }
// void* UserData; // = NULL // Store your own data for retrieval by callbacks.
get UserData(): any { return this.native.UserData; }
set UserData(value: any) { this.native.UserData = value; }
// ImFontAtlas* Fonts; // <auto> // Load and assemble one or more fonts into a single tightly packed texture. Output to Fonts array.
get Fonts(): ImFontAtlas { return new ImFontAtlas(this.native.Fonts); }
// float FontGlobalScale; // = 1.0f // Global scale all fonts
get FontGlobalScale(): number { return this.native.FontGlobalScale; }
set FontGlobalScale(value: number) { this.native.FontGlobalScale = value; }
// bool FontAllowUserScaling; // = false // Allow user scaling text of individual window with CTRL+Wheel.
get FontAllowUserScaling(): boolean { return this.native.FontAllowUserScaling; }
set FontAllowUserScaling(value: boolean) { this.native.FontAllowUserScaling = value; }
// ImFont* FontDefault; // = NULL // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0].
get FontDefault(): ImFont | null {
const font: Bind.reference_ImFont | null = this.native.FontDefault;
return (font === null) ? null : new ImFont(font);
}
set FontDefault(value: ImFont | null) {
this.native.FontDefault = value && value.native;
}
// ImVec2 DisplayFramebufferScale; // = (1.0f,1.0f) // For retina display or other situations where window coordinates are different from framebuffer coordinates. User storage only, presently not used by ImGui.
get DisplayFramebufferScale(): Bind.reference_ImVec2 { return this.native.DisplayFramebufferScale; }
// Miscellaneous configuration options
// bool OptMacOSXBehaviors; // = defined(__APPLE__) // OS X style: Text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl
get ConfigMacOSXBehaviors(): boolean { return this.native.ConfigMacOSXBehaviors; }
set ConfigMacOSXBehaviors(value: boolean) { this.native.ConfigMacOSXBehaviors = value; }
// bool ConfigInputTextCursorBlink; // = true // Enable blinking cursor, for users who consider it annoying.
get ConfigInputTextCursorBlink(): boolean { return this.native.ConfigInputTextCursorBlink; }
set ConfigInputTextCursorBlink(value: boolean) { this.native.ConfigInputTextCursorBlink = value; }
// bool ConfigDragClickToInputText; // = false // [BETA] Enable turning DragXXX widgets into text input with a simple mouse click-release (without moving). Not desirable on devices without a keyboard.
get ConfigDragClickToInputText(): boolean { return this.native.ConfigDragClickToInputText; }
set ConfigDragClickToInputText(value: boolean) { this.native.ConfigDragClickToInputText = value; }
// bool ConfigWindowsResizeFromEdges; // = false // [BETA] Enable resizing of windows from their edges and from the lower-left corner. This requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback. (This used to be the ImGuiWindowFlags_ResizeFromAnySide flag)
get ConfigWindowsResizeFromEdges(): boolean { return this.native.ConfigWindowsResizeFromEdges; }
set ConfigWindowsResizeFromEdges(value: boolean) { this.native.ConfigWindowsResizeFromEdges = value; }
// bool ConfigWindowsMoveFromTitleBarOnly;// = false // [BETA] Set to true to only allow moving windows when clicked+dragged from the title bar. Windows without a title bar are not affected.
get ConfigWindowsMoveFromTitleBarOnly(): boolean { return this.native.ConfigWindowsMoveFromTitleBarOnly; }
set ConfigWindowsMoveFromTitleBarOnly(value: boolean) { this.native.ConfigWindowsMoveFromTitleBarOnly = value; }
// float ConfigMemoryCompactTimer; // = 60.0f // Timer (in seconds) to free transient windows/tables memory buffers when unused. Set to -1.0f to disable.
get ConfigMemoryCompactTimer(): number { return this.native.ConfigMemoryCompactTimer; }
set ConfigMemoryCompactTimer(value: number) { this.native.ConfigMemoryCompactTimer = value; }
//------------------------------------------------------------------
// Settings (User Functions)
//------------------------------------------------------------------
// Optional: Platform/Renderer back-end name (informational only! will be displayed in About Window) + User data for back-end/wrappers to store their own stuff.
// const char* BackendPlatformName; // = NULL
get BackendPlatformName(): string | null { return this.native.BackendPlatformName; }
set BackendPlatformName(value: string | null) { this.native.BackendPlatformName = value; }
// const char* BackendRendererName; // = NULL
get BackendRendererName(): string | null { return this.native.BackendRendererName; }
set BackendRendererName(value: string | null) { this.native.BackendRendererName = value; }
// void* BackendPlatformUserData; // = NULL
get BackendPlatformUserData(): string | null { return this.native.BackendPlatformUserData; }
set BackendPlatformUserData(value: string | null) { this.native.BackendPlatformUserData = value; }
// void* BackendRendererUserData; // = NULL
get BackendRendererUserData(): string | null { return this.native.BackendRendererUserData; }
set BackendRendererUserData(value: string | null) { this.native.BackendRendererUserData = value; }
// void* BackendLanguageUserData; // = NULL
get BackendLanguageUserData(): string | null { return this.native.BackendLanguageUserData; }
set BackendLanguageUserData(value: string | null) { this.native.BackendLanguageUserData = value; }
// Optional: access OS clipboard
// (default to use native Win32 clipboard on Windows, otherwise uses a private clipboard. Override to access OS clipboard on other architectures)
// const char* (*GetClipboardTextFn)(void* user_data);
get GetClipboardTextFn(): ((user_data: any) => string) | null { return this.native.GetClipboardTextFn; }
set GetClipboardTextFn(value: ((user_data: any) => string) | null) { this.native.GetClipboardTextFn = value; }
// void (*SetClipboardTextFn)(void* user_data, const char* text);
get SetClipboardTextFn(): ((user_data: any, text: string) => void) | null { return this.native.SetClipboardTextFn; }
set SetClipboardTextFn(value: ((user_data: any, text: string) => void) | null) { this.native.SetClipboardTextFn = value; }
// void* ClipboardUserData;
get ClipboardUserData(): any { return this.native.ClipboardUserData; }
set ClipboardUserData(value: any) { this.native.ClipboardUserData = value; }
// Optional: override memory allocations. MemFreeFn() may be called with a NULL pointer.
// (default to posix malloc/free)
// void* (*MemAllocFn)(size_t sz);
// void (*MemFreeFn)(void* ptr);
// Optional: notify OS Input Method Editor of the screen position of your cursor for text input position (e.g. when using Japanese/Chinese IME in Windows)
// (default to use native imm32 api on Windows)
// void (*ImeSetInputScreenPosFn)(int x, int y);
// void* ImeWindowHandle; // (Windows) Set this to your HWND to get automatic IME cursor positioning.
//------------------------------------------------------------------
// Input - Fill before calling NewFrame()
//------------------------------------------------------------------
// ImVec2 MousePos; // Mouse position, in pixels. Set to ImVec2(-FLT_MAX,-FLT_MAX) if mouse is unavailable (on another screen, etc.)
get MousePos(): Bind.reference_ImVec2 { return this.native.MousePos; }
// bool MouseDown[5]; // Mouse buttons: left, right, middle + extras. ImGui itself mostly only uses left button (BeginPopupContext** are using right button). Others buttons allows us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API.
public MouseDown: boolean[] = new Proxy([], {
get: (target: boolean[], key: PropertyKey): number | boolean => {
if (key === "length") { return 5; }
return this.native._getAt_MouseDown(Number(key));
},
set: (target: boolean[], key: PropertyKey, value: boolean): boolean => {
return this.native._setAt_MouseDown(Number(key), value);
},
});
// float MouseWheel; // Mouse wheel: 1 unit scrolls about 5 lines text.
public get MouseWheel(): number { return this.native.MouseWheel; }
public set MouseWheel(value: number) { this.native.MouseWheel = value; }
// float MouseWheelH; // Mouse wheel (Horizontal). Most users don't have a mouse with an horizontal wheel, may not be filled by all back-ends.
public get MouseWheelH(): number { return this.native.MouseWheelH; }
public set MouseWheelH(value: number) { this.native.MouseWheelH = value; }
// bool MouseDrawCursor; // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor).
get MouseDrawCursor(): boolean { return this.native.MouseDrawCursor; } set MouseDrawCursor(value: boolean) { this.native.MouseDrawCursor = value; }
// bool KeyCtrl; // Keyboard modifier pressed: Control
get KeyCtrl(): boolean { return this.native.KeyCtrl; } set KeyCtrl(value: boolean) { this.native.KeyCtrl = value; }
// bool KeyShift; // Keyboard modifier pressed: Shift
get KeyShift(): boolean { return this.native.KeyShift; } set KeyShift(value: boolean) { this.native.KeyShift = value; }
// bool KeyAlt; // Keyboard modifier pressed: Alt
get KeyAlt(): boolean { return this.native.KeyAlt; } set KeyAlt(value: boolean) { this.native.KeyAlt = value; }
// bool KeySuper; // Keyboard modifier pressed: Cmd/Super/Windows
get KeySuper(): boolean { return this.native.KeySuper; } set KeySuper(value: boolean) { this.native.KeySuper = value; }
// bool KeysDown[512]; // Keyboard keys that are pressed (in whatever storage order you naturally have access to keyboard data)
public KeysDown: boolean[] = new Proxy([], {
get: (target: boolean[], key: PropertyKey): number | boolean => {
if (key === "length") { return 512; }
return this.native._getAt_KeysDown(Number(key));
},
set: (target: boolean[], key: PropertyKey, value: boolean): boolean => {
return this.native._setAt_KeysDown(Number(key), value);
},
});
// float NavInputs[ImGuiNavInput_COUNT]; // Gamepad inputs (keyboard keys will be auto-mapped and be written here by ImGui::NewFrame)
public NavInputs: number[] = new Proxy([], {
get: (target: number[], key: PropertyKey): number => {
if (key === "length") { return ImGuiNavInput.COUNT; }
return this.native._getAt_NavInputs(Number(key));
},
set: (target: number[], key: PropertyKey, value: number): boolean => {
return this.native._setAt_NavInputs(Number(key), value);
},
});
// Functions
// IMGUI_API void AddInputCharacter(ImWchar c); // Add new character into InputCharacters[]
public AddInputCharacter(c: number): void { this.native.AddInputCharacter(c); }
// IMGUI_API void AddInputCharacterUTF16(ImWchar16 c); // Queue new character input from an UTF-16 character, it can be a surrogate
public AddInputCharacterUTF16(c: number): void { this.native.AddInputCharacterUTF16(c); }
// IMGUI_API void AddInputCharactersUTF8(const char* utf8_chars); // Add new characters into InputCharacters[] from an UTF-8 string
public AddInputCharactersUTF8(utf8_chars: string): void { this.native.AddInputCharactersUTF8(utf8_chars); }
// inline void ClearInputCharacters() { InputCharacters[0] = 0; } // Clear the text input buffer manually
public ClearInputCharacters(): void { this.native.ClearInputCharacters(); }
//------------------------------------------------------------------
// Output - Retrieve after calling NewFrame()
//------------------------------------------------------------------
// bool WantCaptureMouse; // When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. This is set by ImGui when it wants to use your mouse (e.g. unclicked mouse is hovering a window, or a widget is active).
get WantCaptureMouse(): boolean { return this.native.WantCaptureMouse; } set WantCaptureMouse(value: boolean) { this.native.WantCaptureMouse = value; }
// bool WantCaptureKeyboard; // When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. This is set by ImGui when it wants to use your keyboard inputs.
get WantCaptureKeyboard(): boolean { return this.native.WantCaptureKeyboard; } set WantCaptureKeyboard(value: boolean) { this.native.WantCaptureKeyboard = value; }
// bool WantTextInput; // Mobile/console: when io.WantTextInput is true, you may display an on-screen keyboard. This is set by ImGui when it wants textual keyboard input to happen (e.g. when a InputText widget is active).
get WantTextInput(): boolean { return this.native.WantTextInput; } set WantTextInput(value: boolean) { this.native.WantTextInput = value; }
// bool WantSetMousePos; // [BETA-NAV] MousePos has been altered, back-end should reposition mouse on next frame. Set only when 'NavMovesMouse=true'.
get WantSetMousePos(): boolean { return this.native.WantSetMousePos; } set WantSetMousePos(value: boolean) { this.native.WantSetMousePos = value; }
// bool WantSaveIniSettings; // When manual .ini load/save is active (io.IniFilename == NULL), this will be set to notify your application that you can call SaveIniSettingsToMemory() and save yourself. IMPORTANT: You need to clear io.WantSaveIniSettings yourself.
get WantSaveIniSettings(): boolean { return this.native.WantSaveIniSettings; } set WantSaveIniSettings(value: boolean) { this.native.WantSaveIniSettings = value; }
// bool NavActive; // Directional navigation is currently allowed (will handle ImGuiKey_NavXXX events) = a window is focused and it doesn't use the ImGuiWindowFlags_NoNavInputs flag.
get NavActive(): boolean { return this.native.NavActive; } set NavActive(value: boolean) { this.native.NavActive = value; }
// bool NavVisible; // Directional navigation is visible and allowed (will handle ImGuiKey_NavXXX events).
get NavVisible(): boolean { return this.native.NavVisible; } set NavVisible(value: boolean) { this.native.NavVisible = value; }
// float Framerate; // Application framerate estimation, in frame per second. Solely for convenience. Rolling average estimation based on IO.DeltaTime over 120 frames
get Framerate(): number { return this.native.Framerate; }
// int MetricsRenderVertices; // Vertices output during last call to Render()
get MetricsRenderVertices(): number { return this.native.MetricsRenderVertices; }
// int MetricsRenderIndices; // Indices output during last call to Render() = number of triangles * 3
get MetricsRenderIndices(): number { return this.native.MetricsRenderIndices; }
// int MetricsRenderWindows; // Number of visible windows
get MetricsRenderWindows(): number { return this.native.MetricsRenderWindows; }
// int MetricsActiveWindows; // Number of visible root windows (exclude child windows)
get MetricsActiveWindows(): number { return this.native.MetricsActiveWindows; }
// int MetricsActiveAllocations; // Number of active allocations, updated by MemAlloc/MemFree based on current context. May be off if you have multiple imgui contexts.
get MetricsActiveAllocations(): number { return this.native.MetricsActiveAllocations; }
// ImVec2 MouseDelta; // Mouse delta. Note that this is zero if either current or previous position are invalid (-FLT_MAX,-FLT_MAX), so a disappearing/reappearing mouse won't have a huge delta.
get MouseDelta(): Readonly<Bind.reference_ImVec2> { return this.native.MouseDelta; }
//------------------------------------------------------------------
// [Internal] ImGui will maintain those fields. Forward compatibility not guaranteed!
//------------------------------------------------------------------
// ImGuiKeyModFlags KeyMods; // Key mods flags (same as io.KeyCtrl/KeyShift/KeyAlt/KeySuper but merged into flags), updated by NewFrame()
// ImVec2 MousePosPrev; // Previous mouse position temporary storage (nb: not for public use, set to MousePos in NewFrame())
// ImVec2 MouseClickedPos[5]; // Position at time of clicking
public MouseClickedPos: Array<Readonly<Bind.reference_ImVec2>> = new Proxy([], {
get: (target: Array<Readonly<Bind.reference_ImVec2>>, key: PropertyKey): number | Readonly<Bind.reference_ImVec2> => {
if (key === "length") { return 5; }
return this.native._getAt_MouseClickedPos(Number(key));
},
});
// float MouseClickedTime[5]; // Time of last click (used to figure out double-click)
// bool MouseClicked[5]; // Mouse button went from !Down to Down
// bool MouseDoubleClicked[5]; // Has mouse button been double-clicked?
// bool MouseReleased[5]; // Mouse button went from Down to !Down
// bool MouseDownOwned[5]; // Track if button was clicked inside a window. We don't request mouse capture from the application if click started outside ImGui bounds.
// float MouseDownDuration[5]; // Duration the mouse button has been down (0.0f == just clicked)
public MouseDownDuration: number[] = new Proxy([], {
get: (target: number[], key: PropertyKey): number => {
if (key === "length") { return 5; }
return this.native._getAt_MouseDownDuration(Number(key));
},
});
// float MouseDownDurationPrev[5]; // Previous time the mouse button has been down
// ImVec2 MouseDragMaxDistanceAbs[5]; // Maximum distance, absolute, on each axis, of how much mouse has traveled from the clicking point
// float MouseDragMaxDistanceSqr[5]; // Squared maximum distance of how much mouse has traveled from the clicking point
// float KeysDownDuration[512]; // Duration the keyboard key has been down (0.0f == just pressed)
public KeysDownDuration: number[] = new Proxy([], {
get: (target: number[], key: PropertyKey): number => {
if (key === "length") { return 512; }
return this.native._getAt_KeysDownDuration(Number(key));
},
});
// float KeysDownDurationPrev[512]; // Previous duration the key has been down
// float NavInputsDownDuration[ImGuiNavInput_COUNT];
public NavInputsDownDuration: number[] = new Proxy([], {
get: (target: number[], key: PropertyKey): number => {
if (key === "length") { return ImGuiNavInput.COUNT; }
return this.native._getAt_NavInputsDownDuration(Number(key));
},
});
// float NavInputsDownDurationPrev[ImGuiNavInput_COUNT];
// float PenPressure; // Touch/Pen pressure (0.0f to 1.0f, should be >0.0f only when MouseDown[0] == true). Helper storage currently unused by Dear ImGui.
// ImWchar16 InputQueueSurrogate; // For AddInputCharacterUTF16
// ImVector<ImWchar> InputQueueCharacters; // Queue of _characters_ input (obtained by platform backend). Fill using AddInputCharacter() helper.
// IMGUI_API ImGuiIO();
}
// Context creation and access
// Each context create its own ImFontAtlas by default. You may instance one yourself and pass it to CreateContext() to share a font atlas between imgui contexts.
// None of those functions is reliant on the current context.
// IMGUI_API ImGuiContext* CreateContext(ImFontAtlas* shared_font_atlas = NULL);
// IMGUI_API void DestroyContext(ImGuiContext* ctx = NULL); // NULL = destroy current context
// IMGUI_API ImGuiContext* GetCurrentContext();
// IMGUI_API void SetCurrentContext(ImGuiContext* ctx);
export class ImGuiContext {
public static current_ctx: ImGuiContext | null = null;
public static getTexture(index: number): ImTextureID | null {
if (ImGuiContext.current_ctx === null) { throw new Error(); }
return ImGuiContext.current_ctx._getTexture(index);
}
public static setTexture(texture: ImTextureID | null): number {
if (ImGuiContext.current_ctx === null) { throw new Error(); }
return ImGuiContext.current_ctx._setTexture(texture);
}
private static textures: Array<ImTextureID | null> = [];
constructor(public readonly native: Bind.WrapImGuiContext) {}
private _getTexture(index: number): ImTextureID | null {
return ImGuiContext.textures[index] || null;
}
private _setTexture(texture: ImTextureID | null): number {
let index = ImGuiContext.textures.indexOf(texture);
if (index === -1) {
for (let i = 0; i < ImGuiContext.textures.length; ++i) {
if (ImGuiContext.textures[i] === null) {
ImGuiContext.textures[i] = texture;
return i;
}
}
index = ImGuiContext.textures.length;
ImGuiContext.textures.push(texture);
}
return index;
}
}
export function CreateContext(shared_font_atlas: ImFontAtlas | null = null): ImGuiContext | null {
const ctx: ImGuiContext = new ImGuiContext(bind.CreateContext(shared_font_atlas !== null ? shared_font_atlas.native : null));
if (ImGuiContext.current_ctx === null) {
ImGuiContext.current_ctx = ctx;
}
return ctx;
}
export function DestroyContext(ctx: ImGuiContext | null = null): void {
if (ctx === null) {
ctx = ImGuiContext.current_ctx;
ImGuiContext.current_ctx = null;
}
bind.DestroyContext((ctx === null) ? null : ctx.native);
}
export function GetCurrentContext(): ImGuiContext | null {
// const ctx_native: Bind.ImGuiContext | null = bind.GetCurrentContext();
return ImGuiContext.current_ctx;
}
export function SetCurrentContext(ctx: ImGuiContext | null): void {
bind.SetCurrentContext((ctx === null) ? null : ctx.native);
ImGuiContext.current_ctx = ctx;
}
// Main
// IMGUI_API ImGuiIO& GetIO(); // access the IO structure (mouse/keyboard/gamepad inputs, time, various configuration options/flags)
// IMGUI_API ImGuiStyle& GetStyle(); // access the Style structure (colors, sizes). Always use PushStyleCol(), PushStyleVar() to modify style mid-frame!
// IMGUI_API void NewFrame(); // start a new Dear ImGui frame, you can submit any command from this point until Render()/EndFrame().
// IMGUI_API void EndFrame(); // ends the Dear ImGui frame. automatically called by Render(). If you don't need to render data (skipping rendering) you may call EndFrame() without Render()... but you'll have wasted CPU already! If you don't need to render, better to not create any windows and not call NewFrame() at all!
// IMGUI_API void Render(); // ends the Dear ImGui frame, finalize the draw data. You can then get call GetDrawData().
// IMGUI_API ImDrawData* GetDrawData(); // valid after Render() and until the next call to NewFrame(). this is what you have to render.
export function GetIO(): ImGuiIO { return new ImGuiIO(bind.GetIO()); }
export function GetStyle(): ImGuiStyle { return new ImGuiStyle(bind.GetStyle()); }
export function NewFrame(): void { bind.NewFrame(); }
export function EndFrame(): void { bind.EndFrame(); }
export function Render(): void { bind.Render(); }
export function GetDrawData(): ImDrawData | null {
const draw_data: Bind.reference_ImDrawData | null = bind.GetDrawData();
return (draw_data === null) ? null : new ImDrawData(draw_data);
}
// Demo, Debug, Information
// IMGUI_API void ShowDemoWindow(bool* p_open = NULL); // create Demo window. demonstrate most ImGui features. call this to learn about the library! try to make it always available in your application!
// IMGUI_API void ShowMetricsWindow(bool* p_open = NULL); // create Metrics/Debugger window. display Dear ImGui internals: windows, draw commands, various internal state, etc.
// IMGUI_API void ShowAboutWindow(bool* p_open = NULL); // create About window. display Dear ImGui version, credits and build/system information.
// IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // add style editor block (not a window). you can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it uses the default style)
// IMGUI_API bool ShowStyleSelector(const char* label); // add style selector block (not a window), essentially a combo listing the default styles.
// IMGUI_API void ShowFontSelector(const char* label); // add font selector block (not a window), essentially a combo listing the loaded fonts.
// IMGUI_API void ShowUserGuide(); // add basic help/info block (not a window): how to manipulate ImGui as a end-user (mouse/keyboard controls).
// IMGUI_API const char* GetVersion(); // get the compiled version string e.g. "1.80 WIP" (essentially the value for IMGUI_VERSION from the compiled version of imgui.cpp)
export function ShowDemoWindow(p_open: Bind.ImScalar<boolean> | null = null): void { bind.ShowDemoWindow(p_open); }
export function ShowMetricsWindow(p_open: Bind.ImScalar<boolean> | Bind.ImAccess<boolean> | null = null): void {
if (p_open === null) {
bind.ShowMetricsWindow(null);
} else if (Array.isArray(p_open)) {
bind.ShowMetricsWindow(p_open);
} else {
const ref_open: Bind.ImScalar<boolean> = [ p_open() ];
bind.ShowMetricsWindow(ref_open);
p_open(ref_open[0]);
}
}
export function ShowAboutWindow(p_open: Bind.ImScalar<boolean> | Bind.ImAccess<boolean> | null = null): void {
if (p_open === null) {
bind.ShowAboutWindow(null);
} else if (Array.isArray(p_open)) {
bind.ShowAboutWindow(p_open);
} else {
const ref_open: Bind.ImScalar<boolean> = [ p_open() ];
bind.ShowAboutWindow(ref_open);
p_open(ref_open[0]);
}
}
export function ShowStyleEditor(ref: ImGuiStyle | null = null): void {
if (ref === null) {
bind.ShowStyleEditor(null);
} else if (ref.internal instanceof bind.ImGuiStyle) {
bind.ShowStyleEditor(ref.internal);
} else {
const native = new bind.ImGuiStyle();
const wrap = new ImGuiStyle(native);
wrap.Copy(ref);
bind.ShowStyleEditor(native);
ref.Copy(wrap);
native.delete();
}
}
export function ShowStyleSelector(label: string): boolean { return bind.ShowStyleSelector(label); }
export function ShowFontSelector(label: string): void { bind.ShowFontSelector(label); }
export function ShowUserGuide(): void { bind.ShowUserGuide(); }
export function GetVersion(): string { return bind.GetVersion(); }
// Styles
// IMGUI_API void StyleColorsDark(ImGuiStyle* dst = NULL); // new, recommended style (default)
// IMGUI_API void StyleColorsLight(ImGuiStyle* dst = NULL); // best used with borders and a custom, thicker font
// IMGUI_API void StyleColorsClassic(ImGuiStyle* dst = NULL); // classic imgui style
export function StyleColorsDark(dst: ImGuiStyle | null = null): void {
if (dst === null) {
bind.StyleColorsDark(null);
} else if (dst.internal instanceof bind.ImGuiStyle) {
bind.StyleColorsDark(dst.internal);
} else {
const native = new bind.ImGuiStyle();
const wrap = new ImGuiStyle(native);
wrap.Copy(dst);
bind.StyleColorsDark(native);
dst.Copy(wrap);
native.delete();
}
}
export function StyleColorsLight(dst: ImGuiStyle | null = null): void {
if (dst === null) {
bind.StyleColorsLight(null);
} else if (dst.internal instanceof bind.ImGuiStyle) {
bind.StyleColorsLight(dst.internal);
} else {
const native = new bind.ImGuiStyle();
const wrap = new ImGuiStyle(native);
wrap.Copy(dst);
bind.StyleColorsLight(native);
dst.Copy(wrap);
native.delete();
}
}
export function StyleColorsClassic(dst: ImGuiStyle | null = null): void {
if (dst === null) {
bind.StyleColorsClassic(null);
} else if (dst.internal instanceof bind.ImGuiStyle) {
bind.StyleColorsClassic(dst.internal);
} else {
const native = new bind.ImGuiStyle();
const wrap = new ImGuiStyle(native);
wrap.Copy(dst);
bind.StyleColorsClassic(native);
dst.Copy(wrap);
native.delete();
}
}
// Windows
// - Begin() = push window to the stack and start appending to it. End() = pop window from the stack.
// - Passing 'bool* p_open != NULL' shows a window-closing widget in the upper-right corner of the window,
// which clicking will set the boolean to false when clicked.
// - You may append multiple times to the same window during the same frame by calling Begin()/End() pairs multiple times.
// Some information such as 'flags' or 'p_open' will only be considered by the first call to Begin().
// - Begin() return false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting
// anything to the window. Always call a matching End() for each Begin() call, regardless of its return value!
// [Important: due to legacy reason, this is inconsistent with most other functions such as BeginMenu/EndMenu,
// BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding BeginXXX function
// returned true. Begin and BeginChild are the only odd ones out. Will be fixed in a future update.]
// - Note that the bottom of window stack always contains a window called "Debug".
// IMGUI_API bool Begin(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0);
// IMGUI_API void End();
export function Begin(name: string, open: Bind.ImScalar<boolean> | Bind.ImAccess<boolean> | null = null, flags: ImGuiWindowFlags = 0): boolean {
if (open === null) {
return bind.Begin(name, null, flags);
} else if (Array.isArray(open)) {
return bind.Begin(name, open, flags);
} else {
const ref_open: Bind.ImScalar<boolean> = [ open() ];
const opened: boolean = bind.Begin(name, ref_open, flags);
open(ref_open[0]);
return opened;
}
}
export function End(): void { bind.End(); }
// Child Windows
// - Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window. Child windows can embed their own child.
// - For each independent axis of 'size': ==0.0f: use remaining host window size / >0.0f: fixed size / <0.0f: use remaining window size minus abs(size) / Each axis can use a different mode, e.g. ImVec2(0,400).
// - BeginChild() returns false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting anything to the window.
// Always call a matching EndChild() for each BeginChild() call, regardless of its return value.
// [Important: due to legacy reason, this is inconsistent with most other functions such as BeginMenu/EndMenu,
// BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding BeginXXX function
// returned true. Begin and BeginChild are the only odd ones out. Will be fixed in a future update.]
// IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0, 0), bool border = false, ImGuiWindowFlags flags = 0);
// IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0, 0), bool border = false, ImGuiWindowFlags flags = 0);
// IMGUI_API void EndChild();
export function BeginChild(id: string | ImGuiID, size: Readonly<Bind.interface_ImVec2> = ImVec2.ZERO, border: boolean = false, flags: ImGuiWindowFlags = 0): boolean {
return bind.BeginChild(id, size, border, flags);
}
export function EndChild(): void { bind.EndChild(); }
// Windows Utilities
// - 'current window' = the window we are appending into while inside a Begin()/End() block. 'next window' = next window we will Begin() into.
// IMGUI_API bool IsWindowAppearing();
// IMGUI_API bool IsWindowCollapsed();
// IMGUI_API bool IsWindowFocused(ImGuiFocusedFlags flags=0); // is current window focused? or its root/child, depending on flags. see flags for options.
// IMGUI_API bool IsWindowHovered(ImGuiHoveredFlags flags=0); // is current window hovered (and typically: not blocked by a popup/modal)? see flags for options. NB: If you are trying to check whether your mouse should be dispatched to imgui or to your app, you should use the 'io.WantCaptureMouse' boolean for that! Please read the FAQ!
// IMGUI_API ImDrawList* GetWindowDrawList(); // get draw list associated to the current window, to append your own drawing primitives
// IMGUI_API ImVec2 GetWindowPos(); // get current window position in screen space (useful if you want to do your own drawing via the DrawList API)
// IMGUI_API ImVec2 GetWindowSize(); // get current window size
// IMGUI_API float GetWindowWidth(); // get current window width (shortcut for GetWindowSize().x)
// IMGUI_API float GetWindowHeight(); // get current window height (shortcut for GetWindowSize().y)
export function IsWindowAppearing(): boolean { return bind.IsWindowAppearing(); }
export function IsWindowCollapsed(): boolean { return bind.IsWindowCollapsed(); }
export function IsWindowFocused(flags: ImGuiFocusedFlags = 0): boolean { return bind.IsWindowFocused(flags); }
export function IsWindowHovered(flags: ImGuiHoveredFlags = 0): boolean { return bind.IsWindowHovered(flags); }
export function GetWindowDrawList(): ImDrawList { return new ImDrawList(bind.GetWindowDrawList()); }
export function GetWindowPos(out: Bind.interface_ImVec2 = new ImVec2()): Bind.interface_ImVec2 { return bind.GetWindowPos(out); }
export function GetWindowSize(out: Bind.interface_ImVec2 = new ImVec2()): Bind.interface_ImVec2 { return bind.GetWindowSize(out); }
export function GetWindowWidth(): number { return bind.GetWindowWidth(); }
export function GetWindowHeight(): number { return bind.GetWindowHeight(); }
// Prefer using SetNextXXX functions (before Begin) rather that SetXXX functions (after Begin).
// IMGUI_API void SetNextWindowPos(const ImVec2& pos, ImGuiCond cond = 0, const ImVec2& pivot = ImVec2(0, 0)); // set next window position. call before Begin(). use pivot=(0.5f,0.5f) to center on given point, etc.
// IMGUI_API void SetNextWindowSize(const ImVec2& size, ImGuiCond cond = 0); // set next window size. set axis to 0.0f to force an auto-fit on this axis. call before Begin()
// IMGUI_API void SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback = NULL, void* custom_callback_data = NULL); // set next window size limits. use -1,-1 on either X/Y axis to preserve the current size. Sizes will be rounded down. Use callback to apply non-trivial programmatic constraints.
// IMGUI_API void SetNextWindowContentSize(const ImVec2& size); // set next window content size (~ scrollable client area, which enforce the range of scrollbars). Not including window decorations (title bar, menu bar, etc.) nor WindowPadding. set an axis to 0.0f to leave it automatic. call before Begin()
// IMGUI_API void SetNextWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // set next window collapsed state. call before Begin()
// IMGUI_API void SetNextWindowFocus(); // set next window to be focused / top-most. call before Begin()
// IMGUI_API void SetNextWindowBgAlpha(float alpha); // set next window background color alpha. helper to easily override the Alpha component of ImGuiCol_WindowBg/ChildBg/PopupBg. you may also use ImGuiWindowFlags_NoBackground.
// IMGUI_API void SetWindowPos(const ImVec2& pos, ImGuiCond cond = 0); // (not recommended) set current window position - call within Begin()/End(). prefer using SetNextWindowPos(), as this may incur tearing and side-effects.
// IMGUI_API void SetWindowSize(const ImVec2& size, ImGuiCond cond = 0); // (not recommended) set current window size - call within Begin()/End(). set to ImVec2(0, 0) to force an auto-fit. prefer using SetNextWindowSize(), as this may incur tearing and minor side-effects.
// IMGUI_API void SetWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // (not recommended) set current window collapsed state. prefer using SetNextWindowCollapsed().
// IMGUI_API void SetWindowFocus(); // (not recommended) set current window to be focused / top-most. prefer using SetNextWindowFocus().
// IMGUI_API void SetWindowFontScale(float scale); // set font scale. Adjust IO.FontGlobalScale if you want to scale all windows. This is an old API! For correct scaling, prefer to reload font + rebuild ImFontAtlas + call style.ScaleAllSizes().
// IMGUI_API void SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond = 0); // set named window position.
// IMGUI_API void SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond = 0); // set named window size. set axis to 0.0f to force an auto-fit on this axis.
// IMGUI_API void SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond = 0); // set named window collapsed state
// IMGUI_API void SetWindowFocus(const char* name); // set named window to be focused / top-most. use NULL to remove focus.
export function SetNextWindowPos(pos: Readonly<Bind.interface_ImVec2>, cond: ImGuiCond = 0, pivot: Readonly<Bind.interface_ImVec2> = ImVec2.ZERO): void { bind.SetNextWindowPos(pos, cond, pivot); }
export function SetNextWindowSize(pos: Readonly<Bind.interface_ImVec2>, cond: ImGuiCond = 0): void { bind.SetNextWindowSize(pos, cond); }
export function SetNextWindowSizeConstraints(size_min: Readonly<Bind.interface_ImVec2>, size_max: Readonly<Bind.interface_ImVec2>): void;
export function SetNextWindowSizeConstraints<T>(size_min: Readonly<Bind.interface_ImVec2>, size_max: Readonly<Bind.interface_ImVec2>, custom_callback: ImGuiSizeCallback<T>, custom_callback_data?: T): void;
export function SetNextWindowSizeConstraints<T>(size_min: Readonly<Bind.interface_ImVec2>, size_max: Readonly<Bind.interface_ImVec2>, custom_callback: ImGuiSizeCallback<T | null> | null = null, custom_callback_data: T | null = null): void {
if (custom_callback) {
bind.SetNextWindowSizeConstraints(size_min, size_max, (data: Bind.reference_ImGuiSizeCallbackData): void => {
custom_callback(new ImGuiSizeCallbackData(data, custom_callback_data));
}, null);
} else {
bind.SetNextWindowSizeConstraints(size_min, size_max, null, null);
}
}
export function SetNextWindowContentSize(size: Readonly<Bind.interface_ImVec2>): void { bind.SetNextWindowContentSize(size); }
export function SetNextWindowCollapsed(collapsed: boolean, cond: ImGuiCond = 0): void { bind.SetNextWindowCollapsed(collapsed, cond); }
export function SetNextWindowFocus(): void { bind.SetNextWindowFocus(); }
export function SetNextWindowBgAlpha(alpha: number): void { bind.SetNextWindowBgAlpha(alpha); }
export function SetWindowPos(name_or_pos: string | Readonly<Bind.interface_ImVec2>, pos_or_cond: Readonly<Bind.interface_ImVec2> | ImGuiCond = 0, cond: ImGuiCond = 0): void {
if (typeof(name_or_pos) === "string") {
bind.SetWindowNamePos(name_or_pos, pos_or_cond as Readonly<Bind.interface_ImVec2>, cond);
return;
} else {
bind.SetWindowPos(name_or_pos, pos_or_cond as ImGuiCond);
}
}
export function SetWindowSize(name_or_size: string | Readonly<Bind.interface_ImVec2>, size_or_cond: Readonly<Bind.interface_ImVec2> | ImGuiCond = 0, cond: ImGuiCond = 0): void {
if (typeof(name_or_size) === "string") {
bind.SetWindowNamePos(name_or_size, size_or_cond as Readonly<Bind.interface_ImVec2>, cond);
} else {
bind.SetWindowSize(name_or_size, size_or_cond as ImGuiCond);
}
}
export function SetWindowCollapsed(name_or_collapsed: string | boolean, collapsed_or_cond: boolean | ImGuiCond = 0, cond: ImGuiCond = 0): void {
if (typeof(name_or_collapsed) === "string") {
bind.SetWindowNameCollapsed(name_or_collapsed, collapsed_or_cond as boolean, cond);
} else {
bind.SetWindowCollapsed(name_or_collapsed, collapsed_or_cond as ImGuiCond);
}
}
export function SetWindowFocus(name?: string): void {
if (typeof(name) === "string") {
bind.SetWindowNameFocus(name);
} else {
bind.SetWindowFocus();
}
}
export function SetWindowFontScale(scale: number): void { bind.SetWindowFontScale(scale); }
// Content region
// - Retrieve available space from a given point. GetContentRegionAvail() is frequently useful.
// - Those functions are bound to be redesigned (they are confusing, incomplete and the Min/Max return values are in local window coordinates which increases confusion)
// IMGUI_API ImVec2 GetContentRegionAvail(); // == GetContentRegionMax() - GetCursorPos()
// IMGUI_API ImVec2 GetContentRegionMax(); // current content boundaries (typically window boundaries including scrolling, or current column boundaries), in windows coordinates
// IMGUI_API ImVec2 GetWindowContentRegionMin(); // content boundaries min (roughly (0,0)-Scroll), in window coordinates
// IMGUI_API ImVec2 GetWindowContentRegionMax(); // content boundaries max (roughly (0,0)+Size-Scroll) where Size can be override with SetNextWindowContentSize(), in window coordinates
// IMGUI_API float GetWindowContentRegionWidth(); //
export function GetContentRegionAvail(out: Bind.interface_ImVec2 = new ImVec2()): Bind.interface_ImVec2 { return bind.GetContentRegionAvail(out); }
export function GetContentRegionMax(out: Bind.interface_ImVec2 = new ImVec2()): Bind.interface_ImVec2 { return bind.GetContentRegionMax(out); }
export function GetWindowContentRegionMin(out: Bind.interface_ImVec2 = new ImVec2()): Bind.interface_ImVec2 { return bind.GetWindowContentRegionMin(out); }
export function GetWindowContentRegionMax(out: Bind.interface_ImVec2 = new ImVec2()): Bind.interface_ImVec2 { return bind.GetWindowContentRegionMax(out); }
export function GetWindowContentRegionWidth(): number { return bind.GetWindowContentRegionWidth(); }
// Windows Scrolling
// IMGUI_API float GetScrollX(); // get scrolling amount [0 .. GetScrollMaxX()]
// IMGUI_API float GetScrollY(); // get scrolling amount [0 .. GetScrollMaxY()]
// IMGUI_API void SetScrollX(float scroll_x); // set scrolling amount [0 .. GetScrollMaxX()]
// IMGUI_API void SetScrollY(float scroll_y); // set scrolling amount [0 .. GetScrollMaxY()]
// IMGUI_API float GetScrollMaxX(); // get maximum scrolling amount ~~ ContentSize.x - WindowSize.x - DecorationsSize.x
// IMGUI_API float GetScrollMaxY(); // get maximum scrolling amount ~~ ContentSize.y - WindowSize.y - DecorationsSize.y
// IMGUI_API void SetScrollHereX(float center_x_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_x_ratio=0.0: left, 0.5: center, 1.0: right. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead.
// IMGUI_API void SetScrollHereY(float center_y_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_y_ratio=0.0: top, 0.5: center, 1.0: bottom. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead.
// IMGUI_API void SetScrollFromPosX(float local_x, float center_x_ratio = 0.5f); // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position.
// IMGUI_API void SetScrollFromPosY(float local_y, float center_y_ratio = 0.5f); // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position.
export function GetScrollX(): number { return bind.GetScrollX(); }
export function GetScrollY(): number { return bind.GetScrollY(); }
export function SetScrollX(scroll_x: number): void { bind.SetScrollX(scroll_x); }
export function SetScrollY(scroll_y: number): void { bind.SetScrollY(scroll_y); }
export function GetScrollMaxX(): number { return bind.GetScrollMaxX(); }
export function GetScrollMaxY(): number { return bind.GetScrollMaxY(); }
export function SetScrollHereX(center_x_ratio: number = 0.5): void { bind.SetScrollHereX(center_x_ratio); }
export function SetScrollHereY(center_y_ratio: number = 0.5): void { bind.SetScrollHereY(center_y_ratio); }
export function SetScrollFromPosX(pos_x: number, center_x_ratio: number = 0.5): void { bind.SetScrollFromPosX(pos_x, center_x_ratio); }
export function SetScrollFromPosY(pos_y: number, center_y_ratio: number = 0.5): void { bind.SetScrollFromPosY(pos_y, center_y_ratio); }
// Parameters stacks (shared)
// IMGUI_API void PushFont(ImFont* font); // use NULL as a shortcut to push default font
// IMGUI_API void PopFont();
// IMGUI_API void PushStyleColor(ImGuiCol idx, ImU32 col); // modify a style color. always use this if you modify the style after NewFrame().
// IMGUI_API void PushStyleColor(ImGuiCol idx, const ImVec4& col);
// IMGUI_API void PopStyleColor(int count = 1);
// IMGUI_API void PushStyleVar(ImGuiStyleVar idx, float val); // modify a style float variable. always use this if you modify the style after NewFrame().
// IMGUI_API void PushStyleVar(ImGuiStyleVar idx, const ImVec2& val); // modify a style ImVec2 variable. always use this if you modify the style after NewFrame().
// IMGUI_API void PopStyleVar(int count = 1);
// IMGUI_API void PushAllowKeyboardFocus(bool allow_keyboard_focus); // allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets
// IMGUI_API void PopAllowKeyboardFocus();
// IMGUI_API void PushButtonRepeat(bool repeat); // in 'repeat' mode, Button*() functions return repeated true in a typematic manner (using io.KeyRepeatDelay/io.KeyRepeatRate setting). Note that you can call IsItemActive() after any Button() to tell if the button is held in the current frame.
// IMGUI_API void PopButtonRepeat();
export function PushFont(font: ImFont | null): void { bind.PushFont(font ? font.native : null); }
export function PopFont(): void { bind.PopFont(); }
export function PushStyleColor(idx: ImGuiCol, col: Bind.ImU32 | Readonly<Bind.interface_ImVec4> | Readonly<ImColor>): void {
if (col instanceof ImColor) {
bind.PushStyleColor(idx, col.Value);
} else {
bind.PushStyleColor(idx, col as (Bind.ImU32 | Readonly<Bind.interface_ImVec4>));
}
}
export function PopStyleColor(count: number = 1): void { bind.PopStyleColor(count); }
export function PushStyleVar(idx: ImGuiStyleVar, val: number | Readonly<Bind.interface_ImVec2>): void { bind.PushStyleVar(idx, val); }
export function PopStyleVar(count: number = 1): void { bind.PopStyleVar(count); }
export function PushAllowKeyboardFocus(allow_keyboard_focus: boolean): void { bind.PushAllowKeyboardFocus(allow_keyboard_focus); }
export function PopAllowKeyboardFocus(): void { bind.PopAllowKeyboardFocus(); }
export function PushButtonRepeat(repeat: boolean): void { bind.PushButtonRepeat(repeat); }
export function PopButtonRepeat(): void { bind.PopButtonRepeat(); }
// Parameters stacks (current window)
// IMGUI_API void PushItemWidth(float item_width); // push width of items for common large "item+label" widgets. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -FLT_MIN always align width to the right side). 0.0f = default to ~2/3 of windows width,
// IMGUI_API void PopItemWidth();
// IMGUI_API void SetNextItemWidth(float item_width); // set width of the _next_ common large "item+label" widget. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -FLT_MIN always align width to the right side)
// IMGUI_API float CalcItemWidth(); // width of item given pushed settings and current cursor position. NOT necessarily the width of last item unlike most 'Item' functions.
// IMGUI_API void PushTextWrapPos(float wrap_local_pos_x = 0.0f); // push word-wrapping position for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at 'wrap_pos_x' position in window local space
// IMGUI_API void PopTextWrapPos();
export function PushItemWidth(item_width: number): void { bind.PushItemWidth(item_width); }
export function PopItemWidth(): void { bind.PopItemWidth(); }
export function SetNextItemWidth(item_width: number): void { bind.SetNextItemWidth(item_width); } // set width of the _next_ common large "item+label" widget. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -1.0f always align width to the right side)
export function CalcItemWidth(): number { return bind.CalcItemWidth(); }
export function PushTextWrapPos(wrap_pos_x: number = 0.0): void { bind.PushTextWrapPos(wrap_pos_x); }
export function PopTextWrapPos(): void { bind.PopTextWrapPos(); }
// Style read access
// IMGUI_API ImFont* GetFont(); // get current font
// IMGUI_API float GetFontSize(); // get current font size (= height in pixels) of current font with current scale applied
// IMGUI_API ImVec2 GetFontTexUvWhitePixel(); // get UV coordinate for a while pixel, useful to draw custom shapes via the ImDrawList API
// IMGUI_API ImU32 GetColorU32(ImGuiCol idx, float alpha_mul = 1.0f); // retrieve given style color with style alpha applied and optional extra alpha multiplier, packed as a 32-bit value suitable for ImDrawList
// IMGUI_API ImU32 GetColorU32(const ImVec4& col); // retrieve given color with style alpha applied, packed as a 32-bit value suitable for ImDrawList
// IMGUI_API ImU32 GetColorU32(ImU32 col); // retrieve given color with style alpha applied, packed as a 32-bit value suitable for ImDrawList
// IMGUI_API const ImVec4& GetStyleColorVec4(ImGuiCol idx); // retrieve style color as stored in ImGuiStyle structure. use to feed back into PushStyleColor(), otherwise use GetColorU32() to get style color with style alpha baked in.
export function GetFont(): ImFont { return new ImFont(bind.GetFont()); }
export function GetFontSize(): number { return bind.GetFontSize(); }
export function GetFontTexUvWhitePixel(out: Bind.interface_ImVec2 = new ImVec2()): Bind.interface_ImVec2 { return bind.GetFontTexUvWhitePixel(out); }
export function GetColorU32(idx: ImGuiCol, alpha_mul?: number): Bind.ImU32;
export function GetColorU32(col: Readonly<Bind.interface_ImVec4>): Bind.ImU32;
export function GetColorU32(col: Bind.ImU32): Bind.ImU32;
export function GetColorU32(...args: any[]): Bind.ImU32 {
if (args.length === 1) {
if (typeof(args[0]) === "number") {
if (0 <= args[0] && args[0] < ImGuiCol.COUNT) {
const idx: ImGuiCol = args[0];
return bind.GetColorU32_A(idx, 1.0);
}
else {
const col: Bind.ImU32 = args[0];
return bind.GetColorU32_C(col);
}
} else {
const col: Readonly<Bind.interface_ImVec4> = args[0];
return bind.GetColorU32_B(col);
}
} else {
const idx: ImGuiCol = args[0];
const alpha_mul: number = args[1];
return bind.GetColorU32_A(idx, alpha_mul);
}
}
export function GetStyleColorVec4(idx: ImGuiCol): Readonly<Bind.reference_ImVec4> { return bind.GetStyleColorVec4(idx); }
// Cursor / Layout
// - By "cursor" we mean the current output position.
// - The typical widget behavior is to output themselves at the current cursor position, then move the cursor one line down.
// - You can call SameLine() between widgets to undo the last carriage return and output at the right of the preceding widget.
// - Attention! We currently have inconsistencies between window-local and absolute positions we will aim to fix with future API:
// Window-local coordinates: SameLine(), GetCursorPos(), SetCursorPos(), GetCursorStartPos(), GetContentRegionMax(), GetWindowContentRegion*(), PushTextWrapPos()
// Absolute coordinate: GetCursorScreenPos(), SetCursorScreenPos(), all ImDrawList:: functions.
// IMGUI_API void Separator(); // separator, generally horizontal. inside a menu bar or in horizontal layout mode, this becomes a vertical separator.
// IMGUI_API void SameLine(float offset_from_start_x=0.0f, float spacing=-1.0f); // call between widgets or groups to layout them horizontally. X position given in window coordinates.
// IMGUI_API void NewLine(); // undo a SameLine() or force a new line when in an horizontal-layout context.
// IMGUI_API void Spacing(); // add vertical spacing.
// IMGUI_API void Dummy(const ImVec2& size); // add a dummy item of given size. unlike InvisibleButton(), Dummy() won't take the mouse click or be navigable into.
// IMGUI_API void Indent(float indent_w = 0.0f); // move content position toward the right, by indent_w, or style.IndentSpacing if indent_w <= 0
// IMGUI_API void Unindent(float indent_w = 0.0f); // move content position back to the left, by indent_w, or style.IndentSpacing if indent_w <= 0
// IMGUI_API void BeginGroup(); // lock horizontal starting position
// IMGUI_API void EndGroup(); // unlock horizontal starting position + capture the whole group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
// IMGUI_API ImVec2 GetCursorPos(); // cursor position in window coordinates (relative to window position)
// IMGUI_API float GetCursorPosX(); // (some functions are using window-relative coordinates, such as: GetCursorPos, GetCursorStartPos, GetContentRegionMax, GetWindowContentRegion* etc.
// IMGUI_API float GetCursorPosY(); // other functions such as GetCursorScreenPos or everything in ImDrawList::
// IMGUI_API void SetCursorPos(const ImVec2& local_pos); // are using the main, absolute coordinate system.
// IMGUI_API void SetCursorPosX(float local_x); // GetWindowPos() + GetCursorPos() == GetCursorScreenPos() etc.)
// IMGUI_API void SetCursorPosY(float local_y); //
// IMGUI_API ImVec2 GetCursorStartPos(); // initial cursor position in window coordinates
// IMGUI_API ImVec2 GetCursorScreenPos(); // cursor position in absolute screen coordinates [0..io.DisplaySize] (useful to work with ImDrawList API)
// IMGUI_API void SetCursorScreenPos(const ImVec2& pos); // cursor position in absolute screen coordinates [0..io.DisplaySize]
// IMGUI_API void AlignTextToFramePadding(); // vertically align upcoming text baseline to FramePadding.y so that it will align properly to regularly framed items (call if you have text on a line before a framed item)
// IMGUI_API float GetTextLineHeight(); // ~ FontSize
// IMGUI_API float GetTextLineHeightWithSpacing(); // ~ FontSize + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of text)
// IMGUI_API float GetFrameHeight(); // ~ FontSize + style.FramePadding.y * 2
// IMGUI_API float GetFrameHeightWithSpacing(); // ~ FontSize + style.FramePadding.y * 2 + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of framed widgets)
export function Separator(): void { bind.Separator(); }
export function SameLine(pos_x: number = 0.0, spacing_w: number = -1.0): void { bind.SameLine(pos_x, spacing_w); }
export function NewLine(): void { bind.NewLine(); }
export function Spacing(): void { bind.Spacing(); }
export function Dummy(size: Readonly<Bind.interface_ImVec2>): void { bind.Dummy(size); }
export function Indent(indent_w: number = 0.0) { bind.Indent(indent_w); }
export function Unindent(indent_w: number = 0.0) { bind.Unindent(indent_w); }
export function BeginGroup(): void { bind.BeginGroup(); }
export function EndGroup(): void { bind.EndGroup(); }
export function GetCursorPos(out: Bind.interface_ImVec2 = new ImVec2()): Bind.interface_ImVec2 { return bind.GetCursorPos(out); }
export function GetCursorPosX(): number { return bind.GetCursorPosX(); }
export function GetCursorPosY(): number { return bind.GetCursorPosY(); }
export function SetCursorPos(local_pos: Readonly<Bind.interface_ImVec2>): void { bind.SetCursorPos(local_pos); }
export function SetCursorPosX(x: number): void { bind.SetCursorPosX(x); }
export function SetCursorPosY(y: number): void { bind.SetCursorPosY(y); }
export function GetCursorStartPos(out: Bind.interface_ImVec2 = new ImVec2()): Bind.interface_ImVec2 { return bind.GetCursorStartPos(out); }
export function GetCursorScreenPos(out: Bind.interface_ImVec2 = new ImVec2()): Bind.interface_ImVec2 { return bind.GetCursorScreenPos(out); }
export function SetCursorScreenPos(pos: Readonly<Bind.interface_ImVec2>): void { bind.SetCursorScreenPos(pos); }
export function AlignTextToFramePadding(): void { bind.AlignTextToFramePadding(); }
export function GetTextLineHeight(): number { return bind.GetTextLineHeight(); }
export function GetTextLineHeightWithSpacing(): number { return bind.GetTextLineHeightWithSpacing(); }
export function GetFrameHeight(): number { return bind.GetFrameHeight(); }
export function GetFrameHeightWithSpacing(): number { return bind.GetFrameHeightWithSpacing(); }
// ID stack/scopes
// - Read the FAQ for more details about how ID are handled in dear imgui. If you are creating widgets in a loop you most
// likely want to push a unique identifier (e.g. object pointer, loop index) to uniquely differentiate them.
// - The resulting ID are hashes of the entire stack.
// - You can also use the "Label##foobar" syntax within widget label to distinguish them from each others.
// - In this header file we use the "label"/"name" terminology to denote a string that will be displayed and used as an ID,
// whereas "str_id" denote a string that is only used as an ID and not normally displayed.
// IMGUI_API void PushID(const char* str_id); // push string into the ID stack (will hash string).
// IMGUI_API void PushID(const char* str_id_begin, const char* str_id_end); // push string into the ID stack (will hash string).
// IMGUI_API void PushID(const void* ptr_id); // push pointer into the ID stack (will hash pointer).
// IMGUI_API void PushID(int int_id); // push integer into the ID stack (will hash integer).
// IMGUI_API void PopID(); // pop from the ID stack.
// IMGUI_API ImGuiID GetID(const char* str_id); // calculate unique ID (hash of whole ID stack + given parameter). e.g. if you want to query into ImGuiStorage yourself
// IMGUI_API ImGuiID GetID(const char* str_id_begin, const char* str_id_end);
// IMGUI_API ImGuiID GetID(const void* ptr_id);
export function PushID(id: string | number): void { bind.PushID(id); }
export function PopID(): void { bind.PopID(); }
export function GetID(id: string | number): ImGuiID { return bind.GetID(id); }
// Widgets: Text
// IMGUI_API void TextUnformatted(const char* text, const char* text_end = NULL); // raw text without formatting. Roughly equivalent to Text("%s", text) but: A) doesn't require null terminated string if 'text_end' is specified, B) it's faster, no memory copy is done, no buffer size limits, recommended for long chunks of text.
// IMGUI_API void Text(const char* fmt, ...) IM_FMTARGS(1); // formatted text
// IMGUI_API void TextV(const char* fmt, va_list args) IM_FMTLIST(1);
// IMGUI_API void TextColored(const ImVec4& col, const char* fmt, ...) IM_FMTARGS(2); // shortcut for PushStyleColor(ImGuiCol_Text, col); Text(fmt, ...); PopStyleColor();
// IMGUI_API void TextColoredV(const ImVec4& col, const char* fmt, va_list args) IM_FMTLIST(2);
// IMGUI_API void TextDisabled(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); Text(fmt, ...); PopStyleColor();
// IMGUI_API void TextDisabledV(const char* fmt, va_list args) IM_FMTLIST(1);
// IMGUI_API void TextWrapped(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushTextWrapPos(0.0f); Text(fmt, ...); PopTextWrapPos();. Note that this won't work on an auto-resizing window if there's no other widgets to extend the window width, yoy may need to set a size using SetNextWindowSize().
// IMGUI_API void TextWrappedV(const char* fmt, va_list args) IM_FMTLIST(1);
// IMGUI_API void LabelText(const char* label, const char* fmt, ...) IM_FMTARGS(2); // display text+label aligned the same way as value+label widgets
// IMGUI_API void LabelTextV(const char* label, const char* fmt, va_list args) IM_FMTLIST(2);
// IMGUI_API void BulletText(const char* fmt, ...) IM_FMTARGS(1); // shortcut for Bullet()+Text()
// IMGUI_API void BulletTextV(const char* fmt, va_list args) IM_FMTLIST(1);
export function TextUnformatted(text: string, text_end: number | null = null): void { bind.TextUnformatted(text_end !== null ? text.substring(0, text_end) : text); }
export function Text(text: string): void { bind.Text(text); }
export function TextColored(col: Readonly<Bind.interface_ImVec4> | Readonly<ImColor>, text: string): void { bind.TextColored((col instanceof ImColor) ? col.Value : col as Readonly<Bind.interface_ImVec4>, text); }
export function TextDisabled(text: string): void { bind.TextDisabled(text); }
export function TextWrapped(text: string): void { bind.TextWrapped(text); }
export function LabelText(label: string, text: string): void { bind.LabelText(label, text); }
export function BulletText(text: string): void { bind.BulletText(text); }
// Widgets: Main
// - Most widgets return true when the value has been changed or when pressed/selected
// - You may also use one of the many IsItemXXX functions (e.g. IsItemActive, IsItemHovered, etc.) to query widget state.
// IMGUI_API bool Button(const char* label, const ImVec2& size = ImVec2(0, 0)); // button
// IMGUI_API bool SmallButton(const char* label); // button with FramePadding=(0,0) to easily embed within text
// IMGUI_API bool InvisibleButton(const char* str_id, const ImVec2& size, ImGuiButtonFlags flags = 0); // flexible button behavior without the visuals, frequently useful to build custom behaviors using the public api (along with IsItemActive, IsItemHovered, etc.)
// IMGUI_API bool ArrowButton(const char* str_id, ImGuiDir dir); // square button with an arrow shape
// IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1,1), const ImVec4& tint_col = ImVec4(1,1,1,1), const ImVec4& border_col = ImVec4(0,0,0,0));
// IMGUI_API bool ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1,1), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0,0,0,0), const ImVec4& tint_col = ImVec4(1,1,1,1)); // <0 frame_padding uses default frame padding settings. 0 for no padding
// IMGUI_API bool Checkbox(const char* label, bool* v);
// IMGUI_API bool CheckboxFlags(const char* label, int* flags, int flags_value);
// IMGUI_API bool CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value);
// IMGUI_API bool RadioButton(const char* label, bool active); // use with e.g. if (RadioButton("one", my_value==1)) { my_value = 1; }
// IMGUI_API bool RadioButton(const char* label, int* v, int v_button); // shortcut to handle the above pattern when value is an integer
// IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-FLT_MIN, 0), const char* overlay = NULL);
// IMGUI_API void Bullet(); // draw a small circle + keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses
export function Button(label: string, size: Readonly<Bind.interface_ImVec2> = ImVec2.ZERO): boolean { return bind.Button(label, size); }
export function SmallButton(label: string): boolean { return bind.SmallButton(label); }
export function ArrowButton(str_id: string, dir: ImGuiDir): boolean { return bind.ArrowButton(str_id, dir); }
export function InvisibleButton(str_id: string, size: Readonly<Bind.interface_ImVec2>, flags: ImGuiButtonFlags = 0): boolean { return bind.InvisibleButton(str_id, size, flags); }
export function Image(user_texture_id: ImTextureID | null, size: Readonly<Bind.interface_ImVec2>, uv0: Readonly<Bind.interface_ImVec2> = ImVec2.ZERO, uv1: Readonly<Bind.interface_ImVec2> = ImVec2.UNIT, tint_col: Readonly<Bind.interface_ImVec4> = ImVec4.WHITE, border_col: Readonly<Bind.interface_ImVec4> = ImVec4.ZERO): void {
bind.Image(ImGuiContext.setTexture(user_texture_id), size, uv0, uv1, tint_col, border_col);
}
export function ImageButton(user_texture_id: ImTextureID | null, size: Readonly<Bind.interface_ImVec2> = new ImVec2(Number.MIN_SAFE_INTEGER, 0), uv0: Readonly<Bind.interface_ImVec2> = ImVec2.ZERO, uv1: Readonly<Bind.interface_ImVec2> = ImVec2.UNIT, frame_padding: number = -1, bg_col: Readonly<Bind.interface_ImVec4> = ImVec4.ZERO, tint_col: Readonly<Bind.interface_ImVec4> = ImVec4.WHITE): boolean {
return bind.ImageButton(ImGuiContext.setTexture(user_texture_id), size, uv0, uv1, frame_padding, bg_col, tint_col);
}
export function Checkbox(label: string, v: Bind.ImScalar<boolean> | Bind.ImAccess<boolean>): boolean {
if (Array.isArray(v)) {
return bind.Checkbox(label, v);
} else {
const ref_v: Bind.ImScalar<boolean> = [ v() ];
const ret = bind.Checkbox(label, ref_v);
v(ref_v[0]);
return ret;
}
}
export function CheckboxFlags(label: string, flags: Bind.ImAccess<number> | Bind.ImScalar<number>, flags_value: number): boolean {
if (Array.isArray(flags)) {
return bind.CheckboxFlags(label, flags, flags_value);
} else {
const ref_flags: Bind.ImScalar<number> = [ flags() ];
const ret = bind.CheckboxFlags(label, ref_flags, flags_value);
flags(ref_flags[0]);
return ret;
}
}
export function RadioButton(label: string, active: boolean): boolean;
export function RadioButton(label: string, v: Bind.ImAccess<number> | Bind.ImScalar<number>, v_button: number): boolean;
export function RadioButton(label: string, ...args: any[]): boolean {
if (typeof(args[0]) === "boolean") {
const active: boolean = args[0];
return bind.RadioButton_A(label, active);
} else {
const v: Bind.ImAccess<number> | Bind.ImScalar<number> = args[0];
const v_button: number = args[1];
const _v: Bind.ImScalar<number> = Array.isArray(v) ? v : [ v() ];
const ret = bind.RadioButton_B(label, _v, v_button);
if (!Array.isArray(v)) { v(_v[0]); }
return ret;
}
}
export function ProgressBar(fraction: number, size_arg: Readonly<Bind.interface_ImVec2> = new ImVec2(-1, 0), overlay: string | null = null): void {
bind.ProgressBar(fraction, size_arg, overlay);
}
export function Bullet(): void { bind.Bullet(); }
// Widgets: Combo Box
// - The BeginCombo()/EndCombo() api allows you to manage your contents and selection state however you want it, by creating e.g. Selectable() items.
// - The old Combo() api are helpers over BeginCombo()/EndCombo() which are kept available for convenience purpose.
// IMGUI_API bool BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags = 0);
// IMGUI_API void EndCombo(); // only call EndCombo() if BeginCombo() returns true!
// IMGUI_API bool Combo(const char* label, int* current_item, const char* const items[], int items_count, int popup_max_height_in_items = -1);
// IMGUI_API bool Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int popup_max_height_in_items = -1); // Separate items with \0 within a string, end item-list with \0\0. e.g. "One\0Two\0Three\0"
// IMGUI_API bool Combo(const char* label, int* current_item, bool(*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int popup_max_height_in_items = -1);
export function BeginCombo(label: string, preview_value: string | null = null, flags: ImGuiComboFlags = 0): boolean { return bind.BeginCombo(label, preview_value, flags); }
export function EndCombo(): void { bind.EndCombo(); }
export type ComboValueGetter<T> = (data: T, idx: number, out_text: [string]) => boolean;
export function Combo(label: string, current_item: Bind.ImAccess<number> | Bind.ImScalar<number>, items: string[], items_count?: number, popup_max_height_in_items?: number): boolean;
export function Combo(label: string, current_item: Bind.ImAccess<number> | Bind.ImScalar<number>, items_separated_by_zeros: string, popup_max_height_in_items?: number): boolean;
export function Combo<T>(label: string, current_item: Bind.ImAccess<number> | Bind.ImScalar<number>, items_getter: ComboValueGetter<T>, data: T, items_count: number, popup_max_height_in_items?: number): boolean;
export function Combo<T>(label: string, current_item: Bind.ImAccess<number> | Bind.ImScalar<number>, ...args: any[]): boolean {
let ret = false;
const _current_item: Bind.ImScalar<number> = Array.isArray(current_item) ? current_item : [ current_item() ];
if (Array.isArray(args[0])) {
const items: string[] = args[0];
const items_count = typeof(args[1]) === "number" ? args[1] : items.length;
const popup_max_height_in_items: number = typeof(args[2]) === "number" ? args[2] : -1;
const items_getter = (data: null, idx: number, out_text: [string]): boolean => { out_text[0] = items[idx]; return true; };
ret = bind.Combo(label, _current_item, items_getter, null, items_count, popup_max_height_in_items);
} else if (typeof(args[0]) === "string") {
const items_separated_by_zeros: string = args[0]
const popup_max_height_in_items: number = typeof(args[1]) === "number" ? args[1] : -1;
const items: string[] = items_separated_by_zeros.replace(/^\0+|\0+$/g, "").split("\0");
const items_count: number = items.length;
const items_getter = (data: null, idx: number, out_text: [string]): boolean => { out_text[0] = items[idx]; return true; };
ret = bind.Combo(label, _current_item, items_getter, null, items_count, popup_max_height_in_items);
} else {
const items_getter: (data: T, idx: number, out_text: [string]) => boolean = args[0];
const data: T = args[1];
const items_count = args[2];
const popup_max_height_in_items: number = typeof(args[3]) === "number" ? args[3] : -1;
ret = bind.Combo(label, _current_item, items_getter, data, items_count, popup_max_height_in_items);
}
if (!Array.isArray(current_item)) { current_item(_current_item[0]); }
return ret;
}
// Widgets: Drag Sliders
// - CTRL+Click on any drag box to turn them into an input box. Manually input values aren't clamped and can go off-bounds.
// - For all the Float2/Float3/Float4/Int2/Int3/Int4 versions of every functions, note that a 'float v[X]' function argument is the same as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible. You can pass address of your first element out of a contiguous set, e.g. &myvector.x
// - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc.
// - Format string may also be set to NULL or use the default format ("%f" or "%d").
// - Speed are per-pixel of mouse movement (v_speed=0.2f: mouse needs to move by 5 pixels to increase value by 1). For gamepad/keyboard navigation, minimum speed is Max(v_speed, minimum_step_at_given_precision).
// - Use v_min < v_max to clamp edits to given limits. Note that CTRL+Click manual input can override those limits.
// - Use v_max = FLT_MAX / INT_MAX etc to avoid clamping to a maximum, same with v_min = -FLT_MAX / INT_MIN to avoid clamping to a minimum.
// - We use the same sets of flags for DragXXX() and SliderXXX() functions as the features are the same and it makes it easier to swap them.
// - Legacy: Pre-1.78 there are DragXXX() function signatures that takes a final `float power=1.0f' argument instead of the `ImGuiSliderFlags flags=0' argument.
// If you get a warning converting a float to ImGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361
// IMGUI_API bool DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); // If v_min >= v_max we have no bound
// IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0);
// IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0);
// IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0);
// IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", const char* format_max = NULL, ImGuiSliderFlags flags = 0);
// IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); // If v_min >= v_max we have no bound
// IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0);
// IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0);
// IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0);
// IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", const char* format_max = NULL, ImGuiSliderFlags flags = 0);
// IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiSliderFlags flags = 0);
// IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiSliderFlags flags = 0);
export function DragFloat(label: string, v: Bind.ImAccess<number> | Bind.ImScalar<number> | XY | XYZ | XYZW | Bind.ImTuple2<number> | Bind.ImTuple3<number> | Bind.ImTuple4<number>, v_speed: number = 1.0, v_min: number = 0.0, v_max: number = 0.0, display_format: string | null = "%.3f", flags: ImGuiSliderFlags = 0): boolean {
const _v = import_Scalar(v);
const ret = bind.DragFloat(label, _v, v_speed, v_min, v_max, display_format, flags);
export_Scalar(_v, v);
return ret;
}
export function DragFloat2(label: string, v: XY | XYZ | XYZW | Bind.ImTuple2<number> | Bind.ImTuple3<number> | Bind.ImTuple4<number> | ImVec2, v_speed: number = 1.0, v_min: number = 0.0, v_max: number = 0.0, display_format: string = "%.3f", flags: ImGuiSliderFlags = 0): boolean {
const _v = import_Vector2(v);
const ret = bind.DragFloat2(label, _v, v_speed, v_min, v_max, display_format, flags);
export_Vector2(_v, v);
return ret;
}
export function DragFloat3(label: string, v: XYZ | XYZW | Bind.ImTuple3<number> | Bind.ImTuple4<number>, v_speed: number = 1.0, v_min: number = 0.0, v_max: number = 0.0, display_format: string = "%.3f", flags: ImGuiSliderFlags = 0): boolean {
const _v = import_Vector3(v);
const ret = bind.DragFloat3(label, _v, v_speed, v_min, v_max, display_format, flags);
export_Vector3(_v, v);
return ret;
}
export function DragFloat4(label: string, v: XYZW | Bind.ImTuple4<number> | ImVec4, v_speed: number = 1.0, v_min: number = 0.0, v_max: number = 0.0, display_format: string = "%.3f", flags: ImGuiSliderFlags = 0): boolean {
const _v = import_Vector4(v);
const ret = bind.DragFloat4(label, _v, v_speed, v_min, v_max, display_format, flags);
export_Vector4(_v, v);
return ret;
}
export function DragFloatRange2(label: string, v_current_min: Bind.ImAccess<number> | Bind.ImScalar<number> | XY | XYZ | XYZW | Bind.ImTuple2<number> | Bind.ImTuple3<number> | Bind.ImTuple4<number>, v_current_max: Bind.ImAccess<number> | Bind.ImScalar<number> | XY | XYZ | XYZW | Bind.ImTuple2<number> | Bind.ImTuple3<number> | Bind.ImTuple4<number>, v_speed: number = 1.0, v_min: number = 0.0, v_max: number = 0.0, display_format: string = "%.3f", display_format_max: string | null = null, flags: ImGuiSliderFlags = 0): boolean {
const _v_current_min = import_Scalar(v_current_min);
const _v_current_max = import_Scalar(v_current_max);
const ret = bind.DragFloatRange2(label, _v_current_min, _v_current_max, v_speed, v_min, v_max, display_format, display_format_max, flags);
export_Scalar(_v_current_min, v_current_min);
export_Scalar(_v_current_max, v_current_max);
return ret;
}
export function DragInt(label: string, v: Bind.ImAccess<number> | Bind.ImScalar<number> | XY | XYZ | XYZW | Bind.ImTuple2<number> | Bind.ImTuple3<number> | Bind.ImTuple4<number>, v_speed: number = 1.0, v_min: number = 0, v_max: number = 0, format: string = "%d", flags: ImGuiSliderFlags = 0): boolean {
const _v = import_Scalar(v);
const ret = bind.DragInt(label, _v, v_speed, v_min, v_max, format, flags);
export_Scalar(_v, v);
return ret;
}
export function DragInt2(label: string, v: XY | XYZ | XYZW | Bind.ImTuple2<number> | Bind.ImTuple3<number> | Bind.ImTuple4<number>, v_speed: number = 1.0, v_min: number = 0, v_max: number = 0, format: string = "%d", flags: ImGuiSliderFlags = 0): boolean {
const _v = import_Vector2(v);
const ret = bind.DragInt2(label, _v, v_speed, v_min, v_max, format, flags);
export_Vector2(_v, v);
return ret;
}
export function DragInt3(label: string, v: XYZ | XYZW | Bind.ImTuple3<number> | Bind.ImTuple4<number>, v_speed: number = 1.0, v_min: number = 0, v_max: number = 0, format: string = "%d", flags: ImGuiSliderFlags = 0): boolean {
const _v = import_Vector3(v);
const ret = bind.DragInt3(label, _v, v_speed, v_min, v_max, format, flags);
export_Vector3(_v, v);
return ret;
}
export function DragInt4(label: string, v: XYZW | Bind.ImTuple4<number>, v_speed: number = 1.0, v_min: number = 0, v_max: number = 0, format: string = "%d", flags: ImGuiSliderFlags = 0): boolean {
const _v = import_Vector4(v);
const ret = bind.DragInt4(label, _v, v_speed, v_min, v_max, format, flags);
export_Vector4(_v, v);
return ret;
}
export function DragIntRange2(label: string, v_current_min: Bind.ImAccess<number> | Bind.ImScalar<number> | XY | XYZ | XYZW | Bind.ImTuple2<number> | Bind.ImTuple3<number> | Bind.ImTuple4<number>, v_current_max: Bind.ImAccess<number> | Bind.ImScalar<number> | XY | XYZ | XYZW | Bind.ImTuple2<number> | Bind.ImTuple3<number> | Bind.ImTuple4<number>, v_speed: number = 1.0, v_min: number = 0, v_max: number = 0, format: string = "%d", format_max: string | null = null, flags: ImGuiSliderFlags = 0): boolean {
const _v_current_min = import_Scalar(v_current_min);
const _v_current_max = import_Scalar(v_current_max);
const ret = bind.DragIntRange2(label, _v_current_min, _v_current_max, v_speed, v_min, v_max, format, format_max, flags);
export_Scalar(_v_current_min, v_current_min);
export_Scalar(_v_current_max, v_current_max);
return ret;
}
export function DragScalar(label: string, v: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array, v_speed: number, v_min: number | null = null, v_max: number | null = null, format: string | null = null, flags: ImGuiSliderFlags = 0): boolean {
if (v instanceof Int8Array) { return bind.DragScalar(label, ImGuiDataType.S8, v, v_speed, v_min, v_max, format, flags); }
if (v instanceof Uint8Array) { return bind.DragScalar(label, ImGuiDataType.U8, v, v_speed, v_min, v_max, format, flags); }
if (v instanceof Int16Array) { return bind.DragScalar(label, ImGuiDataType.S16, v, v_speed, v_min, v_max, format, flags); }
if (v instanceof Uint16Array) { return bind.DragScalar(label, ImGuiDataType.U16, v, v_speed, v_min, v_max, format, flags); }
if (v instanceof Int32Array) { return bind.DragScalar(label, ImGuiDataType.S32, v, v_speed, v_min, v_max, format, flags); }
if (v instanceof Uint32Array) { return bind.DragScalar(label, ImGuiDataType.U32, v, v_speed, v_min, v_max, format, flags); }
// if (v instanceof Int64Array) { return bind.DragScalar(label, ImGuiDataType.S64, v, v_speed, v_min, v_max, format, flags); }
// if (v instanceof Uint64Array) { return bind.DragScalar(label, ImGuiDataType.U64, v, v_speed, v_min, v_max, format, flags); }
if (v instanceof Float32Array) { return bind.DragScalar(label, ImGuiDataType.Float, v, v_speed, v_min, v_max, format, flags); }
if (v instanceof Float64Array) { return bind.DragScalar(label, ImGuiDataType.Double, v, v_speed, v_min, v_max, format, flags); }
throw new Error();
}
// Widgets: Regular Sliders
// - CTRL+Click on any slider to turn them into an input box. Manually input values aren't clamped and can go off-bounds.
// - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc.
// - Format string may also be set to NULL or use the default format ("%f" or "%d").
// - Legacy: Pre-1.78 there are SliderXXX() function signatures that takes a final `float power=1.0f' argument instead of the `ImGuiSliderFlags flags=0' argument.
// If you get a warning converting a float to ImGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361
// IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display.
// IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0);
// IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0);
// IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0);
// IMGUI_API bool SliderAngle(const char* label, float* v_rad, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f, const char* format = "%.0f deg", ImGuiSliderFlags flags = 0);
// IMGUI_API bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0);
// IMGUI_API bool SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0);
// IMGUI_API bool SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0);
// IMGUI_API bool SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0);
// IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0);
// IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0);
// IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0);
// IMGUI_API bool VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0);
// IMGUI_API bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0);
export function SliderFloat(label: string, v: Bind.ImAccess<number> | Bind.ImScalar<number> | XY | XYZ | XYZW | Bind.ImTuple2<number> | Bind.ImTuple3<number> | Bind.ImTuple4<number>, v_min: number, v_max: number, format: string = "%.3f", flags: ImGuiSliderFlags = 0): boolean {
const _v = import_Scalar(v);
const ret = bind.SliderFloat(label, _v, v_min, v_max, format, flags);
export_Scalar(_v, v);
return ret;
}
export function SliderFloat2(label: string, v: XY | XYZ | XYZW | Bind.ImTuple2<number> | Bind.ImTuple3<number> | Bind.ImTuple4<number> | Bind.interface_ImVec2, v_min: number, v_max: number, format: string = "%.3f", flags: ImGuiSliderFlags = 0): boolean {
const _v = import_Vector2(v);
const ret = bind.SliderFloat2(label, _v, v_min, v_max, format, flags);
export_Vector2(_v, v);
return ret;
}
export function SliderFloat3(label: string, v: XYZ | XYZW | Bind.ImTuple3<number> | Bind.ImTuple4<number>, v_min: number, v_max: number, format: string = "%.3f", flags: ImGuiSliderFlags = 0): boolean {
const _v = import_Vector3(v);
const ret = bind.SliderFloat3(label, _v, v_min, v_max, format, flags);
export_Vector3(_v, v);
return ret;
}
export function SliderFloat4(label: string, v: XYZW | Bind.ImTuple4<number> | XYZW, v_min: number, v_max: number, format: string = "%.3f", flags: ImGuiSliderFlags = 0): boolean {
const _v = import_Vector4(v);
const ret = bind.SliderFloat4(label, _v, v_min, v_max, format, flags);
export_Vector4(_v, v);
return ret;
}
export function SliderAngle(label: string, v_rad: Bind.ImAccess<number> | Bind.ImScalar<number> | XY | XYZ | XYZW | Bind.ImTuple2<number> | Bind.ImTuple3<number> | Bind.ImTuple4<number>, v_degrees_min: number = -360.0, v_degrees_max: number = +360.0, format: string = "%.0f deg", flags: ImGuiSliderFlags = 0): boolean {
const _v_rad = import_Scalar(v_rad);
const ret = bind.SliderAngle(label, _v_rad, v_degrees_min, v_degrees_max, format, flags);
export_Scalar(_v_rad, v_rad);
return ret;
}
export function SliderAngle3(label: string, v_rad: XYZ | XYZW | Bind.ImTuple3<number> | Bind.ImTuple4<number>, v_degrees_min: number = -360.0, v_degrees_max: number = +360.0, format: string = "%.0f deg", flags: ImGuiSliderFlags = 0): boolean {
const _v_rad = import_Vector3(v_rad);
_v_rad[0] = Math.floor(_v_rad[0] * 180 / Math.PI);
_v_rad[1] = Math.floor(_v_rad[1] * 180 / Math.PI);
_v_rad[2] = Math.floor(_v_rad[2] * 180 / Math.PI);
const ret = bind.SliderInt3(label, _v_rad, v_degrees_min, v_degrees_max, format, flags);
_v_rad[0] = _v_rad[0] * Math.PI / 180;
_v_rad[1] = _v_rad[1] * Math.PI / 180;
_v_rad[2] = _v_rad[2] * Math.PI / 180;
export_Vector3(_v_rad, v_rad);
return ret;
}
export function SliderInt(label: string, v: Bind.ImAccess<number> | Bind.ImScalar<number> | XY | XYZ | XYZW | Bind.ImTuple2<number> | Bind.ImTuple3<number> | Bind.ImTuple4<number>, v_min: number, v_max: number, format: string = "%d", flags: ImGuiSliderFlags = 0): boolean {
const _v = import_Scalar(v);
const ret = bind.SliderInt(label, _v, v_min, v_max, format, flags);
export_Scalar(_v, v);
return ret;
}
export function SliderInt2(label: string, v: XY | XYZ | XYZW | Bind.ImTuple2<number> | Bind.ImTuple3<number> | Bind.ImTuple4<number>, v_min: number, v_max: number, format: string = "%d", flags: ImGuiSliderFlags = 0): boolean {
const _v = import_Vector2(v);
const ret = bind.SliderInt2(label, _v, v_min, v_max, format, flags);
export_Vector2(_v, v);
return ret;
}
export function SliderInt3(label: string, v: XYZ | XYZW | Bind.ImTuple3<number> | Bind.ImTuple4<number>, v_min: number, v_max: number, format: string = "%d", flags: ImGuiSliderFlags = 0): boolean {
const _v = import_Vector3(v);
const ret = bind.SliderInt3(label, _v, v_min, v_max, format, flags);
export_Vector3(_v, v);
return ret;
}
export function SliderInt4(label: string, v: XYZW | Bind.ImTuple4<number>, v_min: number, v_max: number, format: string = "%d", flags: ImGuiSliderFlags = 0): boolean {
const _v = import_Vector4(v);
const ret = bind.SliderInt4(label, _v, v_min, v_max, format, flags);
export_Vector4(_v, v);
return ret;
}
export function SliderScalar(label: string, v: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array, v_min: number, v_max: number, format: string | null = null, flags: ImGuiSliderFlags = 0): boolean {
if (v instanceof Int8Array) { return bind.SliderScalar(label, ImGuiDataType.S8, v, v_min, v_max, format, flags); }
if (v instanceof Uint8Array) { return bind.SliderScalar(label, ImGuiDataType.U8, v, v_min, v_max, format, flags); }
if (v instanceof Int16Array) { return bind.SliderScalar(label, ImGuiDataType.S16, v, v_min, v_max, format, flags); }
if (v instanceof Uint16Array) { return bind.SliderScalar(label, ImGuiDataType.U16, v, v_min, v_max, format, flags); }
if (v instanceof Int32Array) { return bind.SliderScalar(label, ImGuiDataType.S32, v, v_min, v_max, format, flags); }
if (v instanceof Uint32Array) { return bind.SliderScalar(label, ImGuiDataType.U32, v, v_min, v_max, format, flags); }
// if (v instanceof Int64Array) { return bind.SliderScalar(label, ImGuiDataType.S64, v, v_min, v_max, format, flags); }
// if (v instanceof Uint64Array) { return bind.SliderScalar(label, ImGuiDataType.U64, v, v_min, v_max, format, flags); }
if (v instanceof Float32Array) { return bind.SliderScalar(label, ImGuiDataType.Float, v, v_min, v_max, format, flags); }
if (v instanceof Float64Array) { return bind.SliderScalar(label, ImGuiDataType.Double, v, v_min, v_max, format, flags); }
throw new Error();
}
export function VSliderFloat(label: string, size: Readonly<Bind.interface_ImVec2>, v: Bind.ImAccess<number> | Bind.ImScalar<number> | XY | XYZ | XYZW | Bind.ImTuple2<number> | Bind.ImTuple3<number> | Bind.ImTuple4<number>, v_min: number, v_max: number, format: string = "%.3f", flags: ImGuiSliderFlags = 0): boolean {
const _v = import_Scalar(v);
const ret = bind.VSliderFloat(label, size, _v, v_min, v_max, format, flags);
export_Scalar(_v, v);
return ret;
}
export function VSliderInt(label: string, size: Readonly<Bind.interface_ImVec2>, v: Bind.ImAccess<number> | Bind.ImScalar<number> | XY | XYZ | XYZW | Bind.ImTuple2<number> | Bind.ImTuple3<number> | Bind.ImTuple4<number>, v_min: number, v_max: number, format: string = "%d", flags: ImGuiSliderFlags = 0): boolean {
const _v = import_Scalar(v);
const ret = bind.VSliderInt(label, size, _v, v_min, v_max, format, flags);
export_Scalar(_v, v);
return ret;
}
export function VSliderScalar(label: string, size: Readonly<Bind.interface_ImVec2>, data_type: ImGuiDataType, v: Bind.ImAccess<number> | Bind.ImScalar<number>, v_min: number, v_max: number, format: string | null = null, flags: ImGuiSliderFlags = 0): boolean {
if (v instanceof Int8Array) { return bind.VSliderScalar(label, size, ImGuiDataType.S8, v, v_min, v_max, format, flags); }
if (v instanceof Uint8Array) { return bind.VSliderScalar(label, size, ImGuiDataType.U8, v, v_min, v_max, format, flags); }
if (v instanceof Int16Array) { return bind.VSliderScalar(label, size, ImGuiDataType.S16, v, v_min, v_max, format, flags); }
if (v instanceof Uint16Array) { return bind.VSliderScalar(label, size, ImGuiDataType.U16, v, v_min, v_max, format, flags); }
if (v instanceof Int32Array) { return bind.VSliderScalar(label, size, ImGuiDataType.S32, v, v_min, v_max, format, flags); }
if (v instanceof Uint32Array) { return bind.VSliderScalar(label, size, ImGuiDataType.U32, v, v_min, v_max, format, flags); }
// if (v instanceof Int64Array) { return bind.VSliderScalar(label, size, ImGuiDataType.S64, v, v_min, v_max, format, flags); }
// if (v instanceof Uint64Array) { return bind.VSliderScalar(label, size, ImGuiDataType.U64, v, v_min, v_max, format, flags); }
if (v instanceof Float32Array) { return bind.VSliderScalar(label, size, ImGuiDataType.Float, v, v_min, v_max, format, flags); }
if (v instanceof Float64Array) { return bind.VSliderScalar(label, size, ImGuiDataType.Double, v, v_min, v_max, format, flags); }
throw new Error();
}
// Widgets: Input with Keyboard
// - If you want to use InputText() with std::string or any custom dynamic string type, see misc/cpp/imgui_stdlib.h and comments in imgui_demo.cpp.
// - Most of the ImGuiInputTextFlags flags are only useful for InputText() and not for InputFloatX, InputIntX, InputDouble etc.
// IMGUI_API bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);
// IMGUI_API bool InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);
// IMGUI_API bool InputTextWithHint(const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);
// IMGUI_API bool InputFloat(const char* label, float* v, float step = 0.0f, float step_fast = 0.0f, const char* format = "%.3f", ImGuiInputTextFlags flags = 0);
// IMGUI_API bool InputFloat2(const char* label, float v[2], const char* format = "%.3f", ImGuiInputTextFlags flags = 0);
// IMGUI_API bool InputFloat3(const char* label, float v[3], const char* format = "%.3f", ImGuiInputTextFlags flags = 0);
// IMGUI_API bool InputFloat4(const char* label, float v[4], const char* format = "%.3f", ImGuiInputTextFlags flags = 0);
// IMGUI_API bool InputInt(const char* label, int* v, int step = 1, int step_fast = 100, ImGuiInputTextFlags flags = 0);
// IMGUI_API bool InputInt2(const char* label, int v[2], ImGuiInputTextFlags flags = 0);
// IMGUI_API bool InputInt3(const char* label, int v[3], ImGuiInputTextFlags flags = 0);
// IMGUI_API bool InputInt4(const char* label, int v[4], ImGuiInputTextFlags flags = 0);
// IMGUI_API bool InputDouble(const char* label, double* v, double step = 0.0, double step_fast = 0.0, const char* format = "%.6f", ImGuiInputTextFlags flags = 0);
// IMGUI_API bool InputScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_step = NULL, const void* p_step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags flags = 0);
// IMGUI_API bool InputScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_step = NULL, const void* p_step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags flags = 0);
export function InputText<T>(label: string, buf: ImStringBuffer | Bind.ImAccess<string> | Bind.ImScalar<string>, buf_size: number = buf instanceof ImStringBuffer ? buf.size : ImGuiInputTextDefaultSize, flags: ImGuiInputTextFlags = 0, callback: ImGuiInputTextCallback<T> | null = null, user_data: T | null = null): boolean {
const _callback = callback && ((data: Bind.reference_ImGuiInputTextCallbackData): number => callback(new ImGuiInputTextCallbackData<T>(data, user_data))) || null;
if (Array.isArray(buf)) {
return bind.InputText(label, buf, buf_size, flags, _callback, null);
} else if (buf instanceof ImStringBuffer) {
const ref_buf: Bind.ImScalar<string> = [ buf.buffer ];
const _buf_size: number = Math.min(buf_size, buf.size);
const ret: boolean = bind.InputText(label, ref_buf, _buf_size, flags, _callback, null);
buf.buffer = ref_buf[0];
return ret;
} else {
const ref_buf: Bind.ImScalar<string> = [ buf() ];
const ret: boolean = bind.InputText(label, ref_buf, buf_size + 1, flags, _callback, null);
buf(ref_buf[0]);
return ret;
}
}
export function InputTextMultiline<T>(label: string, buf: ImStringBuffer | Bind.ImAccess<string> | Bind.ImScalar<string>, buf_size: number = buf instanceof ImStringBuffer ? buf.size : ImGuiInputTextDefaultSize, size: Readonly<Bind.interface_ImVec2> = ImVec2.ZERO, flags: ImGuiInputTextFlags = 0, callback: ImGuiInputTextCallback<T> | null = null, user_data: T | null = null): boolean {
const _callback = callback && ((data: Bind.reference_ImGuiInputTextCallbackData): number => callback(new ImGuiInputTextCallbackData<T>(data, user_data))) || null;
if (Array.isArray(buf)) {
return bind.InputTextMultiline(label, buf, buf_size, size, flags, _callback, null);
} else if (buf instanceof ImStringBuffer) {
const ref_buf: Bind.ImScalar<string> = [ buf.buffer ];
const _buf_size: number = Math.min(buf_size, buf.size);
const ret: boolean = bind.InputTextMultiline(label, ref_buf, _buf_size, size, flags, _callback, null);
buf.buffer = ref_buf[0];
return ret;
} else {
const ref_buf: Bind.ImScalar<string> = [ buf() ];
const ret: boolean = bind.InputTextMultiline(label, ref_buf, buf_size, size, flags, _callback, null);
buf(ref_buf[0]);
return ret;
}
}
export function InputTextWithHint<T>(label: string, hint: string, buf: ImStringBuffer | Bind.ImAccess<string> | Bind.ImScalar<string>, buf_size: number = buf instanceof ImStringBuffer ? buf.size : ImGuiInputTextDefaultSize, flags: ImGuiInputTextFlags = 0, callback: ImGuiInputTextCallback<T> | null = null, user_data: T | null = null): boolean {
const _callback = callback && ((data: Bind.reference_ImGuiInputTextCallbackData): number => callback(new ImGuiInputTextCallbackData<T>(data, user_data))) || null;
if (Array.isArray(buf)) {
return bind.InputTextWithHint(label, hint, buf, buf_size, flags, _callback, null);
} else if (buf instanceof ImStringBuffer) {
const ref_buf: Bind.ImScalar<string> = [ buf.buffer ];
const _buf_size: number = Math.min(buf_size, buf.size);
const ret: boolean = bind.InputTextWithHint(label, hint, ref_buf, _buf_size, flags, _callback, null);
buf.buffer = ref_buf[0];
return ret;
} else {
const ref_buf: Bind.ImScalar<string> = [ buf() ];
const ret: boolean = bind.InputTextWithHint(label, hint, ref_buf, buf_size, flags, _callback, null);
buf(ref_buf[0]);
return ret;
}
}
export function InputFloat(label: string, v: Bind.ImAccess<number> | Bind.ImScalar<number> | XY | XYZ | XYZW | Bind.ImTuple2<number> | Bind.ImTuple3<number> | Bind.ImTuple4<number>, step: number = 0.0, step_fast: number = 0.0, format: string = "%.3f", flags: ImGuiInputTextFlags = 0): boolean {
const _v = import_Scalar(v);
const ret = bind.InputFloat(label, _v, step, step_fast, format, flags);
export_Scalar(_v, v);
return ret;
}
export function InputFloat2(label: string, v: XY | XYZ | XYZW | Bind.ImTuple2<number> | Bind.ImTuple3<number> | Bind.ImTuple4<number>, format: string = "%.3f", flags: ImGuiInputTextFlags = 0): boolean {
const _v = import_Vector2(v);
const ret = bind.InputFloat2(label, _v, format, flags);
export_Vector2(_v, v);
return ret;
}
export function InputFloat3(label: string, v: XYZ | XYZW | Bind.ImTuple3<number> | Bind.ImTuple4<number>, format: string = "%.3f", flags: ImGuiInputTextFlags = 0): boolean {
const _v = import_Vector3(v);
const ret = bind.InputFloat3(label, _v, format, flags);
export_Vector3(_v, v);
return ret;
}
export function InputFloat4(label: string, v: XYZW | Bind.ImTuple4<number>, format: string = "%.3f", flags: ImGuiInputTextFlags = 0): boolean {
const _v = import_Vector4(v);
const ret = bind.InputFloat4(label, _v, format, flags);
export_Vector4(_v, v);
return ret;
}
export function InputInt(label: string, v: Bind.ImAccess<number> | Bind.ImScalar<number> | XY | XYZ | XYZW | Bind.ImTuple2<number> | Bind.ImTuple3<number> | Bind.ImTuple4<number>, step: number = 1, step_fast: number = 100, flags: ImGuiInputTextFlags = 0): boolean {
const _v = import_Scalar(v);
const ret = bind.InputInt(label, _v, step, step_fast, flags);
export_Scalar(_v, v);
return ret;
}
export function InputInt2(label: string, v: XY | XYZ | XYZW | Bind.ImTuple2<number> | Bind.ImTuple3<number> | Bind.ImTuple4<number>, flags: ImGuiInputTextFlags = 0): boolean {
const _v = import_Vector2(v);
const ret = bind.InputInt2(label, _v, flags);
export_Vector2(_v, v);
return ret;
}
export function InputInt3(label: string, v: XYZ | XYZW | Bind.ImTuple3<number> | Bind.ImTuple4<number>, flags: ImGuiInputTextFlags = 0): boolean {
const _v = import_Vector3(v);
const ret = bind.InputInt3(label, _v, flags);
export_Vector3(_v, v);
return ret;
}
export function InputInt4(label: string, v: XYZW | Bind.ImTuple4<number>, flags: ImGuiInputTextFlags = 0): boolean {
const _v = import_Vector4(v);
const ret = bind.InputInt4(label, _v, flags);
export_Vector4(_v, v);
return ret;
}
export function InputDouble(label: string, v: Bind.ImAccess<number> | Bind.ImScalar<number> | XY | XYZ | XYZW | Bind.ImTuple2<number> | Bind.ImTuple3<number> | Bind.ImTuple4<number>, step: number = 0.0, step_fast: number = 0.0, format: string = "%.6f", flags: ImGuiInputTextFlags = 0): boolean {
const _v = import_Scalar(v);
const ret = bind.InputDouble(label, _v, step, step_fast, format, flags);
export_Scalar(_v, v);
return ret;
}
export function InputScalar(label: string, v: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array, step: number | null = null, step_fast: number | null = null, format: string | null = null, flags: ImGuiInputTextFlags = 0): boolean {
if (v instanceof Int8Array) { return bind.InputScalar(label, ImGuiDataType.S8, v, step, step_fast, format, flags); }
if (v instanceof Uint8Array) { return bind.InputScalar(label, ImGuiDataType.U8, v, step, step_fast, format, flags); }
if (v instanceof Int16Array) { return bind.InputScalar(label, ImGuiDataType.S16, v, step, step_fast, format, flags); }
if (v instanceof Uint16Array) { return bind.InputScalar(label, ImGuiDataType.U16, v, step, step_fast, format, flags); }
if (v instanceof Int32Array) { return bind.InputScalar(label, ImGuiDataType.S32, v, step, step_fast, format, flags); }
if (v instanceof Uint32Array) { return bind.InputScalar(label, ImGuiDataType.U32, v, step, step_fast, format, flags); }
// if (v instanceof Int64Array) { return bind.InputScalar(label, ImGuiDataType.S64, v, step, step_fast, format, flags); }
// if (v instanceof Uint64Array) { return bind.InputScalar(label, ImGuiDataType.U64, v, step, step_fast, format, flags); }
if (v instanceof Float32Array) { return bind.InputScalar(label, ImGuiDataType.Float, v, step, step_fast, format, flags); }
if (v instanceof Float64Array) { return bind.InputScalar(label, ImGuiDataType.Double, v, step, step_fast, format, flags); }
throw new Error();
}
// Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little color square that can be left-clicked to open a picker, and right-clicked to open an option menu.)
// - Note that in C++ a 'float v[X]' function argument is the _same_ as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible.
// - You can pass the address of a first float element out of a contiguous structure, e.g. &myvector.x
// IMGUI_API bool ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags = 0);
// IMGUI_API bool ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0);
// IMGUI_API bool ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags = 0);
// IMGUI_API bool ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags = 0, const float* ref_col = NULL);
// IMGUI_API bool ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0)); // display a color square/button, hover for details, return true when pressed.
// IMGUI_API void SetColorEditOptions(ImGuiColorEditFlags flags); // initialize current options (generally on application startup) if you want to select a default format, picker type, etc. User will be able to change many settings, unless you pass the _NoOptions flag to your calls.
export function ColorEdit3(label: string, col: RGB | RGBA | Bind.ImTuple3<number> | Bind.ImTuple4<number> | Bind.interface_ImVec4, flags: ImGuiColorEditFlags = 0): boolean {
const _col = import_Color3(col);
const ret = bind.ColorEdit3(label, _col, flags);
export_Color3(_col, col);
return ret;
}
export function ColorEdit4(label: string, col: RGBA | Bind.ImTuple4<number> | Bind.interface_ImVec4, flags: ImGuiColorEditFlags = 0): boolean {
const _col = import_Color4(col);
const ret = bind.ColorEdit4(label, _col, flags);
export_Color4(_col, col);
return ret;
}
export function ColorPicker3(label: string, col: RGB | RGBA | Bind.ImTuple3<number> | Bind.ImTuple4<number> | Bind.interface_ImVec4, flags: ImGuiColorEditFlags = 0): boolean {
const _col = import_Color3(col);
const ret = bind.ColorPicker3(label, _col, flags);
export_Color3(_col, col);
return ret;
}
export function ColorPicker4(label: string, col: RGBA | Bind.ImTuple4<number> | Bind.interface_ImVec4, flags: ImGuiColorEditFlags = 0, ref_col: Bind.ImTuple4<number> | Bind.interface_ImVec4 | null = null): boolean {
const _col = import_Color4(col);
const _ref_col = ref_col ? import_Color4(ref_col) : null;
const ret = bind.ColorPicker4(label, _col, flags, _ref_col);
export_Color4(_col, col);
if (_ref_col && ref_col) { export_Color4(_ref_col, ref_col); }
return ret;
}
export function ColorButton(desc_id: string, col: Readonly<Bind.interface_ImVec4>, flags: ImGuiColorEditFlags = 0, size: Readonly<Bind.interface_ImVec2> = ImVec2.ZERO): boolean {
return bind.ColorButton(desc_id, col, flags, size);
}
export function SetColorEditOptions(flags: ImGuiColorEditFlags): void {
bind.SetColorEditOptions(flags);
}
// Widgets: Trees
// - TreeNode functions return true when the node is open, in which case you need to also call TreePop() when you are finished displaying the tree node contents.
// IMGUI_API bool TreeNode(const char* label);
// IMGUI_API bool TreeNode(const char* str_id, const char* fmt, ...) IM_FMTARGS(2); // helper variation to easily decorelate the id from the displayed string. Read the FAQ about why and how to use ID. to align arbitrary text at the same level as a TreeNode() you can use Bullet().
// IMGUI_API bool TreeNode(const void* ptr_id, const char* fmt, ...) IM_FMTARGS(2); // "
// IMGUI_API bool TreeNodeV(const char* str_id, const char* fmt, va_list args) IM_FMTLIST(2);
// IMGUI_API bool TreeNodeV(const void* ptr_id, const char* fmt, va_list args) IM_FMTLIST(2);
// IMGUI_API bool TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags = 0);
// IMGUI_API bool TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3);
// IMGUI_API bool TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3);
// IMGUI_API bool TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3);
// IMGUI_API bool TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3);
// IMGUI_API void TreePush(const char* str_id); // ~ Indent()+PushId(). Already called by TreeNode() when returning true, but you can call TreePush/TreePop yourself if desired.
// IMGUI_API void TreePush(const void* ptr_id = NULL); // "
// IMGUI_API void TreePop(); // ~ Unindent()+PopId()
// IMGUI_API float GetTreeNodeToLabelSpacing(); // horizontal distance preceding label when using TreeNode*() or Bullet() == (g.FontSize + style.FramePadding.x*2) for a regular unframed TreeNode
// IMGUI_API bool CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags = 0); // if returning 'true' the header is open. doesn't indent nor push on ID stack. user doesn't have to call TreePop().
// IMGUI_API bool CollapsingHeader(const char* label, bool* p_visible, ImGuiTreeNodeFlags flags = 0); // when 'p_visible != NULL': if '*p_visible==true' display an additional small close button on upper right of the header which will set the bool to false when clicked, if '*p_visible==false' don't display the header.
// IMGUI_API void SetNextItemOpen(bool is_open, ImGuiCond cond = 0); // set next TreeNode/CollapsingHeader open state.
export function TreeNode(label: string): boolean;
export function TreeNode(label: string, fmt: string): boolean;
export function TreeNode(label: number, fmt: string): boolean;
export function TreeNode(...args: any[]): boolean {
if (typeof(args[0]) === "string") {
if (args.length === 1) {
const label: string = args[0];
return bind.TreeNode_A(label);
} else {
const str_id: string = args[0];
const fmt: string = args[1];
return bind.TreeNode_B(str_id, fmt);
}
} else {
const ptr_id: number = args[0];
const fmt: string = args[1];
return bind.TreeNode_C(ptr_id, fmt);
}
}
export function TreeNodeEx(label: string, flags?: ImGuiTreeNodeFlags): boolean;
export function TreeNodeEx(str_id: string, flags: ImGuiTreeNodeFlags, fmt: string): boolean;
export function TreeNodeEx(ptr_id: number, flags: ImGuiTreeNodeFlags, fmt: string): boolean;
export function TreeNodeEx(...args: any[]): boolean {
if (typeof(args[0]) === "string") {
if (args.length < 3) {
const label: string = args[0];
const flags: ImGuiTreeNodeFlags = args[1] || 0;
return bind.TreeNodeEx_A(label, flags);
} else {
const str_id: string = args[0];
const flags: ImGuiTreeNodeFlags = args[1];
const fmt: string = args[2];
return bind.TreeNodeEx_B(str_id, flags, fmt);
}
} else {
const ptr_id: number = args[0];
const flags: ImGuiTreeNodeFlags = args[1];
const fmt: string = args[2];
return bind.TreeNodeEx_C(ptr_id, flags, fmt);
}
}
export function TreePush(str_id: string): void;
export function TreePush(ptr_id: number): void;
export function TreePush(...args: any[]): void {
if (typeof(args[0]) === "string") {
const str_id: string = args[0];
bind.TreePush_A(str_id);
} else {
const ptr_id: number = args[0];
bind.TreePush_B(ptr_id);
}
}
export function TreePop(): void { bind.TreePop(); }
export function GetTreeNodeToLabelSpacing(): number { return bind.GetTreeNodeToLabelSpacing(); }
export function CollapsingHeader(label: string, flags?: ImGuiTreeNodeFlags): boolean;
export function CollapsingHeader(label: string, p_open: Bind.ImScalar<boolean> | Bind.ImAccess<boolean>, flags?: ImGuiTreeNodeFlags): boolean;
export function CollapsingHeader(label: string, ...args: any[]): boolean {
if (args.length === 0) {
return bind.CollapsingHeader_A(label, 0);
} else {
if (typeof(args[0]) === "number") {
const flags: ImGuiTreeNodeFlags = args[0];
return bind.CollapsingHeader_A(label, flags);
} else {
const p_open: Bind.ImScalar<boolean> | Bind.ImAccess<boolean> = args[0];
const flags: ImGuiTreeNodeFlags = args[1] || 0;
const ref_open: Bind.ImScalar<boolean> = Array.isArray(p_open) ? p_open : [ p_open() ];
const ret = bind.CollapsingHeader_B(label, ref_open, flags);
if (!Array.isArray(p_open)) { p_open(ref_open[0]); }
return ret;
}
}
}
export function SetNextItemOpen(is_open: boolean, cond: ImGuiCond = 0): void {
bind.SetNextItemOpen(is_open, cond);
}
// Widgets: Selectables
// - A selectable highlights when hovered, and can display another color when selected.
// - Neighbors selectable extend their highlight bounds in order to leave no gap between them. This is so a series of selected Selectable appear contiguous.
// IMGUI_API bool Selectable(const char* label, bool selected = false, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0, 0)); // "bool selected" carry the selection state (read-only). Selectable() is clicked is returns true so you can modify your selection state. size.x==0.0: use remaining width, size.x>0.0: specify width. size.y==0.0: use label height, size.y>0.0: specify height
// IMGUI_API bool Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0, 0)); // "bool* p_selected" point to the selection state (read-write), as a convenient helper.
export function Selectable(label: string, selected?: boolean, flags?: ImGuiSelectableFlags, size?: Readonly<Bind.interface_ImVec2>): boolean;
export function Selectable(label: string, p_selected: Bind.ImScalar<boolean> | Bind.ImAccess<boolean>, flags?: ImGuiSelectableFlags, size?: Readonly<Bind.interface_ImVec2>): boolean;
export function Selectable(label: string, ...args: any[]): boolean {
if (args.length === 0) {
return bind.Selectable_A(label, false, 0, ImVec2.ZERO);
} else {
if (typeof(args[0]) === "boolean") {
const selected: boolean = args[0];
const flags: ImGuiSelectableFlags = args[1] || 0;
const size: Readonly<Bind.interface_ImVec2> = args[2] || ImVec2.ZERO;
return bind.Selectable_A(label, selected, flags, size);
} else {
const p_selected: Bind.ImScalar<boolean> | Bind.ImAccess<boolean> = args[0];
const flags: ImGuiSelectableFlags = args[1] || 0;
const size: Readonly<Bind.interface_ImVec2> = args[2] || ImVec2.ZERO;
const ref_selected: Bind.ImScalar<boolean> = Array.isArray(p_selected) ? p_selected : [ p_selected() ];
const ret = bind.Selectable_B(label, ref_selected, flags, size);
if (!Array.isArray(p_selected)) { p_selected(ref_selected[0]); }
return ret;
}
}
}
// Widgets: List Boxes
// - FIXME: To be consistent with all the newer API, ListBoxHeader/ListBoxFooter should in reality be called BeginListBox/EndListBox. Will rename them.
// IMGUI_API bool ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items = -1);
// IMGUI_API bool ListBox(const char* label, int* current_item, bool (*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int height_in_items = -1);
// IMGUI_API bool ListBoxHeader(const char* label, const ImVec2& size = ImVec2(0, 0)); // use if you want to reimplement ListBox() will custom data or interactions. if the function return true, you can output elements then call ListBoxFooter() afterwards.
// IMGUI_API bool ListBoxHeader(const char* label, int items_count, int height_in_items = -1); // "
// IMGUI_API void ListBoxFooter(); // terminate the scrolling region. only call ListBoxFooter() if ListBoxHeader() returned true!
export type ListBoxItemGetter<T> = (data: T, idx: number, out_text: [string]) => boolean;
export function ListBox(label: string, current_item: Bind.ImAccess<number> | Bind.ImScalar<number>, items: string[], items_count?: number, height_in_items?: number): boolean;
export function ListBox<T>(label: string, current_item: Bind.ImAccess<number> | Bind.ImScalar<number>, items_getter: ListBoxItemGetter<T>, data: T, items_count: number, height_in_items?: number): boolean;
export function ListBox<T>(label: string, current_item: Bind.ImAccess<number> | Bind.ImScalar<number>, ...args: any[]): boolean {
let ret: boolean = false;
const _current_item: Bind.ImScalar<number> = Array.isArray(current_item) ? current_item : [ current_item() ];
if (Array.isArray(args[0])) {
const items: string[] = args[0];
const items_count: number = typeof(args[1]) === "number" ? args[1] : items.length;
const height_in_items: number = typeof(args[2]) === "number" ? args[2] : -1;
ret = bind.ListBox_A(label, _current_item, items, items_count, height_in_items);
} else {
const items_getter: ListBoxItemGetter<T> = args[0];
const data: any = args[1];
const items_count: number = args[2];
const height_in_items: number = typeof(args[3]) === "number" ? args[3] : -1;
ret = bind.ListBox_B(label, _current_item, items_getter, data, items_count, height_in_items);
}
if (!Array.isArray(current_item)) { current_item(_current_item[0]); }
return ret;
}
export function ListBoxHeader(label: string, size: Readonly<Bind.interface_ImVec2>): boolean;
export function ListBoxHeader(label: string, items_count: number, height_in_items?: number): boolean;
export function ListBoxHeader(label: string, ...args: any[]): boolean {
if (typeof(args[0]) === "object") {
const size: Readonly<Bind.interface_ImVec2> = args[0];
return bind.ListBoxHeader_A(label, size);
} else {
const items_count: number = args[0];
const height_in_items: number = typeof(args[1]) === "number" ? args[1] : -1;
return bind.ListBoxHeader_B(label, items_count, height_in_items);
}
}
export function ListBoxFooter(): void { bind.ListBoxFooter(); }
// Widgets: Data Plotting
// IMGUI_API void PlotLines(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0), int stride = sizeof(float));
// IMGUI_API void PlotLines(const char* label, float(*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0));
// IMGUI_API void PlotHistogram(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0), int stride = sizeof(float));
// IMGUI_API void PlotHistogram(const char* label, float(*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0));
export type PlotLinesValueGetter<T> = (data: T, idx: number) => number;
export function PlotLines(label: string, values: ArrayLike<number>, values_count?: number, value_offset?: number, overlay_text?: string | null, scale_min?: number, scale_max?: number, graph_size?: Readonly<Bind.interface_ImVec2>, stride?: number): void;
export function PlotLines<T>(label: string, values_getter: PlotLinesValueGetter<T>, data: T, values_count?: number, value_offset?: number, overlay_text?: string | null, scale_min?: number, scale_max?: number, graph_size?: Readonly<Bind.interface_ImVec2>): void;
export function PlotLines<T>(label: string, ...args: any[]): void {
if (Array.isArray(args[0])) {
const values: ArrayLike<number> = args[0];
const values_getter: PlotLinesValueGetter<null> = (data: null, idx: number): number => values[idx * stride];
const values_count: number = typeof(args[1]) === "number" ? args[1] : values.length;
const values_offset: number = typeof(args[2]) === "number" ? args[2] : 0;
const overlay_text: string | null = typeof(args[3]) === "string" ? args[3] : null;
const scale_min: number = typeof(args[4]) === "number" ? args[4] : Number.MAX_VALUE;
const scale_max: number = typeof(args[5]) === "number" ? args[5] : Number.MAX_VALUE;
const graph_size: Readonly<Bind.interface_ImVec2> = args[6] || ImVec2.ZERO;
const stride: number = typeof(args[7]) === "number" ? args[7] : 1;
bind.PlotLines(label, values_getter, null, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
} else {
const values_getter: PlotLinesValueGetter<T> = args[0];
const data: any = args[1];
const values_count: number = args[2];
const values_offset: number = typeof(args[3]) === "number" ? args[3] : 0;
const overlay_text: string | null = typeof(args[4]) === "string" ? args[4] : null;
const scale_min: number = typeof(args[5]) === "number" ? args[5] : Number.MAX_VALUE;
const scale_max: number = typeof(args[6]) === "number" ? args[6] : Number.MAX_VALUE;
const graph_size: Readonly<Bind.interface_ImVec2> = args[7] || ImVec2.ZERO;
bind.PlotLines(label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
}
}
export type PlotHistogramValueGetter<T> = (data: T, idx: number) => number;
export function PlotHistogram(label: string, values: ArrayLike<number>, values_count?: number, value_offset?: number, overlay_text?: string | null, scale_min?: number, scale_max?: number, graph_size?: Readonly<Bind.interface_ImVec2>, stride?: number): void;
export function PlotHistogram<T>(label: string, values_getter: PlotHistogramValueGetter<T>, data: T, values_count?: number, value_offset?: number, overlay_text?: string | null, scale_min?: number, scale_max?: number, graph_size?: Readonly<Bind.interface_ImVec2>): void;
export function PlotHistogram<T>(label: string, ...args: any[]): void {
if (Array.isArray(args[0])) {
const values: ArrayLike<number> = args[0];
const values_getter: PlotHistogramValueGetter<null> = (data: null, idx: number): number => values[idx * stride];
const values_count: number = typeof(args[1]) === "number" ? args[1] : values.length;
const values_offset: number = typeof(args[2]) === "number" ? args[2] : 0;
const overlay_text: string | null = typeof(args[3]) === "string" ? args[3] : null;
const scale_min: number = typeof(args[4]) === "number" ? args[4] : Number.MAX_VALUE;
const scale_max: number = typeof(args[5]) === "number" ? args[5] : Number.MAX_VALUE;
const graph_size: Readonly<Bind.interface_ImVec2> = args[6] || ImVec2.ZERO;
const stride: number = typeof(args[7]) === "number" ? args[7] : 1;
bind.PlotHistogram(label, values_getter, null, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
} else {
const values_getter: PlotHistogramValueGetter<T> = args[0];
const data: T = args[1];
const values_count: number = args[2];
const values_offset: number = typeof(args[3]) === "number" ? args[3] : 0;
const overlay_text: string | null = typeof(args[4]) === "string" ? args[4] : null;
const scale_min: number = typeof(args[5]) === "number" ? args[5] : Number.MAX_VALUE;
const scale_max: number = typeof(args[6]) === "number" ? args[6] : Number.MAX_VALUE;
const graph_size: Readonly<Bind.interface_ImVec2> = args[7] || ImVec2.ZERO;
bind.PlotHistogram(label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
}
}
// Widgets: Value() Helpers.
// - Those are merely shortcut to calling Text() with a format string. Output single value in "name: value" format (tip: freely declare more in your code to handle your types. you can add functions to the ImGui namespace)
// IMGUI_API void Value(const char* prefix, bool b);
// IMGUI_API void Value(const char* prefix, int v);
// IMGUI_API void Value(const char* prefix, unsigned int v);
// IMGUI_API void Value(const char* prefix, float v, const char* float_format = NULL);
export function Value(prefix: string, b: boolean): void;
export function Value(prefix: string, v: number): void;
export function Value(prefix: string, v: number, float_format?: string | null): void;
export function Value(prefix: string, v: any): void;
export function Value(prefix: string, ...args: any[]): void {
if (typeof(args[0]) === "boolean") {
bind.Value_A(prefix, args[0]);
} else if (typeof(args[0]) === "number") {
if (Number.isInteger(args[0])) {
bind.Value_B(prefix, args[0]);
} else {
bind.Value_D(prefix, args[0], typeof(args[1]) === "string" ? args[1] : null);
}
} else {
bind.Text(prefix + String(args[0]));
}
}
// Widgets: Menus
// - Use BeginMenuBar() on a window ImGuiWindowFlags_MenuBar to append to its menu bar.
// - Use BeginMainMenuBar() to create a menu bar at the top of the screen and append to it.
// - Use BeginMenu() to create a menu. You can call BeginMenu() multiple time with the same identifier to append more items to it.
// IMGUI_API bool BeginMenuBar(); // append to menu-bar of current window (requires ImGuiWindowFlags_MenuBar flag set on parent window).
// IMGUI_API void EndMenuBar(); // only call EndMenuBar() if BeginMenuBar() returns true!
// IMGUI_API bool BeginMainMenuBar(); // create and append to a full screen menu-bar.
// IMGUI_API void EndMainMenuBar(); // only call EndMainMenuBar() if BeginMainMenuBar() returns true!
// IMGUI_API bool BeginMenu(const char* label, bool enabled = true); // create a sub-menu entry. only call EndMenu() if this returns true!
// IMGUI_API void EndMenu(); // only call EndMenu() if BeginMenu() returns true!
// IMGUI_API bool MenuItem(const char* label, const char* shortcut = NULL, bool selected = false, bool enabled = true); // return true when activated. shortcuts are displayed for convenience but not processed by ImGui at the moment
// IMGUI_API bool MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled = true); // return true when activated + toggle (*p_selected) if p_selected != NULL
export function BeginMenuBar(): boolean { return bind.BeginMenuBar(); }
export function EndMenuBar(): void { bind.EndMenuBar(); }
export function BeginMainMenuBar(): boolean { return bind.BeginMainMenuBar(); }
export function EndMainMenuBar(): void { bind.EndMainMenuBar(); }
export function BeginMenu(label: string, enabled: boolean = true): boolean { return bind.BeginMenu(label, enabled); }
export function EndMenu(): void { bind.EndMenu(); }
export function MenuItem(label: string, shortcut?: string | null, selected?: boolean, enabled?: boolean): boolean;
export function MenuItem(label: string, shortcut: string | null, p_selected: Bind.ImScalar<boolean> | Bind.ImAccess<boolean> | null, enabled?: boolean): boolean;
export function MenuItem(label: string, ...args: any[]): boolean {
if (args.length === 0) {
return bind.MenuItem_A(label, null, false, true);
} else if (args.length === 1) {
const shortcut: string | null = args[0];
return bind.MenuItem_A(label, shortcut, false, true);
} else {
const shortcut: string | null = args[0];
if (typeof(args[1]) === "boolean") {
const selected: boolean = args[1];
const enabled: boolean = typeof(args[2]) === "boolean" ? args[2] : true;
return bind.MenuItem_A(label, shortcut, selected, enabled);
} else {
const p_selected: Bind.ImScalar<boolean> | Bind.ImAccess<boolean> = args[1];
const enabled: boolean = typeof(args[2]) === "boolean" ? args[2] : true;
const ref_selected: Bind.ImScalar<boolean> = Array.isArray(p_selected) ? p_selected : [ p_selected() ];
const ret = bind.MenuItem_B(label, shortcut, ref_selected, enabled);
if (!Array.isArray(p_selected)) { p_selected(ref_selected[0]); }
return ret;
}
}
}
// Tooltips
// - Tooltip are windows following the mouse. They do not take focus away.
// IMGUI_API void BeginTooltip(); // begin/append a tooltip window. to create full-featured tooltip (with any kind of items).
// IMGUI_API void EndTooltip();
// IMGUI_API void SetTooltip(const char* fmt, ...) IM_FMTARGS(1); // set a text-only tooltip, typically use with ImGui::IsItemHovered(). override any previous call to SetTooltip().
// IMGUI_API void SetTooltipV(const char* fmt, va_list args) IM_FMTLIST(1);
export function BeginTooltip(): void { bind.BeginTooltip(); }
export function EndTooltip(): void { bind.EndTooltip(); }
export function SetTooltip(fmt: string): void { bind.SetTooltip(fmt); }
// Popups, Modals
// - They block normal mouse hovering detection (and therefore most mouse interactions) behind them.
// - If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE.
// - Their visibility state (~bool) is held internally instead of being held by the programmer as we are used to with regular Begin*() calls.
// - The 3 properties above are related: we need to retain popup visibility state in the library because popups may be closed as any time.
// - You can bypass the hovering restriction by using ImGuiHoveredFlags_AllowWhenBlockedByPopup when calling IsItemHovered() or IsWindowHovered().
// - IMPORTANT: Popup identifiers are relative to the current ID stack, so OpenPopup and BeginPopup generally needs to be at the same level of the stack.
// This is sometimes leading to confusing mistakes. May rework this in the future.
// Popups: begin/end functions
// - BeginPopup(): query popup state, if open start appending into the window. Call EndPopup() afterwards. ImGuiWindowFlags are forwarded to the window.
// - BeginPopupModal(): block every interactions behind the window, cannot be closed by user, add a dimming background, has a title bar.
// IMGUI_API bool BeginPopup(const char* str_id, ImGuiWindowFlags flags = 0); // return true if the popup is open, and you can start outputting to it.
// IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // return true if the modal is open, and you can start outputting to it.
// IMGUI_API void EndPopup(); // only call EndPopup() if BeginPopupXXX() returns true!
export function BeginPopup(str_id: string, flags: ImGuiWindowFlags = 0): boolean { return bind.BeginPopup(str_id, flags); }
export function BeginPopupModal(str_id: string, p_open: Bind.ImScalar<boolean> | Bind.ImAccess<boolean> | null = null, flags: ImGuiWindowFlags = 0): boolean {
if (Array.isArray(p_open)) {
return bind.BeginPopupModal(str_id, p_open, flags);
} else if (typeof(p_open) === "function") {
const _p_open: Bind.ImScalar<boolean> = [ p_open() ];
const ret = bind.BeginPopupModal(str_id, _p_open, flags);
p_open(_p_open[0]);
return ret;
} else {
return bind.BeginPopupModal(str_id, null, flags);
}
}
export function EndPopup(): void { bind.EndPopup(); }
// Popups: open/close functions
// - OpenPopup(): set popup state to open. ImGuiPopupFlags are available for opening options.
// - If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE.
// - CloseCurrentPopup(): use inside the BeginPopup()/EndPopup() scope to close manually.
// - CloseCurrentPopup() is called by default by Selectable()/MenuItem() when activated (FIXME: need some options).
// - Use ImGuiPopupFlags_NoOpenOverExistingPopup to avoid opening a popup if there's already one at the same level. This is equivalent to e.g. testing for !IsAnyPopupOpen() prior to OpenPopup().
// IMGUI_API void OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags = 0); // call to mark popup as open (don't call every frame!).
// IMGUI_API void OpenPopupOnItemClick(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // helper to open popup when clicked on last item. return true when just opened. (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors)
// IMGUI_API void CloseCurrentPopup(); // manually close the popup we have begin-ed into.
export function OpenPopup(str_id: string, popup_flags: ImGuiPopupFlags = 0): void { bind.OpenPopup(str_id, popup_flags); }
export function OpenPopupOnItemClick(str_id: string | null = null, popup_flags: ImGuiPopupFlags = 1): void { bind.OpenPopupOnItemClick(str_id, popup_flags); }
export function CloseCurrentPopup(): void { bind.CloseCurrentPopup(); }
// Popups: open+begin combined functions helpers
// - Helpers to do OpenPopup+BeginPopup where the Open action is triggered by e.g. hovering an item and right-clicking.
// - They are convenient to easily create context menus, hence the name.
// - IMPORTANT: Notice that BeginPopupContextXXX takes ImGuiPopupFlags just like OpenPopup() and unlike BeginPopup(). For full consistency, we may add ImGuiWindowFlags to the BeginPopupContextXXX functions in the future.
// - IMPORTANT: we exceptionally default their flags to 1 (== ImGuiPopupFlags_MouseButtonRight) for backward compatibility with older API taking 'int mouse_button = 1' parameter, so if you add other flags remember to re-add the ImGuiPopupFlags_MouseButtonRight.
// IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // open+begin popup when clicked on last item. if you can pass a NULL str_id only if the previous item had an id. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp!
// IMGUI_API bool BeginPopupContextWindow(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1);// open+begin popup when clicked on current window.
// IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // open+begin popup when clicked in void (where there are no windows).
export function BeginPopupContextItem(str_id: string | null = null, popup_flags: ImGuiPopupFlags = 1): boolean { return bind.BeginPopupContextItem(str_id, popup_flags); }
export function BeginPopupContextWindow(str_id: string | null = null, popup_flags: ImGuiPopupFlags = 1): boolean { return bind.BeginPopupContextWindow(str_id, popup_flags); }
export function BeginPopupContextVoid(str_id: string | null = null, popup_flags: ImGuiPopupFlags = 1): boolean { return bind.BeginPopupContextVoid(str_id, popup_flags); }
// Popups: test function
// - IsPopupOpen(): return true if the popup is open at the current BeginPopup() level of the popup stack.
// - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId: return true if any popup is open at the current BeginPopup() level of the popup stack.
// - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId + ImGuiPopupFlags_AnyPopupLevel: return true if any popup is open.
// IMGUI_API bool IsPopupOpen(const char* str_id, ImGuiPopupFlags flags = 0); // return true if the popup is open.
export function IsPopupOpen(str_id: string, flags: ImGuiPopupFlags = 0): boolean { return bind.IsPopupOpen(str_id, flags); }
// Tables
// [BETA API] API may evolve slightly! If you use this, please update to the next version when it comes out!
// - Full-featured replacement for old Columns API.
// - See Demo->Tables for demo code.
// - See top of imgui_tables.cpp for general commentary.
// - See ImGuiTableFlags_ and ImGuiTableColumnFlags_ enums for a description of available flags.
// The typical call flow is:
// - 1. Call BeginTable().
// - 2. Optionally call TableSetupColumn() to submit column name/flags/defaults.
// - 3. Optionally call TableSetupScrollFreeze() to request scroll freezing of columns/rows.
// - 4. Optionally call TableHeadersRow() to submit a header row. Names are pulled from TableSetupColumn() data.
// - 5. Populate contents:
// - In most situations you can use TableNextRow() + TableSetColumnIndex(N) to start appending into a column.
// - If you are using tables as a sort of grid, where every columns is holding the same type of contents,
// you may prefer using TableNextColumn() instead of TableNextRow() + TableSetColumnIndex().
// TableNextColumn() will automatically wrap-around into the next row if needed.
// - IMPORTANT: Comparatively to the old Columns() API, we need to call TableNextColumn() for the first column!
// - Summary of possible call flow:
// --------------------------------------------------------------------------------------------------------
// TableNextRow() -> TableSetColumnIndex(0) -> Text("Hello 0") -> TableSetColumnIndex(1) -> Text("Hello 1") // OK
// TableNextRow() -> TableNextColumn() -> Text("Hello 0") -> TableNextColumn() -> Text("Hello 1") // OK
// TableNextColumn() -> Text("Hello 0") -> TableNextColumn() -> Text("Hello 1") // OK: TableNextColumn() automatically gets to next row!
// TableNextRow() -> Text("Hello 0") // Not OK! Missing TableSetColumnIndex() or TableNextColumn()! Text will not appear!
// --------------------------------------------------------------------------------------------------------
// - 5. Call EndTable()
// IMGUI_API bool BeginTable(const char* str_id, int column, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0.0f, 0.0f), float inner_width = 0.0f);
// IMGUI_API void EndTable(); // only call EndTable() if BeginTable() returns true!
// IMGUI_API void TableNextRow(ImGuiTableRowFlags row_flags = 0, float min_row_height = 0.0f); // append into the first cell of a new row.
// IMGUI_API bool TableNextColumn(); // append into the next column (or first column of next row if currently in last column). Return true when column is visible.
// IMGUI_API bool TableSetColumnIndex(int column_n); // append into the specified column. Return true when column is visible.
export function BeginTable(str_id: string, column: number, flags: ImGuiTableFlags = 0, outer_size: Bind.interface_ImVec2 = ImVec2.ZERO, inner_width: number = 0.0): boolean { return bind.BeginTable(str_id, column, flags, outer_size, inner_width); }
export function EndTable(): void { bind.EndTable(); }
export function TableNextRow(row_flags: ImGuiTableRowFlags = 0, min_row_height: number = 0.0): void { bind.TableNextRow(row_flags, min_row_height); }
export function TableNextColumn(): boolean { return bind.TableNextColumn(); }
export function TableSetColumnIndex(column_n: number): boolean { return bind.TableSetColumnIndex(column_n); }
// Tables: Headers & Columns declaration
// - Use TableSetupColumn() to specify label, resizing policy, default width/weight, id, various other flags etc.
// - Use TableHeadersRow() to create a header row and automatically submit a TableHeader() for each column.
// Headers are required to perform: reordering, sorting, and opening the context menu.
// The context menu can also be made available in columns body using ImGuiTableFlags_ContextMenuInBody.
// - You may manually submit headers using TableNextRow() + TableHeader() calls, but this is only useful in
// some advanced use cases (e.g. adding custom widgets in header row).
// - Use TableSetupScrollFreeze() to lock columns/rows so they stay visible when scrolled.
// IMGUI_API void TableSetupColumn(const char* label, ImGuiTableColumnFlags flags = 0, float init_width_or_weight = 0.0f, ImU32 user_id = 0);
// IMGUI_API void TableSetupScrollFreeze(int cols, int rows); // lock columns/rows so they stay visible when scrolled.
// IMGUI_API void TableHeadersRow(); // submit all headers cells based on data provided to TableSetupColumn() + submit context menu
// IMGUI_API void TableHeader(const char* label); // submit one header cell manually (rarely used)
export function TableSetupColumn(label: string, flags: ImGuiTableColumnFlags = 0, init_width_or_weight: number = 0.0, user_id: Bind.ImU32 = 0): void { bind.TableSetupColumn(label, flags, init_width_or_weight, user_id); }
export function TableSetupScrollFreeze(cols: number, rows: number): void { bind.TableSetupScrollFreeze(cols, rows); }
export function TableHeadersRow(): void { bind.TableHeadersRow(); }
export function TableHeader(label: string): void { bind.TableHeader(label); }
// Tables: Sorting
// - Call TableGetSortSpecs() to retrieve latest sort specs for the table. NULL when not sorting.
// - When 'SpecsDirty == true' you should sort your data. It will be true when sorting specs have changed
// since last call, or the first time. Make sure to set 'SpecsDirty = false' after sorting, else you may
// wastefully sort your data every frame!
// - Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable().
// IMGUI_API ImGuiTableSortSpecs* TableGetSortSpecs(); // get latest sort specs for the table (NULL if not sorting).
export function TableGetSortSpecs(): ImGuiTableSortSpecs | null {
const sort_specs: Bind.reference_ImGuiTableSortSpecs | null = bind.TableGetSortSpecs();
return (sort_specs === null) ? null : new ImGuiTableSortSpecs(sort_specs);
}
// Tables: Miscellaneous functions
// - Functions args 'int column_n' treat the default value of -1 as the same as passing the current column index.
// IMGUI_API int TableGetColumnCount(); // return number of columns (value passed to BeginTable)
// IMGUI_API int TableGetColumnIndex(); // return current column index.
// IMGUI_API int TableGetRowIndex(); // return current row index.
// IMGUI_API const char* TableGetColumnName(int column_n = -1); // return "" if column didn't have a name declared by TableSetupColumn(). Pass -1 to use current column.
// IMGUI_API ImGuiTableColumnFlags TableGetColumnFlags(int column_n = -1); // return column flags so you can query their Enabled/Visible/Sorted/Hovered status flags. Pass -1 to use current column.
// IMGUI_API void TableSetBgColor(ImGuiTableBgTarget target, ImU32 color, int column_n = -1); // change the color of a cell, row, or column. See ImGuiTableBgTarget_ flags for details.
export function TableGetColumnCount(): number { return bind.TableGetColumnCount(); }
export function TableGetColumnIndex(): number { return bind.TableGetColumnIndex(); }
export function TableGetRowIndex(): number { return bind.TableGetRowIndex(); }
export function TableGetColumnName(column_n: number = -1): string { return bind.TableGetColumnName(column_n); }
export function TableGetColumnFlags(column_n: number = -1): ImGuiTableColumnFlags { return bind.TableGetColumnFlags(column_n); }
export function TableSetBgColor(target: ImGuiTableBgTarget, color: Bind.ImU32, column_n: number = -1) { bind.TableSetBgColor(target, color, column_n); }
// Legacy Columns API (2020: prefer using Tables!)
// - You can also use SameLine(pos_x) to mimic simplified columns.
// IMGUI_API void Columns(int count = 1, const char* id = NULL, bool border = true);
// IMGUI_API void NextColumn(); // next column, defaults to current row or next row if the current row is finished
// IMGUI_API int GetColumnIndex(); // get current column index
// IMGUI_API float GetColumnWidth(int column_index = -1); // get column width (in pixels). pass -1 to use current column
// IMGUI_API void SetColumnWidth(int column_index, float width); // set column width (in pixels). pass -1 to use current column
// IMGUI_API float GetColumnOffset(int column_index = -1); // get position of column line (in pixels, from the left side of the contents region). pass -1 to use current column, otherwise 0..GetColumnsCount() inclusive. column 0 is typically 0.0f
// IMGUI_API void SetColumnOffset(int column_index, float offset_x); // set position of column line (in pixels, from the left side of the contents region). pass -1 to use current column
// IMGUI_API int GetColumnsCount();
export function Columns(count: number = 1, id: string | null = null, border: boolean = true): void { bind.Columns(count, id, border); }
export function NextColumn(): void { bind.NextColumn(); }
export function GetColumnIndex(): number { return bind.GetColumnIndex(); }
export function GetColumnWidth(column_index: number = -1): number { return bind.GetColumnWidth(column_index); }
export function SetColumnWidth(column_index: number, width: number): void { bind.SetColumnWidth(column_index, width); }
export function GetColumnOffset(column_index: number = -1): number { return bind.GetColumnOffset(column_index); }
export function SetColumnOffset(column_index: number, offset_x: number): void { bind.SetColumnOffset(column_index, offset_x); }
export function GetColumnsCount(): number { return bind.GetColumnsCount(); }
// Tab Bars, Tabs
// IMGUI_API bool BeginTabBar(const char* str_id, ImGuiTabBarFlags flags = 0); // create and append into a TabBar
// IMGUI_API void EndTabBar(); // only call EndTabBar() if BeginTabBar() returns true!
// IMGUI_API bool BeginTabItem(const char* label, bool* p_open = NULL, ImGuiTabItemFlags flags = 0); // create a Tab. Returns true if the Tab is selected.
// IMGUI_API void EndTabItem(); // only call EndTabItem() if BeginTabItem() returns true!
// IMGUI_API bool TabItemButton(const char* label, ImGuiTabItemFlags flags = 0); // create a Tab behaving like a button. return true when clicked. cannot be selected in the tab bar.
// IMGUI_API void SetTabItemClosed(const char* tab_or_docked_window_label); // notify TabBar or Docking system of a closed tab/window ahead (useful to reduce visual flicker on reorderable tab bars). For tab-bar: call after BeginTabBar() and before Tab submissions. Otherwise call with a window name.
export function BeginTabBar(str_id: string, flags: ImGuiTabBarFlags = 0): boolean { return bind.BeginTabBar(str_id, flags); }
export function EndTabBar(): void { bind.EndTabBar(); }
export function BeginTabItem(label: string, p_open: Bind.ImScalar<boolean> | Bind.ImAccess<boolean> | null = null, flags: ImGuiTabItemFlags = 0): boolean {
if (p_open === null) {
return bind.BeginTabItem(label, null, flags);
} else if (Array.isArray(p_open)) {
return bind.BeginTabItem(label, p_open, flags);
} else {
const ref_open: Bind.ImScalar<boolean> = [ p_open() ];
const ret = bind.BeginTabItem(label, ref_open, flags);
p_open(ref_open[0]);
return ret;
}
}
export function EndTabItem(): void { bind.EndTabItem(); }
export function TabItemButton(label: string, flags: ImGuiTabItemFlags = 0): boolean { return bind.TabItemButton(label, flags); }
export function SetTabItemClosed(tab_or_docked_window_label: string): void { bind.SetTabItemClosed(tab_or_docked_window_label); }
// Logging/Capture
// - All text output from the interface can be captured into tty/file/clipboard. By default, tree nodes are automatically opened during logging.
// IMGUI_API void LogToTTY(int auto_open_depth = -1); // start logging to tty (stdout)
// IMGUI_API void LogToFile(int auto_open_depth = -1, const char* filename = NULL); // start logging to file
// IMGUI_API void LogToClipboard(int auto_open_depth = -1); // start logging to OS clipboard
// IMGUI_API void LogFinish(); // stop logging (close file, etc.)
// IMGUI_API void LogButtons(); // helper to display buttons for logging to tty/file/clipboard
// IMGUI_API void LogText(const char* fmt, ...) IM_FMTARGS(1); // pass text data straight to log (without being displayed)
export function LogToTTY(max_depth: number = -1): void { bind.LogToTTY(max_depth); }
export function LogToFile(max_depth: number = -1, filename: string | null = null): void { bind.LogToFile(max_depth, filename); }
export function LogToClipboard(max_depth: number = -1): void { bind.LogToClipboard(max_depth); }
export function LogFinish(): void { bind.LogFinish(); }
export function LogButtons(): void { bind.LogButtons(); }
export function LogText(fmt: string): void { bind.LogText(fmt); }
// Drag and Drop
// - If you stop calling BeginDragDropSource() the payload is preserved however it won't have a preview tooltip (we currently display a fallback "..." tooltip as replacement)
// IMGUI_API bool BeginDragDropSource(ImGuiDragDropFlags flags = 0); // call when the current item is active. If this return true, you can call SetDragDropPayload() + EndDragDropSource()
// IMGUI_API bool SetDragDropPayload(const char* type, const void* data, size_t sz, ImGuiCond cond = 0); // type is a user defined string of maximum 32 characters. Strings starting with '_' are reserved for dear imgui internal types. Data is copied and held by imgui.
// IMGUI_API void EndDragDropSource(); // only call EndDragDropSource() if BeginDragDropSource() returns true!
// IMGUI_API bool BeginDragDropTarget(); // call after submitting an item that may receive a payload. If this returns true, you can call AcceptDragDropPayload() + EndDragDropTarget()
// IMGUI_API const ImGuiPayload* AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags = 0); // accept contents of a given type. If ImGuiDragDropFlags_AcceptBeforeDelivery is set you can peek into the payload before the mouse button is released.
// IMGUI_API void EndDragDropTarget(); // only call EndDragDropTarget() if BeginDragDropTarget() returns true!
// IMGUI_API const ImGuiPayload* GetDragDropPayload(); // peek directly into the current payload from anywhere. may return NULL. use ImGuiPayload::IsDataType() to test for the payload type.
const _ImGui_DragDropPayload_data: {[key: string]: any} = {};
export function BeginDragDropSource(flags: ImGuiDragDropFlags = 0): boolean {
return bind.BeginDragDropSource(flags);
}
export function SetDragDropPayload<T>(type: string, data: T, cond: ImGuiCond = 0): boolean {
_ImGui_DragDropPayload_data[type] = data;
return bind.SetDragDropPayload(type, data, 0, cond);
}
export function EndDragDropSource(): void {
bind.EndDragDropSource();
}
export function BeginDragDropTarget(): boolean {
return bind.BeginDragDropTarget();
}
export function AcceptDragDropPayload<T>(type: string, flags: ImGuiDragDropFlags = 0): ImGuiPayload<T> | null {
const data: T = _ImGui_DragDropPayload_data[type];
return bind.AcceptDragDropPayload(type, flags) ? { Data: data } : null;
}
export function EndDragDropTarget(): void {
bind.EndDragDropTarget();
}
export function GetDragDropPayload<T>(): ImGuiPayload<T> | null {
return bind.GetDragDropPayload();
}
// Clipping
// - Mouse hovering is affected by ImGui::PushClipRect() calls, unlike direct calls to ImDrawList::PushClipRect() which are render only.
// IMGUI_API void PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect);
// IMGUI_API void PopClipRect();
export function PushClipRect(clip_rect_min: Readonly<Bind.interface_ImVec2>, clip_rect_max: Readonly<Bind.interface_ImVec2>, intersect_with_current_clip_rect: boolean): void {
bind.PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
}
export function PopClipRect(): void {
bind.PopClipRect();
}
// Focus, Activation
// - Prefer using "SetItemDefaultFocus()" over "if (IsWindowAppearing()) SetScrollHereY()" when applicable to signify "this is the default item"
// IMGUI_API void SetItemDefaultFocus(); // make last item the default focused item of a window.
// IMGUI_API void SetKeyboardFocusHere(int offset = 0); // focus keyboard on the next widget. Use positive 'offset' to access sub components of a multiple component widget. Use -1 to access previous widget.
export function SetItemDefaultFocus(): void { bind.SetItemDefaultFocus(); }
export function SetKeyboardFocusHere(offset: number = 0): void { bind.SetKeyboardFocusHere(offset); }
// Item/Widgets Utilities
// - Most of the functions are referring to the last/previous item we submitted.
// - See Demo Window under "Widgets->Querying Status" for an interactive visualization of most of those functions.
// IMGUI_API bool IsItemHovered(ImGuiHoveredFlags flags = 0); // is the last item hovered? (and usable, aka not blocked by a popup, etc.). See ImGuiHoveredFlags for more options.
// IMGUI_API bool IsItemActive(); // is the last item active? (e.g. button being held, text field being edited. This will continuously return true while holding mouse button on an item. Items that don't interact will always return false)
// IMGUI_API bool IsItemFocused(); // is the last item focused for keyboard/gamepad navigation?
// IMGUI_API bool IsItemClicked(ImGuiMouseButton mouse_button = 0); // is the last item clicked? (e.g. button/node just clicked on) == IsMouseClicked(mouse_button) && IsItemHovered()
// IMGUI_API bool IsItemVisible(); // is the last item visible? (items may be out of sight because of clipping/scrolling)
// IMGUI_API bool IsItemEdited(); // did the last item modify its underlying value this frame? or was pressed? This is generally the same as the "bool" return value of many widgets.
// IMGUI_API bool IsItemActivated(); // was the last item just made active (item was previously inactive).
// IMGUI_API bool IsItemDeactivated(); // was the last item just made inactive (item was previously active). Useful for Undo/Redo patterns with widgets that requires continuous editing.
// IMGUI_API bool IsItemDeactivatedAfterEdit(); // was the last item just made inactive and made a value change when it was active? (e.g. Slider/Drag moved). Useful for Undo/Redo patterns with widgets that requires continuous editing. Note that you may get false positives (some widgets such as Combo()/ListBox()/Selectable() will return true even when clicking an already selected item).
// IMGUI_API bool IsItemToggledOpen(); // was the last item open state toggled? set by TreeNode().
// IMGUI_API bool IsAnyItemHovered(); // is any item hovered?
// IMGUI_API bool IsAnyItemActive(); // is any item active?
// IMGUI_API bool IsAnyItemFocused(); // is any item focused?
// IMGUI_API ImVec2 GetItemRectMin(); // get upper-left bounding rectangle of the last item (screen space)
// IMGUI_API ImVec2 GetItemRectMax(); // get lower-right bounding rectangle of the last item (screen space)
// IMGUI_API ImVec2 GetItemRectSize(); // get size of last item
// IMGUI_API void SetItemAllowOverlap(); // allow last item to be overlapped by a subsequent item. sometimes useful with invisible buttons, selectables, etc. to catch unused area.
export function IsItemHovered(flags: ImGuiHoveredFlags = 0): boolean { return bind.IsItemHovered(flags); }
export function IsItemActive(): boolean { return bind.IsItemActive(); }
export function IsItemFocused(): boolean { return bind.IsItemFocused(); }
export function IsItemClicked(mouse_button: ImGuiMouseButton = 0): boolean { return bind.IsItemClicked(mouse_button); }
export function IsItemVisible(): boolean { return bind.IsItemVisible(); }
export function IsItemEdited(): boolean { return bind.IsItemEdited(); }
export function IsItemActivated(): boolean { return bind.IsItemActivated(); }
export function IsItemDeactivated(): boolean { return bind.IsItemDeactivated(); }
export function IsItemDeactivatedAfterEdit(): boolean { return bind.IsItemDeactivatedAfterEdit(); }
export function IsItemToggledOpen(): boolean { return bind.IsItemToggledOpen(); }
export function IsAnyItemHovered(): boolean { return bind.IsAnyItemHovered(); }
export function IsAnyItemActive(): boolean { return bind.IsAnyItemActive(); }
export function IsAnyItemFocused(): boolean { return bind.IsAnyItemFocused(); }
export function GetItemRectMin(out: Bind.interface_ImVec2 = new ImVec2()): Bind.interface_ImVec2 { return bind.GetItemRectMin(out); }
export function GetItemRectMax(out: Bind.interface_ImVec2 = new ImVec2()): Bind.interface_ImVec2 { return bind.GetItemRectMax(out); }
export function GetItemRectSize(out: Bind.interface_ImVec2 = new ImVec2()): Bind.interface_ImVec2 { return bind.GetItemRectSize(out); }
export function SetItemAllowOverlap(): void { bind.SetItemAllowOverlap(); }
// Miscellaneous Utilities
// IMGUI_API bool IsRectVisible(const ImVec2& size); // test if rectangle (of given size, starting from cursor position) is visible / not clipped.
// IMGUI_API bool IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max); // test if rectangle (in screen space) is visible / not clipped. to perform coarse clipping on user's side.
// IMGUI_API double GetTime(); // get global imgui time. incremented by io.DeltaTime every frame.
// IMGUI_API int GetFrameCount(); // get global imgui frame count. incremented by 1 every frame.
// IMGUI_API ImDrawList* GetBackgroundDrawList(); // this draw list will be the first rendering one. Useful to quickly draw shapes/text behind dear imgui contents.
// IMGUI_API ImDrawList* GetForegroundDrawList(); // this draw list will be the last rendered one. Useful to quickly draw shapes/text over dear imgui contents.
// IMGUI_API ImDrawListSharedData* GetDrawListSharedData(); // you may use this when creating your own ImDrawList instances.
// IMGUI_API const char* GetStyleColorName(ImGuiCol idx); // get a string corresponding to the enum value (for display, saving, etc.).
// IMGUI_API void SetStateStorage(ImGuiStorage* storage); // replace current window storage with our own (if you want to manipulate it yourself, typically clear subsection of it)
// IMGUI_API ImGuiStorage* GetStateStorage();
// IMGUI_API void CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end); // calculate coarse clipping for large list of evenly sized items. Prefer using the ImGuiListClipper higher-level helper if you can.
// IMGUI_API bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags flags = 0); // helper to create a child window / scrolling region that looks like a normal widget frame
// IMGUI_API void EndChildFrame(); // always call EndChildFrame() regardless of BeginChildFrame() return values (which indicates a collapsed/clipped window)
export function IsRectVisible(size: Readonly<Bind.interface_ImVec2>): boolean;
export function IsRectVisible(rect_min: Readonly<Bind.interface_ImVec2>, rect_max: Readonly<Bind.interface_ImVec2>): boolean;
export function IsRectVisible(...args: any[]): boolean {
if (args.length === 1) {
const size: Readonly<Bind.interface_ImVec2> = args[0];
return bind.IsRectVisible_A(size);
} else {
const rect_min: Readonly<Bind.interface_ImVec2> = args[0];
const rect_max: Readonly<Bind.interface_ImVec2> = args[1];
return bind.IsRectVisible_B(rect_min, rect_max);
}
}
export function GetTime(): number { return bind.GetTime(); }
export function GetFrameCount(): number { return bind.GetFrameCount(); }
export function GetBackgroundDrawList(): ImDrawList {
return new ImDrawList(bind.GetBackgroundDrawList());
}
export function GetForegroundDrawList(): ImDrawList {
return new ImDrawList(bind.GetForegroundDrawList());
}
export function GetDrawListSharedData(): ImDrawListSharedData {
return new ImDrawListSharedData(bind.GetDrawListSharedData());
}
export function GetStyleColorName(idx: ImGuiCol): string { return bind.GetStyleColorName(idx); }
// IMGUI_API void SetStateStorage(ImGuiStorage* tree);
// IMGUI_API ImGuiStorage* GetStateStorage();
export function CalcListClipping(items_count: number, items_height: number, out_items_display_start: Bind.ImScalar<number>, out_items_display_end: Bind.ImScalar<number>): void {
return bind.CalcListClipping(items_count, items_height, out_items_display_start, out_items_display_end);
}
export function BeginChildFrame(id: ImGuiID, size: Readonly<Bind.interface_ImVec2>, flags: ImGuiWindowFlags = 0): boolean { return bind.BeginChildFrame(id, size, flags); }
export function EndChildFrame(): void { bind.EndChildFrame(); }
// Text Utilities
// IMGUI_API ImVec2 CalcTextSize(const char* text, const char* text_end = NULL, bool hide_text_after_double_hash = false, float wrap_width = -1.0f);
export function CalcTextSize(text: string, text_end: number | null = null, hide_text_after_double_hash: boolean = false, wrap_width: number = -1, out: Bind.interface_ImVec2 = new ImVec2()): Bind.interface_ImVec2 {
return bind.CalcTextSize(text_end !== null ? text.substring(0, text_end) : text, hide_text_after_double_hash, wrap_width, out);
}
// Color Utilities
// IMGUI_API ImVec4 ColorConvertU32ToFloat4(ImU32 in);
// IMGUI_API ImU32 ColorConvertFloat4ToU32(const ImVec4& in);
// IMGUI_API void ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v);
// IMGUI_API void ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b);
export function ColorConvertU32ToFloat4(in_: Bind.ImU32, out: Bind.interface_ImVec4 = new ImVec4()): Bind.interface_ImVec4 { return bind.ColorConvertU32ToFloat4(in_, out); }
export function ColorConvertFloat4ToU32(in_: Readonly<Bind.interface_ImVec4>): Bind.ImU32 { return bind.ColorConvertFloat4ToU32(in_); }
export function ColorConvertRGBtoHSV(r: number, g: number, b: number, out_h: Bind.ImScalar<number>, out_s: Bind.ImScalar<number>, out_v: Bind.ImScalar<number>): void { bind.ColorConvertRGBtoHSV(r, g, b, out_h, out_s, out_v); }
export function ColorConvertHSVtoRGB(h: number, s: number, v: number, out_r: Bind.ImScalar<number>, out_g: Bind.ImScalar<number>, out_b: Bind.ImScalar<number>): void { bind.ColorConvertHSVtoRGB(h, s, v, out_r, out_g, out_b); }
// Inputs Utilities: Keyboard
// - For 'int user_key_index' you can use your own indices/enums according to how your backend/engine stored them in io.KeysDown[].
// - We don't know the meaning of those value. You can use GetKeyIndex() to map a ImGuiKey_ value into the user index.
// IMGUI_API int GetKeyIndex(ImGuiKey imgui_key); // map ImGuiKey_* values into user's key index. == io.KeyMap[key]
// IMGUI_API bool IsKeyDown(int user_key_index); // is key being held. == io.KeysDown[user_key_index].
// IMGUI_API bool IsKeyPressed(int user_key_index, bool repeat = true); // was key pressed (went from !Down to Down)? if repeat=true, uses io.KeyRepeatDelay / KeyRepeatRate
// IMGUI_API bool IsKeyReleased(int user_key_index); // was key released (went from Down to !Down)?
// IMGUI_API int GetKeyPressedAmount(int key_index, float repeat_delay, float rate); // uses provided repeat rate/delay. return a count, most often 0 or 1 but might be >1 if RepeatRate is small enough that DeltaTime > RepeatRate
// IMGUI_API void CaptureKeyboardFromApp(bool want_capture_keyboard_value = true); // attention: misleading name! manually override io.WantCaptureKeyboard flag next frame (said flag is entirely left for your application to handle). e.g. force capture keyboard when your widget is being hovered. This is equivalent to setting "io.WantCaptureKeyboard = want_capture_keyboard_value"; after the next NewFrame() call.
export function GetKeyIndex(imgui_key: ImGuiKey): number { return bind.GetKeyIndex(imgui_key); }
export function IsKeyDown(user_key_index: number): boolean { return bind.IsKeyDown(user_key_index); }
export function IsKeyPressed(user_key_index: number, repeat: boolean = true): boolean { return bind.IsKeyPressed(user_key_index, repeat); }
export function IsKeyReleased(user_key_index: number): boolean { return bind.IsKeyReleased(user_key_index); }
export function GetKeyPressedAmount(user_key_index: number, repeat_delay: number, rate: number): number { return bind.GetKeyPressedAmount(user_key_index, repeat_delay, rate); }
export function CaptureKeyboardFromApp(capture: boolean = true) { return bind.CaptureKeyboardFromApp(capture); }
// Inputs Utilities: Mouse
// - To refer to a mouse button, you may use named enums in your code e.g. ImGuiMouseButton_Left, ImGuiMouseButton_Right.
// - You can also use regular integer: it is forever guaranteed that 0=Left, 1=Right, 2=Middle.
// - Dragging operations are only reported after mouse has moved a certain distance away from the initial clicking position (see 'lock_threshold' and 'io.MouseDraggingThreshold')
// IMGUI_API bool IsMouseDown(ImGuiMouseButton button); // is mouse button held?
// IMGUI_API bool IsMouseClicked(ImGuiMouseButton button, bool repeat = false); // did mouse button clicked? (went from !Down to Down)
// IMGUI_API bool IsMouseReleased(ImGuiMouseButton button); // did mouse button released? (went from Down to !Down)
// IMGUI_API bool IsMouseDoubleClicked(ImGuiMouseButton button); // did mouse button double-clicked? (note that a double-click will also report IsMouseClicked() == true)
// IMGUI_API bool IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip = true);// is mouse hovering given bounding rect (in screen space). clipped by current clipping settings, but disregarding of other consideration of focus/window ordering/popup-block.
// IMGUI_API bool IsMousePosValid(const ImVec2* mouse_pos = NULL); // by convention we use (-FLT_MAX,-FLT_MAX) to denote that there is no mouse available
// IMGUI_API bool IsAnyMouseDown(); // is any mouse button held?
// IMGUI_API ImVec2 GetMousePos(); // shortcut to ImGui::GetIO().MousePos provided by user, to be consistent with other calls
// IMGUI_API ImVec2 GetMousePosOnOpeningCurrentPopup(); // retrieve mouse position at the time of opening popup we have BeginPopup() into (helper to avoid user backing that value themselves)
// IMGUI_API bool IsMouseDragging(ImGuiMouseButton button, float lock_threshold = -1.0f); // is mouse dragging? (if lock_threshold < -1.0f, uses io.MouseDraggingThreshold)
// IMGUI_API ImVec2 GetMouseDragDelta(ImGuiMouseButton button = 0, float lock_threshold = -1.0f); // return the delta from the initial clicking position while the mouse button is pressed or was just released. This is locked and return 0.0f until the mouse moves past a distance threshold at least once (if lock_threshold < -1.0f, uses io.MouseDraggingThreshold)
// IMGUI_API void ResetMouseDragDelta(ImGuiMouseButton button = 0); //
// IMGUI_API ImGuiMouseCursor GetMouseCursor(); // get desired cursor type, reset in ImGui::NewFrame(), this is updated during the frame. valid before Render(). If you use software rendering by setting io.MouseDrawCursor ImGui will render those for you
// IMGUI_API void SetMouseCursor(ImGuiMouseCursor cursor_type); // set desired cursor type
// IMGUI_API void CaptureMouseFromApp(bool want_capture_mouse_value = true); // attention: misleading name! manually override io.WantCaptureMouse flag next frame (said flag is entirely left for your application to handle). This is equivalent to setting "io.WantCaptureMouse = want_capture_mouse_value;" after the next NewFrame() call.
export function IsMouseDown(button: number): boolean { return bind.IsMouseDown(button); }
export function IsMouseClicked(button: number, repeat: boolean = false): boolean { return bind.IsMouseClicked(button, repeat); }
export function IsMouseDoubleClicked(button: number): boolean { return bind.IsMouseDoubleClicked(button); }
export function IsMouseReleased(button: number): boolean { return bind.IsMouseReleased(button); }
export function IsMouseHoveringRect(r_min: Readonly<Bind.interface_ImVec2>, r_max: Readonly<Bind.interface_ImVec2>, clip: boolean = true): boolean { return bind.IsMouseHoveringRect(r_min, r_max, clip); }
export function IsMousePosValid(mouse_pos: Readonly<Bind.interface_ImVec2> | null = null): boolean { return bind.IsMousePosValid(mouse_pos); }
export function IsAnyMouseDown(): boolean { return bind.IsAnyMouseDown(); }
export function GetMousePos(out: Bind.interface_ImVec2 = new ImVec2()): Bind.interface_ImVec2 { return bind.GetMousePos(out); }
export function GetMousePosOnOpeningCurrentPopup(out: Bind.interface_ImVec2 = new ImVec2()): Bind.interface_ImVec2 { return bind.GetMousePosOnOpeningCurrentPopup(out); }
export function IsMouseDragging(button: number = 0, lock_threshold: number = -1.0): boolean { return bind.IsMouseDragging(button, lock_threshold); }
export function GetMouseDragDelta(button: number = 0, lock_threshold: number = -1.0, out: Bind.interface_ImVec2 = new ImVec2()): Bind.interface_ImVec2 { return bind.GetMouseDragDelta(button, lock_threshold, out); }
export function ResetMouseDragDelta(button: number = 0): void { bind.ResetMouseDragDelta(button); }
export function GetMouseCursor(): ImGuiMouseCursor { return bind.GetMouseCursor(); }
export function SetMouseCursor(type: ImGuiMouseCursor): void { bind.SetMouseCursor(type); }
export function CaptureMouseFromApp(capture: boolean = true): void { bind.CaptureMouseFromApp(capture); }
// Clipboard Utilities
// - Also see the LogToClipboard() function to capture GUI into clipboard, or easily output text data to the clipboard.
// IMGUI_API const char* GetClipboardText();
// IMGUI_API void SetClipboardText(const char* text);
export function GetClipboardText(): string { return bind.GetClipboardText(); }
export function SetClipboardText(text: string): void { bind.SetClipboardText(text); }
// Settings/.Ini Utilities
// - The disk functions are automatically called if io.IniFilename != NULL (default is "imgui.ini").
// - Set io.IniFilename to NULL to load/save manually. Read io.WantSaveIniSettings description about handling .ini saving manually.
// IMGUI_API void LoadIniSettingsFromDisk(const char* ini_filename); // call after CreateContext() and before the first call to NewFrame(). NewFrame() automatically calls LoadIniSettingsFromDisk(io.IniFilename).
// IMGUI_API void LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size=0); // call after CreateContext() and before the first call to NewFrame() to provide .ini data from your own data source.
// IMGUI_API void SaveIniSettingsToDisk(const char* ini_filename); // this is automatically called (if io.IniFilename is not empty) a few seconds after any modification that should be reflected in the .ini file (and also by DestroyContext).
// IMGUI_API const char* SaveIniSettingsToMemory(size_t* out_ini_size = NULL); // return a zero-terminated string with the .ini data which you can save by your own mean. call when io.WantSaveIniSettings is set, then save data by your own mean and clear io.WantSaveIniSettings.
export function LoadIniSettingsFromDisk(ini_filename: string): void { throw new Error(); } // TODO
export function LoadIniSettingsFromMemory(ini_data: string, ini_size: number = 0): void { bind.LoadIniSettingsFromMemory(ini_data); }
export function SaveIniSettingsToDisk(ini_filename: string): void { throw new Error(); } // TODO
export function SaveIniSettingsToMemory(out_ini_size: Bind.ImScalar<number> | null = null): string { return bind.SaveIniSettingsToMemory(); }
// Debug Utilities
// IMGUI_API bool DebugCheckVersionAndDataLayout(const char* version_str, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_drawvert, size_t sz_drawidx); // This is called by IMGUI_CHECKVERSION() macro.
export function DebugCheckVersionAndDataLayout(version_str: string, sz_io: number, sz_style: number, sz_vec2: number, sz_vec4: number, sz_draw_vert: number, sz_draw_idx: number): boolean {
return bind.DebugCheckVersionAndDataLayout(version_str, sz_io, sz_style, sz_vec2, sz_vec4, sz_draw_vert, sz_draw_idx);
}
// Memory Allocators
// - All those functions are not reliant on the current context.
// - If you reload the contents of imgui.cpp at runtime, you may need to call SetCurrentContext() + SetAllocatorFunctions() again because we use global storage for those.
// IMGUI_API void SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data = NULL);
// IMGUI_API void* MemAlloc(size_t size);
// IMGUI_API void MemFree(void* ptr);
export function SetAllocatorFunctions(alloc_func: (sz: number, user_data: any) => number, free_func: (ptr: number, user_data: any) => void, user_data: any = null): void {
bind.SetAllocatorFunctions(alloc_func, free_func, user_data);
}
export function MemAlloc(sz: number): void { bind.MemAlloc(sz); }
export function MemFree(ptr: any): void { bind.MemFree(ptr); } | the_stack |
declare const map: AMap.Map;
declare const lnglat: AMap.LngLat;
declare const lnglatTuple: [number, number];
// $ExpectError
new AMap.Transfer();
// $ExpectType Transfer
new AMap.Transfer({
city: 'city'
});
// $ExpectType Transfer
const transfer = new AMap.Transfer({
city: 'city1',
policy: AMap.TransferPolicy.LEAST_TIME,
nightflag: true,
cityd: 'city2',
extensions: 'base',
map,
panel: 'panel',
hideMarkers: false,
isOutline: true,
outlineColor: 'green',
autoFitView: true
});
// $ExpectType void
transfer.search(lnglat, lnglat);
// $ExpectType void
transfer.search(lnglatTuple, lnglatTuple);
// $ExpectType void
transfer.search(lnglat, lnglat, (status, result) => {
const temp: 'complete' | 'no_data' | 'error' = status;
if (typeof result !== 'string') {
// $ExpectType SearchResultBase
result;
// $ExpectType LngLat
result.destination;
// $ExpectType Poi | undefined
result.end;
if (result.end) {
const end = result.end;
// $ExpectType LngLat
end.location;
// $ExpectType string
end.name;
// $ExpectType "end" | "start" || "start" | "end"
end.type;
}
// $ExpectType string
result.info;
// $ExpectType LngLat
result.origin;
// $ExpectType TransferPlan[]
result.plans;
{
const plan = result.plans[0];
// $ExpectType number
plan.cost;
// $ExpectType number
plan.distance;
// $ExpectType boolean
plan.nightLine;
// $ExpectType LngLat[]
plan.path;
// $ExpectType number
plan.railway_distance;
// $ExpectType Segment[]
plan.segments;
const segments = plan.segments[0];
switch (segments.transit_mode) {
case 'WALK':
// $ExpectType number
segments.distance;
// $ExpectType string
segments.instruction;
// $ExpectType number
segments.time;
// $ExpectType WalkDetails
const walkDetails = segments.transit;
{
// $ExpectType LngLat
walkDetails.destination;
// $ExpectType LngLat
walkDetails.origin;
// $ExpectType LngLat[]
walkDetails.path;
// $ExpectType WalkStep[]
walkDetails.steps;
const walkStep = walkDetails.steps[0];
if (walkStep) {
// $ExpectType string
walkStep.action;
// $ExpectType string
walkStep.assist_action;
// $ExpectType number
walkStep.distance;
// $ExpectType string
walkStep.instruction;
// $ExpectType LngLat[]
walkStep.path;
// $ExpectType string
walkStep.road;
// $ExpectType number
walkStep.time;
}
}
// $ExpectType "WALK"
segments.transit_mode;
break;
case 'TAXI':
// $ExpectType number
segments.distance;
// $ExpectType string
segments.instruction;
// $ExpectType number
segments.time;
// $ExpectType string
segments.instruction;
// $ExpectType TaxiDetails
const taxiDetails = segments.transit;
{
// $ExpectType LngLat
taxiDetails.destination;
// $ExpectType number
taxiDetails.distance;
// $ExpectType LngLat
taxiDetails.origin;
// $ExpectType string
taxiDetails.sname;
// $ExpectType number
taxiDetails.time;
// $ExpectType string
taxiDetails.tname;
}
// $ExpectType "TAXI"
segments.transit_mode;
break;
case 'RAILWAY':
// $ExpectType number
segments.distance;
// $ExpectType string
segments.instruction;
// $ExpectType number
segments.time;
// $ExpectType RailwayDetails
const railwayDetails = segments.transit;
{
// $ExpectType RailStop
const arrivalStop = railwayDetails.arrival_stop;
{
// $ExpectType string
arrivalStop.adcode;
// $ExpectType string
arrivalStop.id;
// $ExpectType LngLat
arrivalStop.location;
// $ExpectType string
arrivalStop.name;
// $ExpectType RailwaySegment | undefined
arrivalStop.segment;
// $ExpectType number
arrivalStop.time;
}
// $ExpectType RailStop
railwayDetails.departure_stop;
// $ExpectType number
railwayDetails.distance;
// $ExpectType string
railwayDetails.id;
// $ExpectType string
railwayDetails.name;
// $ExpectType Space[]
railwayDetails.spaces;
{
const space = railwayDetails.spaces[0];
// $ExpectType number
space.cost;
// $ExpectType string | never[]
space.type;
}
// $ExpectType number
railwayDetails.time;
// $ExpectType string
railwayDetails.trip;
// $ExpectType string
railwayDetails.type;
if ('alters' in railwayDetails) {
// $ExpectType Alter[]
railwayDetails.alters;
{
const alter = railwayDetails.alters[0];
// $ExpectType string
alter.id;
// $ExpectType string
alter.name;
}
railwayDetails.alters;
// $ExpectType number
railwayDetails.via_num;
// $ExpectType ViaStop[]
railwayDetails.via_stops;
{
const viaStop = railwayDetails.via_stops[0];
// $ExpectType string
viaStop.id;
// $ExpectType LngLat
viaStop.location;
// $ExpectType string
viaStop.name;
// $ExpectType number
viaStop.time;
// $ExpectType number
viaStop.wait;
}
}
}
// $ExpectType "RAILWAY"
segments.transit_mode;
break;
case 'SUBWAY':
case 'METRO_RAIL':
case 'BUS':
// $ExpectType number
segments.distance;
// $ExpectType string
segments.instruction;
// $ExpectType number
segments.time;
// $ExpectType TransitDetails
const transitDetail = segments.transit;
{
// $ExpectType SubwayEntrance | undefined
const exit = transitDetail.exit;
if (exit) {
// $ExpectType LngLat
exit.location;
// $ExpectType string
exit.name;
}
// $ExpectType SubwayEntrance | undefined
transitDetail.entrance;
// $ExpectType TransitLine[]
transitDetail.lines;
{
const line = transitDetail.lines[0];
// $ExpectType string | never[]
line.etime;
// $ExpectType string
line.id;
// $ExpectType string
line.name;
// $ExpectType string | never[]
line.stime;
// $ExpectType string
line.type;
}
// $ExpectType Stop
const offStation = transitDetail.off_station;
{
// $ExpectType string
offStation.id;
// $ExpectType LngLat
offStation.location;
// $ExpectType string
offStation.name;
// $ExpectType TransitSegment | undefined
offStation.segment;
}
// $ExpectType Stop
transitDetail.on_station;
// $ExpectType LngLat[]
transitDetail.path;
// $ExpectType number
transitDetail.via_num;
// $ExpectType Stop[]
transitDetail.via_stops;
{
const viaStop = transitDetail.via_stops[0];
// $ExpectType string
viaStop.id;
// $ExpectType LngLat
viaStop.location;
// $ExpectType string
viaStop.name;
}
}
// $ExpectType "SUBWAY" | "METRO_RAIL" | "BUS"
segments.transit_mode;
break;
default:
// $ExpectType never
segments;
}
// $ExpectType number
plan.taxi_distance;
// $ExpectType number
plan.time;
// $ExpectType number
plan.transit_distance;
// $ExpectType number
plan.walking_distance;
}
// $ExpectType Poi | undefined
result.start;
// $ExpectType number
result.taxi_cost;
} else {
// $ExpectType string
result;
}
});
// $ExpectType void
transfer.search([{ keyword: 'origin' }, { keyword: 'destination' }], (status, result) => {
const temp: 'complete' | 'no_data' | 'error' = status;
if (typeof result !== 'string') {
// $ExpectType SearchResultExt
result;
// $ExpectType PoiExt
result.start;
// $ExpectType string
result.originName;
// $ExpectType PoiExt
result.end;
// $ExpectType string
result.destinationName;
} else {
// $ExpectType string
result;
}
});
transfer.on('complete', (event: AMap.Transfer.EventMap['complete']) => {
// $ExpectType "complete"
event.type;
if ('info' in event) {
// $ExpectType string
event.info;
// $ExpectType LngLat
event.origin;
// $ExpectType LngLat
event.destination;
// $ExpectType number
event.taxi_cost;
// $ExpectType TransferPlan[]
event.plans;
}
if ('originName' in event) {
// $ExpectType PoiExt
event.start;
// $ExpectType PoiExt
event.end;
// $ExpectType string
event.originName;
// $ExpectType string
event.destinationName;
} else {
// $ExpectType Poi | undefined
event.start;
// $ExpectType Poi | undefined
event.end;
}
});
transfer.on('error', (event: AMap.Transfer.EventMap['error']) => {
// $ExpectType "error"
event.type;
// $ExpectType string
event.info;
}); | the_stack |
//% weight=2 color=#002050 icon="\uf09e"
//% blockGap=8
//% groups='["Sender", "Receiver", "Packet", "Mode", "Configuration"]'
namespace lora {
export const enum LoRaState {
None,
/**
* Started initialization
*/
Initializing,
/**
* LoRa module initialized and ready to go.
*/
Ready,
/**
* Firmware update is required on the LoRa module
*/
LoRaIncorrectFirmwareVersion,
/**
* Pins are not configured properly
*/
LoRaInvalidConfiguration
}
/**
* Priority of log messages
*/
export let consolePriority = ConsolePriority.Log;
function log(msg: string) {
console.add(consolePriority, `lora: ${msg}`);
}
const FIRMWARE_VERSION = 0x12;
// registers
const REG_FIFO = 0x00;
const REG_OP_MODE = 0x01;
// unused
const REG_FRF_MSB = 0x06;
const REG_FRF_MID = 0x07;
const REG_FRF_LSB = 0x08;
const REG_PA_CONFIG = 0x09;
const REG_PA_RAMP = 0x0a;
const REG_OCP = 0x0b;
const REG_LNA = 0x0c;
const REG_FIFO_ADDR_PTR = 0x0d;
const REG_FIFO_TX_BASE_ADDR = 0x0e;
const REG_FIFO_RX_BASE_ADDR = 0x0f;
const REG_FIFO_RX_CURRENT_ADDR = 0x10;
const REG_IRQ_FLAGS = 0x12;
const REG_RX_NB_BYTES = 0x13;
const REG_RX_HEADER_COUNT_VALUE_MSB = 0x14;
const REG_RX_HEADER_COUNT_VALUE_LSB = 0x15;
const REG_RX_PACKET_COUNT_VALUE_MSB = 0x16;
const REG_RX_PACKET_COUNT_VALUE_LSB = 0x17;
const REG_MODEM_STAT = 0x18;
const REG_PKT_SNR_VALUE = 0x19;
const REG_PKT_RSSI_VALUE = 0x1a;
const REG_MODEM_CONFIG_1 = 0x1d;
const REG_MODEM_CONFIG_2 = 0x1e;
const REG_PREAMBLE_MSB = 0x20;
const REG_PREAMBLE_LSB = 0x21;
const REG_PAYLOAD_LENGTH = 0x22;
const REG_MAX_PAYLOAD_LENGTH = 0x23;
const REG_HOP_PERIOD = 0x24;
const REG_FIFO_RX_BYTE_AD = 0x25;
const REG_MODEM_CONFIG_3 = 0x26;
// 0x27 reserved
const REG_FREQ_ERROR_MSB = 0x28;
const REG_FREQ_ERROR_MID = 0x29;
const REG_FREQ_ERROR_LSB = 0x2a;
// 2b reserved
const REG_RSSI_WIDEBAND = 0x2c;
// 2d-2f reserved
const REG_DETECTION_OPTIMIZE = 0x31;
const REG_INVERT_IQ = 0x33;
const REG_DETECTION_THRESHOLD = 0x37;
const REG_SYNC_WORD = 0x39;
const REG_DIO_MAPPING_1 = 0x40;
const REG_DIO_MAPPING_2 = 0x40;
const REG_VERSION = 0x42;
const REG_TCXO = 0x4b;
const REG_PA_DAC = 0x4d;
const REG_FORMER_TEMP = 0x5b;
const REG_AGC_REF = 0x61;
const REG_AGC_THRESH_1 = 0x62;
const REG_AGC_THRESH_2 = 0x63;
const REG_AGC_THRESH_3 = 0x64;
const REG_PLL = 0x70;
// modes
const MODE_LONG_RANGE_MODE = 0x80;
const MODE_SLEEP = 0x00;
const MODE_STDBY = 0x01;
const MODE_TX = 0x03;
const MODE_RX_CONTINUOUS = 0x05;
const MODE_RX_SINGLE = 0x06;
// PA config
const PA_BOOST = 0x80;
// IRQ masks
const IRQ_TX_DONE_MASK = 0x08;
const IRQ_PAYLOAD_CRC_ERROR_MASK = 0x20;
const IRQ_RX_DONE_MASK = 0x40;
const MAX_PKT_LENGTH = 255;
const PA_OUTPUT_RFO_PIN = 0;
const PA_OUTPUT_PA_BOOST_PIN = 1;
// Arduino hacks
function bitSet(value: number, bit: number) {
return value |= 1 << bit;
// return ((value) |= (1UL << (bit)));
}
function bitClear(value: number, bit: number) {
return value &= ~(1 << bit);
// return ((value) &= ~(1UL << (bit)));
}
function bitWrite(value: number, bit: number, bitvalue: number) {
return (bitvalue ? bitSet(value, bit) : bitClear(value, bit));
}
/**
* State of the driver
*/
export let state: LoRaState = LoRaState.None;
let _version: number;
let _frequency = 915E6;
let _packetIndex = 0;
let _implicitHeaderMode = 0;
let _implicitHeader = false;
let _outputPin = PA_OUTPUT_PA_BOOST_PIN;
let _spi: SPI;
let _cs: DigitalInOutPin;
let _boot: DigitalInOutPin;
let _rst: DigitalInOutPin;
export function setPins(spiDevice: SPI,
csPin: DigitalInOutPin,
bootPin: DigitalInOutPin,
rstPin: DigitalInOutPin) {
_spi = spiDevice;
_cs = csPin;
_boot = bootPin;
_rst = rstPin;
// force reset
state = LoRaState.None;
}
function init() {
if (state != LoRaState.None) return; // already inited
log(`init`);
state = LoRaState.Initializing;
if (!_spi) {
log(`init using builtin lora pins`);
const mosi = pins.pinByCfg(DAL.CFG_PIN_LORA_MOSI);
const miso = pins.pinByCfg(DAL.CFG_PIN_LORA_MISO);
const sck = pins.pinByCfg(DAL.CFG_PIN_LORA_SCK);
// make sure pins are ok
if (!mosi || !miso || !sck) {
log(`missing SPI pins (MOSI ${!!mosi} MISO ${!!miso} SCK ${!!sck})`)
state = LoRaState.LoRaInvalidConfiguration;
return;
}
_spi = pins.createSPI(mosi, miso, sck);
_cs = pins.pinByCfg(DAL.CFG_PIN_LORA_CS);
_boot = pins.pinByCfg(DAL.CFG_PIN_LORA_BOOT);
_rst = pins.pinByCfg(DAL.CFG_PIN_LORA_RESET);
}
// final check for pins
if (!_cs || !_boot || !_rst) {
log(`missing pins (CS ${!!_cs} BOOT ${!!_boot} RST ${!!_rst})`)
state = LoRaState.LoRaInvalidConfiguration;
return;
}
_cs.digitalWrite(false);
// Hardware reset
log('hw reset')
_boot.digitalWrite(false);
_rst.digitalWrite(true);
pause(200);
_rst.digitalWrite(false);
pause(200);
_rst.digitalWrite(true);
pause(50);
// init spi
_cs.digitalWrite(true);
_spi.setFrequency(250000);
_spi.setMode(0);
_version = readRegister(REG_VERSION);
log(`version v${version()}, required v${FIRMWARE_VERSION}`);
if (_version != FIRMWARE_VERSION) {
log(`firmware upgrade required`);
state = LoRaState.LoRaIncorrectFirmwareVersion;
return;
}
//Sleep
writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_SLEEP);
// set frequency
setFrequencyRegisters(_frequency);
// set base addresses
writeRegister(REG_FIFO_TX_BASE_ADDR, 0);
writeRegister(REG_FIFO_RX_BASE_ADDR, 0);
// set LNA boost
writeRegister(REG_LNA, readRegister(REG_LNA) | 0x03);
// set auto AGC
writeRegister(REG_MODEM_CONFIG_3, 0x04);
// set output power to 17 dBm
setTxPowerRegisters(17);
// put in standby mode
writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_STDBY);
state = LoRaState.Ready;
log(`ready`);
}
// Write Register of SX.
function writeRegister(address: number, value: number) {
_cs.digitalWrite(false);
_spi.write(address | 0x80);
_spi.write(value);
_cs.digitalWrite(true);
}
// Read register of SX
function readRegister(address: number): number {
_cs.digitalWrite(false);
_spi.write(address & 0x7f);
const response = _spi.write(0x00);
_cs.digitalWrite(true);
return response;
}
function explicitHeaderMode() {
_implicitHeaderMode = 0;
writeRegister(REG_MODEM_CONFIG_1, readRegister(REG_MODEM_CONFIG_1) & 0xfe);
}
function implicitHeaderMode() {
_implicitHeaderMode = 1;
writeRegister(REG_MODEM_CONFIG_1, readRegister(REG_MODEM_CONFIG_1) | 0x01);
}
/**
* Indicates the LoRa module is correctly initialized
*/
//% group="Configuration"
//% blockId=loraeady block="lora is ready"
export function isReady(): boolean {
init();
return state == LoRaState.Ready;
}
/**
* Read Version of firmware
**/
//% parts="lora"
export function version(): number {
init();
return _version;
}
/**
* Parse a packet as a string
**/
//% group="Receiver"
//% parts="lora"
//% blockId=lorareadstring block="lora read string"
export function readString(): string {
if (!isReady()) return "";
const buf = readBuffer();
return buf.toString();
}
/**
* Parse a packet as a buffer
**/
//% group="Receiver"
//% parts="lora"
//% blockId=lorareadbuffer block="lora read buffer"
export function readBuffer(): Buffer {
if (!isReady()) return control.createBuffer(0);
let length = parsePacket(0);
if (length <= 0)
return control.createBuffer(0); // nothing to read
// allocate buffer to store data
let buf = control.createBuffer(length);
let i = 0;
// read all bytes
for (let i = 0; i < buf.length; ++i) {
const c = read();
if (c < 0) break;
buf[i] = c;
}
if (i != buf.length)
buf = buf.slice(0, i);
return buf;
}
/**
* Parse Packet to send
**/
//% group="Packet"
//% parts="lora"
//% weight=45 blockGap=8 blockId=loraparsepacket block="lora parse packet %size"
export function parsePacket(size: number): number {
if (!isReady()) return 0;
let packetLength = 0;
let irqFlags = readRegister(REG_IRQ_FLAGS);
if (size > 0) {
implicitHeaderMode();
writeRegister(REG_PAYLOAD_LENGTH, size & 0xff);
} else {
explicitHeaderMode();
}
// clear IRQ's
writeRegister(REG_IRQ_FLAGS, irqFlags);
if ((irqFlags & IRQ_RX_DONE_MASK) && (irqFlags & IRQ_PAYLOAD_CRC_ERROR_MASK) == 0) {
// received a packet
_packetIndex = 0;
// read packet length
if (_implicitHeaderMode) {
packetLength = readRegister(REG_PAYLOAD_LENGTH);
} else {
packetLength = readRegister(REG_RX_NB_BYTES);
}
// set FIFO address to current RX address
writeRegister(REG_FIFO_ADDR_PTR, readRegister(REG_FIFO_RX_CURRENT_ADDR));
// put in standby mode
idle();
} else if (readRegister(REG_OP_MODE) != (MODE_LONG_RANGE_MODE | MODE_RX_SINGLE)) {
// not currently in RX mode
// reset FIFO address
writeRegister(REG_FIFO_ADDR_PTR, 0);
// put in single RX mode
writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_RX_SINGLE);
}
return packetLength;
}
/**
* Packet RSSI
**/
//% group="Packet"
//% parts="lora"
//% weight=45 blockGap=8 blockId=lorapacketRssi block="lora packet RSSI"
export function packetRssi(): number {
if (!isReady()) return -1;
return (readRegister(REG_PKT_RSSI_VALUE) - (_frequency < 868E6 ? 164 : 157));
}
/**
* Packet SNR
*/
//% group="Packet"
//% parts="lora"
//% blockId=lorapacketsnr block="lora packet SNR"
export function packetSnr(): number {
if (!isReady()) return -1;
return (readRegister(REG_PKT_SNR_VALUE)) * 0.25;
}
// Begin Packet Frecuency Error
function packetFrequencyError(): number {
init();
let freqError = 0;
freqError = readRegister(REG_FREQ_ERROR_MSB) & 0xb111; //TODO Covert B111 to c++
freqError <<= 8;
freqError += readRegister(REG_FREQ_ERROR_MID) | 0;
freqError <<= 8;
freqError += readRegister(REG_FREQ_ERROR_LSB) | 0;
if (readRegister(REG_FREQ_ERROR_MSB) & 0xb1000) { // Sign bit is on //TODO Covert B1000 to c++
freqError -= 524288; // B1000'0000'0000'0000'0000
}
const fXtal = 32E6; // FXOSC: crystal oscillator (XTAL) frequency (2.5. Chip Specification, p. 14)
const fError = ((freqError * (1 << 24)) / fXtal) * (signalBandwidth() / 500000.0); // p. 37
return fError | 0;
}
// Begin Packet to send
function beginPacket(): void {
log(`begin packet`)
// put in standby mode
idle();
if (_implicitHeader) {
implicitHeaderMode();
} else {
explicitHeaderMode();
}
// reset FIFO address and payload length
writeRegister(REG_FIFO_ADDR_PTR, 0);
writeRegister(REG_PAYLOAD_LENGTH, 0);
}
function endPacket(): number {
log(`end packet`)
// put in TX mode
writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_TX);
// wait for TX done
// TODO interupts!
let k = 0;
while ((readRegister(REG_IRQ_FLAGS) & IRQ_TX_DONE_MASK) == 0) {
if (k++ % 100 == 0)
log(`wait tx`)
pause(10);
}
// clear IRQ's
writeRegister(REG_IRQ_FLAGS, IRQ_TX_DONE_MASK);
return 1;
}
/**
* Write string to send
**/
//% parts="lora"
//% group="Sender"
//% blockId=lorasendstring block="lora send string $text"
export function sendString(text: string) {
if (!text) return;
if (!isReady()) return;
const buf = control.createBufferFromUTF8(text);
sendBuffer(buf);
}
/**
* Write buffer to send
**/
//% parts="lora"
//% group="Sender"
//% blockId=lorasendbuffer block="lora send buffer $buffer"
export function sendBuffer(buffer: Buffer) {
if (!buffer || buffer.length == 0) return;
if (!isReady()) return;
log('send')
beginPacket();
log(`write payload (${buffer.length} bytes)`)
writeRaw(buffer);
endPacket();
}
function writeRaw(buffer: Buffer) {
const currentLength = readRegister(REG_PAYLOAD_LENGTH);
let size = buffer.length;
log(`current payload length: ${currentLength}`)
// check size
if ((currentLength + size) > MAX_PKT_LENGTH) {
size = MAX_PKT_LENGTH - currentLength;
}
log(`write raw ${buffer.length} -> ${size} bytes`)
// write data
for (let i = 0; i < size; i++) {
writeRegister(REG_FIFO, buffer[i]);
}
// update length
writeRegister(REG_PAYLOAD_LENGTH, currentLength + size);
log(`updated payload length: ${readRegister(REG_PAYLOAD_LENGTH)}`)
}
/**
* Available Packet
**/
//% parts="lora"
//% group="Packet"
//% weight=45 blockGap=8
//% blockId=loraavailable block="lora available"
export function available(): number {
if (!isReady()) return 0;
return readRegister(REG_RX_NB_BYTES) - _packetIndex;
}
/**
* Read Packet
**/
//% parts="lora"
//% group="Packet"
//% blockId=loraread block="lora read"
export function read(): number {
if (!isReady()) return -1;
if (!available())
return -1;
_packetIndex++;
return readRegister(REG_FIFO);
}
/**
* Peek Packet to send
**/
//% parts="lora"
//% group="Packet"
//% blockId=lorapeek block="lora peek"
export function peek(): number {
if (!isReady()) return -1;
if (!available())
return -1;
// store current FIFO address
const currentAddress = readRegister(REG_FIFO_ADDR_PTR);
// read
const b = readRegister(REG_FIFO);
// restore FIFO address
writeRegister(REG_FIFO_ADDR_PTR, currentAddress);
return b;
}
function flush() {
//TODO
}
/**
* Put LoRa in idle mode
*/
//% parts="lora"
//% group="Mode"
//% blockId=loraidle block="lora idle"
export function idle() {
if (!isReady()) return;
log('idle')
writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_STDBY);
}
/**
* Sleep Mode
**/
//% parts="lora"
//% group="Mode"
//% blockId=lorasleep block="lora sleep"
export function sleep() {
if (!isReady()) return;
writeRegister(REG_OP_MODE, MODE_LONG_RANGE_MODE | MODE_SLEEP);
}
function setTxPowerRegisters(level: number, rfo?: boolean) {
level = level | 0;
if (rfo) {
// RFO
if (level < 0) {
level = 0;
} else if (level > 14) {
level = 14;
}
writeRegister(REG_PA_CONFIG, 0x70 | level);
} else {
// PA BOOST
if (level < 2) {
level = 2;
} else if (level > 17) {
level = 17;
}
writeRegister(REG_PA_CONFIG, PA_BOOST | (level - 2));
}
}
/**
* Set Tx Power
**/
//% parts="lora"
//% group="Configuration"
//% blockId=lorasettxpower block="lora set tx power to $level dBm"
export function setTxPower(level: number, rfo?: boolean) {
if (!isReady()) return;
setTxPowerRegisters(level, rfo);
}
function setFrequencyRegisters(frequency: number) {
_frequency = frequency;
const frf = ((frequency * (1 << 19)) / 32000000) | 0;
log(`frequency ${_frequency} -> ${frf}`);
writeRegister(REG_FRF_MSB, (frf >> 16) & 0xff);
writeRegister(REG_FRF_MID, (frf >> 8) & 0xff);
writeRegister(REG_FRF_LSB, (frf >> 0) & 0xff);
}
/**
* Set Frecuency of LoRa
**/
//% parts="lora"
//% group="Configuration"
//% blockId=lorasetsetfrequency block="lora set frequency to $frequency"
export function setFrequency(frequency: number) {
if (!isReady()) return;
setFrequencyRegisters(_frequency);
}
/**
* Get Spreading Factor of LoRa
**/
//% parts="lora"
//% group="Configuration"
//% blockId=loraspreadingfactor block="lora spreading factor"
export function spreadingFactor(): number {
if (!isReady()) return -1;
return readRegister(REG_MODEM_CONFIG_2) >> 4;
}
/**
* Sets the spreading factoring
* @param factor spreading factor
*/
//% parts="lora"
//% blockId=lorasetspreadingfactor block="lora set spreading factor $factor"
//% factor.min=6 factor.max=12
//% factor.defl=8
//% group="Configuration"
export function setSpreadingFactor(factor: number) {
if (!isReady()) return;
factor = factor | 0;
if (factor < 6) {
factor = 6;
} else if (factor > 12) {
factor = 12;
}
if (factor == 6) {
writeRegister(REG_DETECTION_OPTIMIZE, 0xc5);
writeRegister(REG_DETECTION_THRESHOLD, 0x0c);
} else {
writeRegister(REG_DETECTION_OPTIMIZE, 0xc3);
writeRegister(REG_DETECTION_THRESHOLD, 0x0a);
}
writeRegister(REG_MODEM_CONFIG_2, (readRegister(REG_MODEM_CONFIG_2) & 0x0f) | ((factor << 4) & 0xf0));
setLdoFlag();
}
/**
* Get Signal Bandwidth of LoRa
**/
//% parts="lora"
//% group="Configuration"
//% blockId=lorasignalbandwith block="signal bandwidth"
export function signalBandwidth(): number {
if (!isReady()) return 0;
const bw = (readRegister(REG_MODEM_CONFIG_1) >> 4);
switch (bw) {
case 0: return 7.8E3;
case 1: return 10.4E3;
case 2: return 15.6E3;
case 3: return 20.8E3;
case 4: return 31.25E3;
case 5: return 41.7E3;
case 6: return 62.5E3;
case 7: return 125E3;
case 8: return 250E3;
case 9: return 500E3;
}
// unknown
return 0;
}
/**
* Set Signal Bandwidth of LoRa
**/
//% parts="lora"
//% group="Configuration"
//% blockId=lorasetsignalbandwith block="set signal bandwidth to $value"
export function setSignalBandwidth(value: number) {
if (!isReady()) return;
let bw;
if (value <= 7.8E3) {
bw = 0;
} else if (value <= 10.4E3) {
bw = 1;
} else if (value <= 15.6E3) {
bw = 2;
} else if (value <= 20.8E3) {
bw = 3;
} else if (value <= 31.25E3) {
bw = 4;
} else if (value <= 41.7E3) {
bw = 5;
} else if (value <= 62.5E3) {
bw = 6;
} else if (value <= 125E3) {
bw = 7;
} else if (value <= 250E3) {
bw = 8;
} else /*if (sbw <= 250E3)*/ {
bw = 9;
}
writeRegister(REG_MODEM_CONFIG_1, (readRegister(REG_MODEM_CONFIG_1) & 0x0f) | (bw << 4));
setLdoFlag();
}
function setLdoFlag() {
// Section 4.1.1.5
const symbolDuration = 1000 / (signalBandwidth() / (1 << spreadingFactor()));
// Section 4.1.1.6
const ldoOn = symbolDuration > 16 ? 1 : 0;
const config3 = readRegister(REG_MODEM_CONFIG_3);
bitWrite(config3, 3, ldoOn);
writeRegister(REG_MODEM_CONFIG_3, config3);
}
function setCodingRate4(denominator: number) {
if (denominator < 5) {
denominator = 5;
} else if (denominator > 8) {
denominator = 8;
}
const cr = denominator - 4;
writeRegister(REG_MODEM_CONFIG_1, (readRegister(REG_MODEM_CONFIG_1) & 0xf1) | (cr << 1));
}
function setPreambleLength(length: number) {
writeRegister(REG_PREAMBLE_MSB, (length >> 8) & 0xff);
writeRegister(REG_PREAMBLE_LSB, (length >> 0) & 0xff);
}
function setSyncWord(sw: number) {
writeRegister(REG_SYNC_WORD, sw);
}
//% parts="lora"
//% group="Configuration"
//% blockId=lorasetcrc block="lora set crc $on"
//% on.shadow=toggleOnOff
export function setCrc(on: boolean) {
if (!isReady()) return;
let v = readRegister(REG_MODEM_CONFIG_2);
if (on) v = v | 0x04; else v = v & 0xfb;
writeRegister(REG_MODEM_CONFIG_2, v);
}
export function dumpRegisters() {
init();
log(`state: ${["none", "initializing", "ready", "incorrect firmware", "invalid config"][state]}`)
if (!isReady()) return;
log(`registers:`)
const buf = control.createBuffer(1);
const regNames: any = {};
regNames[REG_FIFO] = "REG_FIFO";
regNames[REG_OP_MODE] = "REG_OP_MODE";
// unused
regNames[REG_FRF_MSB] = "REG_FRF_MSB";
regNames[REG_FRF_MID] = "REG_FRF_MID";
regNames[REG_FRF_LSB] = "REG_FRF_LSB";
regNames[REG_PA_CONFIG] = "REG_PA_CONFIG";
regNames[REG_PA_RAMP] = "REG_PA_RAMP";
regNames[REG_OCP] = "REG_OCP";
regNames[REG_LNA] = "REG_LNA";
regNames[REG_FIFO_ADDR_PTR] = "REG_FIFO_ADDR_PTR";
regNames[REG_FIFO_TX_BASE_ADDR] = "REG_FIFO_TX_BASE_ADDR";
regNames[REG_FIFO_RX_BASE_ADDR] = "REG_FIFO_RX_BASE_ADDR";
regNames[REG_FIFO_RX_CURRENT_ADDR] = "REG_FIFO_RX_CURRENT_ADDR";
regNames[REG_IRQ_FLAGS] = "REG_IRQ_FLAGS";
regNames[REG_RX_NB_BYTES] = "REG_RX_NB_BYTES";
regNames[REG_RX_HEADER_COUNT_VALUE_MSB] = "REG_RX_HEADER_COUNT_VALUE_MSB";
regNames[REG_RX_HEADER_COUNT_VALUE_LSB] = "REG_RX_HEADER_COUNT_VALUE_LSB";
regNames[REG_RX_PACKET_COUNT_VALUE_MSB] = "REG_RX_PACKET_COUNT_VALUE_MSB";
regNames[REG_RX_PACKET_COUNT_VALUE_LSB] = "REG_RX_PACKET_COUNT_VALUE_LSB";
regNames[REG_MODEM_STAT] = "REG_MODEM_STAT";
regNames[REG_PKT_SNR_VALUE] = "REG_PKT_SNR_VALUE";
regNames[REG_PKT_RSSI_VALUE] = "REG_PKT_RSSI_VALUE";
regNames[REG_MODEM_CONFIG_1] = "REG_MODEM_CONFIG_1";
regNames[REG_MODEM_CONFIG_2] = "REG_MODEM_CONFIG_2";
regNames[REG_PREAMBLE_MSB] = "REG_PREAMBLE_MSB";
regNames[REG_PREAMBLE_LSB] = "REG_PREAMBLE_LSB";
regNames[REG_PAYLOAD_LENGTH] = "REG_PAYLOAD_LENGTH";
regNames[REG_MAX_PAYLOAD_LENGTH] = "REG_MAX_PAYLOAD_LENGTH";
regNames[REG_HOP_PERIOD] = "REG_HOP_PERIOD";
regNames[REG_FIFO_RX_BYTE_AD] = "REG_FIFO_RX_BYTE_AD";
regNames[REG_MODEM_CONFIG_3] = "REG_MODEM_CONFIG_3";
// 0x27 reserved
regNames[REG_FREQ_ERROR_MSB] = "REG_FREQ_ERROR_MSB";
regNames[REG_FREQ_ERROR_MID] = "REG_FREQ_ERROR_MID";
regNames[REG_FREQ_ERROR_LSB] = "REG_FREQ_ERROR_LSB";
// 2b reserved
regNames[REG_RSSI_WIDEBAND] = "REG_RSSI_WIDEBAND";
// 2d-2f reserved
regNames[REG_DETECTION_OPTIMIZE] = "REG_DETECTION_OPTIMIZE";
regNames[REG_INVERT_IQ] = "REG_INVERT_IQ";
regNames[REG_DETECTION_THRESHOLD] = "REG_DETECTION_THRESHOLD";
regNames[REG_SYNC_WORD] = "REG_SYNC_WORD";
regNames[REG_DIO_MAPPING_1] = "REG_DIO_MAPPING_1";
regNames[REG_DIO_MAPPING_2] = "REG_DIO_MAPPING_2";
regNames[REG_VERSION] = "REG_VERSION";
regNames[REG_TCXO] = "REG_TCXO";
regNames[REG_PA_DAC] = "REG_PA_DAC";
regNames[REG_FORMER_TEMP] = "REG_FORMER_TEMP";
regNames[REG_AGC_REF] = "REG_AGC_REF";
regNames[REG_AGC_THRESH_1] = "REG_AGC_THRESH_1";
regNames[REG_AGC_THRESH_2] = "REG_AGC_THRESH_2";
regNames[REG_AGC_THRESH_3] = "REG_AGC_THRESH_3";
regNames[REG_PLL] = "REG_PLL";
for (let i = 0; i < 128; i++) {
let r: string = regNames[i];
if (!!r) {
r += " (0x";
buf[0] = i;
r += buf.toHex();
r += "): 0x";
buf[0] = readRegister(i);
r += buf.toHex();
log(r);
}
}
}
} | the_stack |
export as namespace Prism;
export const languages: Languages;
export const plugins: Record<string, any>;
/**
* A function which will be invoked after an element was successfully highlighted.
*
* @param element The element successfully highlighted.
*/
export type HighlightCallback = (element: Element) => void;
/**
* This is the most high-level function in Prism’s API.
* It fetches all the elements that have a `.language-xxxx` class and then calls {@link Prism.highlightElement} on
* each one of them.
*
* This is equivalent to `Prism.highlightAllUnder(document, async, callback)`.
*
* @param [async=false] Same as in {@link Prism.highlightAllUnder}.
* @param [callback] Same as in {@link Prism.highlightAllUnder}.
*/
export function highlightAll(
async?: boolean,
callback?: HighlightCallback
): void;
/**
* Fetches all the descendants of `container` that have a `.language-xxxx` class and then calls
* {@link Prism.highlightElement} on each one of them.
*
* The following hooks will be run:
* 1. `before-highlightall`
* 2. All hooks of {@link Prism.highlightElement} for each element.
*
* @param container The root element, whose descendants that have a `.language-xxxx` class will be highlighted.
* @param [async=false] Whether each element is to be highlighted asynchronously using Web Workers.
* @param [callback] An optional callback to be invoked on each element after its highlighting is done.
*/
export function highlightAllUnder(
container: ParentNode,
async?: boolean,
callback?: HighlightCallback
): void;
/**
* Highlights the code inside a single element.
*
* The following hooks will be run:
* 1. `before-sanity-check`
* 2. `before-highlight`
* 3. All hooks of {@link Prism.highlightElement}. These hooks will only be run by the current worker if `async` is `true`.
* 4. `before-insert`
* 5. `after-highlight`
* 6. `complete`
*
* @param element The element containing the code.
* It must have a class of `language-xxxx` to be processed, where `xxxx` is a valid language identifier.
* @param [async=false] Whether the element is to be highlighted asynchronously using Web Workers
* to improve performance and avoid blocking the UI when highlighting very large chunks of code. This option is
* [disabled by default](https://prismjs.com/faq.html#why-is-asynchronous-highlighting-disabled-by-default).
*
* Note: All language definitions required to highlight the code must be included in the main `prism.js` file for
* asynchronous highlighting to work. You can build your own bundle on the
* [Download page](https://prismjs.com/download.html).
* @param [callback] An optional callback to be invoked after the highlighting is done.
* Mostly useful when `async` is `true`, since in that case, the highlighting is done asynchronously.
*/
export function highlightElement(
element: Element,
async?: boolean,
callback?: HighlightCallback
): void;
/**
* Low-level function, only use if you know what you’re doing. It accepts a string of text as input
* and the language definitions to use, and returns a string with the HTML produced.
*
* The following hooks will be run:
* 1. `before-tokenize`
* 2. `after-tokenize`
* 3. `wrap`: On each {@link Prism.Token}.
*
* @param text A string with the code to be highlighted.
* @param grammar An object containing the tokens to use.
*
* Usually a language definition like `Prism.languages.markup`.
* @param language The name of the language definition passed to `grammar`.
* @returns The highlighted HTML.
*
* @example
* Prism.highlight('var foo = true;', Prism.languages.js, 'js');
*/
export function highlight(
text: string,
grammar: Grammar,
language: string
): string;
/**
* This is the heart of Prism, and the most low-level function you can use. It accepts a string of text as input
* and the language definitions to use, and returns an array with the tokenized code.
*
* When the language definition includes nested tokens, the function is called recursively on each of these tokens.
*
* This method could be useful in other contexts as well, as a very crude parser.
*
* @param text A string with the code to be highlighted.
* @param grammar An object containing the tokens to use.
*
* Usually a language definition like `Prism.languages.markup`.
* @returns An array of strings, tokens and other arrays.
*/
export function tokenize(
text: string,
grammar: Grammar
): Array<string | Token>;
export interface Environment extends Record<string, any> {
selector?: string | undefined;
element?: Element | undefined;
language?: string | undefined;
grammar?: Grammar | undefined;
code?: string | undefined;
highlightedCode?: string | undefined;
type?: string | undefined;
content?: string | undefined;
tag?: string | undefined;
classes?: string[] | undefined;
attributes?: Record<string, string> | undefined;
parent?: Array<string | Token> | undefined;
}
export namespace util {
interface Identifier {
value: number;
}
/** Encode raw strings in tokens in preparation to display as HTML */
function encode(tokens: TokenStream): TokenStream;
/** Determine the type of the object */
function type(o: null): "Null";
function type(o: undefined): "Undefined";
// tslint:disable:ban-types
function type(o: boolean | Boolean): "Boolean";
function type(o: number | Number): "Number";
function type(o: string | String): "String";
function type(o: Function): "Function";
// tslint:enable:ban-types
function type(o: RegExp): "RegExp";
function type(o: any[]): "Array";
function type(o: any): string;
/** Get the unique id of this object or give it one if it does not have one */
function objId(obj: any): Identifier;
/** Deep clone a language definition (e.g. to extend it) */
function clone<T>(o: T): T;
}
export type GrammarValue = RegExp | TokenObject | Array<RegExp | TokenObject>;
export type Grammar = GrammarRest & Record<string, GrammarValue>;
export interface GrammarRest {
keyword?: GrammarValue | undefined;
number?: GrammarValue | undefined;
function?: GrammarValue | undefined;
string?: GrammarValue | undefined;
boolean?: GrammarValue | undefined;
operator?: GrammarValue | undefined;
punctuation?: GrammarValue | undefined;
atrule?: GrammarValue | undefined;
url?: GrammarValue | undefined;
selector?: GrammarValue | undefined;
property?: GrammarValue | undefined;
important?: GrammarValue | undefined;
style?: GrammarValue | undefined;
comment?: GrammarValue | undefined;
"class-name"?: GrammarValue | undefined;
/**
* An optional grammar object that will appended to this grammar.
*/
rest?: Grammar | undefined;
}
/**
* The expansion of a simple `RegExp` literal to support additional properties.
*/
export interface TokenObject {
/**
* The regular expression of the token.
*/
pattern: RegExp;
/**
* If `true`, then the first capturing group of `pattern` will (effectively) behave as a lookbehind
* group meaning that the captured text will not be part of the matched text of the new token.
*/
lookbehind?: boolean | undefined;
/**
* Whether the token is greedy.
*
* @default false
*/
greedy?: boolean | undefined;
/**
* An optional alias or list of aliases.
*/
alias?: string | string[] | undefined;
/**
* The nested tokens of this token.
*
* This can be used for recursive language definitions.
*
* Note that this can cause infinite recursion.
*/
inside?: Grammar | undefined;
}
export type Languages = LanguageMapProtocol & LanguageMap;
export interface LanguageMap {
/**
* Get a defined language's definition.
*/
[language: string]: Grammar;
}
export interface LanguageMapProtocol {
/**
* Creates a deep copy of the language with the given id and appends the given tokens.
*
* If a token in `redef` also appears in the copied language, then the existing token in the copied language
* will be overwritten at its original position.
*
* @param id The id of the language to extend. This has to be a key in `Prism.languages`.
* @param redef The new tokens to append.
* @returns The new language created.
* @example
* Prism.languages['css-with-colors'] = Prism.languages.extend('css', {
* 'color': /\b(?:red|green|blue)\b/
* });
*/
extend(id: string, redef: Grammar): Grammar;
/**
* Inserts tokens _before_ another token in a language definition or any other grammar.
*
* As this needs to recreate the object (we cannot actually insert before keys in object literals),
* we cannot just provide an object, we need an object and a key.
*
* If the grammar of `inside` and `insert` have tokens with the same name, the tokens in `inside` will be ignored.
*
* All references of the old object accessible from `Prism.languages` or `insert` will be replace with the new one.
*
* @param inside The property of `root` that contains the object to be modified.
*
* This is usually a language id.
* @param before The key to insert before.
* @param insert An object containing the key-value pairs to be inserted.
* @param [root] The object containing `inside`, i.e. the object that contains the object that will be modified.
*
* Defaults to `Prism.languages`.
* @returns The new grammar created.
* @example
* Prism.languages.insertBefore('markup', 'cdata', {
* 'style': { ... }
* });
*/
insertBefore(
inside: string,
before: string,
insert: Grammar,
root?: LanguageMap
): Grammar;
}
export namespace hooks {
/**
* @param env The environment variables of the hook.
*/
type HookCallback = (env: Environment) => void;
type HookTypes = keyof HookEnvironmentMap;
interface HookEnvironmentMap {
"before-highlightall": RequiredEnvironment<"selector">;
"before-sanity-check": ElementEnvironment;
"before-highlight": ElementEnvironment;
"before-insert": ElementHighlightedEnvironment;
"after-highlight": ElementHighlightedEnvironment;
complete: ElementHighlightedEnvironment;
"before-tokenize": TokenizeEnvironment;
"after-tokenize": TokenizeEnvironment;
wrap: RequiredEnvironment<
"type" | "content" | "tag" | "classes" | "attributes" | "language"
>;
}
type RequiredEnvironment<
T extends keyof Environment,
U extends Environment = Environment
> = U & Required<Pick<U, T>>;
type ElementEnvironment = RequiredEnvironment<
"element" | "language" | "grammar" | "code"
>;
type ElementHighlightedEnvironment = RequiredEnvironment<
"highlightedCode",
ElementEnvironment
>;
type TokenizeEnvironment = RequiredEnvironment<
"code" | "grammar" | "language"
>;
interface RegisteredHooks {
[hook: string]: HookCallback[];
}
const all: RegisteredHooks;
/**
* Adds the given callback to the list of callbacks for the given hook.
*
* The callback will be invoked when the hook it is registered for is run.
* Hooks are usually directly run by a highlight function but you can also run hooks yourself.
*
* One callback function can be registered to multiple hooks and the same hook multiple times.
*
* @param name The name of the hook.
* @param callback The callback function which is given environment variables.
*/
function add<K extends keyof HookEnvironmentMap>(
name: K,
callback: (env: HookEnvironmentMap[K]) => void
): void;
function add(name: string, callback: HookCallback): void;
/**
* Runs a hook invoking all registered callbacks with the given environment variables.
*
* Callbacks will be invoked synchronously and in the order in which they were registered.
*
* @param name The name of the hook.
* @param env The environment variables of the hook passed to all callbacks registered.
*/
function run<K extends keyof HookEnvironmentMap>(
name: K,
env: HookEnvironmentMap[K]
): void;
function run(name: string, env: Environment): void;
}
export type TokenStream = string | Token | Array<string | Token>;
export class Token {
/**
* Creates a new token.
*
* @param type See {@link Prism.Token#type type}
* @param content See {@link Prism.Token#content content}
* @param [alias] The alias(es) of the token.
* @param [matchedStr=""] A copy of the full string this token was created from.
* @param [greedy=false] See {@link Prism.Token#greedy greedy}
*/
constructor(
type: string,
content: TokenStream,
alias?: string | string[],
matchedStr?: string,
greedy?: boolean
);
/**
* The type of the token.
*
* This is usually the key of a pattern in a {@link Grammar}.
*/
type: string;
/**
* The strings or tokens contained by this token.
*
* This will be a token stream if the pattern matched also defined an `inside` grammar.
*/
content: TokenStream;
/**
* The alias(es) of the token.
*
* @see TokenObject
*/
alias: string | string[];
/**
* The length of the matched string or 0.
*/
length: number;
/**
* Whether the pattern that created this token is greedy or not.
*
* @see TokenObject
*/
greedy: boolean;
/**
* Converts the given token or token stream to an HTML representation.
*
* The following hooks will be run:
* 1. `wrap`: On each {@link Prism.Token}.
*
* @param token The token or token stream to be converted.
* @param language The name of current language.
* @param [parent] The parent token stream, if any.
* @return The HTML representation of the token or token stream.
*/
static stringify(
token: TokenStream,
language: string,
parent?: Array<string | Token>
): string;
} | the_stack |
let kernel: any;
// eslint-disable-next-line
// @ts-ignore: breaks typedoc
let interpreter: any;
// eslint-disable-next-line
// @ts-ignore: breaks typedoc
let pyodide: any;
// eslint-disable-next-line
// @ts-ignore: breaks typedoc
let stdout_stream: any;
// eslint-disable-next-line
// @ts-ignore: breaks typedoc
let stderr_stream: any;
// eslint-disable-next-line
// @ts-ignore: breaks typedoc
let resolveInputReply: any;
/**
* Load pyodide and initialize the interpreter.
*
* The first package loaded, `piplite`, is a build-time configurable wrapper
* around `micropip` that supports multiple warehouse API endpoints, as well
* as a multipackage summary JSON format in `all.json`.
*/
async function loadPyodideAndPackages() {
// as of 0.17.0 indexURL must be provided
pyodide = await loadPyodide({ indexURL });
// this is the only use of `loadPackage`, allow `piplite` to handle the rest
await pyodide.loadPackage(['micropip']);
// get piplite early enough to impact pyolite dependencies
await pyodide.runPythonAsync(`
import micropip
await micropip.install('${_pipliteWheelUrl}')
import piplite.piplite
piplite.piplite._PIPLITE_DISABLE_PYPI = ${_disablePyPIFallback ? 'True' : 'False'}
piplite.piplite._PIPLITE_URLS = ${JSON.stringify(_pipliteUrls)}
`);
// from this point forward, only use piplite
await pyodide.runPythonAsync(`
await piplite.install([
'matplotlib',
'traitlets',
'widgetsnbextension',
'nbformat',
'ipykernel',
])
await piplite.install([
'pyolite',
]);
await piplite.install([
'ipython',
]);
import pyolite
`);
// make copies of these so they don't get garbage collected
kernel = pyodide.globals.get('pyolite').kernel_instance.copy();
stdout_stream = pyodide.globals.get('pyolite').stdout_stream.copy();
stderr_stream = pyodide.globals.get('pyolite').stderr_stream.copy();
interpreter = kernel.interpreter.copy();
interpreter.send_comm = sendComm;
const version = pyodide.globals.get('pyolite').__version__;
console.log('Pyolite kernel initialized, version', version);
}
/**
* Recursively convert a Map to a JavaScript object
* @param The Map object to convert
*/
function mapToObject(obj: any) {
const out: any = obj instanceof Array ? [] : {};
obj.forEach((value: any, key: string) => {
out[key] =
value instanceof Map || value instanceof Array ? mapToObject(value) : value;
});
return out;
}
/**
* Format the response from the Pyodide evaluation.
*
* @param res The result object from the Pyodide evaluation
*/
function formatResult(res: any): any {
if (!pyodide.isPyProxy(res)) {
return res;
}
// TODO: this is a bit brittle
const m = res.toJs();
const results = mapToObject(m);
return results;
}
// eslint-disable-next-line
// @ts-ignore: breaks typedoc
const pyodideReadyPromise = loadPyodideAndPackages();
/**
* Send a comm message to the front-end.
*
* @param type The type of the comm message.
* @param content The content.
* @param metadata The metadata.
* @param ident The ident.
* @param buffers The binary buffers.
*/
async function sendComm(
type: string,
content: any,
metadata: any,
ident: any,
buffers: any
) {
postMessage({
type: type,
content: formatResult(content),
metadata: formatResult(metadata),
ident: formatResult(ident),
buffers: formatResult(buffers),
parentHeader: formatResult(kernel._parent_header)['header']
});
}
async function getpass(prompt: string) {
prompt = typeof prompt === 'undefined' ? '' : prompt;
await sendInputRequest(prompt, true);
const replyPromise = new Promise(resolve => {
resolveInputReply = resolve;
});
const result: any = await replyPromise;
return result['value'];
}
async function input(prompt: string) {
prompt = typeof prompt === 'undefined' ? '' : prompt;
await sendInputRequest(prompt, false);
const replyPromise = new Promise(resolve => {
resolveInputReply = resolve;
});
const result: any = await replyPromise;
return result['value'];
}
/**
* Send a input request to the front-end.
*
* @param prompt the text to show at the prompt
* @param password Is the request for a password?
*/
async function sendInputRequest(prompt: string, password: boolean) {
const content = {
prompt,
password
};
postMessage({
type: 'input_request',
parentHeader: formatResult(kernel._parent_header)['header'],
content
});
}
/**
* Execute code with the interpreter.
*
* @param content The incoming message with the code to execute.
*/
async function execute(content: any) {
const publishExecutionResult = (
prompt_count: any,
data: any,
metadata: any
): void => {
const bundle = {
execution_count: prompt_count,
data: formatResult(data),
metadata: formatResult(metadata)
};
postMessage({
parentHeader: formatResult(kernel._parent_header)['header'],
bundle,
type: 'execute_result'
});
};
const publishExecutionError = (ename: any, evalue: any, traceback: any): void => {
const bundle = {
ename: ename,
evalue: evalue,
traceback: traceback
};
postMessage({
parentHeader: formatResult(kernel._parent_header)['header'],
bundle,
type: 'execute_error'
});
};
const clearOutputCallback = (wait: boolean): void => {
const bundle = {
wait: formatResult(wait)
};
postMessage({
parentHeader: formatResult(kernel._parent_header)['header'],
bundle,
type: 'clear_output'
});
};
const displayDataCallback = (data: any, metadata: any, transient: any): void => {
const bundle = {
data: formatResult(data),
metadata: formatResult(metadata),
transient: formatResult(transient)
};
postMessage({
parentHeader: formatResult(kernel._parent_header)['header'],
bundle,
type: 'display_data'
});
};
const updateDisplayDataCallback = (
data: any,
metadata: any,
transient: any
): void => {
const bundle = {
data: formatResult(data),
metadata: formatResult(metadata),
transient: formatResult(transient)
};
postMessage({
parentHeader: formatResult(kernel._parent_header)['header'],
bundle,
type: 'update_display_data'
});
};
const publishStreamCallback = (name: any, text: any): void => {
const bundle = {
name: formatResult(name),
text: formatResult(text)
};
postMessage({
parentHeader: formatResult(kernel._parent_header)['header'],
bundle,
type: 'stream'
});
};
stdout_stream.publish_stream_callback = publishStreamCallback;
stderr_stream.publish_stream_callback = publishStreamCallback;
interpreter.display_pub.clear_output_callback = clearOutputCallback;
interpreter.display_pub.display_data_callback = displayDataCallback;
interpreter.display_pub.update_display_data_callback = updateDisplayDataCallback;
interpreter.displayhook.publish_execution_result = publishExecutionResult;
interpreter.input = input;
interpreter.getpass = getpass;
const res = await kernel.run(content.code);
const results = formatResult(res);
if (results['status'] === 'error') {
publishExecutionError(results['ename'], results['evalue'], results['traceback']);
}
return results;
}
/**
* Complete the code submitted by a user.
*
* @param content The incoming message with the code to complete.
*/
function complete(content: any) {
const res = kernel.complete(content.code, content.cursor_pos);
const results = formatResult(res);
return results;
}
/**
* Inspect the code submitted by a user.
*
* @param content The incoming message with the code to inspect.
*/
function inspect(content: { code: string; cursor_pos: number; detail_level: 0 | 1 }) {
const res = kernel.inspect(content.code, content.cursor_pos, content.detail_level);
const results = formatResult(res);
return results;
}
/**
* Check code for completeness submitted by a user.
*
* @param content The incoming message with the code to check.
*/
function isComplete(content: { code: string }) {
const res = kernel.is_complete(content.code);
const results = formatResult(res);
return results;
}
/**
* Respond to the commInfoRequest.
*
* @param content The incoming message with the comm target name.
*/
function commInfo(content: any) {
const res = kernel.comm_info(content.target_name);
const results = formatResult(res);
return {
comms: results,
status: 'ok'
};
}
/**
* Respond to the commOpen.
*
* @param content The incoming message with the comm open.
*/
function commOpen(content: any) {
const res = kernel.comm_manager.comm_open(pyodide.toPy(content));
const results = formatResult(res);
return results;
}
/**
* Respond to the commMsg.
*
* @param content The incoming message with the comm msg.
*/
function commMsg(content: any) {
const res = kernel.comm_manager.comm_msg(pyodide.toPy(content));
const results = formatResult(res);
return results;
}
/**
* Respond to the commClose.
*
* @param content The incoming message with the comm close.
*/
function commClose(content: any) {
const res = kernel.comm_manager.comm_close(pyodide.toPy(content));
const results = formatResult(res);
return results;
}
/**
* Process a message sent to the worker.
*
* @param event The message event to process
*/
self.onmessage = async (event: MessageEvent): Promise<void> => {
await pyodideReadyPromise;
const data = event.data;
let results;
const messageType = data.type;
const messageContent = data.data;
kernel._parent_header = pyodide.toPy(data.parent);
switch (messageType) {
case 'execute-request':
console.log('Perform execution inside worker', data);
results = await execute(messageContent);
break;
case 'input-reply':
resolveInputReply(messageContent);
return;
case 'inspect-request':
results = inspect(messageContent);
break;
case 'is-complete-request':
results = isComplete(messageContent);
break;
case 'complete-request':
results = complete(messageContent);
break;
case 'comm-info-request':
results = commInfo(messageContent);
break;
case 'comm-open':
results = commOpen(messageContent);
break;
case 'comm-msg':
results = commMsg(messageContent);
break;
case 'comm-close':
results = commClose(messageContent);
break;
default:
break;
}
const reply = {
parentHeader: data.parent['header'],
type: 'reply',
results
};
postMessage(reply);
}; | the_stack |
import * as DiscoveryEntryWithMetaInfo from "../../generated/joynr/types/DiscoveryEntryWithMetaInfo";
import * as MessagingQos from "../messaging/MessagingQos";
import * as Request from "./types/Request";
import * as Reply from "./types/Reply";
import * as OneWayRequest from "./types/OneWayRequest";
import BroadcastSubscriptionRequest from "./types/BroadcastSubscriptionRequest";
import MulticastSubscriptionRequest from "./types/MulticastSubscriptionRequest";
import SubscriptionRequest from "./types/SubscriptionRequest";
import SubscriptionReply from "./types/SubscriptionReply";
import SubscriptionStop from "./types/SubscriptionStop";
import * as SubscriptionPublication from "./types/SubscriptionPublication";
import * as MulticastPublication from "./types/MulticastPublication";
import JoynrMessage from "../messaging/JoynrMessage";
import * as MessagingQosEffort from "../messaging/MessagingQosEffort";
import defaultMessagingSettings from "../start/settings/defaultMessagingSettings";
import * as DiagnosticTags from "../system/DiagnosticTags";
import * as UtilInternal from "../util/UtilInternal";
import * as JSONSerializer from "../util/JSONSerializer";
import * as Typing from "../util/Typing";
import SubscriptionQos from "../proxy/SubscriptionQos";
import LoggingManager from "../system/LoggingManager";
import PlatformSecurityManagerNode = require("../security/PlatformSecurityManagerNode");
import InProcessMessagingStub = require("../messaging/inprocess/InProcessMessagingStub");
import MessageRouter = require("../messaging/routing/MessageRouter");
import RequestReplyManager = require("./RequestReplyManager");
import SubscriptionManager = require("./subscription/SubscriptionManager");
import PublicationManager = require("./subscription/PublicationManager");
const log = LoggingManager.getLogger("joynr.dispatching.Dispatcher");
class Dispatcher {
private ttlUpLiftMs?: number;
private securityManager: PlatformSecurityManagerNode;
private clusterControllerMessagingStub: InProcessMessagingStub;
private messageRouter!: MessageRouter;
private publicationManager!: PublicationManager;
private subscriptionManager!: SubscriptionManager;
private requestReplyManager!: RequestReplyManager;
/**
* @constructor
*
* @param clusterControllerMessagingStub for sending outgoing joynr messages
* @param securityManager for setting the creator user ID header
* @param ttlUpLiftMs
*/
public constructor(
clusterControllerMessagingStub: InProcessMessagingStub,
securityManager: PlatformSecurityManagerNode,
ttlUpLiftMs?: number
) {
this.clusterControllerMessagingStub = clusterControllerMessagingStub;
this.securityManager = securityManager;
this.ttlUpLiftMs = ttlUpLiftMs;
this.sendSubscriptionReply = this.sendSubscriptionReply.bind(this);
// bind due to InProcessMessagingSkeleton using receive as callback.
this.receive = this.receive.bind(this);
}
/**
* @param expiryDate the expiry date in milliseconds
* @returns the expiry date with TTL_UPLIFT added as time delta
*/
private upLiftTtl(expiryDate: number): number {
expiryDate += this.ttlUpLiftMs !== undefined ? this.ttlUpLiftMs : defaultMessagingSettings.TTL_UPLIFT;
if (expiryDate > UtilInternal.getMaxLongValue()) {
expiryDate = UtilInternal.getMaxLongValue();
}
return expiryDate;
}
/**
* @param subscriptionRequest the subscription request
* @returns the subscription request with qos.expiry date with TTL_UPLIFT added as time delta
*/
private upLiftExpiryDateInSubscriptionRequest<T extends SubscriptionRequest>(subscriptionRequest: T): T {
// if expiryDateMs == SubscriptionQos.NO_EXPIRY_DATE (=0), expiryDateMs must not be changed
if (subscriptionRequest.qos.expiryDateMs !== SubscriptionQos.NO_EXPIRY_DATE) {
subscriptionRequest.qos.expiryDateMs = this.upLiftTtl(subscriptionRequest.qos.expiryDateMs);
}
return subscriptionRequest;
}
/**
* @param joynrMessage
* @param settings
* @param settings.from participantId of the sender
* @param settings.toDiscoveryEntry DiscoveryEntry of the receiver
* @param settings.messagingQos the messaging Qos object for the ttl
* @returns Promise resolved on success
*/
private sendJoynrMessage(
joynrMessage: JoynrMessage,
settings: {
from: string;
toDiscoveryEntry: DiscoveryEntryWithMetaInfo;
messagingQos: MessagingQos;
}
): Promise<void> {
// set headers
joynrMessage.creator = this.securityManager.getCurrentProcessUserId();
joynrMessage.from = settings.from;
joynrMessage.to = settings.toDiscoveryEntry.participantId;
joynrMessage.expiryDate = this.upLiftTtl(Date.now() + settings.messagingQos.ttl);
const effort = settings.messagingQos.effort;
if (effort !== MessagingQosEffort.NORMAL) {
joynrMessage.effort = effort.value;
}
if (settings.messagingQos.compress) {
joynrMessage.compress = true;
}
joynrMessage.isLocalMessage = settings.toDiscoveryEntry.isLocal;
if (log.isDebugEnabled()) {
log.debug(`sendJoynrMessage, message = ${JSON.stringify(joynrMessage)}`);
}
// send message
return this.clusterControllerMessagingStub.transmit(joynrMessage);
}
private getJoynrMessageType(subscriptionRequest: SubscriptionRequest): string {
const type = Typing.getObjectType(subscriptionRequest);
switch (type) {
case "BroadcastSubscriptionRequest":
return JoynrMessage.JOYNRMESSAGE_TYPE_BROADCAST_SUBSCRIPTION_REQUEST;
case "MulticastSubscriptionRequest":
return JoynrMessage.JOYNRMESSAGE_TYPE_MULTICAST_SUBSCRIPTION_REQUEST;
default:
return JoynrMessage.JOYNRMESSAGE_TYPE_SUBSCRIPTION_REQUEST;
}
}
/**
* @param settings
* @param settings.from participantId of the sender
* @param settings.to participantId of the receiver
* @param settings.expiryDate time-to-live
* @param settings.customHeaders custom headers from request
* @param settings.messageType
* @param settings.effort
* @param settings.compress
* @param settings.reply the reply to be transmitted. It can either be a Reply or a SubscriptionReply object
* @returns A+ promise object
*/
private sendReply(settings: {
from: string;
to: string;
expiryDate: number;
customHeaders: Record<string, any>;
messageType: string;
effort?: MessagingQosEffort.effort;
compress?: boolean;
reply: string;
}): Promise<void> {
// reply with the result in a JoynrMessage
const joynrMessage = new JoynrMessage({
type: settings.messageType,
payload: settings.reply
});
joynrMessage.from = settings.from;
joynrMessage.to = settings.to;
joynrMessage.expiryDate = settings.expiryDate;
// set custom headers
joynrMessage.setCustomHeaders(settings.customHeaders);
if (settings.effort && settings.effort !== MessagingQosEffort.NORMAL) {
joynrMessage.effort = settings.effort.value;
}
if (settings.compress) {
joynrMessage.compress = true;
}
if (log.isDebugEnabled()) {
log.debug(`sendReply, message = ${JSON.stringify(joynrMessage)}`);
}
return this.clusterControllerMessagingStub.transmit(joynrMessage);
}
/**
* @param settings
* @param settings.from participantId of the sender
* @param settings.to participantId of the receiver
* @param settings.expiryDate time-to-live
* @param settings.customHeaders custom headers from request
* @param settings.messageType
* @param settings.effort
* @param settings.compress
* @param reply
* @returns A+ promise object
*/
private sendRequestReply(
settings: {
from: string;
to: string;
expiryDate: number;
customHeaders: Record<string, any>;
effort: MessagingQosEffort.effort;
compress: boolean;
},
reply: Reply.Reply
): Promise<void> {
const toParticipantId = settings.to;
log.info(
"replying",
DiagnosticTags.forReply({
reply,
to: toParticipantId,
from: settings.from
})
);
type Settings = typeof settings & { reply: string; messageType: string };
(settings as Settings).reply = JSONSerializer.stringifyOptional(reply, reply.error !== undefined);
(settings as Settings).messageType = JoynrMessage.JOYNRMESSAGE_TYPE_REPLY;
return this.sendReply(settings as Settings);
}
/**
* @param settings
* @param settings.from participantId of the sender
* @param settings.to participantId of the receiver
* @param settings.expiryDate time-to-live
* @param settings.customHeaders custom headers from request
* @param subscriptionReply
*/
private sendSubscriptionReply(
settings: {
from: string;
to: string;
expiryDate: number;
customHeaders: Record<string, any>;
},
subscriptionReply: SubscriptionReply
): void {
const toParticipantId = settings.to;
log.info(
"replying",
DiagnosticTags.forSubscriptionReply({
subscriptionReply,
to: toParticipantId,
from: settings.from
})
);
type Settings = typeof settings & { reply: string; messageType: string };
(settings as Settings).reply = JSONSerializer.stringifyOptional(
subscriptionReply,
subscriptionReply.error !== undefined
);
(settings as Settings).messageType = JoynrMessage.JOYNRMESSAGE_TYPE_SUBSCRIPTION_REPLY;
this.sendReply(settings as Settings);
}
private sendPublicationInternal(
settings: {
from: string;
to: string;
expiryDate: number;
},
type: string,
publication: SubscriptionPublication.SubscriptionPublication
): void {
// create JoynrMessage for the publication
const publicationMessage = new JoynrMessage({
type,
payload: JSONSerializer.stringify(publication)
});
// set reply headers
const toParticipantId = settings.to;
publicationMessage.from = settings.from;
publicationMessage.to = toParticipantId;
publicationMessage.expiryDate = this.upLiftTtl(settings.expiryDate);
this.addRequestReplyIdCustomHeader(publicationMessage, publication.subscriptionId);
if (log.isDebugEnabled()) {
log.debug(`sendPublicationInternal, message = ${JSON.stringify(publicationMessage)}`);
}
this.clusterControllerMessagingStub.transmit(publicationMessage);
}
private createReplySettings(
joynrMessage: JoynrMessage
): {
from: string;
to: string;
expiryDate: number;
customHeaders: Record<string, any>;
effort?: MessagingQosEffort.effort;
compress?: boolean;
} {
return {
from: joynrMessage.to,
to: joynrMessage.from,
expiryDate: joynrMessage.expiryDate,
customHeaders: joynrMessage.getCustomHeaders()
};
}
/**
* @param newRequestReplyManager handles incoming and outgoing requests and replies
*/
public registerRequestReplyManager(newRequestReplyManager: RequestReplyManager): void {
this.requestReplyManager = newRequestReplyManager;
}
/**
* @param newMessageRouter
*/
public registerMessageRouter(newMessageRouter: MessageRouter): void {
this.messageRouter = newMessageRouter;
}
/**
* @param newSubscriptionManager sends subscription requests; handles incoming publications
* and incoming replies to subscription requests
*/
public registerSubscriptionManager(newSubscriptionManager: SubscriptionManager): void {
this.subscriptionManager = newSubscriptionManager;
}
/**
* @param newPublicationManager sends publications; handles incoming subscription start and stop requests
*/
public registerPublicationManager(newPublicationManager: PublicationManager): void {
this.publicationManager = newPublicationManager;
}
/**
* @param joynrMessage
* @param requestReplyId
*/
private addRequestReplyIdCustomHeader(joynrMessage: JoynrMessage, requestReplyId: string): void {
joynrMessage.setCustomHeaders({ z4: requestReplyId });
}
/**
* @param settings
* @param settings.from participantId of the sender
* @param settings.toDiscoveryEntry DiscoveryEntry of the receiver
* @param settings.messagingQos the messaging Qos object for the ttl
* @param settings.request
* @returns A+ promise object
*/
public sendRequest(settings: {
from: string;
toDiscoveryEntry: DiscoveryEntryWithMetaInfo;
messagingQos: MessagingQos;
request: Request.Request;
}): Promise<void> {
// Create a JoynrMessage with the Request
const requestMessage = new JoynrMessage({
type: JoynrMessage.JOYNRMESSAGE_TYPE_REQUEST,
payload: JSONSerializer.stringify(settings.request)
});
if (settings.messagingQos.customHeaders) {
requestMessage.setCustomHeaders(settings.messagingQos.customHeaders);
}
this.addRequestReplyIdCustomHeader(requestMessage, settings.request.requestReplyId);
log.info(
`calling ${settings.request.methodName}.`,
DiagnosticTags.forRequest({
request: settings.request,
to: settings.toDiscoveryEntry.participantId,
from: settings.from
})
);
return this.sendJoynrMessage(requestMessage, settings);
}
/**
* @param settings
* @param settings.from participantId of the sender
* @param settings.toDiscoveryEntry DiscoveryEntry of the receiver
* @param settings.messagingQos the messaging Qos object for the ttl
* @param settings.request
* @returns A+ promise object
*/
public sendOneWayRequest(settings: {
from: string;
toDiscoveryEntry: DiscoveryEntryWithMetaInfo;
messagingQos: MessagingQos;
request: OneWayRequest.OneWayRequest;
}): Promise<void> {
// Create a JoynrMessage with the OneWayRequest
const oneWayRequestMessage = new JoynrMessage({
type: JoynrMessage.JOYNRMESSAGE_TYPE_ONE_WAY,
payload: JSONSerializer.stringify(settings.request)
});
if (settings.messagingQos.customHeaders) {
oneWayRequestMessage.setCustomHeaders(settings.messagingQos.customHeaders);
}
log.info(
`calling ${settings.request.methodName}.`,
DiagnosticTags.forOneWayRequest({
request: settings.request,
to: settings.toDiscoveryEntry.participantId,
from: settings.from
})
);
return this.sendJoynrMessage(oneWayRequestMessage, settings);
}
/**
* @param settings
* @param settings.from participantId of the sender
* @param settings.toDiscoveryEntry DiscoveryEntry of the receiver
* @param settings.messagingQos the messaging Qos object for the ttl
* @param settings.subscriptionRequest
* @returns promise object that is resolved when the request is sent by the messaging stub
*/
public sendSubscriptionRequest(settings: {
from: string;
toDiscoveryEntry: DiscoveryEntryWithMetaInfo;
messagingQos: MessagingQos;
subscriptionRequest: SubscriptionRequest;
}): Promise<void> {
log.info(
`subscription to ${settings.subscriptionRequest.subscribedToName}`,
DiagnosticTags.forSubscriptionRequest({
subscriptionRequest: settings.subscriptionRequest,
to: settings.toDiscoveryEntry.participantId,
from: settings.from
})
);
const requestMessage = new JoynrMessage({
type: JoynrMessage.JOYNRMESSAGE_TYPE_SUBSCRIPTION_REQUEST,
payload: JSONSerializer.stringify(settings.subscriptionRequest)
});
if (settings.messagingQos.customHeaders) {
requestMessage.setCustomHeaders(settings.messagingQos.customHeaders);
}
this.addRequestReplyIdCustomHeader(requestMessage, settings.subscriptionRequest.subscriptionId);
return this.sendJoynrMessage(requestMessage, settings);
}
/**
* @param settings
* @param settings.from participantId of the sender
* @param settings.toDiscoveryEntry DiscoveryEntry of the receiver
* @param settings.messagingQos the messaging Qos object for the ttl
* @param settings.subscriptionRequest
* @returns promise object that is resolved when the request is sent by the messaging stub
*/
public sendBroadcastSubscriptionRequest(settings: {
from: string;
toDiscoveryEntry: DiscoveryEntryWithMetaInfo;
messagingQos: MessagingQos;
subscriptionRequest: MulticastSubscriptionRequest | BroadcastSubscriptionRequest;
}): Promise<void> {
const type = this.getJoynrMessageType(settings.subscriptionRequest);
const requestMessage = new JoynrMessage({
type,
payload: JSONSerializer.stringify(settings.subscriptionRequest)
});
if (type === JoynrMessage.JOYNRMESSAGE_TYPE_MULTICAST_SUBSCRIPTION_REQUEST) {
log.info(
`multicast subscription to ${settings.subscriptionRequest.subscribedToName}`,
DiagnosticTags.forMulticastSubscriptionRequest({
subscriptionRequest: settings.subscriptionRequest,
to: settings.toDiscoveryEntry.participantId,
from: settings.from
})
);
return this.messageRouter.addMulticastReceiver({
multicastId: (settings.subscriptionRequest as MulticastSubscriptionRequest).multicastId,
subscriberParticipantId: settings.from,
providerParticipantId: settings.toDiscoveryEntry.participantId
});
}
log.info(
`broadcast subscription to ${settings.subscriptionRequest.subscribedToName}`,
DiagnosticTags.forBroadcastSubscriptionRequest({
subscriptionRequest: settings.subscriptionRequest,
to: settings.toDiscoveryEntry.participantId,
from: settings.from
})
);
if (settings.messagingQos.customHeaders) {
requestMessage.setCustomHeaders(settings.messagingQos.customHeaders);
}
this.addRequestReplyIdCustomHeader(requestMessage, settings.subscriptionRequest.subscriptionId);
return this.sendJoynrMessage(requestMessage, settings);
}
/**
* @param settings
* @param settings.from participantId of the sender
* @param settings.toDiscoveryEntry DiscoveryEntry of the receiver
* @param settings.multicastId of the multicast
* @param settings.subscriptionStop
* @param settings.messagingQos the messaging Qos object for the ttl
* @returns A+ promise object
*/
public sendMulticastSubscriptionStop(settings: {
from: string;
toDiscoveryEntry: DiscoveryEntryWithMetaInfo;
multicastId: string;
subscriptionStop: SubscriptionStop;
messagingQos: MessagingQos;
}): Promise<void> {
this.sendSubscriptionStop(settings);
return this.messageRouter.removeMulticastReceiver({
multicastId: settings.multicastId,
subscriberParticipantId: settings.from,
providerParticipantId: settings.toDiscoveryEntry.participantId
});
}
/**
* @param settings
* @param settings.from participantId of the sender
* @param settings.toDiscoveryEntry DiscoveryEntry of the receiver
* @param settings.subscriptionStop
* @param settings.messagingQos the messaging Qos object for the ttl
* @returns A+ promise object
*/
public sendSubscriptionStop(settings: {
from: string;
toDiscoveryEntry: DiscoveryEntryWithMetaInfo;
subscriptionStop: SubscriptionStop;
messagingQos: MessagingQos;
}): Promise<void> {
log.info(
`subscription stop ${settings.subscriptionStop.subscriptionId}`,
DiagnosticTags.forSubscriptionStop({
subscriptionId: settings.subscriptionStop.subscriptionId,
to: settings.toDiscoveryEntry.participantId,
from: settings.from
})
);
const message = new JoynrMessage({
type: JoynrMessage.JOYNRMESSAGE_TYPE_SUBSCRIPTION_STOP,
payload: JSONSerializer.stringify(settings.subscriptionStop)
});
if (settings.messagingQos.customHeaders) {
message.setCustomHeaders(settings.messagingQos.customHeaders);
}
this.addRequestReplyIdCustomHeader(message, settings.subscriptionStop.subscriptionId);
return this.sendJoynrMessage(message, settings);
}
/**
* @param settings
* @param settings.from participantId of the sender
* @param settings.to participantId of the receiver
* @param settings.expiryDate time-to-live
* @param publication
* @param [publication.response]
* @param [publication.error]
* @param publication.subscriptionId
*/
public sendPublication(
settings: {
from: string;
to: string;
expiryDate: number;
},
publication: SubscriptionPublication.SubscriptionPublication
): void {
log.info(
"publication",
DiagnosticTags.forPublication({
publication,
to: settings.to,
from: settings.from
})
);
this.sendPublicationInternal(settings, JoynrMessage.JOYNRMESSAGE_TYPE_PUBLICATION, publication);
}
/**
* @param settings
* @param settings.from participantId of the sender
* @param settings.multicastName name of multicast
* @param {String[]} partitions partitions for this multicast
* @param settings.expiryDate time-to-live
* @param publication
* @param [publication.response]
* @param [publication.error]
* @param publication.multicastId
*/
public sendMulticastPublication(
settings: {
from: string;
multicastName?: string;
expiryDate: number;
},
publication: {
response?: any;
error?: any;
multicastId: string;
}
): void {
const multicastId = publication.multicastId;
log.info(
"publication",
DiagnosticTags.forMulticastPublication({
publication,
from: settings.from
})
);
// Reply with the result in a JoynrMessage
const publicationMessage = new JoynrMessage({
type: JoynrMessage.JOYNRMESSAGE_TYPE_MULTICAST,
payload: JSONSerializer.stringify(publication)
});
publicationMessage.from = settings.from;
publicationMessage.to = multicastId;
publicationMessage.expiryDate = this.upLiftTtl(settings.expiryDate);
if (log.isDebugEnabled()) {
log.debug(`sendMulticastPublication, message = ${JSON.stringify(publicationMessage)}`);
}
this.clusterControllerMessagingStub.transmit(publicationMessage);
}
/**
* receives a new JoynrMessage that has to be routed to one of the managers
*
* @param joynrMessage being routed
*/
public receive(joynrMessage: JoynrMessage): Promise<void> {
log.debug(`received message with id "${joynrMessage.msgId}"`);
if (log.isDebugEnabled()) {
log.debug(`receive, message = ${JSON.stringify(joynrMessage)}`);
}
let payload;
try {
payload = JSON.parse(joynrMessage.payload);
} catch (error) {
log.error(`error parsing joynrMessage: ${error} payload: ${joynrMessage.payload}`);
return Promise.resolve();
}
switch (joynrMessage.type) {
case JoynrMessage.JOYNRMESSAGE_TYPE_REQUEST:
try {
const request = Request.create(payload);
log.info(
`received request for ${request.methodName}.`,
DiagnosticTags.forRequest({
request,
to: joynrMessage.to,
from: joynrMessage.from
})
);
const handleReplySettings = this.createReplySettings(joynrMessage);
const effort = joynrMessage.effort;
if (effort && MessagingQosEffort[effort]) {
handleReplySettings.effort = MessagingQosEffort[effort];
}
if (joynrMessage.compress) {
handleReplySettings.compress = true;
}
return this.requestReplyManager.handleRequest(
joynrMessage.to,
request,
(handleReplySettings: any, reply: Reply.Reply) =>
this.sendRequestReply(handleReplySettings, reply),
handleReplySettings
);
} catch (errorInRequest) {
// TODO handle error in handling the request
log.error(`error handling request: ${errorInRequest}`);
}
break;
case JoynrMessage.JOYNRMESSAGE_TYPE_REPLY:
try {
const reply = Reply.create(payload);
log.info(
"received reply ",
DiagnosticTags.forReply({
reply,
to: joynrMessage.to,
from: joynrMessage.from
})
);
this.requestReplyManager.handleReply(reply);
} catch (errorInReply) {
// TODO handle error in handling the reply
log.error(`error handling reply: ${errorInReply}`);
}
break;
case JoynrMessage.JOYNRMESSAGE_TYPE_ONE_WAY:
try {
const oneWayRequest = OneWayRequest.create(payload);
log.info(
`received one way request for ${oneWayRequest.methodName}.`,
DiagnosticTags.forOneWayRequest({
request: oneWayRequest,
to: joynrMessage.to,
from: joynrMessage.from
})
);
this.requestReplyManager.handleOneWayRequest(joynrMessage.to, oneWayRequest);
} catch (errorInOneWayRequest) {
log.error(`error handling one way: ${errorInOneWayRequest}`);
}
break;
case JoynrMessage.JOYNRMESSAGE_TYPE_SUBSCRIPTION_REQUEST:
try {
const subscriptionRequest = this.upLiftExpiryDateInSubscriptionRequest(
new SubscriptionRequest(payload)
);
log.info(
`received subscription to ${subscriptionRequest.subscribedToName}`,
DiagnosticTags.forSubscriptionRequest({
subscriptionRequest,
to: joynrMessage.to,
from: joynrMessage.from
})
);
this.publicationManager.handleSubscriptionRequest(
joynrMessage.from,
joynrMessage.to,
subscriptionRequest,
this.sendSubscriptionReply,
this.createReplySettings(joynrMessage)
);
} catch (errorInSubscriptionRequest) {
// TODO handle error in handling the subscriptionRequest
log.error(`error handling subscriptionRequest: ${errorInSubscriptionRequest}`);
}
break;
case JoynrMessage.JOYNRMESSAGE_TYPE_BROADCAST_SUBSCRIPTION_REQUEST:
try {
const broadcastSubscriptionRequest = this.upLiftExpiryDateInSubscriptionRequest(
new BroadcastSubscriptionRequest(payload)
);
log.info(
`received broadcast subscription to ${broadcastSubscriptionRequest.subscribedToName}`,
DiagnosticTags.forBroadcastSubscriptionRequest({
subscriptionRequest: broadcastSubscriptionRequest,
to: joynrMessage.to,
from: joynrMessage.from
})
);
this.publicationManager.handleBroadcastSubscriptionRequest(
joynrMessage.from,
joynrMessage.to,
broadcastSubscriptionRequest,
this.sendSubscriptionReply,
this.createReplySettings(joynrMessage)
);
} catch (errorInBroadcastSubscriptionRequest) {
// TODO handle error in handling the subscriptionRequest
log.error(`error handling broadcastSubscriptionRequest: ${errorInBroadcastSubscriptionRequest}`);
}
break;
case JoynrMessage.JOYNRMESSAGE_TYPE_MULTICAST_SUBSCRIPTION_REQUEST:
try {
const multicastSubscriptionRequest = this.upLiftExpiryDateInSubscriptionRequest(
new MulticastSubscriptionRequest(payload)
);
log.info(
`received broadcast subscription to ${multicastSubscriptionRequest.subscribedToName}`,
DiagnosticTags.forMulticastSubscriptionRequest({
subscriptionRequest: multicastSubscriptionRequest,
to: joynrMessage.to,
from: joynrMessage.from
})
);
this.publicationManager.handleMulticastSubscriptionRequest(
joynrMessage.from,
joynrMessage.to,
multicastSubscriptionRequest,
this.sendSubscriptionReply,
this.createReplySettings(joynrMessage)
);
} catch (errorInMulticastSubscriptionRequest) {
// TODO handle error in handling the subscriptionRequest
log.error(`error handling multicastSubscriptionRequest: ${errorInMulticastSubscriptionRequest}`);
}
break;
case JoynrMessage.JOYNRMESSAGE_TYPE_SUBSCRIPTION_REPLY:
try {
const subscriptionReply = new SubscriptionReply(payload);
log.info(
"received subscription reply",
DiagnosticTags.forSubscriptionReply({
subscriptionReply,
to: joynrMessage.to,
from: joynrMessage.from
})
);
this.subscriptionManager.handleSubscriptionReply(subscriptionReply);
} catch (errorInSubscriptionReply) {
// TODO handle error in handling the subscriptionReply
log.error(`error handling subscriptionReply: ${errorInSubscriptionReply}`);
}
break;
case JoynrMessage.JOYNRMESSAGE_TYPE_SUBSCRIPTION_STOP:
try {
const subscriptionStop = new SubscriptionStop(payload);
log.info(
`received subscription stop ${subscriptionStop.subscriptionId}`,
DiagnosticTags.forSubscriptionStop({
subscriptionId: subscriptionStop.subscriptionId,
to: joynrMessage.to,
from: joynrMessage.from
})
);
this.publicationManager.handleSubscriptionStop(subscriptionStop);
} catch (errorInSubscriptionStop) {
// TODO handle error in handling the subscriptionStop
log.error(`error handling subscriptionStop: ${errorInSubscriptionStop}`);
}
break;
case JoynrMessage.JOYNRMESSAGE_TYPE_PUBLICATION:
try {
const subscriptionPublication = SubscriptionPublication.create(payload);
log.info(
"received publication",
DiagnosticTags.forPublication({
publication: subscriptionPublication,
to: joynrMessage.to,
from: joynrMessage.from
})
);
this.subscriptionManager.handlePublication(subscriptionPublication);
} catch (errorInPublication) {
// TODO handle error in handling the publication
log.error(`error handling publication: ${errorInPublication}`);
}
break;
case JoynrMessage.JOYNRMESSAGE_TYPE_MULTICAST:
try {
const multicastPublication = MulticastPublication.create(payload);
log.info(
"received publication",
DiagnosticTags.forMulticastPublication({
publication: multicastPublication,
from: joynrMessage.from
})
);
this.subscriptionManager.handleMulticastPublication(multicastPublication);
} catch (errorInMulticastPublication) {
// TODO handle error in handling the multicast publication
log.error(`error handling multicast publication: ${errorInMulticastPublication}`);
}
break;
default:
log.error(
`unknown JoynrMessage type : ${joynrMessage.type}. Discarding message: ${JSONSerializer.stringify(
joynrMessage
)}`
);
break;
}
return Promise.resolve();
}
/**
* Shutdown the dispatcher
*/
public shutdown(): void {
log.debug("Dispatcher shut down");
/* do nothing, as either the managers on the layer above (RRM, PM, SM) or
* the message router on the layer below are implementing the
* correct handling when the runtime is shut down
*/
}
}
export = Dispatcher; | the_stack |
const animInfo: { [anim: string]: { type: string } } = {
"idle": {type: "static"},
"attack": {type: "static"},
"weapon-reload": {type: "static"},
"walk": {type: "move"},
"static-idle": {type: "static"},
"static": {type: "static"},
"use": {type: "static"},
"pickUp": {type: "static"},
"climb": {type: "static"},
"hitFront": {type: "static"},
"death": {type: "static"},
"death-explode": {type: "static"},
"run": {type: "move"}
};
const weaponSkins: { [weapon: string]: string } = {
"uzi": 'i', "rifle": 'j'
};
const weaponAnims: { [weapon: string]: { [anim: string]: string } } = {
'punch': {'idle': 'aa', 'attack': 'aq'}
};
// TODO: (Double-sided) enum
const attackMode: { [mode: string]: string|number } = {
'none': 0, 'punch': 1, 'kick': 2, 'swing': 3,
'thrust': 4, 'throw': 5, 'fire single': 6,
'fire burst': 7, 'flame': 8,
0 : 'none', 1: 'punch', 2: 'kick', 3: 'swing',
4: 'thrust', 5: 'throw', 6: 'fire single',
7: 'fire burst', 8: 'flame'
};
// TODO: (Double-sided) enum
const damageType: { [type: string]: string|number } = {
'Normal': 0, 'Laser': 1, 'Fire': 2, 'Plasma': 3,
'Electrical': 4, 'EMP': 5, 'Explosive': 6,
0:'Normal', 1: 'Laser', 2: 'Fire', 3: 'Plasma',
4: 'Electrical', 5: 'EMP', 6: 'Explosive'
};
// TODO: Figure out if we can derive the correct info from the game somehow
const weaponSkillMap: { [weapon: string]: string } = {
'uzi': 'Small Guns',
'rifle': 'Small Guns',
'spear': 'Melee Weapons',
'knife': 'Melee Weapons',
'club': 'Melee Weapons',
'sledge': 'Melee Weapons',
'flamethr': 'Big Guns',
'pistol': 'Small Guns',
};
interface AttackInfo {
mode: number;
APCost: number;
maxRange: number;
}
function parseAttack(weapon: WeaponObj): {first: AttackInfo; second: AttackInfo} {
var attackModes = weapon.pro.extra['attackMode']
var modeOne = attackMode[attackModes & 0xf] as number
var modeTwo = attackMode[(attackModes >> 4) & 0xf] as number
var attackOne: AttackInfo = {mode: modeOne, APCost: 0, maxRange: 0}
var attackTwo: AttackInfo = {mode: modeTwo, APCost: 0, maxRange: 0}
if(modeOne !== attackMode.none) {
attackOne.APCost = weapon.pro.extra.APCost1
attackOne.maxRange = weapon.pro.extra.maxRange1
}
if(modeTwo !== attackMode.none) {
attackTwo.APCost = weapon.pro.extra.APCost2
attackTwo.maxRange = weapon.pro.extra.maxRange2
}
return {first: attackOne, second: attackTwo}
}
// TODO: improve handling of melee
class Weapon {
weapon: any; // TODO: any (because of melee)
name: string;
modes: string[];
mode: string; // current mode
type: string;
minDmg: number;
maxDmg: number;
weaponSkillType: string;
attackOne!: {mode: number; APCost: number; maxRange: number};
attackTwo!: {mode: number; APCost: number; maxRange: number};
constructor(weapon: WeaponObj) {
this.weapon = weapon
this.modes = ['single', 'called']
if(weapon === null) { // default punch
// todo: use character stats...
// todo: fully turn this into a real weapon
this.type = 'melee'
this.minDmg = 1
this.maxDmg = 2
this.name = 'punch'
this.weaponSkillType = 'Unarmed'
this.weapon = {}
this.weapon.pro = {extra: {}}
this.weapon.pro.extra.maxRange1 = 1
this.weapon.pro.extra.maxRange2 = 1
this.weapon.pro.extra.APCost1 = 4
this.weapon.pro.extra.APCost2 = 4
} else { // todo: spears, etc
this.type = 'gun'
this.minDmg = weapon.pro.extra.minDmg
this.maxDmg = weapon.pro.extra.maxDmg
var s = weapon.art.split('/')
this.name = s[s.length-1]
var attacks = parseAttack(weapon)
this.attackOne = attacks.first
this.attackTwo = attacks.second
this.weaponSkillType = weaponSkillMap[this.name]
if(this.weaponSkillType === undefined)
console.log("unknown weapon type for " + this.name)
}
this.mode = this.modes[0]
}
cycleMode(): void {
this.mode = this.modes[(this.modes.indexOf(this.mode) + 1) % this.modes.length]
}
isCalled(): boolean {
return this.mode === "called"
}
getProjectilePID(): number {
if(this.type === "melee")
return -1
return this.weapon.pro.extra.projPID
}
// TODO: enum
getMaximumRange(attackType: number): number {
if(attackType === 1) return this.weapon.pro.extra.maxRange1
if(attackType === 2) return this.weapon.pro.extra.maxRange2
else throw "invalid attack type " + attackType
}
getAPCost(attackMode: number): number {
return this.weapon.pro.extra["APCost" + attackMode]
}
getSkin(): string|null {
if(this.weapon.pro === undefined || this.weapon.pro.extra === undefined)
return null
const animCodeMap: { [animCode: number]: string } = {
0: 'a',// None
1: 'd', // Knife
2: 'e', // Club
3: 'f', // Sledgehammer
4: 'g', // Spear
5: 'h', // Pistol
6: 'i', // SMG
7: 'j', // Rifle
8: 'k', // Big Gun
9: 'l', // Minigun
10: 'm'} // Rocket Launcher
return animCodeMap[this.weapon.pro.extra.animCode]
}
getAttackSkin(): string|null {
if(this.weapon.pro === undefined || this.weapon.pro.extra === undefined)
return null
if(this.weapon === 'punch') return 'q'
const modeSkinMap: { [mode: string]: string } = {
'punch': 'q',
'kick': 'r',
'swing': 'g',
'thrust': 'f',
'throw': 's',
'fire single': 'j',
'fire burst': 'k',
'flame': 'l'
}
// TODO: mode equipped
if(this.attackOne.mode !== attackMode.none) {
return modeSkinMap[this.attackOne.mode]
}
throw "TODO"
}
getAnim(anim: string): string|null {
if(weaponAnims[this.name] && weaponAnims[this.name][anim])
return weaponAnims[this.name][anim]
var wep = this.getSkin() || 'a'
switch(anim) {
case 'idle': return wep + 'a'
case 'walk': return wep + 'b'
case 'attack':
var attackSkin = this.getAttackSkin()
return wep + attackSkin
default: return null // let something else handle it
}
}
canEquip(obj: Critter): boolean {
return imageInfo[critterGetBase(obj) + this.getAnim('attack')] !== undefined
}
getDamageType(): string {
// Return the (string) damage type of the weapon, e.g. "Normal", "Laser", ...
// Defaults to "Normal" if the weapon's PRO does not provide one.
const rawDmgType = this.weapon.pro.extra.dmgType;
return rawDmgType !== undefined ? damageType[rawDmgType] as string : "Normal";
}
}
function critterGetBase(obj: Critter): string {
return obj.art.slice(0, -2)
}
function critterGetEquippedWeapon(obj: Critter): WeaponObj|null {
// TODO: Get actual selection
if(objectIsWeapon(obj.leftHand)) return obj.leftHand || null
if(objectIsWeapon(obj.rightHand)) return obj.rightHand || null
return null
}
function critterGetAnim(obj: Critter, anim: string): string {
var base = critterGetBase(obj)
// try weapon animation first
var weaponObj = critterGetEquippedWeapon(obj)
if(weaponObj !== null && Config.engine.doUseWeaponModel === true) {
if(!weaponObj.weapon) throw Error();
var wepAnim = weaponObj.weapon.getAnim(anim)
if(wepAnim)
return base + wepAnim
}
var wep = 'a'
switch(anim) {
case "attack":
console.log("default attack animation instead of weapon animation.")
return base + wep + 'a'
case "idle": return base + wep + 'a'
case "walk": return base + wep + 'b'
case "run": return base + wep + 't'
case "shoot": return base + wep + 'j'
case "weapon-reload": return base + wep + 'a'
case "static-idle": return base + wep + 'a'
case "static": return obj.art
case "hitFront": return base + 'ao'
case "use": return base + 'al'
case "pickUp": return base + 'ak'
case "climb": return base + 'ae'
//case "punch": return base + 'aq'
case "called-shot": return base + 'na'
case "death":
if(obj.pro && obj.pro.extra.killType === 18) { // Boss is special-cased
console.log("Boss death...")
return base + 'bl'
}
return base + 'bo' // TODO: choose death animation better
case "death-explode": return base + 'bl'
default: throw "Unknown animation: " + anim
}
}
function critterHasAnim(obj: Critter, anim: string): boolean {
return imageInfo[critterGetAnim(obj, anim)] !== undefined
}
function critterGetKillType(obj: Critter): number|null {
if(obj.isPlayer) return 19 // last type
if(!obj.pro || !obj.pro.extra) return null
return obj.pro.extra.killType
}
function getAnimDistance(art: string): number {
var info = imageInfo[art]
if(info === undefined)
throw "no image info for " + art
var firstShift = info.frameOffsets[0][0].ox
var lastShift = info.frameOffsets[1][info.numFrames-1].ox
// distance = (shift x of last frame) - (shift x of first frame(?) + 16) / 32
return Math.floor((lastShift - firstShift + 16) / 32)
}
function critterStaticAnim(obj: Critter, anim: string, callback?: () => void, waitForLoad: boolean=true): void {
obj.art = critterGetAnim(obj, anim)
obj.frame = 0
obj.lastFrameTime = 0
if(waitForLoad) {
lazyLoadImage(obj.art, function() {
obj.anim = anim
obj.animCallback = callback || (() => obj.clearAnim())
})
}
else {
obj.anim = anim
obj.animCallback = callback || (() => obj.clearAnim())
}
}
function getDirectionalOffset(obj: Critter): Point {
var info = imageInfo[obj.art]
if(info === undefined)
throw "No image map info for: " + obj.art
return info.directionOffsets[obj.orientation]
}
interface PartialAction {
startFrame: number;
endFrame: number;
step: number;
}
function getAnimPartialActions(art: string, anim: string): { movement: number, actions: PartialAction[] } {
const partialActions = { movement: 0, actions: [] as PartialAction[] };
let numPartials = 1
if(anim === "walk" || anim === "run") {
numPartials = getAnimDistance(art)
partialActions.movement = numPartials
}
if(numPartials === 0)
numPartials = 1
var delta = Math.floor(imageInfo[art].numFrames / numPartials)
var startFrame = 0
var endFrame = delta
for(var i = 0; i < numPartials; i++) {
partialActions.actions.push({startFrame: startFrame,
endFrame: endFrame,
step: i})
startFrame += delta
endFrame += delta // ?
}
// extend last partial action to the last frame
partialActions.actions[partialActions.actions.length-1].endFrame = imageInfo[art].numFrames
//console.log("partials: %o", partialActions)
return partialActions
}
function hitSpatialTrigger(position: Point): any { // TODO: return type (SpatialTrigger)
return gMap.getSpatials().filter(spatial => hexDistance(position, spatial.position) <= spatial.range)
}
function critterKill(obj: Critter, source?: Critter, useScript?: boolean, animName?: string, callback?: () => void) {
obj.dead = true
obj.outline = null
if(useScript === undefined || useScript === true) {
Scripting.destroy(obj, source)
}
if(!animName || !critterHasAnim(obj, animName))
animName = "death"
critterStaticAnim(obj, animName, function() {
// todo: corpse-ify
obj.frame-- // go to last frame
obj.anim = undefined
if(callback) callback()
}, true)
}
function critterDamage(obj: Critter, damage: number, source: Critter, useScript: boolean=true, useAnim: boolean=true, damageType?: string, callback?: () => void) {
obj.stats.modifyBase("HP", -damage);
if(critterGetStat(obj, "HP") <= 0)
return critterKill(obj, source, useScript);
if(useScript) {
// TODO: Call damage_p_proc
}
// TODO: other hit animations
if(useAnim && critterHasAnim(obj, "hitFront")) {
critterStaticAnim(obj, "hitFront", () => {
obj.clearAnim();
if(callback) callback();
});
}
}
function critterGetStat(obj: Critter, stat: string) {
return obj.stats.get(stat);
}
function critterGetRawStat(obj: Critter, stat: string) {
return obj.stats.getBase(stat);
}
function critterSetRawStat(obj: Critter, stat: string, amount: number) {
// obj.stats[stat] = amount
console.warn(`TODO: Change stat ${stat} to ${amount}`);
}
function critterGetSkill(obj: Critter, skill: string) {
return obj.skills.get(skill, obj.stats);
}
function critterGetRawSkill(obj: Critter, skill: string) {
return obj.skills.getBase(skill);
}
function critterSetRawSkill(obj: Critter, skill: string, amount: number) {
// obj.skills[skill] = amount
console.warn(`TODO: Change skill ${skill} to ${amount}`);
}
interface SerializedCritter extends SerializedObj {
stats: any;
skills: any;
// TODO: Properly (de)serialize WeaponObj
// leftHand: SerializedObj;
// rightHand: SerializedObj;
aiNum: number;
teamNum: number;
// ai: AI; // TODO
hostile: boolean;
isPlayer: boolean;
dead: boolean;
}
const SERIALIZED_CRITTER_PROPS = ["stats", "skills", "aiNum", "teamNum", "hostile", "isPlayer", "dead"];
class Critter extends Obj {
stats!: StatSet;
skills!: SkillSet;
leftHand?: WeaponObj; // Left-hand object slot
rightHand?: WeaponObj; // Right-hand object slot
type = "critter";
anim = "idle";
path: any = null; // Holds pathfinding objects
AP: ActionPoints|null = null;
aiNum: number = -1; // AI packet number
teamNum: number = -1; // AI team number (TODO: implement this)
ai: AI|null = null; // AI packet
hostile: boolean = false; // Currently engaging an enemy?
isPlayer: boolean = false; // Is this critter the player character?
dead: boolean = false; // Is this critter dead?
static fromPID(pid: number, sid?: number): Critter {
return Obj.fromPID_(new Critter(), pid, sid)
}
static fromMapObject(mobj: any, deserializing: boolean=false): Critter {
const obj = Obj.fromMapObject_(new Critter(), mobj, deserializing);
if(deserializing) { // deserialize critter: copy fields from SerializedCritter
console.log("Deserializing critter");
// console.trace();
for(const prop of SERIALIZED_CRITTER_PROPS) {
// console.log(`loading prop ${prop} from SerializedCritter = ${mobj[prop]}`);
(<any>obj)[prop] = mobj[prop];
}
if(mobj.stats) {
obj.stats = new StatSet(mobj.stats.baseStats, mobj.stats.useBonuses);
console.warn("Deserializing stat set: %o to: %o", mobj.stats, obj.stats)
}
if(mobj.skills) {
obj.skills = new SkillSet(mobj.skills.baseSkills, mobj.skills.tagged, mobj.skills.skillPoints);
console.warn("Deserializing skill set: %o to: %o", mobj.skills, obj.skills)
}
}
return obj;
}
init() {
super.init()
this.stats = StatSet.fromPro(this.pro)
this.skills = SkillSet.fromPro(this.pro.extra.skills)
// console.log("Loaded stats/skills from PRO: HP=%d Speech=%d", this.stats.get("HP"), this.skills.get("Speech", this.stats))
this.name = getMessage("pro_crit", this.pro.textID) || ""
// initialize AI packet / team number
this.aiNum = this.pro.extra.AI
this.teamNum = this.pro.extra.team
// initialize weapons
this.inventory.forEach(inv => {
if(inv.subtype === "weapon") {
var w = <WeaponObj>inv
if(this.leftHand === undefined) {
if(w.weapon!.canEquip(this))
this.leftHand = w
}
else if(this.rightHand === undefined) {
if(w.weapon!.canEquip(this))
this.rightHand = w
}
//console.log("left: " + this.leftHand + " | right: " + this.rightHand)
}
})
// default to punches
if(!this.leftHand)
this.leftHand = <WeaponObj>{type: "item", subtype: "weapon", weapon: new Weapon(null)}
if(!this.rightHand)
this.rightHand = <WeaponObj>{type: "item", subtype: "weapon", weapon: new Weapon(null)}
// set them in their proper idle state for the weapon
this.art = critterGetAnim(this, "idle")
}
updateStaticAnim(): void {
var time = heart.timer.getTime()
var fps = 8 // todo: get FPS from image info
if(time - this.lastFrameTime >= 1000/fps) {
this.frame++
this.lastFrameTime = time
if(this.frame === imageInfo[this.art].numFrames) {
// animation is done
if(this.animCallback)
this.animCallback()
}
}
}
updateAnim(): void {
if(!this.anim || this.anim === "idle") return
if(animInfo[this.anim].type === "static") return this.updateStaticAnim()
var time = heart.timer.getTime()
var fps = imageInfo[this.art].fps
var targetScreen = hexToScreen(this.path.target.x, this.path.target.y)
var partials = getAnimPartialActions(this.art, this.anim)
var currentPartial = partials.actions[this.path.partial]
if(time - this.lastFrameTime >= 1000/fps) {
// advance frame
this.lastFrameTime = time
if(this.frame === currentPartial.endFrame || this.frame+1 >= imageInfo[this.art].numFrames) {
// completed an action frame (partial action)
// do we have another partial action?
if(this.path.partial+1 < partials.actions.length) {
// then proceed to next partial action
this.path.partial++
} else {
// otherwise we're done animating this, loop
this.path.partial = 0
}
// move to the start of the next partial action
// we're already on its startFrame which coincides with the current endFrame,
// so we add one to get to the next frame.
// unless we're the first one, in which case just 0.
var nextFrame = partials.actions[this.path.partial].startFrame + 1
if(this.path.partial === 0)
nextFrame = 0
this.frame = nextFrame
// reset shift
this.shift = {x: 0, y: 0}
// move to new path hex
var pos = this.path.path[this.path.index++]
var hex = {x: pos[0], y: pos[1]}
if(!this.move(hex))
return
if(!this.path) // it's possible for move() to have side effects which can clear the anim
return
// set orientation towards new path hex
pos = this.path.path[this.path.index]
if(pos) {
const dir = directionOfDelta(this.position.x, this.position.y, pos[0], pos[1]);
if(dir == null) throw Error();
this.orientation = dir;
}
}
else {
// advance frame
this.frame++
var info = imageInfo[this.art]
if(info === undefined)
throw "No image map info for: " + this.art
// add the new frame's offset to our shift
var frameInfo = info.frameOffsets[this.orientation][this.frame]
this.shift.x += frameInfo.x
this.shift.y += frameInfo.y
}
if(this.position.x === this.path.target.x && this.position.y === this.path.target.y) {
// reached target position
// TODO: better logging system
//console.log("target reached")
var callback = this.animCallback
this.clearAnim()
if(callback)
callback()
}
}
}
blocks(): boolean {
return (this.dead !== true) && (this.visible !== false)
}
inAnim(): boolean {
return !!(this.path || this.animCallback)
}
move(position: Point, curIdx?: number, signalEvents: boolean=true): boolean {
if(!super.move(position, curIdx, signalEvents))
return false
if(Config.engine.doSpatials !== false) {
var hitSpatials = hitSpatialTrigger(position)
for(var i = 0; i < hitSpatials.length; i++) {
var spatial = hitSpatials[i]
console.log("triggered spatial " + spatial.script + " (" + spatial.range + ") @ " +
spatial.position.x + ", " + spatial.position.y)
Scripting.spatial(spatial, this)
}
}
return true
}
canRun(): boolean {
return critterHasAnim(this, "run")
}
clearAnim(): void {
super.clearAnim()
this.path = null
// reset to idle pose
this.anim = "idle"
this.art = critterGetAnim(this, "idle")
}
walkTo(target: Point, running?: boolean, callback?: () => void, maxLength?: number, path?: any): boolean {
// pathfind and set walking to target
if(this.position.x === target.x && this.position.y === target.y) {
// can't walk to the same tile
return false
}
if(path === undefined)
path = recalcPath(this.position, target)
if(path.length === 0) {
// no path
//console.log("not a valid path")
return false
}
if(maxLength !== undefined && path.length > maxLength) {
console.log("truncating path (to length " + maxLength + ")")
path = path.slice(0, maxLength + 1)
}
// some critters can't run
if(running && !this.canRun())
running = false
// set up animation properties
var actualTarget = {x: path[path.length-1][0], y: path[path.length-1][1]}
this.path = {path: path, index: 1, target: actualTarget, partial: 0}
this.anim = running ? "run" : "walk"
this.art = critterGetAnim(this, this.anim)
this.animCallback = callback || (() => this.clearAnim())
this.frame = 0
this.lastFrameTime = heart.timer.getTime()
this.shift = {x: 0, y: 0}
const dir = directionOfDelta(this.position.x, this.position.y, path[1][0], path[1][1])
if(dir == null) throw Error();
this.orientation = dir;
//console.log("start dir: %o", this.orientation)
return true
}
walkInFrontOf(targetPos: Point, callback?: () => void): boolean {
var path = recalcPath(this.position, targetPos, false)
if(path.length === 0) // invalid path
return false
else if(path.length <= 2) { // we're already infront of or on it
if(callback)
callback()
return true
}
path.pop() // we don't want targetPos in the path
var target = path[path.length - 1]
targetPos = {x: target[0], y: target[1]}
var running = Config.engine.doAlwaysRun
if(hexDistance(this.position, targetPos) > 5)
running = true
//console.log("path: %o, callback %o", path, callback)
return this.walkTo(targetPos, running, callback, undefined, path)
}
serialize(): SerializedCritter {
const obj = <SerializedCritter>super.serialize();
for(const prop of SERIALIZED_CRITTER_PROPS) {
// console.log(`saving prop ${prop} from SerializedCritter = ${this[prop]}`);
(<any>obj)[prop] = (<any>this)[prop];
}
return obj;
}
} | the_stack |
import { ReplayMap } from './ReplayMap'
import { ReplayChunk } from './ReplayChunk'
import { ReplayState } from './ReplayState'
import { Reader, ReaderDataType } from '../Reader'
import { FrameDataReader } from './FrameDataReader'
import { getInitialDeltaDecoders } from './readDelta'
const checkType = (r: Reader) => {
let magic = r.nstr(8)
return magic === 'HLDEMO'
}
const readHeader = (r: Reader) => ({
demoProtocol: r.ui(),
netProtocol: r.ui(),
mapName: r.nstr(260),
modName: r.nstr(260),
mapCrc: r.i(),
dirOffset: r.ui()
})
const readDirectories = (r: Reader, offset: number) => {
r.seek(offset)
let count = r.ui()
let directories = []
for (let i = 0; i < count; ++i) {
directories.push({
id: r.ui(),
name: r.nstr(64),
flags: r.ui(),
cdTrack: r.i(),
time: r.f(),
frames: r.ui(),
offset: r.ui(),
length: r.ui()
})
}
return directories
}
const readFrameData = (r: Reader, deltaDecoders: any, customMessages: any) => {
let length = r.ui()
let limit = r.tell() + length
let data = []
while (r.tell() < limit) {
let type = r.ub()
if (type === 1) {
continue
} else if (type >= 64) {
if (customMessages[type] && customMessages[type].size > -1) {
r.skip(customMessages[type].size)
} else {
r.skip(r.ub())
}
continue
}
let message = FrameDataReader.read(r, type, deltaDecoders)
if (message) {
if (type === 39) {
customMessages[message.index] = message
}
data.push({
type,
data: message
})
} else {
r.seek(limit)
}
}
// just in case
r.seek(limit)
return data
}
const readFrame = (r: Reader, deltaDecoders: any, customMessages: any) => {
let frame: any = {
type: r.ub(),
time: r.f(),
tick: r.ui()
}
switch (frame.type) {
case 0:
case 1: {
r.skip(4)
frame.camera = {
position: [r.f(), r.f(), r.f()],
orientation: [r.f(), r.f(), r.f()]
}
r.skip(436)
frame.data = readFrameData(r, deltaDecoders, customMessages)
break
}
case 2: {
break
}
case 3: {
frame.command = r.nstr(64)
break
}
case 4: {
r.skip(32)
break
}
case 5: {
break
}
case 6: {
r.skip(84)
break
}
case 7: {
r.skip(8)
break
}
case 8: {
frame.sound = {
channel: r.i(),
sample: r.nstr(r.ui()),
attenuation: r.f(),
volume: r.f(),
flags: r.ui(),
pitch: r.i()
}
break
}
case 9: {
r.skip(r.ui())
break
}
default: {
frame.error = true
break
}
}
return frame
}
export class Replay {
header: any
mapName: string
directories: any
constructor(header: any, directories: any) {
this.header = header
this.mapName = this.header.mapName
this.directories = directories
}
static parseFromArrayBuffer(buffer: ArrayBuffer) {
let r = new Reader(buffer)
let magic = r.nstr(8)
if (magic !== 'HLDEMO') {
throw new Error('Invalid replay format')
}
let header: any = {}
header.demoProtocol = r.ui()
header.netProtocol = r.ui()
header.mapName = r.nstr(260)
header.modName = r.nstr(260)
header.mapCrc = r.i()
header.dirOffset = r.ui()
r.seek(header.dirOffset)
let directoryCount = r.ui()
let directories: any[] = []
for (let i = 0; i < directoryCount; ++i) {
directories.push({
id: r.ui(),
name: r.nstr(64),
flags: r.ui(),
cdTrack: r.i(),
time: r.f(),
frames: r.ui(),
offset: r.ui(),
length: r.ui(),
macros: []
})
}
for (let i = 0; i < directories.length; ++i) {
r.seek(directories[i].offset)
let isFinalMacroReached = false
while (!isFinalMacroReached) {
let macro: any = {
type: r.b(),
time: r.f(),
frame: r.ui()
}
switch (macro.type) {
case 0:
case 1: {
r.skip(4)
macro.camera = {
position: [r.f(), r.f(), r.f()],
orientation: [r.f(), r.f(), r.f()]
}
r.skip(436)
r.skip(r.ui())
break
}
case 2: {
// empty macro
// signals the beginning of directory entry
break
}
case 3: {
macro.command = r.nstr(64)
break
}
case 4: {
r.skip(32)
break
}
case 5: {
// empty macro that signals end of directory entry
isFinalMacroReached = true
break
}
case 6: {
r.skip(84)
break
}
case 7: {
r.skip(8)
break
}
case 8: {
r.skip(4)
r.skip(r.ui() + 16)
break
}
case 9: {
r.skip(r.ui())
break
}
default: {
const offset = Number(r.tell() - 9).toString(16)
const msg = [
`Unexpected macro (${macro.type})`,
` at offset = ${offset}.`
].join('')
throw new Error(msg)
}
}
directories[i].macros.push(macro)
}
}
return new Replay(header, directories)
}
static parseFullFromArrayBuffer(buffer: ArrayBuffer) {
let r = new Reader(buffer)
let magic = r.nstr(8)
if (magic !== 'HLDEMO') {
throw new Error('Invalid replay format')
}
let header: any = {}
header.demoProtocol = r.ui()
header.netProtocol = r.ui()
header.mapName = r.nstr(260)
header.modName = r.nstr(260)
header.mapCrc = r.i()
header.dirOffset = r.ui()
r.seek(header.dirOffset)
let directoryCount = r.ui()
let directories: any[] = []
for (let i = 0; i < directoryCount; ++i) {
directories.push({
id: r.ui(),
name: r.nstr(64),
flags: r.ui(),
cdTrack: r.i(),
time: r.f(),
frames: r.ui(),
offset: r.ui(),
length: r.ui(),
macros: []
})
}
let deltaDecoders = getInitialDeltaDecoders()
let customMessages = []
for (let i = 0; i < directories.length; ++i) {
r.seek(directories[i].offset)
let isFinalMacroReached = false
while (!isFinalMacroReached) {
let macro: any = {
type: r.b(),
time: r.f(),
frame: r.ui()
}
switch (macro.type) {
case 0:
case 1: {
r.skip(4)
macro.camera = {
position: [r.f(), r.f(), r.f()],
orientation: [r.f(), r.f(), r.f()],
forward: [r.f(), r.f(), r.f()],
right: [r.f(), r.f(), r.f()],
up: [r.f(), r.f(), r.f()]
}
macro.RefParams = {
frametime: r.f(),
time: r.f(),
intermission: r.i(),
paused: r.i(),
spectator: r.i(),
onground: r.i(),
waterlevel: r.i(),
velocity: [r.f(), r.f(), r.f()],
origin: [r.f(), r.f(), r.f()],
viewHeight: [r.f(), r.f(), r.f()],
idealPitch: r.f(),
viewAngles: [r.f(), r.f(), r.f()],
health: r.i(),
crosshairAngle: [r.f(), r.f(), r.f()],
viewSize: r.f(),
punchAngle: [r.f(), r.f(), r.f()],
maxClients: r.i(),
viewEntity: r.i(),
playerCount: r.i(),
maxEntities: r.i(),
demoPlayback: r.i(),
hardware: r.i(),
smoothing: r.i(),
ptr_cmd: r.i(),
ptr_movevars: r.i(),
viewport: [r.i(), r.i(), r.i(), r.i()],
nextView: r.i(),
onlyClientDraw: r.i()
}
macro.UserCmd = {
lerp_msec: r.s(),
msec: r.ub(),
UNUSED1: r.ub(),
viewAngles: [r.f(), r.f(), r.f()],
forwardMove: r.f(),
sideMove: r.f(),
upMove: r.f(),
lightLevel: r.b(),
UNUSED2: r.ub(),
buttons: r.us(),
impulse: r.b(),
weaponSelect: r.b(),
UNUSED: r.s(),
impactIndex: r.i(),
impactPosition: [r.f(), r.f(), r.f()]
}
macro.MoveVars = {
gravity: r.f(),
stopSpeed: r.f(),
maxSpeed: r.f(),
spectatorMaxSpeed: r.f(),
acceleration: r.f(),
airAcceleration: r.f(),
waterAcceleration: r.f(),
friction: r.f(),
edgeFriction: r.f(),
waterFriction: r.f(),
entityGravity: r.f(),
bounce: r.f(),
stepSize: r.f(),
maxVelocity: r.f(),
zMax: r.f(),
waveHeight: r.f(),
footsteps: r.i(),
skyName: r.nstr(32),
rollAngle: r.f(),
rollSpeed: r.f(),
skyColor: [r.f(), r.f(), r.f()],
skyVec: [r.f(), r.f(), r.f()]
}
macro.view = [r.f(), r.f(), r.f()]
macro.viewModel = r.i()
macro.incoming_sequence = r.i()
macro.incoming_acknowledged = r.i()
macro.incoming_reliable_acknowledged = r.i()
macro.incoming_reliable_sequence = r.i()
macro.outgoing_sequence = r.i()
macro.reliable_sequence = r.i()
macro.last_reliable_sequence = r.i()
let frameDataLength = r.ui()
let frameDataEnd = frameDataLength + r.tell()
macro.frameData = []
while (r.tell() < frameDataEnd) {
let type = r.ub()
if (type === 1) {
continue // skip SVC_NOP
} else if (type >= 64) {
// TODO: parse custom message
if (customMessages[type] && customMessages[type].size > -1) {
r.skip(customMessages[type].size)
} else {
r.skip(r.ub())
}
continue
}
let frameData = FrameDataReader.read(r, type, deltaDecoders)
if (frameData) {
if (type === 39) {
customMessages[frameData.index] = frameData
}
macro.frameData.push({ type, frameData })
} else {
r.seek(frameDataEnd)
}
}
// if r.tell() > frameDataEnd something wrong happened
r.seek(frameDataEnd)
break
}
case 2: {
// empty macro
// signals the beginning of directory entry
break
}
case 3: {
macro.command = r.nstr(64)
break
}
case 4: {
macro.clientData = {
position: [r.f(), r.f(), r.f()],
rotation: [r.f(), r.f(), r.f()],
weaponFlags: r.ui(),
fov: r.f()
}
break
}
case 5: {
// empty macro that signals end of directory entry
isFinalMacroReached = true
break
}
case 6: {
macro.event = {
flags: r.ui(),
index: r.ui(),
delay: r.f(),
args: {
flags: r.ui(),
entityIndex: r.ui(),
position: [r.f(), r.f(), r.f()],
rotation: [r.f(), r.f(), r.f()],
velocity: [r.f(), r.f(), r.f()],
ducking: r.ui(),
fparam1: r.f(),
fparam2: r.f(),
iparam1: r.i(),
iparam2: r.i(),
bparam1: r.i(),
bparam2: r.i()
}
}
break
}
case 7: {
macro.weaponAnimation = {
animation: r.i(),
body: r.i()
}
break
}
case 8: {
macro.sound = {
channel: r.i(),
sample: r.nstr(r.ui()),
attenuation: r.f(),
volume: r.f(),
flags: r.ui(),
pitch: r.i()
}
break
}
case 9: {
r.skip(r.ui())
break
}
default: {
const offset = Number(r.tell() - 9).toString(16)
const msg = `Unexpected macro (${macro.type}) at offset = ${offset}`
throw new Error(msg)
}
}
directories[i].macros.push(macro)
}
}
return new Replay(header, directories)
}
static parseIntoChunks(buffer: ArrayBuffer) {
let r = new Reader(buffer)
if (!checkType(r)) {
throw new Error('Invalid replay file format')
}
let maps = []
let deltaDecoders = getInitialDeltaDecoders()
let customMessages: any[] = []
let header = readHeader(r)
let directories = readDirectories(r, header.dirOffset)
let currentMap: ReplayMap | undefined
let currentChunk
let lastFrame
let lastFrameOffset
let state = new ReplayState()
let directoryEndOffset
// read loading segment
directoryEndOffset = directories[0].offset + directories[0].length
r.seek(directories[0].offset)
while (r.tell() < directoryEndOffset) {
let frame = readFrame(r, deltaDecoders, customMessages)
state.feedFrame(frame)
if (frame.error) {
throw new Error('Encountered error while reading replay')
}
if (frame.type < 2 /* 0 or 1 */) {
let serverInfo = frame.data.find(
(msg: any) => msg.type === FrameDataReader.SVC.SERVERINFO
)
if (serverInfo) {
currentMap = new ReplayMap(serverInfo.data.mapFileName)
maps.push(currentMap)
}
let resourceList = frame.data.find(
(msg: any) => msg.type === FrameDataReader.SVC.RESOURCELIST
)
if (resourceList && currentMap) {
currentMap.setResources(resourceList.data)
}
}
}
if (!(currentMap instanceof ReplayMap)) {
throw new Error('Error while parsing replay.')
}
lastFrameOffset = r.tell()
currentChunk = new ReplayChunk(state, 0)
currentMap.addChunk(currentChunk)
// read playback segment
directoryEndOffset = directories[1].offset + directories[1].length
r.seek(directories[1].offset)
while (true) {
let offset = r.tell()
if (offset >= directoryEndOffset) {
// set last and final chunks data
let timeLength = lastFrame.time - currentChunk.startTime
currentChunk.timeLength = timeLength
let lastFrameLength = offset - lastFrameOffset
r.seek(lastFrameOffset)
currentChunk.setData(r.arrx(lastFrameLength, ReaderDataType.UByte))
r.seek(offset)
break
}
let frame = readFrame(r, deltaDecoders, customMessages)
state.feedFrame(frame)
lastFrame = frame
if (frame.error) {
throw new Error('Encountered error while reading replay')
}
if (frame.type < 2) {
let serverInfo = frame.data.find(
(msg: any) => msg.type === FrameDataReader.SVC.SERVERINFO
)
if (serverInfo) {
// create new map
currentMap = new ReplayMap(serverInfo.data.mapFileName)
maps.push(currentMap)
// set last chunks data
let timeLength = lastFrame.time - currentChunk.startTime
currentChunk.timeLength = timeLength
let lastFrameLength = offset - lastFrameOffset
let tempOffset = r.tell()
r.seek(lastFrameOffset)
currentChunk.setData(r.arrx(lastFrameLength, ReaderDataType.UByte))
r.seek(tempOffset)
// create new chunk
lastFrameOffset = offset
currentChunk = new ReplayChunk(state, frame.time)
currentMap.addChunk(currentChunk)
}
let resourceList = frame.data.find(
(msg: any) => msg.type === FrameDataReader.SVC.RESOURCELIST
)
if (resourceList) {
currentMap.setResources(resourceList.data)
}
if (serverInfo) {
continue
}
for (let i = 0; i < frame.data.length; ++i) {
let message = frame.data[i]
if (
message.type === FrameDataReader.SVC.SOUND ||
message.type === FrameDataReader.SVC.SPAWNSTATICSOUND
) {
let sound = currentMap.resources.sounds.find(
(s: any) => s.index === message.data.soundIndex
)
if (sound) {
sound.used = true
}
} else if (message.type === FrameDataReader.SVC.STUFFTEXT) {
let sounds = currentMap.resources.sounds
let commands = message.data.commands
for (let i = 0; i < commands.length; ++i) {
let command = commands[i]
let func = command.func
if (
(func === 'speak' || func === 'spk') &&
command.params.length === 1
) {
let soundName = command.params[0] + '.wav'
let sound = sounds.find((s: any) => s.name === soundName)
if (sound) {
sound.used = true
}
}
}
}
}
} else if (frame.type === 8) {
let sound = currentMap.resources.sounds.find(
(s: any) => s.name === frame.sound.sample
)
if (sound) {
sound.used = true
}
}
if (currentChunk.startTime + 10 < frame.time) {
// set last chunks data
let lastFrameLength = offset - lastFrameOffset
let tempOffset = r.tell()
r.seek(lastFrameOffset)
currentChunk.setData(r.arrx(lastFrameLength, ReaderDataType.UByte))
r.seek(tempOffset)
// create new chunk
lastFrameOffset = offset
currentChunk = new ReplayChunk(state, frame.time)
currentMap.addChunk(currentChunk)
}
}
return {
length: directories[1].time,
maps,
deltaDecoders,
customMessages
}
}
static readHeader(r: Reader) {
return readHeader(r)
}
static readDirectories(r: Reader, offset: number) {
return readDirectories(r, offset)
}
static readFrame(r: Reader, deltaDecoders: any, customMessages: any) {
return readFrame(r, deltaDecoders, customMessages)
}
static readFrameData(r: Reader, deltaDecoders: any, customMessages: any) {
return readFrame(r, deltaDecoders, customMessages)
}
} | the_stack |
import { Environment } from "@hoppscotch/data"
import { cloneDeep } from "lodash"
import isEqual from "lodash/isEqual"
import { combineLatest, Observable } from "rxjs"
import { distinctUntilChanged, map, pluck } from "rxjs/operators"
import DispatchingStore, {
defineDispatchers,
} from "~/newstore/DispatchingStore"
const defaultEnvironmentsState = {
environments: [
{
name: "My Environment Variables",
variables: [],
},
] as Environment[],
globals: [] as Environment["variables"],
// Current environment index specifies the index
// -1 means no environments are selected
currentEnvironmentIndex: -1,
}
type EnvironmentStore = typeof defaultEnvironmentsState
const dispatchers = defineDispatchers({
setCurrentEnviromentIndex(
{ environments }: EnvironmentStore,
{ newIndex }: { newIndex: number }
) {
if (newIndex >= environments.length || newIndex <= -2) {
// console.log(
// `Ignoring possibly invalid current environment index assignment (value: ${newIndex})`
// )
return {}
}
return {
currentEnvironmentIndex: newIndex,
}
},
appendEnvironments(
{ environments }: EnvironmentStore,
{ envs }: { envs: Environment[] }
) {
return {
environments: [...environments, ...envs],
}
},
replaceEnvironments(
_: EnvironmentStore,
{ environments }: { environments: Environment[] }
) {
return {
environments,
}
},
createEnvironment(
{ environments }: EnvironmentStore,
{ name }: { name: string }
) {
return {
environments: [
...environments,
{
name,
variables: [],
},
],
}
},
duplicateEnvironment(
{ environments }: EnvironmentStore,
{ envIndex }: { envIndex: number }
) {
const newEnvironment = environments.find((_, index) => index === envIndex)
if (!newEnvironment) {
return {
environments,
}
}
return {
environments: [
...environments,
{
...cloneDeep(newEnvironment),
name: `${newEnvironment.name} - Duplicate`,
},
],
}
},
deleteEnvironment(
{ environments, currentEnvironmentIndex }: EnvironmentStore,
{ envIndex }: { envIndex: number }
) {
let newCurrEnvIndex = currentEnvironmentIndex
// Scenario 1: Currently Selected Env is removed -> Set currently selected to none
if (envIndex === currentEnvironmentIndex) newCurrEnvIndex = -1
// Scenario 2: Currently Selected Env Index > Deletion Index -> Current Selection Index Shifts One Position to the left -> Correct Env Index by moving back 1 index
if (envIndex < currentEnvironmentIndex)
newCurrEnvIndex = currentEnvironmentIndex - 1
// Scenario 3: Currently Selected Env Index < Deletion Index -> No change happens at selection position -> Noop
return {
environments: environments.filter((_, index) => index !== envIndex),
currentEnvironmentIndex: newCurrEnvIndex,
}
},
renameEnvironment(
{ environments }: EnvironmentStore,
{ envIndex, newName }: { envIndex: number; newName: string }
) {
return {
environments: environments.map((env, index) =>
index === envIndex
? {
...env,
name: newName,
}
: env
),
}
},
updateEnvironment(
{ environments }: EnvironmentStore,
{ envIndex, updatedEnv }: { envIndex: number; updatedEnv: Environment }
) {
return {
environments: environments.map((env, index) =>
index === envIndex ? updatedEnv : env
),
}
},
addEnvironmentVariable(
{ environments }: EnvironmentStore,
{ envIndex, key, value }: { envIndex: number; key: string; value: string }
) {
return {
environments: environments.map((env, index) =>
index === envIndex
? {
...env,
variables: [...env.variables, { key, value }],
}
: env
),
}
},
removeEnvironmentVariable(
{ environments }: EnvironmentStore,
{ envIndex, variableIndex }: { envIndex: number; variableIndex: number }
) {
return {
environments: environments.map((env, index) =>
index === envIndex
? {
...env,
variables: env.variables.filter(
(_, vIndex) => vIndex !== variableIndex
),
}
: env
),
}
},
setEnvironmentVariables(
{ environments }: EnvironmentStore,
{
envIndex,
vars,
}: { envIndex: number; vars: { key: string; value: string }[] }
) {
return {
environments: environments.map((env, index) =>
index === envIndex
? {
...env,
variables: vars,
}
: env
),
}
},
updateEnvironmentVariable(
{ environments }: EnvironmentStore,
{
envIndex,
variableIndex,
updatedKey,
updatedValue,
}: {
envIndex: number
variableIndex: number
updatedKey: string
updatedValue: string
}
) {
return {
environments: environments.map((env, index) =>
index === envIndex
? {
...env,
variables: env.variables.map((v, vIndex) =>
vIndex === variableIndex
? { key: updatedKey, value: updatedValue }
: v
),
}
: env
),
}
},
setGlobalVariables(_, { entries }: { entries: Environment["variables"] }) {
return {
globals: entries,
}
},
clearGlobalVariables() {
return {
globals: [],
}
},
addGlobalVariable(
{ globals },
{ entry }: { entry: Environment["variables"][number] }
) {
return {
globals: [...globals, entry],
}
},
removeGlobalVariable({ globals }, { envIndex }: { envIndex: number }) {
return {
globals: globals.filter((_, i) => i !== envIndex),
}
},
updateGlobalVariable(
{ globals },
{
envIndex,
updatedEntry,
}: { envIndex: number; updatedEntry: Environment["variables"][number] }
) {
return {
globals: globals.map((x, i) => (i !== envIndex ? x : updatedEntry)),
}
},
})
export const environmentsStore = new DispatchingStore(
defaultEnvironmentsState,
dispatchers
)
export const environments$ = environmentsStore.subject$.pipe(
pluck("environments"),
distinctUntilChanged()
)
export const globalEnv$ = environmentsStore.subject$.pipe(
pluck("globals"),
distinctUntilChanged()
)
export const selectedEnvIndex$ = environmentsStore.subject$.pipe(
pluck("currentEnvironmentIndex"),
distinctUntilChanged()
)
export const currentEnvironment$ = environmentsStore.subject$.pipe(
map(({ currentEnvironmentIndex, environments }) => {
if (currentEnvironmentIndex === -1) {
const env: Environment = {
name: "No environment",
variables: [],
}
return env
} else {
return environments[currentEnvironmentIndex]
}
})
)
export type AggregateEnvironment = {
key: string
value: string
sourceEnv: string
}
/**
* Stream returning all the environment variables accessible in
* the current state (Global + The Selected Environment).
* NOTE: The source environment attribute will be "Global" for Global Env as source.
*/
export const aggregateEnvs$: Observable<AggregateEnvironment[]> = combineLatest(
[currentEnvironment$, globalEnv$]
).pipe(
map(([selectedEnv, globalVars]) => {
const results: AggregateEnvironment[] = []
selectedEnv.variables.forEach(({ key, value }) =>
results.push({ key, value, sourceEnv: selectedEnv.name })
)
globalVars.forEach(({ key, value }) =>
results.push({ key, value, sourceEnv: "Global" })
)
return results
}),
distinctUntilChanged(isEqual)
)
export function getAggregateEnvs() {
const currentEnv = getCurrentEnvironment()
return [
...currentEnv.variables.map(
(x) =>
<AggregateEnvironment>{
key: x.key,
value: x.value,
sourceEnv: currentEnv.name,
}
),
...getGlobalVariables().map(
(x) =>
<AggregateEnvironment>{
key: x.key,
value: x.value,
sourceEnv: "Global",
}
),
]
}
export function getCurrentEnvironment(): Environment {
if (environmentsStore.value.currentEnvironmentIndex === -1) {
return {
name: "No environment",
variables: [],
}
}
return environmentsStore.value.environments[
environmentsStore.value.currentEnvironmentIndex
]
}
export function setCurrentEnvironment(newEnvIndex: number) {
environmentsStore.dispatch({
dispatcher: "setCurrentEnviromentIndex",
payload: {
newIndex: newEnvIndex,
},
})
}
export function getLegacyGlobalEnvironment(): Environment | null {
const envs = environmentsStore.value.environments
const el = envs.find(
(env) => env.name === "globals" || env.name === "Globals"
)
return el ?? null
}
export function getGlobalVariables(): Environment["variables"] {
return environmentsStore.value.globals
}
export function addGlobalEnvVariable(entry: Environment["variables"][number]) {
environmentsStore.dispatch({
dispatcher: "addGlobalVariable",
payload: {
entry,
},
})
}
export function setGlobalEnvVariables(entries: Environment["variables"]) {
environmentsStore.dispatch({
dispatcher: "setGlobalVariables",
payload: {
entries,
},
})
}
export function clearGlobalEnvVariables() {
environmentsStore.dispatch({
dispatcher: "clearGlobalVariables",
payload: {},
})
}
export function removeGlobalEnvVariable(envIndex: number) {
environmentsStore.dispatch({
dispatcher: "removeGlobalVariable",
payload: {
envIndex,
},
})
}
export function updateGlobalEnvVariable(
envIndex: number,
updatedEntry: Environment["variables"][number]
) {
environmentsStore.dispatch({
dispatcher: "updateGlobalVariable",
payload: {
envIndex,
updatedEntry,
},
})
}
export function replaceEnvironments(newEnvironments: any[]) {
environmentsStore.dispatch({
dispatcher: "replaceEnvironments",
payload: {
environments: newEnvironments,
},
})
}
export function appendEnvironments(envs: Environment[]) {
environmentsStore.dispatch({
dispatcher: "appendEnvironments",
payload: {
envs,
},
})
}
export function createEnvironment(envName: string) {
environmentsStore.dispatch({
dispatcher: "createEnvironment",
payload: {
name: envName,
},
})
}
export function duplicateEnvironment(envIndex: number) {
environmentsStore.dispatch({
dispatcher: "duplicateEnvironment",
payload: {
envIndex,
},
})
}
export function deleteEnvironment(envIndex: number) {
environmentsStore.dispatch({
dispatcher: "deleteEnvironment",
payload: {
envIndex,
},
})
}
export function renameEnvironment(envIndex: number, newName: string) {
environmentsStore.dispatch({
dispatcher: "renameEnvironment",
payload: {
envIndex,
newName,
},
})
}
export function updateEnvironment(envIndex: number, updatedEnv: Environment) {
environmentsStore.dispatch({
dispatcher: "updateEnvironment",
payload: {
envIndex,
updatedEnv,
},
})
}
export function setEnvironmentVariables(
envIndex: number,
vars: { key: string; value: string }[]
) {
environmentsStore.dispatch({
dispatcher: "setEnvironmentVariables",
payload: {
envIndex,
vars,
},
})
}
export function addEnvironmentVariable(
envIndex: number,
{ key, value }: { key: string; value: string }
) {
environmentsStore.dispatch({
dispatcher: "addEnvironmentVariable",
payload: {
envIndex,
key,
value,
},
})
}
export function removeEnvironmentVariable(
envIndex: number,
variableIndex: number
) {
environmentsStore.dispatch({
dispatcher: "removeEnvironmentVariable",
payload: {
envIndex,
variableIndex,
},
})
}
export function updateEnvironmentVariable(
envIndex: number,
variableIndex: number,
{ key, value }: { key: string; value: string }
) {
environmentsStore.dispatch({
dispatcher: "updateEnvironmentVariable",
payload: {
envIndex,
variableIndex,
updatedKey: key,
updatedValue: value,
},
})
}
export function getEnvironment(index: number) {
return environmentsStore.value.environments[index]
} | the_stack |
import bcd from "@mdn/browser-compat-data";
import type { Identifier } from "@mdn/browser-compat-data/types";
import browserslist from "browserslist";
import compareVersions from "compare-versions";
import { css } from "mdn-data";
const enum CSSPrefixFlags {
"-webkit-" = 1 << 0,
"-moz-" = 1 << 1,
"-ms-" = 1 << 2,
}
export const nonObsoleteProperties = Object.keys(css.properties).filter(
(property) => {
const { status } = css.properties[property];
return (
status !== "obsolete" &&
property !== "box-direction" && // Replaced by "flex-direction"
property !== "unicode-bidi" // Site authors shouldn't override this
);
},
);
function normalizeVersion(version: string) {
return version.replace("≤", "");
}
const prefixFlagsByPrefix = new Map([
["-webkit-", CSSPrefixFlags["-webkit-"]],
["-moz-", CSSPrefixFlags["-moz-"]],
["-ms-", CSSPrefixFlags["-ms-"]],
]);
const browsersByBrowserslistId: ReadonlyMap<string, string> = new Map([
/* Keys: https://github.com/browserslist/browserslist#browsers */
/* Values: https://github.com/mdn/browser-compat-data/blob/master/schemas/compat-data-schema.md#browser-identifiers */
["chrome", "chrome"],
["and_chr", "chrome_android"],
["edge", "edge"],
["firefox", "firefox"],
["and_ff", "firefox_android"],
["ie", "ie"],
["node", "nodejs"],
["opera", "opera"],
["op_mob", "opera_android"],
["and_qq", "qq_android"],
["safari", "safari"],
["ios_saf", "safari_ios"],
["samsung", "samsunginternet_android"],
["and_uc", "uc_android"],
["android", "webview_android"],
]);
const minSupportedVersionsByBrowser = new Map<string, string>();
/* TODO: Adjust query when necessary */
// UC Browser 12.12 -> Chrome >=57
// KaiOS 2.5 -> Firefox >=48
browserslist(
"defaults, chrome >=57, edge >=16, firefox >=48, opera >=46, safari >=12.2",
)
.map((stat) => {
const [browserslistId, versionRange] = stat.split(" ");
return [
browsersByBrowserslistId.get(browserslistId),
versionRange.split("-")[0], // Uses lower version if a range is given
] as const;
})
.forEach(([browser, version]) => {
if (!browser) return; // Filter out unknown browsers
// Find minimum version of each browser
if (
!minSupportedVersionsByBrowser.has(browser) ||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
compareVersions(version, minSupportedVersionsByBrowser.get(browser)!) < 0
) {
minSupportedVersionsByBrowser.set(browser, version);
}
});
const prefixesByProperty = new Map<string, Set<string>>();
const prefixesByPropertyValuePair = new Map<string, Set<string>>();
const aliasesByProperty = new Map<string, Set<string>>();
const aliasesByPropertyValuePair = new Map<string, Set<string>>();
function traverse(
{ __compat, ...subfeatures }: Identifier,
property: string,
value?: string,
) {
for (const [value, subfeatureIdentifier] of Object.entries(subfeatures)) {
traverse(subfeatureIdentifier, property, __compat ? value : undefined);
}
if (!__compat || (__compat.status && !__compat.status.standard_track)) return;
for (const [browser, supportStatement] of Object.entries(__compat.support)) {
const minSupportedVersion = minSupportedVersionsByBrowser.get(browser);
if (!minSupportedVersion) continue;
const supportStatements = Array.isArray(supportStatement)
? supportStatement
: // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
[supportStatement!];
const hasNativeSupport =
!supportStatements[0].prefix &&
!supportStatements[0].alternative_name &&
(typeof supportStatements[0].version_added === "string"
? compareVersions(
normalizeVersion(supportStatements[0].version_added),
minSupportedVersion,
) <= 0
: supportStatements[0].version_added);
if (!hasNativeSupport) {
supportStatements.forEach(
({ prefix, version_added, version_removed, alternative_name }, i) => {
if (
(typeof version_removed === "string"
? compareVersions(
normalizeVersion(version_removed),
minSupportedVersion,
) > 0
: !version_removed) &&
(i === 0 ||
(typeof version_added === "string" &&
typeof supportStatements[0].version_added === "string"
? compareVersions(
normalizeVersion(version_added),
normalizeVersion(supportStatements[0].version_added),
) < 0
: version_added))
) {
if (prefix) {
if (value) {
const propertyValuePair = `${property}:${value}`;
const prefixes =
prefixesByPropertyValuePair.get(propertyValuePair) ||
new Set();
if (prefixes.size === 0) {
prefixesByPropertyValuePair.set(propertyValuePair, prefixes);
}
prefixes.add(prefix);
} else {
const prefixes = prefixesByProperty.get(property) || new Set();
if (prefixes.size === 0) {
prefixesByProperty.set(property, prefixes);
}
prefixes.add(prefix);
}
}
if (alternative_name) {
if (value) {
const propertyValuePair = `${property}:${value}`;
const aliases =
aliasesByPropertyValuePair.get(propertyValuePair) ||
new Set();
if (aliases.size === 0) {
aliasesByPropertyValuePair.set(propertyValuePair, aliases);
}
aliases.add(alternative_name);
} else {
const aliases = aliasesByProperty.get(property) || new Set();
if (aliases.size === 0) {
aliasesByProperty.set(property, aliases);
}
aliases.add(alternative_name);
}
}
}
},
);
}
}
}
Object.entries(bcd.css.properties).forEach(([property, featureIdentifier]) => {
traverse(featureIdentifier, property);
});
/* TODO: Remove adjustments below as @mdn/browser-compat-data gets fixed */
export const expectedPrefixFlagsByProperty = new Map(
[...prefixesByProperty.entries()].map(([property, prefixes]) => [
property,
[...prefixes.values()]
.map((prefix) => prefixFlagsByPrefix.get(prefix))
.reduce(
(accumulator = 0, currentValue = 0) => accumulator | currentValue,
),
]),
);
expectedPrefixFlagsByProperty.set("mask", CSSPrefixFlags["-webkit-"]);
expectedPrefixFlagsByProperty.set(
"text-decoration",
CSSPrefixFlags["-webkit-"],
);
expectedPrefixFlagsByProperty.delete("align-self"); // "-ms-grid-row-align" in IE 11
expectedPrefixFlagsByProperty.delete("justify-self"); // "-ms-grid-column-align" in IE 11
expectedPrefixFlagsByProperty.delete("line-break"); // Supported by iOS Safari 11+
expectedPrefixFlagsByProperty.delete("ruby-position"); // "-webkit-ruby-position" uses non-standard values
expectedPrefixFlagsByProperty.delete("scroll-snap-type"); // IE 11 uses non-standard values
expectedPrefixFlagsByProperty.set(
"text-size-adjust",
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
expectedPrefixFlagsByProperty.get("text-size-adjust")! ^
CSSPrefixFlags["-moz-"], // Prefer responsive "viewport" meta tag
);
expectedPrefixFlagsByProperty.set(
"user-select",
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
expectedPrefixFlagsByProperty.get("user-select")! ^ CSSPrefixFlags["-moz-"], // Firefox 49+ supports the "-webkit-" prefix
);
export const expectedPrefixFlagsByPropertyValuePair = new Map(
[...prefixesByPropertyValuePair.entries()].map(
([propertyValuePair, prefixes]) => {
return [
propertyValuePair,
[...prefixes.values()]
.map((prefix) => prefixFlagsByPrefix.get(prefix))
.reduce(
(accumulator = 0, currentValue = 0) => accumulator | currentValue,
),
];
},
),
);
expectedPrefixFlagsByPropertyValuePair.delete("background-image:element"); // Only supported by Firefox
expectedPrefixFlagsByPropertyValuePair.delete("cursor:grab"); // Not required for Opera Mobile and QQ Browser
expectedPrefixFlagsByPropertyValuePair.delete("flex-basis:max-content"); // Only supported by Firefox
expectedPrefixFlagsByPropertyValuePair.delete("flex-basis:min-content"); // Only supported by Firefox
expectedPrefixFlagsByPropertyValuePair.delete("image-rendering:crisp-edges"); // Only supported by Firefox
expectedPrefixFlagsByPropertyValuePair.delete(
"list-style-type:ethiopic-halehame",
); // Non-standard
expectedPrefixFlagsByPropertyValuePair.delete(
"list-style-type:ethiopic-halehame-am",
); // Non-standard
expectedPrefixFlagsByPropertyValuePair.delete(
"list-style-type:ethiopic-halehame-ti-er",
); // Non-standard
expectedPrefixFlagsByPropertyValuePair.delete(
"list-style-type:ethiopic-halehame-ti-et",
); // Non-standard
expectedPrefixFlagsByPropertyValuePair.delete("list-style-type:hangul"); // Non-standard
expectedPrefixFlagsByPropertyValuePair.delete(
"list-style-type:hangul-consonant",
); // Non-standard
expectedPrefixFlagsByPropertyValuePair.delete("list-style-type:urdu"); // Non-standard
expectedPrefixFlagsByPropertyValuePair.delete(
"mask-position:three_value_syntax",
); // Not universally supported
expectedPrefixFlagsByPropertyValuePair.delete(
"perspective-origin:three_value_syntax",
); // Not universally supported
expectedPrefixFlagsByPropertyValuePair.delete("text-decoration:shorthand"); // Supported with property prefix
expectedPrefixFlagsByPropertyValuePair.delete("transform:3d"); // Supported by newer WebView versions
expectedPrefixFlagsByPropertyValuePair.delete("unicode-bidi:isolate"); // Site authors shouldn't override this
expectedPrefixFlagsByPropertyValuePair.delete("unicode-bidi:isolate-override"); // Site authors shouldn't override this
expectedPrefixFlagsByPropertyValuePair.delete("unicode-bidi:plaintext"); // Site authors shouldn't override this
export const expectedAliasesByProperty = new Map(
[...aliasesByProperty.entries()]
.filter(
([property]) =>
property !== "word-wrap" && // IE 11 has non-standard behavior with "overflow-wrap"
// Older Firefox supports these, but KaiOS target (~ Firefox 48) doesn't
!property.startsWith("inset") && // Firefox 51–62
property !== "text-decoration-thickness", // Firefox 69
)
.map(([property, aliases]) => {
if (property.startsWith("grid-auto-")) {
property = property.replace("auto", "template");
} else if (property === "text-combine-upright") {
aliases.delete("-webkit-text-combine"); // Uses non-standard values
}
if (aliases.size > 1) {
throw new Error(
`A property may only have one alias, but "${property}" has more: ${[
...aliases.values(),
]
.map((value) => `"${value}"`)
.join(", ")}`,
);
}
return [property, aliases.values().next().value];
}),
);
expectedAliasesByProperty.set("align-self", "-ms-grid-row-align");
expectedAliasesByProperty.set("justify-self", "-ms-grid-column-align"); | the_stack |
module WinJSTests {
"use strict";
var list;
var oldHasWinRT;
// As a side effect, this will scroll the browser to make the element visible
function createPointerUpEvent(element) {
element.scrollIntoView(false);
var rect = element.getBoundingClientRect();
// Simulate clicking the middle of the element
return {
target: element,
clientX: (rect.left + rect.right) / 2,
clientY: (rect.top + rect.bottom) / 2
};
}
export class ListViewEventsTest {
// This is the setup function that will be called at the beginning of each test function.
setUp() {
LiveUnit.LoggingCore.logComment("In setup");
var newNode = document.createElement("div");
newNode.id = "ListViewEventsTest";
newNode.innerHTML =
"<div id='list' style='width:350px; height:400px'></div>";
document.body.appendChild(newNode);
list = document.getElementById("list");
list.setPointerCapture = function () { };
list.releasePointerCapture = function () { };
oldHasWinRT = WinJS.Utilities.hasWinRT;
WinJS.Utilities._setHasWinRT(false);
}
tearDown() {
LiveUnit.LoggingCore.logComment("In tearDown");
WinJS.Utilities._setHasWinRT(oldHasWinRT);
var element = document.getElementById("ListViewEventsTest");
if (element) {
document.body.removeChild(element);
}
}
}
function generate(eventName, layoutName, testFunction, options?) {
options = options || {};
function generateTest(eventType) {
var testName = 'testEvent_' + eventName + '_' + eventType + (layoutName == "GridLayout" ? "" : "_" + layoutName);
ListViewEventsTest.prototype[testName] = function (complete) {
var data = [];
for (var i = 0; i < 400; i++) {
data.push(i);
}
var bindingList1 = new WinJS.Binding.List(data);
var listView = new WinJS.UI.ListView(list, {
layout: new WinJS.UI[layoutName](),
itemDataSource: bindingList1.dataSource,
itemTemplate: function (itemPromise) {
var element = document.createElement("div");
element.style.width = options.size || "100px";
element.style.height = options.size || "100px";
element.style.backgroundColor = "#777";
return {
element: element,
renderComplete: itemPromise.then(function (item) {
element.textContent = '' + item.data;
})
};
}
});
if (!options.skipInitEvents) {
initEventListener(listView, eventName, eventType, complete);
}
testFunction(listView, complete);
}
}
function initEventListener(listView, eventName, eventType, complete) {
var loadingStatesFired = [];
var loadingStatesExpected = ['itemsLoading', 'viewPortLoaded', 'itemsLoaded', 'complete'];
function handler() {
function finishEventTest() {
if (eventType === 'Level0') {
listView[eventName] = null;
} else {
listView.removeEventListener(eventName, handler);
}
clearTimeout(testTimeout);
complete();
}
if (eventName === 'loadingstatechanged') {
var currentLoadingState = listView.loadingState;
if (currentLoadingState !== 'complete') {
if (loadingStatesFired.indexOf(currentLoadingState) !== -1) {
loadingStatesFired.push(currentLoadingState);
throw Error('Duplicate loadingStates fired: ' + loadingStatesFired.toString());
} else {
loadingStatesFired.push(currentLoadingState);
}
} else {
finishEventTest();
}
} else {
finishEventTest();
}
}
var timeoutmsec = 2000,
testTimeout = setTimeout(function () {
throw Error(eventType + ' event: ' + eventName + ' did not fire in ' + timeoutmsec + ' ms!');
}, timeoutmsec);
if (eventType === 'Level0') {
listView['on' + eventName] = handler;
} else {
listView.addEventListener(eventName, handler);
}
}
generateTest('Level0');
generateTest('Level2');
};
// Test methods
var loadingstatechanged = function (listView) { };
generate('loadingstatechanged', "GridLayout", loadingstatechanged);
var iteminvoked = function (listView) {
var tests = [function () {
// work around exception issue
listView._canvas.setPointerCapture = function () { };
var elements = list.querySelectorAll('.win-container');
LiveUnit.Assert.isTrue(elements.length !== 0);
// Simulate a click on the 4th item
listView._currentMode().onPointerDown({ target: elements[0], button: WinJS.UI._LEFT_MSPOINTER_BUTTON, preventDefault: function () { } });
listView._currentMode().onPointerUp(createPointerUpEvent(elements[0]));
listView._currentMode().onclick();
}];
Helper.ListView.runTests(listView, tests);
};
generate('iteminvoked', "GridLayout", iteminvoked, { size: "50px" });
var selectionchanging = function (listView) {
var tests = [function () {
var elements = list.querySelectorAll('.win-container');
LiveUnit.Assert.isTrue(elements.length !== 0);
// Set selection using API
listView.selection.set([0]);
}];
Helper.ListView.runTests(listView, tests);
};
generate('selectionchanging', "GridLayout", selectionchanging);
var selectionchanged = function (listView) {
var tests = [function () {
var elements = list.querySelectorAll('.win-container');
LiveUnit.Assert.isTrue(elements.length !== 0);
// Set selection using API
listView.selection.set([0]);
}];
Helper.ListView.runTests(listView, tests);
};
generate('selectionchanged', "GridLayout", selectionchanged);
var keyboardnavigating = function (listView) {
function createKeyEvent(key, target) {
return {
keyCode: key,
target: target,
stopPropagation: function () { },
preventDefault: function () { }
};
}
var tests = [function () {
var elements = list.querySelectorAll('.win-container');
LiveUnit.Assert.isTrue(elements.length !== 0);
// Simulate keyboard event
listView._currentMode().onKeyDown(createKeyEvent(WinJS.Utilities.Key.downArrow, elements[0]));
}];
Helper.ListView.runTests(listView, tests);
};
generate('keyboardnavigating', "GridLayout", keyboardnavigating);
var loadingstatechanged_NumItemsLoadedEventProperty = function (listView, complete) {
listView.addEventListener("loadingstatechanged", function (e) {
var isComplete = listView.loadingState === "complete";
if (isComplete) {
complete();
}
});
};
generate('loadingstatechanged_NumItemsLoadedEventProperty', "GridLayout", loadingstatechanged_NumItemsLoadedEventProperty, { skipInitEvents: true });
var headerfooterevents = function (listView, complete) {
var lastHeaderEvent = null,
lastFooterEvent = null;
listView.addEventListener("headervisibilitychanged", function (e) {
lastHeaderEvent = e;
});
listView.addEventListener("footervisibilitychanged", function (e) {
lastFooterEvent = e;
});
function createSimpleElement() {
var element = document.createElement("div");
element.style.width = "100px";
element.style.height = "100px";
return element;
}
var header = createSimpleElement(),
footer = createSimpleElement();
var tests = [
function () {
listView.header = header;
listView.footer = footer;
return true;
},
function () {
LiveUnit.Assert.isTrue(!!lastHeaderEvent);
LiveUnit.Assert.isTrue(lastHeaderEvent.detail.visible);
LiveUnit.Assert.isTrue(!lastFooterEvent);
listView.scrollPosition = footer[(listView._horizontal() ? "offsetLeft" : "offsetTop")] + 100;
return true;
},
function () {
LiveUnit.Assert.isFalse(lastHeaderEvent.detail.visible);
LiveUnit.Assert.isTrue(!!lastFooterEvent);
LiveUnit.Assert.isTrue(lastFooterEvent.detail.visible);
listView.scrollPosition = 0;
return true;
},
function () {
LiveUnit.Assert.isTrue(lastHeaderEvent.detail.visible);
LiveUnit.Assert.isFalse(lastFooterEvent.detail.visible);
complete();
}
];
Helper.ListView.runTests(listView, tests);
};
generate('headerfooterevents', "GridLayout", headerfooterevents, { skipInitEvents: true });
}
// register the object as a test class by passing in the name
LiveUnit.registerTestClass("WinJSTests.ListViewEventsTest"); | the_stack |
import chai, { expect } from 'chai'
import { Contract } from 'ethers'
import { BigNumber, bigNumberify } from 'ethers/utils'
import { solidity, MockProvider, createFixtureLoader, deployContract } from 'ethereum-waffle'
import { expandTo18Decimals, mineBlock, encodePrice } from './shared/utilities'
import { v2Fixture } from './shared/fixtures'
import ExampleSlidingWindowOracle from '../build/ExampleSlidingWindowOracle.json'
chai.use(solidity)
const overrides = {
gasLimit: 9999999
}
const defaultToken0Amount = expandTo18Decimals(5)
const defaultToken1Amount = expandTo18Decimals(10)
describe('ExampleSlidingWindowOracle', () => {
const provider = new MockProvider({
hardfork: 'istanbul',
mnemonic: 'horn horn horn horn horn horn horn horn horn horn horn horn',
gasLimit: 9999999
})
const [wallet] = provider.getWallets()
const loadFixture = createFixtureLoader(provider, [wallet])
let token0: Contract
let token1: Contract
let pair: Contract
let weth: Contract
let factory: Contract
async function addLiquidity(amount0: BigNumber = defaultToken0Amount, amount1: BigNumber = defaultToken1Amount) {
if (!amount0.isZero()) await token0.transfer(pair.address, amount0)
if (!amount1.isZero()) await token1.transfer(pair.address, amount1)
await pair.sync()
}
const defaultWindowSize = 86400 // 24 hours
const defaultGranularity = 24 // 1 hour each
function observationIndexOf(
timestamp: number,
windowSize: number = defaultWindowSize,
granularity: number = defaultGranularity
): number {
const periodSize = Math.floor(windowSize / granularity)
const epochPeriod = Math.floor(timestamp / periodSize)
return epochPeriod % granularity
}
function deployOracle(windowSize: number, granularity: number) {
return deployContract(wallet, ExampleSlidingWindowOracle, [factory.address, windowSize, granularity], overrides)
}
beforeEach('deploy fixture', async function() {
const fixture = await loadFixture(v2Fixture)
token0 = fixture.token0
token1 = fixture.token1
pair = fixture.pair
weth = fixture.WETH
factory = fixture.factoryV2
})
// 1/1/2020 @ 12:00 am UTC
// cannot be 0 because that instructs ganache to set it to current timestamp
// cannot be 86400 because then timestamp 0 is a valid historical observation
const startTime = 1577836800
// must come before adding liquidity to pairs for correct cumulative price computations
// cannot use 0 because that resets to current timestamp
beforeEach(`set start time to ${startTime}`, () => mineBlock(provider, startTime))
it('requires granularity to be greater than 0', async () => {
await expect(deployOracle(defaultWindowSize, 0)).to.be.revertedWith('SlidingWindowOracle: GRANULARITY')
})
it('requires windowSize to be evenly divisible by granularity', async () => {
await expect(deployOracle(defaultWindowSize - 1, defaultGranularity)).to.be.revertedWith(
'SlidingWindowOracle: WINDOW_NOT_EVENLY_DIVISIBLE'
)
})
it('computes the periodSize correctly', async () => {
const oracle = await deployOracle(defaultWindowSize, defaultGranularity)
expect(await oracle.periodSize()).to.eq(3600)
const oracleOther = await deployOracle(defaultWindowSize * 2, defaultGranularity / 2)
expect(await oracleOther.periodSize()).to.eq(3600 * 4)
})
describe('#observationIndexOf', () => {
it('works for examples', async () => {
const oracle = await deployOracle(defaultWindowSize, defaultGranularity)
expect(await oracle.observationIndexOf(0)).to.eq(0)
expect(await oracle.observationIndexOf(3599)).to.eq(0)
expect(await oracle.observationIndexOf(3600)).to.eq(1)
expect(await oracle.observationIndexOf(4800)).to.eq(1)
expect(await oracle.observationIndexOf(7199)).to.eq(1)
expect(await oracle.observationIndexOf(7200)).to.eq(2)
expect(await oracle.observationIndexOf(86399)).to.eq(23)
expect(await oracle.observationIndexOf(86400)).to.eq(0)
expect(await oracle.observationIndexOf(90000)).to.eq(1)
})
it('overflow safe', async () => {
const oracle = await deployOracle(25500, 255) // 100 period size
expect(await oracle.observationIndexOf(0)).to.eq(0)
expect(await oracle.observationIndexOf(99)).to.eq(0)
expect(await oracle.observationIndexOf(100)).to.eq(1)
expect(await oracle.observationIndexOf(199)).to.eq(1)
expect(await oracle.observationIndexOf(25499)).to.eq(254) // 255th element
expect(await oracle.observationIndexOf(25500)).to.eq(0)
})
it('matches offline computation', async () => {
const oracle = await deployOracle(defaultWindowSize, defaultGranularity)
for (let timestamp of [0, 5000, 1000, 25000, 86399, 86400, 86401]) {
expect(await oracle.observationIndexOf(timestamp)).to.eq(observationIndexOf(timestamp))
}
})
})
describe('#update', () => {
let slidingWindowOracle: Contract
beforeEach(
'deploy oracle',
async () => (slidingWindowOracle = await deployOracle(defaultWindowSize, defaultGranularity))
)
beforeEach('add default liquidity', () => addLiquidity())
it('succeeds', async () => {
await slidingWindowOracle.update(token0.address, token1.address, overrides)
})
it('sets the appropriate epoch slot', async () => {
const blockTimestamp = (await pair.getReserves())[2]
expect(blockTimestamp).to.eq(startTime)
await slidingWindowOracle.update(token0.address, token1.address, overrides)
expect(await slidingWindowOracle.pairObservations(pair.address, observationIndexOf(blockTimestamp))).to.deep.eq([
bigNumberify(blockTimestamp),
await pair.price0CumulativeLast(),
await pair.price1CumulativeLast()
])
}).retries(2) // we may have slight differences between pair blockTimestamp and the expected timestamp
// because the previous block timestamp may differ from the current block timestamp by 1 second
it('gas for first update (allocates empty array)', async () => {
const tx = await slidingWindowOracle.update(token0.address, token1.address, overrides)
const receipt = await tx.wait()
expect(receipt.gasUsed).to.eq('116816')
}).retries(2) // gas test inconsistent
it('gas for second update in the same period (skips)', async () => {
await slidingWindowOracle.update(token0.address, token1.address, overrides)
const tx = await slidingWindowOracle.update(token0.address, token1.address, overrides)
const receipt = await tx.wait()
expect(receipt.gasUsed).to.eq('25574')
}).retries(2) // gas test inconsistent
it('gas for second update different period (no allocate, no skip)', async () => {
await slidingWindowOracle.update(token0.address, token1.address, overrides)
await mineBlock(provider, startTime + 3600)
const tx = await slidingWindowOracle.update(token0.address, token1.address, overrides)
const receipt = await tx.wait()
expect(receipt.gasUsed).to.eq('94542')
}).retries(2) // gas test inconsistent
it('second update in one timeslot does not overwrite', async () => {
await slidingWindowOracle.update(token0.address, token1.address, overrides)
const before = await slidingWindowOracle.pairObservations(pair.address, observationIndexOf(0))
// first hour still
await mineBlock(provider, startTime + 1800)
await slidingWindowOracle.update(token0.address, token1.address, overrides)
const after = await slidingWindowOracle.pairObservations(pair.address, observationIndexOf(1800))
expect(observationIndexOf(1800)).to.eq(observationIndexOf(0))
expect(before).to.deep.eq(after)
})
it('fails for invalid pair', async () => {
await expect(slidingWindowOracle.update(weth.address, token1.address)).to.be.reverted
})
})
describe('#consult', () => {
let slidingWindowOracle: Contract
beforeEach(
'deploy oracle',
async () => (slidingWindowOracle = await deployOracle(defaultWindowSize, defaultGranularity))
)
// must come after setting time to 0 for correct cumulative price computations in the pair
beforeEach('add default liquidity', () => addLiquidity())
it('fails if previous bucket not set', async () => {
await slidingWindowOracle.update(token0.address, token1.address, overrides)
await expect(slidingWindowOracle.consult(token0.address, 0, token1.address)).to.be.revertedWith(
'SlidingWindowOracle: MISSING_HISTORICAL_OBSERVATION'
)
})
it('fails for invalid pair', async () => {
await expect(slidingWindowOracle.consult(weth.address, 0, token1.address)).to.be.reverted
})
describe('happy path', () => {
let blockTimestamp: number
let previousBlockTimestamp: number
let previousCumulativePrices: any
beforeEach('add some prices', async () => {
previousBlockTimestamp = (await pair.getReserves())[2]
previousCumulativePrices = [await pair.price0CumulativeLast(), await pair.price1CumulativeLast()]
await slidingWindowOracle.update(token0.address, token1.address, overrides)
blockTimestamp = previousBlockTimestamp + 23 * 3600
await mineBlock(provider, blockTimestamp)
await slidingWindowOracle.update(token0.address, token1.address, overrides)
})
it('has cumulative price in previous bucket', async () => {
expect(
await slidingWindowOracle.pairObservations(pair.address, observationIndexOf(previousBlockTimestamp))
).to.deep.eq([bigNumberify(previousBlockTimestamp), previousCumulativePrices[0], previousCumulativePrices[1]])
}).retries(5) // test flaky because timestamps aren't mocked
it('has cumulative price in current bucket', async () => {
const timeElapsed = blockTimestamp - previousBlockTimestamp
const prices = encodePrice(defaultToken0Amount, defaultToken1Amount)
expect(
await slidingWindowOracle.pairObservations(pair.address, observationIndexOf(blockTimestamp))
).to.deep.eq([bigNumberify(blockTimestamp), prices[0].mul(timeElapsed), prices[1].mul(timeElapsed)])
}).retries(5) // test flaky because timestamps aren't mocked
it('provides the current ratio in consult token0', async () => {
expect(await slidingWindowOracle.consult(token0.address, 100, token1.address)).to.eq(200)
})
it('provides the current ratio in consult token1', async () => {
expect(await slidingWindowOracle.consult(token1.address, 100, token0.address)).to.eq(50)
})
})
describe('price changes over period', () => {
const hour = 3600
beforeEach('add some prices', async () => {
// starting price of 1:2, or token0 = 2token1, token1 = 0.5token0
await slidingWindowOracle.update(token0.address, token1.address, overrides) // hour 0, 1:2
// change the price at hour 3 to 1:1 and immediately update
await mineBlock(provider, startTime + 3 * hour)
await addLiquidity(defaultToken0Amount, bigNumberify(0))
await slidingWindowOracle.update(token0.address, token1.address, overrides)
// change the ratios at hour 6:00 to 2:1, don't update right away
await mineBlock(provider, startTime + 6 * hour)
await token0.transfer(pair.address, defaultToken0Amount.mul(2))
await pair.sync()
// update at hour 9:00 (price has been 2:1 for 3 hours, invokes counterfactual)
await mineBlock(provider, startTime + 9 * hour)
await slidingWindowOracle.update(token0.address, token1.address, overrides)
// move to hour 23:00 so we can check prices
await mineBlock(provider, startTime + 23 * hour)
})
it('provides the correct ratio in consult token0', async () => {
// at hour 23, price of token 0 spent 3 hours at 2, 3 hours at 1, 17 hours at 0.5 so price should
// be less than 1
expect(await slidingWindowOracle.consult(token0.address, 100, token1.address)).to.eq(76)
})
it('provides the correct ratio in consult token1', async () => {
// price should be greater than 1
expect(await slidingWindowOracle.consult(token1.address, 100, token0.address)).to.eq(167)
})
// price has been 2:1 all of 23 hours
describe('hour 32', () => {
beforeEach('set hour 32', () => mineBlock(provider, startTime + 32 * hour))
it('provides the correct ratio in consult token0', async () => {
// at hour 23, price of token 0 spent 3 hours at 2, 3 hours at 1, 17 hours at 0.5 so price should
// be less than 1
expect(await slidingWindowOracle.consult(token0.address, 100, token1.address)).to.eq(50)
})
it('provides the correct ratio in consult token1', async () => {
// price should be greater than 1
expect(await slidingWindowOracle.consult(token1.address, 100, token0.address)).to.eq(200)
})
})
})
})
}) | the_stack |
import * as L from 'leaflet';
declare module 'leaflet-pm' {
/**
* Extends built in leaflet Layer Options.
*/
interface LayerOptions {
pmIgnore?: boolean;
snapIgnore?: boolean;
}
/**
* Extends built in leaflet Map Options.
*/
interface MapOptions {
pmIgnore?: boolean;
}
/**
* Extends built in leaflet Map.
*/
interface Map {
pm: PM.PMMap;
}
/**
* Extends built in leaflet Path.
*/
interface Path {
pm: PM.PMLayer;
}
/**
* Extends built in leaflet ImageOverlay.
*/
interface ImageOverlay {
pm: PM.PMLayer;
}
/**
* Extends built in leaflet LayerGroup.
*/
interface LayerGroup {
pm: PM.PMLayerGroup;
}
/**
* Extends built in leaflet Polyline.
*/
interface Polyline {
/** Returns true if Line or Polygon has a self intersection. */
hasSelfIntersection(): boolean;
}
/**
* Extends @types/leaflet events...
*
* Todo: This is kind of a mess, and it makes all these event handlers show
* up on Layers and Map. Leaflet itself is based around Evented, and @types/leaflet
* makes this very hard to work around.
*
*/
interface Evented {
/******************************************
*
* AVAILABLE ON MAP + LAYER, THESE ARE OK ON EVENTED.
*
********************************************/
/** Fired when a layer is removed via Removal Mode. */
on(type: 'pm:remove', fn: PM.RemoveEventHandler): this;
once(type: 'pm:remove', fn: PM.RemoveEventHandler): this;
off(type: 'pm:remove', fn?: PM.RemoveEventHandler): this;
/** Fired when the layer being cut. Draw+Edit Mode */
on(type: 'pm:cut', fn: PM.CutEventHandler): this;
once(type: 'pm:cut', fn: PM.CutEventHandler): this;
off(type: 'pm:cut', fn?: PM.CutEventHandler): this;
/** Fired when rotation is enabled for a layer. */
on(type: 'pm:rotateenable', fn: PM.RotateEnableEventHandler): this;
once(type: 'pm:rotateenable', fn: PM.RotateEnableEventHandler): this;
off(type: 'pm:rotateenable', fn?: PM.RotateEnableEventHandler): this;
/** Fired when rotation is disabled for a layer. */
on(type: 'pm:rotatedisable', fn: PM.RotateDisableEventHandler): this;
once(type: 'pm:rotatedisable', fn: PM.RotateDisableEventHandler): this;
off(type: 'pm:rotatedisable', fn?: PM.RotateDisableEventHandler): this;
/** Fired when rotation starts on a layer. */
on(type: 'pm:rotatestart', fn: PM.RotateStartEventHandler): this;
once(type: 'pm:rotatestart', fn: PM.RotateStartEventHandler): this;
off(type: 'pm:rotatestart', fn?: PM.RotateStartEventHandler): this;
/** Fired when a layer is rotated. */
on(type: 'pm:rotate', fn: PM.RotateEventHandler): this;
once(type: 'pm:rotate', fn: PM.RotateEventHandler): this;
off(type: 'pm:rotate', fn?: PM.RotateEventHandler): this;
/** Fired when rotation ends on a layer. */
on(type: 'pm:rotateend', fn: PM.RotateEndEventHandler): this;
once(type: 'pm:rotateend', fn: PM.RotateEndEventHandler): this;
off(type: 'pm:rotateend', fn?: PM.RotateEndEventHandler): this;
/******************************************
*
* TODO: DRAW/EDIT MODE EVENTS LAYER ONLY
*
********************************************/
/** Fired during a marker move/drag. */
on(type: 'pm:snapdrag', fn: PM.SnapEventHandler): this;
once(type: 'pm:snapdrag', fn: PM.SnapEventHandler): this;
off(type: 'pm:snapdrag', fn?: PM.SnapEventHandler): this;
/** Fired when a vertex is snapped. */
on(type: 'pm:snap', fn: PM.SnapEventHandler): this;
once(type: 'pm:snap', fn: PM.SnapEventHandler): this;
off(type: 'pm:snap', fn?: PM.SnapEventHandler): this;
/** Fired when a vertex is unsnapped. */
on(type: 'pm:unsnap', fn: PM.SnapEventHandler): this;
once(type: 'pm:unsnap', fn: PM.SnapEventHandler): this;
off(type: 'pm:unsnap', fn?: PM.SnapEventHandler): this;
/** Called when the center of a circle is placed/moved. */
on(type: 'pm:centerplaced', fn: PM.CenterPlacedEventHandler): this;
once(type: 'pm:centerplaced', fn: PM.CenterPlacedEventHandler): this;
off(type: 'pm:centerplaced', fn?: PM.CenterPlacedEventHandler): this;
/******************************************
*
* TODO: CUT/EDIT MODE EVENTS LAYER ONLY
*
********************************************/
/** Fired when a layer is edited. */
on(type: 'pm:edit', fn: PM.EditEventHandler): this;
once(type: 'pm:edit', fn: PM.EditEventHandler): this;
off(type: 'pm:edit', fn?: PM.EditEventHandler): this;
/******************************************
*
* TODO: DRAW MODE EVENTS ON MAP ONLY
*
********************************************/
/** Fired when Drawing Mode is toggled. */
on(
type: 'pm:globaldrawmodetoggled',
fn: PM.GlobalDrawModeToggledEventHandler,
context?: any
): L.Evented;
once(
type: 'pm:globaldrawmodetoggled',
fn: PM.GlobalDrawModeToggledEventHandler,
context?: any
): L.Evented;
off(
type: 'pm:globaldrawmodetoggled',
fn?: PM.GlobalDrawModeToggledEventHandler,
context?: any
): L.Evented;
/** Called when drawing mode is enabled. Payload includes the shape type and working layer. */
on(
type: 'pm:drawstart',
fn: PM.DrawStartEventHandler,
context?: any
): L.Evented;
once(
type: 'pm:drawstart',
fn: PM.DrawStartEventHandler,
context?: any
): L.Evented;
off(
type: 'pm:drawstart',
fn?: PM.DrawStartEventHandler,
context?: any
): L.Evented;
/** Called when drawing mode is disabled. Payload includes the shape type. */
on(
type: 'pm:drawend',
fn: PM.DrawEndEventHandler,
context?: any
): L.Evented;
once(
type: 'pm:drawend',
fn: PM.DrawEndEventHandler,
context?: any
): L.Evented;
off(
type: 'pm:drawend',
fn?: PM.DrawEndEventHandler,
context?: any
): L.Evented;
/** Called when drawing mode is disabled. Payload includes the shape type. */
on(type: 'pm:create', fn: PM.CreateEventHandler, context?: any): L.Evented;
once(
type: 'pm:create',
fn: PM.CreateEventHandler,
context?: any
): L.Evented;
off(
type: 'pm:create',
fn?: PM.CreateEventHandler,
context?: any
): L.Evented;
/******************************************
*
* TODO: DRAW MODE EVENTS ON LAYER ONLY
*
********************************************/
/** Called when a new vertex is added. */
on(type: 'pm:vertexadded', fn: PM.VertexAddedEventHandler): this;
once(type: 'pm:vertexadded', fn: PM.VertexAddedEventHandler): this;
off(type: 'pm:vertexadded', fn?: PM.VertexAddedEventHandler): this;
/******************************************
*
* TODO: EDIT MODE EVENTS ON LAYER ONLY
*
********************************************/
/** Fired when edit mode is disabled and a layer is edited and its coordinates have changed. */
on(type: 'pm:update', fn: PM.UpdateEventHandler): this;
once(type: 'pm:update', fn: PM.UpdateEventHandler): this;
off(type: 'pm:update', fn?: PM.UpdateEventHandler): this;
/** Fired when edit mode on a layer is enabled. */
on(type: 'pm:enable', fn: PM.EnableEventHandler): this;
once(type: 'pm:enable', fn: PM.EnableEventHandler): this;
off(type: 'pm:enable', fn?: PM.EnableEventHandler): this;
/** Fired when edit mode on a layer is disabled. */
on(type: 'pm:disable', fn: PM.DisableEventHandler): this;
once(type: 'pm:disable', fn: PM.DisableEventHandler): this;
off(type: 'pm:disable', fn?: PM.DisableEventHandler): this;
/** Fired when a vertex is added. */
on(type: 'pm:vertexadded', fn: PM.VertexAddedEventHandler2): this;
once(type: 'pm:vertexadded', fn: PM.VertexAddedEventHandler2): this;
off(type: 'pm:vertexadded', fn?: PM.VertexAddedEventHandler2): this;
/** Fired when a vertex is removed. */
on(type: 'pm:vertexremoved', fn: PM.VertexRemovedEventHandler): this;
once(type: 'pm:vertexremoved', fn: PM.VertexRemovedEventHandler): this;
off(type: 'pm:vertexremoved', fn?: PM.VertexRemovedEventHandler): this;
/** Fired when a vertex is clicked. */
on(type: 'pm:vertexclick', fn: PM.VertexClickEventHandler): this;
once(type: 'pm:vertexclick', fn: PM.VertexClickEventHandler): this;
off(type: 'pm:vertexclick', fn?: PM.VertexClickEventHandler): this;
/** Fired when dragging of a marker which corresponds to a vertex starts. */
on(type: 'pm:markerdragstart', fn: PM.MarkerDragStartEventHandler): this;
once(type: 'pm:markerdragstart', fn: PM.MarkerDragStartEventHandler): this;
off(type: 'pm:markerdragstart', fn?: PM.MarkerDragStartEventHandler): this;
/** Fired when dragging a vertex-marker. */
on(type: 'pm:markerdrag', fn: PM.MarkerDragEventHandler): this;
once(type: 'pm:markerdrag', fn: PM.MarkerDragEventHandler): this;
off(type: 'pm:markerdrag', fn?: PM.MarkerDragEventHandler): this;
/** Fired when dragging of a vertex-marker ends. */
on(type: 'pm:markerdragend', fn: PM.MarkerDragEndEventHandler): this;
once(type: 'pm:markerdragend', fn: PM.MarkerDragEndEventHandler): this;
off(type: 'pm:markerdragend', fn?: PM.MarkerDragEndEventHandler): this;
/** Fired when coords of a layer are reset. E.g. by self-intersection.. */
on(type: 'pm:layerreset', fn: PM.LayerResetEventHandler): this;
once(type: 'pm:layerreset', fn: PM.LayerResetEventHandler): this;
off(type: 'pm:layerreset', fn?: PM.LayerResetEventHandler): this;
/** When allowSelfIntersection: false, this event is fired as soon as a self-intersection is detected. */
on(type: 'pm:intersect', fn: PM.IntersectEventHandler): this;
once(type: 'pm:intersect', fn: PM.IntersectEventHandler): this;
off(type: 'pm:intersect', fn?: PM.IntersectEventHandler): this;
/******************************************
*
* TODO: EDIT MODE EVENTS ON MAP ONLY
*
********************************************/
/** Fired when Edit Mode is toggled. */
on(
type: 'pm:globaleditmodetoggled',
fn: PM.GlobalEditModeToggledEventHandler
): this;
once(
type: 'pm:globaleditmodetoggled',
fn: PM.GlobalEditModeToggledEventHandler
): this;
off(
type: 'pm:globaleditmodetoggled',
fn?: PM.GlobalEditModeToggledEventHandler
): this;
/******************************************
*
* TODO: DRAG MODE EVENTS ON MAP ONLY
*
********************************************/
/** Fired when Drag Mode is toggled. */
on(
type: 'pm:globaldragmodetoggled',
fn: PM.GlobalDragModeToggledEventHandler
): this;
once(
type: 'pm:globaldragmodetoggled',
fn: PM.GlobalDragModeToggledEventHandler
): this;
off(
type: 'pm:globaldragmodetoggled',
fn?: PM.GlobalDragModeToggledEventHandler
): this;
/******************************************
*
* TODO: DRAG MODE EVENTS ON LAYER ONLY
*
********************************************/
/** Fired when a layer starts being dragged. */
on(type: 'pm:dragstart', fn: PM.DragStartEventHandler): this;
once(type: 'pm:dragstart', fn: PM.DragStartEventHandler): this;
off(type: 'pm:dragstart', fn?: PM.DragStartEventHandler): this;
/** Fired when a layer is dragged. */
on(type: 'pm:drag', fn: PM.DragEventHandler): this;
once(type: 'pm:drag', fn: PM.DragEventHandler): this;
off(type: 'pm:drag', fn?: PM.DragEventHandler): this;
/** Fired when a layer stops being dragged. */
on(type: 'pm:dragend', fn: PM.DragEndEventHandler): this;
once(type: 'pm:dragend', fn: PM.DragEndEventHandler): this;
off(type: 'pm:dragend', fn?: PM.DragEndEventHandler): this;
/******************************************
*
* TODO: REMOVE MODE EVENTS ON MAP ONLY
*
********************************************/
/** Fired when Removal Mode is toggled. */
on(
type: 'pm:globalremovalmodetoggled',
fn: PM.GlobalRemovalModeToggledEventHandler
): this;
once(
type: 'pm:globalremovalmodetoggled',
fn: PM.GlobalRemovalModeToggledEventHandler
): this;
off(
type: 'pm:globalremovalmodetoggled',
fn?: PM.GlobalRemovalModeToggledEventHandler
): this;
/******************************************
*
* TODO: CUT MODE EVENTS ON MAP ONLY
*
********************************************/
/** Fired when a layer is removed via Removal Mode. */
on(
type: 'pm:globalcutmodetoggled',
fn: PM.GlobalCutModeToggledEventHandler
): this;
once(
type: 'pm:globalcutmodetoggled',
fn: PM.GlobalCutModeToggledEventHandler
): this;
off(
type: 'pm:globalcutmodetoggled',
fn?: PM.GlobalCutModeToggledEventHandler
): this;
/******************************************
*
* TODO: ROTATE MODE EVENTS ON MAP ONLY
*
********************************************/
/** Fired when Rotate Mode is toggled. */
on(
type: 'pm:globalrotatemodetoggled',
fn: PM.GlobalRotateModeToggledEventHandler
): this;
once(
type: 'pm:globalrotatemodetoggled',
fn: PM.GlobalRotateModeToggledEventHandler
): this;
off(
type: 'pm:globalrotatemodetoggled',
fn?: PM.GlobalRotateModeToggledEventHandler
): this;
/******************************************
*
* TODO: TRANSLATION EVENTS ON MAP ONLY
*
********************************************/
/** Standard Leaflet event. Fired when any layer is removed. */
on(type: 'pm:langchange', fn: PM.LangChangeEventHandler): this;
once(type: 'pm:langchange', fn: PM.LangChangeEventHandler): this;
off(type: 'pm:langchange', fn?: PM.LangChangeEventHandler): this;
/******************************************
*
* TODO: CONTROL EVENTS ON MAP ONLY
*
********************************************/
/** Fired when a Toolbar button is clicked. */
on(type: 'pm:buttonclick', fn: PM.ButtonClickEventHandler): this;
once(type: 'pm:buttonclick', fn: PM.ButtonClickEventHandler): this;
off(type: 'pm:buttonclick', fn?: PM.ButtonClickEventHandler): this;
/** Fired when a Toolbar action is clicked. */
on(type: 'pm:actionclick', fn: PM.ActionClickEventHandler): this;
once(type: 'pm:actionclick', fn: PM.ActionClickEventHandler): this;
off(type: 'pm:actionclick', fn?: PM.ActionClickEventHandler): this;
/******************************************
*
* TODO: Keyboard EVENT ON MAP ONLY
*
********************************************/
/** Fired when `keydown` or `keyup` on the document is fired. */
on(type: 'pm:keyevent', fn: PM.KeyboardKeyEventHandler): this;
once(type: 'pm:keyevent', fn: PM.KeyboardKeyEventHandler): this;
off(type: 'pm:keyevent', fn?: PM.KeyboardKeyEventHandler): this;
}
namespace PM {
/** Supported shape names. 'ImageOverlay' is in Edit Mode only. Also accepts custom shape name. */
type SUPPORTED_SHAPES =
| 'Marker'
| 'Circle'
| 'Line'
| 'Rectangle'
| 'Polygon'
| 'Cut'
| 'CircleMarker'
| 'ImageOverlay'
| string;
/**
* Changes default registration of leaflet-geoman on leaflet layers.
*
* @param optIn - if true, a layers pmIgnore property has to be set to false to get initiated.
*/
function setOptIn(optIn: boolean): void;
/**
* Enable leaflet-geoman on an ignored layer.
*
* @param layer - re-reads layer.options.pmIgnore to initialize leaflet-geoman.
*/
function reInitLayer(layer: L.Layer): void;
/**
* PM map interface.
*/
interface PMMap
extends PMDrawMap,
PMEditMap,
PMDragMap,
PMRemoveMap,
PMCutMap,
PMRotateMap {
Toolbar: PMMapToolbar;
Keyboard: PMMapKeyboard;
/** Adds the Toolbar to the map. */
addControls(options?: ToolbarOptions): void;
/** Toggle the visiblity of the Toolbar. */
removeControls(): void;
/** Returns true if the Toolbar is visible on the map. */
controlsVisible(): boolean;
/** Toggle the visiblity of the Toolbar. */
toggleControls(): void;
setLang(
lang:
| 'cz'
| 'da'
| 'de'
| 'el'
| 'en'
| 'es'
| 'fa'
| 'fr'
| 'hu'
| 'id'
| 'it'
| 'nl'
| 'no'
| 'pl'
| 'pt_br'
| 'ro'
| 'ru'
| 'sv'
| 'tr'
| 'ua'
| 'zh'
| 'zh_tw',
customTranslations?: Translations,
fallbackLanguage?: string
): void;
/** Set globalOptions and apply them. */
setGlobalOptions(options: GlobalOptions): void;
/** Apply the current globalOptions to all existing layers. */
applyGlobalOptions(): void;
/** Returns the globalOptions. */
getGlobalOptions(): GlobalOptions;
}
class Translations {
tooltips?: {
placeMarker?: string;
firstVertex?: string;
continueLine?: string;
finishLine?: string;
finishPoly?: string;
finishRect?: string;
startCircle?: string;
finishCircle?: string;
placeCircleMarker?: string;
};
actions?: {
finish?: string;
cancel?: string;
removeLastVertex?: string;
};
buttonTitles?: {
drawMarkerButton?: string;
drawPolyButton?: string;
drawLineButton?: string;
drawCircleButton?: string;
drawRectButton?: string;
editButton?: string;
dragButton?: string;
cutButton?: string;
deleteButton?: string;
drawCircleMarkerButton?: string;
};
}
type ACTION_NAMES = 'cancel' | 'removeLastVertex' | 'finish' | 'finishMode';
class Action {
text: string;
onClick?: (e: any) => void;
}
type TOOLBAR_CONTROL_ORDER =
| 'drawMarker'
| 'drawCircleMarker'
| 'drawPolyline'
| 'drawRectangle'
| 'drawPolygon'
| 'drawCircle'
| 'editMode'
| 'dragMode'
| 'cutPolygon'
| 'removalMode'
| 'rotateMode'
| string;
interface PMMapToolbar {
/** Pass an array of button names to reorder the buttons in the Toolbar. */
changeControlOrder(order?: TOOLBAR_CONTROL_ORDER[]): void;
/** Receive the current order with. */
getControlOrder(): TOOLBAR_CONTROL_ORDER[];
/** The position of a block (draw, edit, custom, options⭐) in the Toolbar can be changed. If not set, the value */
/** from position of the Toolbar is taken. */
setBlockPosition(
block: 'draw' | 'edit' | 'custom' | 'options',
position: L.ControlPosition
): void;
/** Returns a Object with the positions for all blocks */
getBlockPositions(): BlockPositions;
/** To add a custom Control to the Toolbar */
createCustomControl(options: CustomControlOptions): void;
/** Creates a copy of a draw Control. Returns the drawInstance and the control. */
copyDrawControl(
copyInstance: string,
options?: CustomControlOptions
): void;
/** Change the actions of an existing button. */
changeActionsOfControl(
name: string,
actions: (ACTION_NAMES | Action)[]
): void;
/** Disable button by control name */
setButtonDisabled(name: TOOLBAR_CONTROL_ORDER, state: boolean): void;
}
type KEYBOARD_EVENT_TYPE = 'current' | 'keydown' | 'keyup';
interface PMMapKeyboard {
/** Pass an array of button names to reorder the buttons in the Toolbar. */
getLastKeyEvent(type: KEYBOARD_EVENT_TYPE[]): KeyboardKeyEventHandler;
/** Returns the current pressed key. [KeyboardEvent.key](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key). */
getPressedKey(): string;
/** Returns true if the `Shift` key is currently pressed. */
isShiftKeyPressed(): boolean;
/** Returns true if the `Alt` key is currently pressed. */
isAltKeyPressed(): boolean;
/** Returns true if the `Ctrl` key is currently pressed. */
isCtrlKeyPressed(): boolean;
/** Returns true if the `Meta` key is currently pressed. */
isMetaKeyPressed(): boolean;
}
interface Button {
/** Actions */
actions: (ACTION_NAMES | Action)[];
/** Function fired after clicking the control. */
afterClick: () => void;
/** CSS class with the Icon. */
className: string;
/** If true, other buttons will be disabled on click (default: true) */
disableOtherButtons: boolean;
/** Control can be toggled. */
doToggle: boolean;
/** Extending Class f. ex. Line, Polygon, ... L.PM.Draw.EXTENDINGCLASS */
jsClass: string;
/** Function fired when clicking the control. */
onClick: () => void;
position: L.ControlPosition;
/** Text showing when you hover the control. */
title: string;
/** Toggle state true -> enabled, false -> disabled (default: false) */
toggleStatus: boolean;
/** Block of the control. 'options' is ⭐ only. */
tool?: 'draw' | 'edit' | 'custom' | 'options';
}
interface CustomControlOptions {
/** Name of the control */
name: string;
/** Block of the control. 'options' is ⭐ only. */
block?: 'draw' | 'edit' | 'custom' | 'options';
/** Text showing when you hover the control. */
title?: string;
/** CSS class with the Icon. */
className?: string;
/** Function fired when clicking the control. */
onClick?: () => void;
/** Function fired after clicking the control. */
afterClick?: () => void;
/** Actions */
actions?: (ACTION_NAMES | Action)[];
/** Control can be toggled. */
toggle?: boolean;
/** Control is disabled. */
disabled?: boolean;
}
type PANE =
| 'mapPane'
| 'tilePane'
| 'overlayPane'
| 'shadowPane'
| 'markerPane'
| 'tooltipPane'
| 'popupPane'
| string;
interface GlobalOptions extends DrawModeOptions, EditModeOptions {
/** Add the created layers to a layergroup instead to the map. */
layerGroup?: L.Map | L.LayerGroup;
/** Prioritize the order of snapping. Default: ['Marker','CircleMarker','Circle','Line','Polygon','Rectangle']. */
snappingOrder: SUPPORTED_SHAPES[];
/** Defines in which panes the layers and helper vertices are created. Default: */
/** { vertexPane: 'markerPane', layerPane: 'overlayPane', markerPane: 'markerPane' } */
panes: { vertexPane: PANE; layerPane: PANE; markerPane: PANE };
}
interface PMDrawMap {
/** Draw */
Draw: Draw;
/** Enable Draw Mode with the passed shape. */
enableDraw(shape: SUPPORTED_SHAPES, options?: DrawModeOptions): void;
/** Disable all drawing */
disableDraw(shape?: SUPPORTED_SHAPES): void;
/** Returns true if global Draw Mode is enabled. false when disabled. */
globalDrawModeEnabled(): boolean;
/** Customize the style of the drawn layer. Only for L.Path layers. */
/** Shapes can be excluded with a ignoreShapes array or merged with the current style with merge: true in optionsModifier. */
setPathOptions(
options: L.PathOptions,
optionsModifier?: { ignoreShapes?: SUPPORTED_SHAPES[]; merge?: boolean }
): void;
/** Returns all Geoman layers on the map as array. Pass true to get a L.FeatureGroup. */
getGeomanLayers(asFeatureGroup?: boolean): L.FeatureGroup | L.Layer[];
/** Returns all Geoman draw layers on the map as array. Pass true to get a L.FeatureGroup. */
getGeomanDrawLayers(asFeatureGroup?: boolean): L.FeatureGroup | L.Layer[];
}
interface PMEditMap {
/** Enables edit mode. The passed options are preserved, even when the mode is enabled via the Toolbar */
enableGlobalEditMode(options?: EditModeOptions): void;
/** Disables global edit mode. */
disableGlobalEditMode(): void;
/** Toggles global edit mode. */
toggleGlobalEditMode(options?: EditModeOptions): void;
/** Returns true if global edit mode is enabled. false when disabled. */
globalEditModeEnabled(): boolean;
}
interface PMDragMap {
/** Enables global drag mode. */
enableGlobalDragMode(): void;
/** Disables global drag mode. */
disableGlobalDragMode(): void;
/** Toggles global drag mode. */
toggleGlobalDragMode(): void;
/** Returns true if global drag mode is enabled. false when disabled. */
globalDragModeEnabled(): boolean;
}
interface PMRemoveMap {
/** Enables global removal mode. */
enableGlobalRemovalMode(): void;
/** Disables global removal mode. */
disableGlobalRemovalMode(): void;
/** Toggles global removal mode. */
toggleGlobalRemovalMode(): void;
/** Returns true if global removal mode is enabled. false when disabled. */
globalRemovalModeEnabled(): boolean;
}
interface PMCutMap {
/** Enables global cut mode. */
enableGlobalCutMode(options?: CutModeOptions): void;
/** Disables global cut mode. */
disableGlobalCutMode(): void;
/** Toggles global cut mode. */
toggleGlobalCutMode(options?: CutModeOptions): void;
/** Returns true if global cut mode is enabled. false when disabled. */
globalCutModeEnabled(): boolean;
}
interface PMRotateMap {
/** Enables global rotate mode. */
enableGlobalRotateMode(): void;
/** Disables global rotate mode. */
disableGlobalRotateMode(): void;
/** Toggles global rotate mode. */
toggleGlobalRotateMode(): void;
/** Returns true if global rotate mode is enabled. false when disabled. */
globalRotateModeEnabled(): boolean;
}
interface PMRotateLayer {
/** Enables rotate mode on the layer. */
enableRotate(): void;
/** Disables rotate mode on the layer. */
disableRotate(): void;
/** Toggles rotate mode on the layer. */
rotateEnabled(): void;
/** Rotates the layer by x degrees. */
rotateLayer(degrees: number): void;
/** Rotates the layer to x degrees. */
rotateLayerToAngle(degrees: number): void;
/** Returns the angle of the layer in degrees. */
getAngle(): number;
}
interface Draw {
/** Array of available shapes. */
getShapes(): SUPPORTED_SHAPES[];
/** Returns the active shape. */
getActiveShape(): SUPPORTED_SHAPES;
/** Set path options */
setPathOptions(options: L.PathOptions): void;
/** Set options */
setOptions(options: DrawModeOptions): void;
/** Get options */
getOptions(): DrawModeOptions;
}
interface CutModeOptions {
allowSelfIntersection?: boolean;
}
type VertexValidationHandler = (e: {
layer: L.Layer;
marker: L.Marker;
event: any;
}) => boolean;
interface EditModeOptions {
/** Enable snapping to other layers vertices for precision drawing. Can be disabled by holding the ALT key (default:true). */
snappable?: boolean;
/** The distance to another vertex when a snap should happen (default:20). */
snapDistance?: number;
/** Allow self intersections (default:true). */
allowSelfIntersection?: boolean;
/** Allow self intersections (default:true). */
allowSelfIntersectionEdit?: boolean;
/** Disable the removal of markers via right click / vertices via removeVertexOn. (default:false). */
preventMarkerRemoval?: boolean;
/** If true, vertex removal that cause a layer to fall below their minimum required vertices will remove the entire layer. */
/** If false, these vertices can't be removed. Minimum vertices are 2 for Lines and 3 for Polygons (default:true). */
removeLayerBelowMinVertexCount?: boolean;
/** Defines which layers should dragged with this layer together. */
/** true syncs all layers in the same LayerGroup(s) or you pass an `Array` of layers to sync. (default:false). */
syncLayersOnDrag?: L.Layer[] | boolean;
/** Edit-Mode for the layer can disabled (`pm.enable()`). (default:true). */
allowEditing?: boolean;
/** Removing can be disabled for the layer. (default:true). */
allowRemoval?: boolean;
/** Layer can be prevented from cutting. (default:true). */
allowCutting?: boolean;
/** Layer can be prevented from rotation. (default:true). */
allowRotation?: boolean;
/** Dragging can be disabled for the layer. (default:true). */
draggable?: boolean;
/** Leaflet layer event to add a vertex to a Line or Polygon, like dblclick. (default:click). */
addVertexOn?:
| 'click'
| 'dblclick'
| 'mousedown'
| 'mouseover'
| 'mouseout'
| 'contextmenu';
/** A function for validation if a vertex (of a Line / Polygon) is allowed to add. */
/** It passes a object with `[layer, marker, event}`. For example to check if the layer */
/** has a certain property or if the `Ctrl` key is pressed. (default:undefined). */
addVertexValidation?: undefined | VertexValidationHandler;
/** Leaflet layer event to remove a vertex from a Line or Polygon, like dblclick. (default:contextmenu). */
removeVertexOn?:
| 'click'
| 'dblclick'
| 'mousedown'
| 'mouseover'
| 'mouseout'
| 'contextmenu';
/** A function for validation if a vertex (of a Line / Polygon) is allowed to remove. */
/** It passes a object with `[layer, marker, event}`. For example to check if the layer has a certain property */
/** or if the `Ctrl` key is pressed. */
removeVertexValidation?: undefined | VertexValidationHandler;
/** A function for validation if a vertex / helper-marker is allowed to move / drag. It passes a object with */
/** `[layer, marker, event}`. For example to check if the layer has a certain property or if the `Ctrl` key is pressed. */
moveVertexValidation?: undefined | VertexValidationHandler;
/** Shows only n markers closest to the cursor. Use -1 for no limit (default:-1). */
limitMarkersToCount?: number;
/** Shows markers when under the given zoom level ⭐ */
limitMarkersToZoom?: number;
/** Shows only markers in the viewport ⭐ */
limitMarkersToViewport?: boolean;
/** Shows markers only after the layer was clicked ⭐ */
limitMarkersToClick?: boolean;
/** Pin shared vertices/markers together during edit ⭐ */
pinning?: boolean;
/** Hide the middle Markers in edit mode from Polyline and Polygon. */
hideMiddleMarkers?: boolean;
}
interface DrawModeOptions {
/** Enable snapping to other layers vertices for precision drawing. Can be disabled by holding the ALT key (default:true). */
snappable?: boolean;
/** The distance to another vertex when a snap should happen (default:20). */
snapDistance?: number;
/** Allow snapping in the middle of two vertices (middleMarker)(default:false). */
snapMiddle?: boolean;
/** Allow snapping between two vertices. (default: true) */
snapSegment?: boolean;
/** Require the last point of a shape to be snapped. (default: false). */
requireSnapToFinish?: boolean;
/** Show helpful tooltips for your user (default:true). */
tooltips?: boolean;
/** Allow self intersections (default:true). */
allowSelfIntersection?: boolean;
/** Leaflet path options for the lines between drawn vertices/markers. (default:{color:'red'}). */
templineStyle?: L.PathOptions;
/** Leaflet path options for the helper line between last drawn vertex and the cursor. (default:{color:'red',dashArray:[5,5]}). */
hintlineStyle?: L.PathOptions;
/** Leaflet path options for the drawn layer (Only for L.Path layers). (default:null). */
pathOptions?: L.PathOptions;
/** Leaflet marker options (only for drawing markers). (default:{draggable:true}). */
markerStyle?: L.MarkerOptions;
/** Show a marker at the cursor (default:true). */
cursorMarker?: boolean;
/** Leaflet layer event to finish the drawn shape (default:null). */
finishOn?:
| null
| 'click'
| 'dblclick'
| 'mousedown'
| 'mouseover'
| 'mouseout'
| 'contextmenu'
| 'snap';
/** Hide the middle Markers in edit mode from Polyline and Polygon. (default:false). */
hideMiddleMarkers?: boolean;
/** Set the min radius of a Circle. (default:null). */
minRadiusCircle?: number;
/** Set the max radius of a Circle. (default:null). */
maxRadiusCircle?: number;
/** Set the min radius of a CircleMarker when editable is active. (default:null). */
minRadiusCircleMarker?: number;
/** Set the max radius of a CircleMarker when editable is active. (default:null). */
maxRadiusCircleMarker?: number;
/** Makes a CircleMarker editable like a Circle (default:false). */
editable?: boolean;
/** Markers and CircleMarkers are editable during the draw-session */
/** (you can drag them around immediately after drawing them) (default:true). */
markerEditable?: boolean;
/** Draw-Mode stays enabled after finishing a layer to immediately draw the next layer. */
/** Defaults to true for Markers and CircleMarkers and false for all other layers. */
continueDrawing?: boolean;
/** Angel of rectangle. */
rectangleAngle?: number;
/** Cut-Mode: Only the passed layers can be cut. Cutted layers are removed from the */
/** Array until no layers are left anymore and cutting is working on all layers again. (Default: []) */
layersToCut?: L.Layer[];
}
/**
* PM toolbar options.
*/
interface ToolbarOptions {
/** Toolbar position. */
position?: L.ControlPosition;
/** The position of each block can be customized. If not set, the value from position is taken. */
positions?: BlockPositions;
/** Adds button to draw Markers (default:true) */
drawMarker?: boolean;
/** Adds button to draw CircleMarkers (default:true) */
drawCircleMarker?: boolean;
/** Adds button to draw Line (default:true) */
drawPolyline?: boolean;
/** Adds button to draw Rectangle (default:true) */
drawRectangle?: boolean;
/** Adds button to draw Polygon (default:true) */
drawPolygon?: boolean;
/** Adds button to draw Circle (default:true) */
drawCircle?: boolean;
/** Adds button to toggle edit mode for all layers (default:true) */
editMode?: boolean;
/** Adds button to toggle drag mode for all layers (default:true) */
dragMode?: boolean;
/** Adds button to cut a hole in a polygon or line (default:true) */
cutPolygon?: boolean;
/** Adds a button to remove layers (default:true) */
removalMode?: boolean;
/** Adds a button to rotate layers (default:true) */
rotateMode?: boolean;
/** All buttons will be displayed as one block Customize Controls (default:false) */
oneBlock?: boolean;
/** Shows all draw buttons / buttons in the draw block (default:true) */
drawControls?: boolean;
/** Shows all edit buttons / buttons in the edit block (default:true) */
editControls?: boolean;
/** Shows all buttons in the custom block (default:true) */
customControls?: boolean;
/** Shows all options buttons / buttons in the option block ⭐ */
optionsControls?: boolean;
/** Adds a button to toggle the Pinning Option ⭐ */
pinningOption?: boolean;
/** Adds a button to toggle the Snapping Option ⭐ */
snappingOption?: boolean;
}
/** the position of each block. */
interface BlockPositions {
/** Draw control position (default:''). '' also refers to this position. */
draw?: L.ControlPosition;
/** Edit control position (default:''). */
edit?: L.ControlPosition;
/** Custom control position (default:''). */
custom?: L.ControlPosition;
/** Options control position (default:'') ⭐ */
options?: L.ControlPosition;
}
interface PMEditLayer {
/** Enables edit mode. The passed options are preserved, even when the mode is enabled via the Toolbar */
enable(options?: EditModeOptions): void;
/** Sets layer options */
setOptions(options?: EditModeOptions): void;
/** Gets layer options */
getOptions(): EditModeOptions;
/** Disables edit mode. */
disable(): void;
/** Toggles edit mode. Passed options are preserved. */
toggleEdit(options?: EditModeOptions): void;
/** Returns true if edit mode is enabled. false when disabled. */
enabled(): boolean;
/** Returns true if Line or Polygon has a self intersection. */
hasSelfIntersection(): boolean;
/** Removes the layer with the same checks as GlobalRemovalMode. */
remove(): void;
}
interface PMDragLayer {
/** Enables dragging for the layer. */
enableLayerDrag(): void;
/** Disables dragging for the layer. */
disableLayerDrag(): void;
/** Returns if the layer is currently dragging. */
dragging(): boolean;
/** Returns if drag mode is enabled for the layer. */
layerDragEnabled(): boolean;
}
interface PMLayer extends PMRotateLayer, PMEditLayer, PMDragLayer {
/** Get shape of the layer. */
getShape(): SUPPORTED_SHAPES;
}
interface PMLayerGroup {
/** Enables edit mode for all child layers. The passed options are preserved, even when the mode is enabled via the Toolbar */
enable(options?: EditModeOptions): void;
/** Disable edit mode for all child layers. */
disable(): void;
/** Returns if minimum one layer is enabled. */
enabled(): boolean;
/** Toggle enable / disable on all layers. */
toggleEdit(options?: EditModeOptions): void;
/** Returns the layers of the LayerGroup. `deep=true` return also the children of LayerGroup children. */
/** `filterGeoman=true` filter out layers that don't have Leaflet-Geoman or temporary stuff. */
/** `filterGroupsOut=true` does not return the LayerGroup layers self. */
/** (Default: `deep=false`,`filterGeoman=true`, `filterGroupsOut=true` ) */
getLayers(
deep?: boolean,
filterGeoman?: boolean,
filterGroupsOut?: boolean
): L.Layer[];
/** Apply Leaflet-Geoman options to all children. The passed options are preserved, even when the mode is enabled via the Toolbar */
setOptions(options?: EditModeOptions): void;
/** Returns the options of the LayerGroup. */
getOptions(): EditModeOptions;
/** Returns if currently a layer in the LayerGroup is dragging. */
dragging(): boolean;
}
namespace Utils {
/** Returns the translation of the passed path. path = json-string f.ex. tooltips.placeMarker */
function getTranslation(path: string): string;
/** Returns the middle LatLng between two LatLngs */
function calcMiddleLatLng(
map: L.Map,
latlng1: L.LatLng,
latlng2: L.LatLng
): L.LatLng;
/** Returns all layers that are available for Geoman */
function findLayers(map: L.Map): L.Layer[];
/** Converts a circle into a polygon with default 60 sides. For CRS.Simple maps `withBearing` needs to be false */
function circleToPolygon(
circle: L.Circle,
sides?: number,
withBearing?: boolean
): L.Polygon;
/** Converts a px-radius (CircleMarker) to meter-radius (Circle). */
/** The center LatLng is needed because the earth has different projections on different places. */
function pxRadiusToMeterRadius(
radiusInPx: number,
map: L.Map,
center: L.LatLng
): number;
}
/**
* DRAW MODE MAP EVENT HANDLERS
*/
export type GlobalDrawModeToggledEventHandler = (event: {
enabled: boolean;
shape: PM.SUPPORTED_SHAPES;
map: L.Map;
}) => void;
export type DrawStartEventHandler = (e: {
shape: PM.SUPPORTED_SHAPES;
workingLayer: L.Layer;
}) => void;
export type DrawEndEventHandler = (e: {
shape: PM.SUPPORTED_SHAPES;
}) => void;
export type CreateEventHandler = (e: {
shape: PM.SUPPORTED_SHAPES;
layer: L.Layer;
}) => void;
/**
* DRAW MODE LAYER EVENT HANDLERS
*/
export type VertexAddedEventHandler = (e: {
shape: PM.SUPPORTED_SHAPES;
workingLayer: L.Layer;
marker: L.Marker;
latlng: L.LatLng;
}) => void;
export type SnapEventHandler = (e: {
shape: PM.SUPPORTED_SHAPES;
distance: number;
layer: L.Layer;
workingLayer: L.Layer;
marker: L.Marker;
layerInteractedWith: L.Layer;
segement: any;
snapLatLng: L.LatLng;
}) => void;
export type CenterPlacedEventHandler = (e: {
shape: PM.SUPPORTED_SHAPES;
workingLayer: L.Layer;
latlng: L.LatLng;
}) => void;
/**
* EDIT MODE LAYER EVENT HANDLERS
*/
export type EditEventHandler = (e: {
shape: PM.SUPPORTED_SHAPES;
layer: L.Layer;
}) => void;
export type UpdateEventHandler = (e: {
shape: PM.SUPPORTED_SHAPES;
layer: L.Layer;
}) => void;
export type EnableEventHandler = (e: {
shape: PM.SUPPORTED_SHAPES;
layer: L.Layer;
}) => void;
export type DisableEventHandler = (e: {
shape: PM.SUPPORTED_SHAPES;
layer: L.Layer;
}) => void;
export type VertexAddedEventHandler2 = (e: {
layer: L.Layer;
indexPath: number;
latlng: L.LatLng;
marker: L.Marker;
shape: PM.SUPPORTED_SHAPES;
}) => void;
export type VertexRemovedEventHandler = (e: {
layer: L.Layer;
indexPath: number;
marker: L.Marker;
shape: PM.SUPPORTED_SHAPES;
}) => void;
export type VertexClickEventHandler = (e: {
layer: L.Layer;
indexPath: number;
markerEvent: any;
shape: PM.SUPPORTED_SHAPES;
}) => void;
export type MarkerDragStartEventHandler = (e: {
layer: L.Layer;
indexPath: number;
markerEvent: any;
shape: PM.SUPPORTED_SHAPES;
}) => void;
export type MarkerDragEventHandler = (e: {
layer: L.Layer;
indexPath: number;
markerEvent: any;
shape: PM.SUPPORTED_SHAPES;
}) => void;
export type MarkerDragEndEventHandler = (e: {
layer: L.Layer;
indexPath: number;
markerEvent: any;
shape: PM.SUPPORTED_SHAPES;
intersectionRest: boolean;
}) => void;
export type LayerResetEventHandler = (e: {
layer: L.Layer;
indexPath: number;
markerEvent: any;
shape: PM.SUPPORTED_SHAPES;
}) => void;
export type IntersectEventHandler = (e: {
shape: PM.SUPPORTED_SHAPES;
layer: L.Layer;
intersection: L.LatLng;
}) => void;
/**
* EDIT MODE MAP EVENT HANDLERS
*/
export type GlobalEditModeToggledEventHandler = (event: {
enabled: boolean;
map: L.Map;
}) => void;
/**
* DRAG MODE MAP EVENT HANDLERS
*/
export type GlobalDragModeToggledEventHandler = (event: {
enabled: boolean;
map: L.Map;
}) => void;
/**
* DRAG MODE LAYER EVENT HANDLERS
*/
export type DragStartEventHandler = (e: {
layer: L.Layer;
shape: PM.SUPPORTED_SHAPES;
}) => void;
export type DragEventHandler = (e: {
layer: L.Layer;
containerPoint: any;
latlng: L.LatLng;
layerPoint: L.Point;
originalEvent: any;
shape: PM.SUPPORTED_SHAPES;
}) => void;
export type DragEndEventHandler = (e: {
layer: L.Layer;
shape: PM.SUPPORTED_SHAPES;
}) => void;
/**
* REMOVE MODE LAYER EVENT HANDLERS
*/
export type RemoveEventHandler = (e: {
layer: L.Layer;
shape: PM.SUPPORTED_SHAPES;
}) => void;
/**
* REMOVE MODE MAP EVENT HANDLERS
*/
export type GlobalRemovalModeToggledEventHandler = (e: {
enabled: boolean;
map: L.Map;
}) => void;
/**
* CUT MODE MAP EVENT HANDLERS
*/
export type GlobalCutModeToggledEventHandler = (e: {
enabled: boolean;
map: L.Map;
}) => void;
export type CutEventHandler = (e: {
layer: L.Layer;
originalLayer: L.Layer;
shape: PM.SUPPORTED_SHAPES;
}) => void;
/**
* ROTATE MODE LAYER EVENT HANDLERS
*/
export type RotateEnableEventHandler = (e: {
layer: L.Layer;
helpLayer: L.Layer;
}) => void;
export type RotateDisableEventHandler = (e: { layer: L.Layer }) => void;
export type RotateStartEventHandler = (e: {
layer: L.Layer;
helpLayer: L.Layer;
startAngle: number;
originLatLngs: L.LatLng[];
}) => void;
export type RotateEventHandler = (e: {
layer: L.Layer;
helpLayer: L.Layer;
startAngle: number;
angle: number;
angleDiff: number;
oldLatLngs: L.LatLng[];
newLatLngs: L.LatLng[];
}) => void;
export type RotateEndEventHandler = (e: {
layer: L.Layer;
helpLayer: L.Layer;
startAngle: number;
angle: number;
originLatLngs: L.LatLng[];
newLatLngs: L.LatLng[];
}) => void;
/**
* ROTATE MODE MAP EVENT HANDLERS
*/
export type GlobalRotateModeToggledEventHandler = (e: {
enabled: boolean;
map: L.Map;
}) => void;
/**
* TRANSLATION EVENT HANDLERS
*/
export type LangChangeEventHandler = (e: {
activeLang: string;
oldLang: string;
fallback: string;
translations: PM.Translations;
}) => void;
/**
* CONTROL MAP EVENT HANDLERS
*/
export type ButtonClickEventHandler = (e: {
btnName: string;
button: PM.Button;
}) => void;
export type ActionClickEventHandler = (e: {
text: string;
action: string;
btnName: string;
button: PM.Button;
}) => void;
/**
* KEYBOARD EVENT HANDLERS
*/
export type KeyboardKeyEventHandler = (e: {
focusOn: 'document' | 'map';
eventType: 'keydown' | 'keyup';
event: any;
}) => void;
}
namespace PM {
interface PMMapToolbar {
toggleButton(
name: string,
status: boolean,
disableOthers?: boolean
): void;
}
}
} | the_stack |
interface IDispatch { }
interface IDictionary { }
interface IUnknown { }
interface IStream { }
type Guid = string;
declare namespace Enums
{
////////////////////////////////////////////////////////////////////////////////////////////////////
// AGCObjectType Enum
/**
* AGCUniqueID type.
*/
enum AGCObjectType
{
AGCObjectType_Invalid,
AGC_ModelBegin,
AGC_Ship,
AGC_Station,
AGC_Missile,
AGC_Mine,
AGC_Probe,
AGC_Asteroid,
AGC_Projectile,
AGC_Warp,
AGC_Treasure,
AGC_Buoy,
AGC_Chaff,
AGC_BuildingEffect,
AGC_ModelEnd,
AGC_Side,
AGC_Cluster,
AGC_Bucket,
AGC_PartBegin,
AGC_Weapon,
AGC_Shield,
AGC_Cloak,
AGC_Pack,
AGC_Afterburner,
AGC_LauncherBegin,
AGC_Magazine,
AGC_Dispenser,
AGC_LauncherEnd,
AGC_PartEnd,
AGC_StaticBegin,
AGC_ProjectileType,
AGC_MissileType,
AGC_MineType,
AGC_ProbeType,
AGC_ChaffType,
AGC_Civilization,
AGC_TreasureSet,
AGC_BucketStart,
AGC_HullType,
AGC_PartType,
AGC_StationType,
AGC_Development,
AGC_DroneType,
AGC_BucketEnd,
AGC_StaticEnd,
AGC_Constants,
AGC_AdminUser,
AGCObjectType_Max,
AGC_Any_Objects,
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// AGCHullAbility Enum
/**
* Constants for the AGCHullAbilityBitMask type.
*/
enum AGCHullAbility
{
AGCHullAbility_Board,
AGCHullAbility_Rescue,
AGCHullAbility_Lifepod,
AGCHullAbility_NoPickup,
AGCHullAbility_NoEjection,
AGCHullAbility_NoRipcord,
AGCHullAbility_CheatToDock,
AGCHullAbility_Fighter,
AGCHullAbility_Captital,
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// AGCAsteroidAbility Enum
/**
* Constants for the AGCAsteroidAbilityBitMask type.
*/
enum AGCAsteroidAbility
{
AGCAsteroidAbility_MineHe3,
AGCAsteroidAbility_MineIce,
AGCAsteroidAbility_MineGold,
AGCAsteroidAbility_Buildable,
AGCAsteroidAbility_Special,
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// AGCAxis Enum
/**
* Constants for AGCAxis.
*/
enum AGCAxis
{
AGCAxis_Yaw,
AGCAxis_Pitch,
AGCAxis_Roll,
AGCAxis_Throttle,
AGCAxis_Max,
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// AGCEquipmentType Enum
/**
* Constants for AGCEquipmentType.
*/
enum AGCEquipmentType
{
AGCEquipmentType_ChaffLauncher,
AGCEquipmentType_Weapon,
AGCEquipmentType_Magazine,
AGCEquipmentType_Dispenser,
AGCEquipmentType_Shield,
AGCEquipmentType_Cloak,
AGCEquipmentType_Pack,
AGCEquipmentType_Afterburner,
AGCEquipmentType_MAX,
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// AGCTreasureType Enum
/**
* Constants for AGCTreasureType.
*/
enum AGCTreasureType
{
AGCTreasureType_Part,
AGCTreasureType_Development,
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// AGCChatTarget Enum
/**
* Constants for AGCChatTarget.
*/
enum AGCChatTarget
{
AGCChat_Everyone,
AGCChat_Leaders,
AGCChat_Admin,
AGCChat_Ship,
AGCChat_Allies,
AGCChat_Team,
AGCChat_Individual,
AGCChat_Individual_NoFilter,
AGCChat_Wing,
AGCChat_Echo,
AGCChat_AllSector,
AGCChat_FriendlySector,
AGCChat_Group,
AGCChat_GroupNoEcho,
AGCChat_NoSelection,
AGCChat_Max,
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// AGCGameStage Enum
/**
* Constants for AGCGameStage.
*/
enum AGCGameStage
{
AGCGameStage_NotStarted,
AGCGameStage_Starting,
AGCGameStage_Started,
AGCGameStage_Over,
AGCGameStage_Terminate,
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// FileAttributes Enum
/**
* Constants for file attributes.
*/
enum FileAttributes
{
FileAttribute_None,
FileAttribute_ReadOnly,
FileAttribute_Hidden,
FileAttribute_System,
FileAttribute_Directory,
FileAttribute_Archive,
FileAttribute_Encrypted,
FileAttribute_Normal,
FileAttribute_Temporary,
FileAttribute_SparseFile,
FileAttribute_ReparsePoint,
FileAttribute_Compressed,
FileAttribute_Offline,
FileAttribute_NotContentIndexed,
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// PigState Enum
/**
* Constants for pig player states.
*/
enum PigState
{
PigState_NonExistant,
PigState_LoggingOn,
PigState_LoggingOff,
PigState_MissionList,
PigState_CreatingMission,
PigState_JoiningMission,
PigState_QuittingMission,
PigState_TeamList,
PigState_JoiningTeam,
PigState_WaitingForMission,
PigState_Docked,
PigState_Launching,
PigState_Flying,
PigState_Terminated,
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// PigMapType Enum
/**
* Constants for mission map types.
*/
enum PigMapType
{
PigMapType_SingleRing,
PigMapType_DoubleRing,
PigMapType_PinWheel,
PigMapType_DiamondRing,
PigMapType_Snowflake,
PigMapType_SplitBases,
PigMapType_Brawl,
PigMapType_Count,
PigMapType_Default,
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// PigLobbyMode Enum
/**
* Constants for pig lobby server mode.
*/
enum PigLobbyMode
{
PigLobbyMode_Club,
PigLobbyMode_Free,
PigLobbyMode_LAN,
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// PigThrust Enum
/**
* Constants for pig thrust actions.
*/
enum PigThrust
{
ThrustNone,
ThrustLeft,
ThrustRight,
ThrustUp,
ThrustDown,
ThrustForward,
ThrustBackward,
ThrustBooster,
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// AGCUniqueID Alias
/**
* AGCUniqueID type.
*/
type AGCUniqueID = number;
////////////////////////////////////////////////////////////////////////////////////////////////////
// AGCObjectID Alias
/**
* AGCObjectID type.
*/
type AGCObjectID = number;
////////////////////////////////////////////////////////////////////////////////////////////////////
// AGCGameID Alias
/**
* AGCGameID type.
*/
type AGCGameID = number;
////////////////////////////////////////////////////////////////////////////////////////////////////
// AGCMoney Alias
/**
* AGCMoney type.
*/
type AGCMoney = number;
////////////////////////////////////////////////////////////////////////////////////////////////////
// AGCHitPoints Alias
/**
* AGCHitPoints type.
*/
type AGCHitPoints = number;
////////////////////////////////////////////////////////////////////////////////////////////////////
// AGCPartMask Alias
/**
* AGCPartMask type.
*/
type AGCPartMask = number;
////////////////////////////////////////////////////////////////////////////////////////////////////
// AGCMount Alias
/**
* AGCMount type.
*/
type AGCMount = number;
////////////////////////////////////////////////////////////////////////////////////////////////////
// AGCHullAbilityBitMask Alias
/**
* AGCHullAbilityBitMask type.
*/
type AGCHullAbilityBitMask = number;
////////////////////////////////////////////////////////////////////////////////////////////////////
// AGCAsteroidAbilityBitMask Alias
/**
* AGCAsteroidAbilityBitMask type.
*/
type AGCAsteroidAbilityBitMask = number;
////////////////////////////////////////////////////////////////////////////////////////////////////
// AGCSoundID Alias
/**
* AGCSoundID type.
*/
type AGCSoundID = number;
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCEventSink Interface
/**
* Interface implemented by the hosting application to receive triggered events. Intended for use ONLY by host applications.
*/
interface IAGCEventSink extends IUnknown
{
/**
* Called when an AGC event has been triggered.
*/
OnEventTriggered(pEvent: IAGCEvent): void;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCEventSinkSynchronous Interface
/**
* Interface implemented by the hosting application to receive triggered events. Intended for use ONLY by host applications.
*/
interface IAGCEventSinkSynchronous extends IUnknown
{
/**
* Called when an AGC event has been triggered.
*/
OnEventTriggeredSynchronous(pEvent: IAGCEvent): void;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCDebugHook Interface
/**
* Implemented by an AGC host to hook debug events.
*/
interface IAGCDebugHook extends IUnknown
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCGlobal Interface
/**
* Interface to the AGC Global object. Intended for use ONLY by host applications that deal directly with Igc.
*/
interface IAGCGlobal extends IUnknown
{
/**
* Registers the function that is called to create the object that suports the specified interface
*/
GetAGCObject(pvIgc: object, riid: Guid, ppUnk: object): void;
/**
* Adds a mapping of an Igc object pointer to an AGC object.
*/
MakeAGCEvent(idEvent: number, pszContext: string, pszSubject: string, idSubject: AGCUniqueID, cArgTriplets: number, pvArgs: object): IAGCEvent;
/**
* Sets the ranges of event ID's available from the host application.
*/
MakeAGCVector(pVectorRaw: object): IAGCVector;
/**
* Creates an AGCOrientation object, initialized with the specified raw ZLib orientation.
*/
MakeAGCOrientation(pOrientationRaw: object): IAGCOrientation;
/**
* Creates an AGCEventIDRange object, initialized with the specified values.
*/
MakeAGCEventIDRange(lower: number, upper: number): IAGCEventIDRange;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCVector Interface
/**
* Interface to a AGC Vector object.
*/
interface IAGCVector extends IDispatch
{
/**
* Gets/sets the x coordinate of the vector.
*/
X(xArg: number): void;
/**
* Gets/sets the y coordinate of the vector.
*/
Y(yArg: number): void;
/**
* Gets/sets the z coordinate of the vector.
*/
Z(zArg: number): void;
/**
* Gets/sets the displayable string representation of the vector.
*/
DisplayString(bstrDisplayString: string): void;
/**
* Initializes the object with the specified x, y, and z values.
*/
InitXYZ(xArg: number, yArg: number, zArg: number): void;
/**
* Initializes the object by copying the specified vector's x, y, and z values.
*/
InitCopy(pVector: IAGCVector): void;
/**
* Initializes the object with a random direction.
*/
InitRandomDirection(): void;
/**
* Initializes the object with a random position.
*/
InitRandomPosition(fRadius: number): void;
/**
* READONLY: Compares the object to a zero vector.
*/
readonly IsZero: boolean;
/**
* Compares the object to the specified vector.
*/
IsEqual(pVector: IAGCVector): boolean;
/**
* READONLY: Computes the length of the object from a zero vector.
*/
readonly Length: number;
/**
* READONLY: Computes the squared length of the object from a zero vector.
*/
readonly LengthSquared: number;
/**
* READONLY: Computes the orthogonal vector of the object.
*/
readonly OrthogonalVector: IAGCVector;
/**
* Computes the sum of the object and the specified vector. Does not modify the object.
*/
Add(pVector: IAGCVector): IAGCVector;
/**
* Computes the difference of the object and the specified vector. Does not modify the object.
*/
Subtract(pVector: IAGCVector): IAGCVector;
/**
* Computes the product of the object and the specified multiplier value. Does not modify the object.
*/
Multiply(f: number): IAGCVector;
/**
* Computes the quotient of the object and the specified divisor value. Does not modify the object.
*/
Divide(f: number): IAGCVector;
/**
* Computes the normalized vector of the object. Does not modify the object.
*/
Normalize(): IAGCVector;
/**
* Computes the cross product of the object and the specified vector. Does not modify the object.
*/
CrossProduct(pVector: IAGCVector): IAGCVector;
/**
* Computes an interpolation of the object with the specified vector. Does not modify the object.
*/
Interpolate(pVector: IAGCVector, fValue: number): IAGCVector;
/**
* Computes the sum of the object and the specified vector, with the result being stored in the object.
*/
AddInPlace(pVector: IAGCVector): void;
/**
* Computes the difference of the object and the specified vector, with the result being stored in the object.
*/
SubtractInPlace(pVector: IAGCVector): void;
/**
* Computes the product of the object and the specified multiplier value, with the result being stored in the object.
*/
MultiplyInPlace(f: number): void;
/**
* Computes the quotient of the object and the specified divisor value, with the result being stored in the object.
*/
DivideInPlace(f: number): void;
/**
* Computes the normalized vector of the object, with the result being stored in the object.
*/
NormalizeInPlace(): void;
/**
* Computes the cross product of the object and the specified vector, with the result being stored in the object.
*/
CrossProductInPlace(pVector: IAGCVector): void;
/**
* Computes an interpolation of the object with the specified vector, with the result being stored in the object.
*/
InterpolateInPlace(pVector: IAGCVector, fValue: number): void;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCVectorPrivate Interface
/**
* Private interface to an AGC Vector object.
*/
interface IAGCVectorPrivate extends IUnknown
{
/**
* Initializes the object from a raw (ZLib/IGC) Vector pointer.
*/
InitFromVector(pvVector: object): void;
/**
* Copies the object's raw (ZLib/IGC) Vector to the specified Vector pointer.
*/
CopyVectorTo(pvVector: object): void;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCOrientation Interface
/**
* Interface to an AGC Orientation object.
*/
interface IAGCOrientation extends IDispatch
{
/**
* Initializes the object by copying the specified object.
*/
InitCopy(pOrientation: IAGCOrientation): void;
/**
* READONLY: Gets the Forward vector of the orientation matrix.
*/
readonly Forward: IAGCVector;
/**
* READONLY: Gets the Backward vector of the orientation matrix.
*/
readonly Backward: IAGCVector;
/**
* READONLY: Gets the Up vector of the orientation matrix.
*/
readonly Up: IAGCVector;
/**
* READONLY: Gets the Right vector of the orientation matrix.
*/
readonly Right: IAGCVector;
/**
* Compares the object to the specified object for absolute equality.
*/
IsEqual(pOrientation: IAGCOrientation): boolean;
/**
* Compares the object to the specified object for 'fuzzy' equality.
*/
IsRoughlyEqual(pOrientation: IAGCOrientation): boolean;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCOrientationPrivate Interface
/**
* Private interface to an AGC Orientation object.
*/
interface IAGCOrientationPrivate extends IUnknown
{
/**
* Initializes the object from a raw (ZLib/IGC) Orientation pointer.
*/
InitFromOrientation(pvOrientation: object): void;
/**
* Copies the object's raw (ZLib/IGC) Orientation to the specified Orientation pointer.
*/
CopyOrientationTo(pvOrientation: object): void;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCEventType Interface
/**
* IAGCEventType Interface
*/
interface IAGCEventType extends IDispatch
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCEvent Interface
/**
* IAGCEvent Interface
*/
interface IAGCEvent extends IDispatch
{
/**
* READONLY: Gets the event identifier.
*/
readonly ID: number;
/**
* READONLY: Gets the date and time that the event occurred.
*/
readonly Time: Date;
/**
* READONLY: Gets the textual description of the event that occurred.
*/
readonly Description: string;
/**
* READONLY: Gets the number of event parameters in the property map.
*/
readonly PropertyCount: number;
/**
* Gets whether or not the specified event parameter is in the property map.
*/
PropertyExists(bstrKey: string): boolean;
/**
* Gets the specified event parameter from the property map.
*/
Property(pvKey: object): object;
/**
* READONLY: Gets the name of the computer on which the event occurred.
*/
readonly ComputerName: string;
/**
* READONLY: Gets the ID of the subject of the event, if any. Otherwise, -1.
*/
readonly SubjectID: number;
/**
* READONLY: Gets the name of the subject of the event, if any.
*/
readonly SubjectName: string;
/**
* Persists the object to a string representation, to be resolved with LoadFromString.
*/
SaveToString(): string;
/**
* Initializes the object from a persistence string returned by SaveToString.
*/
LoadFromString(bstr: string): void;
/**
* READONLY: Gets a string representing the context in which the event occurred.
*/
readonly Context: string;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCEventCreate Interface
/**
* IAGCEventCreate Interface
*/
interface IAGCEventCreate extends IDispatch
{
/**
* Initializes object.
*/
Init(): void;
/**
* Sets the event identifier.
*/
ID(Val: number): void;
/**
* Sets the date and time that the event occurred.
*/
Time(Val: Date): void;
/**
* Sets the time property to the current date/time.
*/
SetTimeNow(): void;
/**
* Adds the specified event parameter to the property map.
*/
AddProperty(pbstrKey: string, pvValue: object): void;
/**
* Removes the specified event parameter from the property map.
*/
RemoveProperty(pbstrKey: string, pvValue: object): void;
/**
* Sets the ID of the subject of the event, if any. Otherwise, -1.
*/
SubjectID(idSubject: number): void;
/**
* Sets the name of the subject of the event, if any.
*/
SubjectName(bstrSubject: string): void;
/**
* Sets the string representing the context in which the event occurred.
*/
Context(bstrContext: string): void;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCGameParameters Interface
/**
* IAGCGameParameters Interface
*/
interface IAGCGameParameters extends IDispatch
{
/**
* Validates the properties of the object.
*/
Validate(): void;
/**
* Gets/sets the minimum players per team.
*/
MinPlayers(Val: number): void;
/**
* Gets/sets the maximum players per team.
*/
MaxPlayers(Val: number): void;
/**
* property GameName
*/
GameName: string;
/**
* property EjectPods
*/
EjectPods: boolean;
/**
* property AllowPrivateTeams
*/
AllowPrivateTeams: boolean;
/**
* property PowerUps
*/
PowerUps: boolean;
/**
* property AllowJoiners
*/
AllowJoiners: boolean;
/**
* property Stations
*/
Stations: boolean;
/**
* property ScoresCount
*/
ScoresCount: boolean;
/**
* property Drones
*/
Drones: boolean;
/**
* property IsGoalConquest
*/
IsGoalConquest: boolean;
/**
* property IsGoalArtifacts
*/
IsGoalArtifacts: boolean;
/**
* property IsGoalTeamMoney
*/
IsGoalTeamMoney: boolean;
/**
* property IsGoalTeamKills
*/
IsGoalTeamKills: boolean;
/**
* property Resources
*/
Resources: boolean;
/**
* property ResourceAmountsVisible
*/
ResourceAmountsVisible: boolean;
/**
* property RandomWormholes
*/
RandomWormholes: boolean;
/**
* property NoTeams
*/
NoTeams: boolean;
/**
* property ShowHomeSector
*/
ShowHomeSector: boolean;
/**
* property CivIDs
*/
CivIDs(element: number, newVal: number): number;
/**
* property GoalTeamMoney
*/
GoalTeamMoney: AGCMoney;
/**
* property TsiPlayerStart
*/
TsiPlayerStart: number;
/**
* property TsiNeutralStart
*/
TsiNeutralStart: number;
/**
* property TsiPlayerRegenerate
*/
TsiPlayerRegenerate: number;
/**
* property TsiNeutralRegenerate
*/
TsiNeutralRegenerate: number;
/**
* property StartingMoney
*/
StartingMoney: number;
/**
* property Lives
*/
Lives: number;
/**
* property GoalTeamKills
*/
GoalTeamKills: number;
/**
* property MapType
*/
MapType: number;
/**
* property MapSize
*/
MapSize: number;
/**
* property RandomEncounters
*/
RandomEncounters: number;
/**
* property NeutralSectors
*/
NeutralSectors: boolean;
/**
* property AlephPositioning
*/
AlephPositioning: number;
/**
* property AlephsPerSector
*/
AlephsPerSector: number;
/**
* property Teams
*/
Teams: number;
/**
* property MinRank
*/
MinRank: number;
/**
* property MaxRank
*/
MaxRank: number;
/**
* property PlayerSectorAsteroids
*/
PlayerSectorAsteroids: number;
/**
* property NeutralSectorAsteroids
*/
NeutralSectorAsteroids: number;
/**
* property PlayerSectorTreasures
*/
PlayerSectorTreasures: number;
/**
* property NeutralSectorTreasures
*/
NeutralSectorTreasures: number;
/**
* property PlayerSectorTreasureRate
*/
PlayerSectorTreasureRate: number;
/**
* property NeutralSectorTreasureRate
*/
NeutralSectorTreasureRate: number;
/**
* property PlayerSectorMineableAsteroids
*/
PlayerSectorMineableAsteroids: number;
/**
* property NeutralSectorMineableAsteroids
*/
NeutralSectorMineableAsteroids: number;
/**
* property PlayerSectorSpecialAsteroids
*/
PlayerSectorSpecialAsteroids: number;
/**
* property NeutralSectorSpecialAsteroids
*/
NeutralSectorSpecialAsteroids: number;
/**
* property IGCStaticFile
*/
IGCStaticFile: string;
/**
* property GamePassword
*/
GamePassword: string;
/**
* property InvulnerableStations
*/
InvulnerableStations: boolean;
/**
* property ShowMap
*/
ShowMap: boolean;
/**
* property AllowDevelopments
*/
AllowDevelopments: boolean;
/**
* property AllowDefections
*/
AllowDefections: boolean;
/**
* property SquadGame
*/
SquadGame: boolean;
/**
* property AllowFriendlyFire
*/
AllowFriendlyFire: boolean;
/**
* READONLY: property IGCcoreVersion
*/
readonly IGCcoreVersion: number;
/**
* property GameLength
*/
GameLength: number;
/**
* property He3Density
*/
He3Density: number;
/**
* property KillPenalty
*/
KillPenalty: AGCMoney;
/**
* property KillReward
*/
KillReward: AGCMoney;
/**
* property EjectPenalty
*/
EjectPenalty: AGCMoney;
/**
* property EjectReward
*/
EjectReward: AGCMoney;
/**
* READONLY: property TimeStart
*/
readonly TimeStart: number;
/**
* READONLY: property TimeStartClock
*/
readonly TimeStartClock: number;
/**
* property GoalArtifactsCount
*/
GoalArtifactsCount: number;
/**
* property AutoRestart
*/
AutoRestart: boolean;
/**
* property DefaultCountdown (in seconds)
*/
DefaultCountdown: number;
/**
* property InitialMinersPerTeam
*/
InitialMinersPerTeam: number;
/**
* property MaxDronesPerTeam
*/
MaxDronesPerTeam: number;
/**
* property CustomMap
*/
CustomMap: string;
/**
* property RestartCountdown (in seconds)
*/
RestartCountdown: number;
/**
* property TotalMaxPlayers (for the entire game)
*/
TotalMaxPlayers: number;
/**
* property LockTeamSettings (locks settings for players not admins)
*/
LockTeamSettings: boolean;
/**
* property InvitationListID
*/
InvitationListID: number;
/**
* property IsSquadGame
*/
IsSquadGame: boolean;
/**
* property LockGameOpen
*/
LockGameOpen: boolean;
/**
* property TeamName
*/
TeamName(iTeam: number, newVal: string): string;
/**
* property IsTechBitOverridden; returns true iff OverriddenTechBit was set for this Team's BitID
*/
IsTechBitOverridden(iTeam: number, iBitID: number): boolean;
/**
* property OverriddenTechBit
*/
OverriddenTechBit(iTeam: number, iBitID: number, newVal: boolean): boolean;
/**
* property SetOverriddenTechBitRange
*/
SetOverriddenTechBitRange(iTeam: number, iBitID_First: number, iBitID_Last: number, newVal: boolean): void;
/**
* property IsGoalFlags
*/
IsGoalFlags: boolean;
/**
* property GoalFlagsCount
*/
GoalFlagsCount: number;
/**
* The text that describes the story of the game.
*/
StoryText: string;
/**
* property AllowEmptyTeams
*/
AllowEmptyTeams: boolean;
/**
* property AutoStart
*/
AutoStart: boolean;
/**
* property AllowRestart
*/
AllowRestart: boolean;
/**
* property Experimental
*/
Experimental: boolean;
/**
* property AllowShipyardPath
*/
AllowShipyardPath: boolean;
/**
* property AllowSupremacyPath
*/
AllowSupremacyPath: boolean;
/**
* property AllowTacticalPath
*/
AllowTacticalPath: boolean;
/**
* property AllowExpansionPath
*/
AllowExpansionPath: boolean;
/**
* property MaxImbalance: Maximum allowed difference between smallest and largest team.
*/
MaxImbalance: number;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCCommand Interface
/**
* Interface to an AGC Command object.
*/
interface IAGCCommand extends IDispatch
{
/**
* READONLY: Gets the command target.
*/
readonly Target: string;
/**
* READONLY: Gets the command verb.
*/
readonly Verb: string;
/**
* READONLY: Gets the textual represenation of the command.
*/
readonly Text: string;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCCommandPrivate Interface
/**
* Private interface to an AGC Command object.
*/
interface IAGCCommandPrivate extends IUnknown
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCVersionInfo Interface
/**
* IAGCVersionInfo Interface
*/
interface IAGCVersionInfo extends IDispatch
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCDBParams Interface
/**
* IAGCDBParams Interface
*/
interface IAGCDBParams extends IDispatch
{
/**
* Gets/sets the database connection string.
*/
ConnectionString(bstr: string): void;
/**
* Gets/sets the table name.
*/
TableName(bstr: string): void;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCEventLogger Interface
/**
* IAGCEventLogger Interface
*/
interface IAGCEventLogger extends IDispatch
{
/**
* READONLY: Gets the entire list of AGC Events as an XML string.
*/
readonly EventList: string;
/**
* Gets/sets the name of the (WinNT or Win2000) computer to which AGC Events will be logged as NT Events.
*/
NTEventLog(bstrComputer: string): void;
/**
* Gets/sets the parameters of the database to which AGC Events will be logged.
*/
DBEventLog(pDBParams: IAGCDBParams): void;
/**
* Gets/sets the range(s) of AGC Events to be logged to the NT Event log.
*/
EnabledNTEvents(pEvents: IAGCEventIDRanges): void;
/**
* Gets/sets the range(s) of AGC Events to be logged to the database event log.
*/
EnabledDBEvents(pEvents: IAGCEventIDRanges): void;
/**
* READONLY: Gets the default range(s) of AGC Events to be logged to the NT Event log.
*/
readonly DefaultEnabledNTEvents: IAGCEventIDRanges;
/**
* READONLY: Gets the default range(s) of AGC Events to be logged to the DB Event log.
*/
readonly DefaultEnabledDBEvents: IAGCEventIDRanges;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCEventLoggerHook Interface
/**
* Implemented by an AGC host to hook event logging.
*/
interface IAGCEventLoggerHook extends IUnknown
{
/**
* Called to allow the host application to log an event in its own way. Host should return S_FALSE to indicate to the event logger that it should perform 'normal' event logging.
*/
LogEvent(pEvent: IAGCEvent, bSynchronous: boolean): void;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCEventLoggerPrivate Interface
/**
* IAGCEventLoggerPrivate Interface
*/
interface IAGCEventLoggerPrivate extends IUnknown
{
/**
* Should be called immediately upon creating the object (and from the same thread or apartment).
*/
Initialize(bstrSourceApp: string, bstrRegKey: string): void;
/**
* Should be called immediately prior to releasing the object.
*/
Terminate(): void;
/**
* Gets/sets whether or not logging to the NT Event log is enabled or not.
*/
LoggingToNTEnabled(bEnabled: boolean): void;
/**
* Gets/sets whether or not logging to the DB Event log is enabled or not.
*/
LoggingToDBEnabled(bEnabled: boolean): void;
/**
* Gets/sets a callback interface to hook events logged to the NT Event log.
*/
HookForNTLogging(pHook: IAGCEventLoggerHook): void;
/**
* Gets/sets a callback interface to hook events logged to the DB Event log.
*/
HookForDBLogging(pHook: IAGCEventLoggerHook): void;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCRangePrivate Interface
/**
* Private interface to an AGC Range object.
*/
interface IAGCRangePrivate extends IUnknown
{
/**
* Initializes the object from a raw (TCLib) range<T> pointer.
*/
InitFromRange(pvRange: object): void;
/**
* Copies the object's raw (TCLib) range to the specified range<T> pointer.
*/
CopyRangeTo(pvRange: object): void;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCRangesPrivate Interface
/**
* Private interface to an AGC Ranges object.
*/
interface IAGCRangesPrivate extends IUnknown
{
/**
* Initializes the object from a raw (TCLib) rangeset< range<T> > pointer.
*/
InitFromRanges(pvRanges: object): void;
/**
* Copies the object's raw (TCLib) range to the specified rangeset< range<T> > pointer.
*/
CopyRangesTo(pvRanges: object): void;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCEventIDRange Interface
/**
* IAGCEventIDRange Interface
*/
interface IAGCEventIDRange extends IDispatch
{
/**
* Gets/sets the range as a string, formatted for display purposes.
*/
DisplayString(bstr: string): void;
/**
* Sets the lower and upper (open) ends of the range.
*/
Init(lower: number, upper: number): void;
/**
* READONLY: Gets the lower end of the range.
*/
readonly Lower: number;
/**
* READONLY: Gets the upper (open) end of the range.
*/
readonly Upper: number;
/**
* READONLY: Determines whether this range is empty (Lower equals Upper).
*/
readonly IsEmpty: boolean;
/**
* Determines whether the specified value intersects with this range.
*/
IntersectsWithValue(value: number): boolean;
/**
* Determines whether the specified range intersects with this range.
*/
IntersectsWithRangeValues(value1: number, value2: number): boolean;
/**
* Determines whether the specified range intersects with this range.
*/
IntersectsWithRange(pRange: IAGCEventIDRange): boolean;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCEventIDRanges Interface
/**
* IAGCEventIDRanges Interface
*/
interface IAGCEventIDRanges extends IDispatch
{
/**
* READONLY: Returns the number of items in the collection.
*/
readonly Count: number;
/**
* READONLY: Returns an enumerator object that implements IEnumVARIANT.
*/
readonly _NewEnum: IUnknown;
/**
* Returns a AGCShip from the collection, or NULL if the item does not exist. Takes an argument, index, which must be the index into the collection.
*/
Item(pvIndex: object): IAGCEventIDRange;
/**
* Gets/sets the range set as a string, formatted for display purposes.
*/
DisplayString(bstr: string): void;
/**
* Adds a range into the set, specified by the range's lower and upper bounds.
*/
AddByValues(value1: number, value2: number): void;
/**
* Adds a range into the set, specified by a range object.
*/
Add(pRange: IAGCEventIDRange): void;
/**
* Removes a range from the set, specified by the range's lower and upper bounds.
*/
RemoveByValues(value1: number, value2: number): void;
/**
* Removes a range from the set, specified by a range object.
*/
Remove(pRange: IAGCEventIDRange): void;
/**
* Removes all ranges from the set, specified by a range object.
*/
RemoveAll(): void;
/**
* Determines whether the specified value intersects with any range in this set.
*/
IntersectsWithValue(value: number): boolean;
/**
* Determines whether the specified range intersects with any range in this set.
*/
IntersectsWithRangeValues(value1: number, value2: number): boolean;
/**
* Determines whether the specified range intersects with any range in this set.
*/
IntersectsWithRange(pRange: IAGCEventIDRange): boolean;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// ITCCollection Interface
/**
* Base interface for most collection interfaces.
*/
interface ITCCollection extends IDispatch
{
/**
* READONLY: Returns the number of items in the collection.
*/
readonly Count: number;
/**
* READONLY: Returns an enumerator object that implements IEnumVARIANT.
*/
readonly _NewEnum: IUnknown;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// ITCStrings Interface
/**
* Interface to a collection of strings.
*/
interface ITCStrings extends ITCCollection
{
/**
* Returns a BSTR from the collection or NULL if the index is out of range. Takes an argument, index, which must be the index into the collection.
*/
Item(pvIndex: object): string;
/**
* Adds the specified string to the collection.
*/
Add(bstr: string): void;
/**
* Removes the specified string from the collection.
*/
Remove(pvIndex: object): void;
/**
* Removes all strings from the collection.
*/
RemoveAll(): void;
/**
* Adds the specified delimited strings to the collection.
*/
AddDelimited(bstrDelimiter: string, bstrStrings: string): void;
/**
* Returns the entire array of strings as a single string, delimited by the specified delimiter string.
*/
DelimitedItems(bstrDelimiter: string): string;
/**
* Adds the strings of the specified collection.
*/
AddStrings(pStrings: ITCStrings): void;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// ITCPropBagOnRegKey Interface
/**
* Interface to create a property bag on a registry key.
*/
interface ITCPropBagOnRegKey extends IDispatch
{
/**
* Creates or opens the specified registry key.
*/
CreateKey(bstrRegKey: string, bReadOnly: boolean): void;
/**
* Opens the specified registry key. Fails if the key does not exist.
*/
OpenKey(bstrRegKey: string, bReadOnly: boolean): void;
/**
* Creates the object that is stored on the current registry key.
*/
CreateObject(): IUnknown;
/**
* Creates the object, always on the local machine, that is stored on the current registry key.
*/
CreateLocalObject(): IUnknown;
/**
* Creates the object, on the specified server, that is stored on the current registry key.
*/
CreateRemoteObject(bstrServer: string): IUnknown;
/**
* Load the specified object from the values stored in the current registry key.
*/
LoadObject(punkObj: IUnknown): void;
/**
* Saves the specified object to the current registry key.
*/
SaveObject(punkObj: IUnknown, bClearDirty: boolean, bSaveAllProperties: boolean, bSaveCreationInfo: boolean): void;
/**
* Gets/sets the server on which the object stored on the current registry key will be created.
*/
Server(bstrServer: string): void;
/**
* READONLY: Gets the string representation of the CLSID of the object stored on the current registry key.
*/
readonly ObjectCLSID: string;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// ITCSessionInfo Interface
/**
* ITCSessionInfo Interface
*/
interface ITCSessionInfo extends IDispatch
{
/**
* READONLY: Gets the user name of this session.
*/
readonly UserName: string;
/**
* READONLY: Gets the computer name of this session.
*/
readonly ComputerName: string;
/**
* Gets/sets the application name of this session.
*/
ApplicationName(bstrAppName: string): void;
/**
* READONLY: Returns the time the session was created.
*/
readonly TimeCreated: Date;
/**
* READONLY: Returns the duration of the session.
*/
readonly Duration: Date;
/**
* READONLY: Uniquely identifies this session within a process.
*/
readonly Cookie: number;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// ITCSessionInfos Interface
/**
* ITCSessionInfos interface
*/
interface ITCSessionInfos extends ITCCollection
{
/**
* Returns a Session from the collection, or NULL if the session does not exist. Takes an argument, index, which must be the index into the collection.
*/
Item(index: object): ITCSessionInfo;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// ITCCollectionPersistHelper Interface
/**
* ITCCollectionPersistHelper interface
*/
interface ITCCollectionPersistHelper extends IDispatch
{
/**
* Gets/sets the current thread priority.
*/
Collection1(pvarSafeArray: object): void;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// ITCUtility Interface
/**
* ITCUtility interface
*/
interface ITCUtility extends IDispatch
{
/**
* Creates the specified object on the specified computer.
*/
CreateObject(bstrProgID: string, bstrComputer: string): IUnknown;
/**
* Create an object reference string.
*/
ObjectReference(pUnk: IUnknown): string;
/**
* Sleeps for the specified number of milliseconds.
*/
Sleep(nDurationMS: number): void;
/**
* Creates an object by binding the specified moniker display name.
*/
GetObject(bstrMoniker: string, bAllowUI: boolean, nTimeoutMS: number): IUnknown;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAdminSessionHelper Interface
/**
* IAdminSessionHelper interface
*/
interface IAdminSessionHelper extends IDispatch
{
/**
* READONLY: Indicates whether or not the Allegiance Game Server is currently running.
*/
readonly IsAllSrvRunning: boolean;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCPrivate Interface
/**
* Internally-used interface on an AGC object.
*/
interface IAGCPrivate extends IUnknown
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCCommon Interface
/**
* IAGCCommon Interface
*/
interface IAGCCommon extends IDispatch
{
/**
* READONLY: Every object in AGC has a unique id number and this is it.
*/
readonly Type: string;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCCollection Interface
/**
* Base interface for AGC collection interfaces.
*/
interface IAGCCollection extends IAGCCommon
{
/**
* READONLY: Returns the number of items in the collection.
*/
readonly Count: number;
/**
* READONLY: Returns an enumerator object that implements IEnumVARIANT.
*/
readonly _NewEnum: IUnknown;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCBase Interface
/**
* IAGCBase Interface
*/
interface IAGCBase extends IAGCCommon
{
/**
* READONLY:
*/
readonly ObjectType: Enums.AGCObjectType;
/**
* READONLY: This returns the id of the object in terms of its type; use UniqueID() for a completely unique id.
*/
readonly ObjectID: AGCObjectID;
/**
* READONLY: Returns the AGC game in which this object lives.
*/
readonly Game: IAGCGame;
/**
* READONLY: Every object in AGC that has a base also has a unique id number and this is it.
*/
readonly UniqueID: AGCUniqueID;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCModel Interface
/**
* IAGCModel Interface
*/
interface IAGCModel extends IAGCBase
{
/**
* READONLY:
*/
readonly IsVisible: boolean;
/**
*
*/
IsSeenBySide(pTeam: IAGCTeam): boolean;
/**
* READONLY:
*/
readonly Position: IAGCVector;
/**
* READONLY:
*/
readonly Velocity: IAGCVector;
/**
* READONLY:
*/
readonly Orientation: IAGCOrientation;
/**
* READONLY:
*/
readonly Radius: number;
/**
* READONLY:
*/
readonly Team: IAGCTeam;
/**
* READONLY:
*/
readonly Mass: number;
/**
* READONLY:
*/
readonly Sector: IAGCSector;
/**
* READONLY:
*/
readonly Signature: number;
/**
* READONLY: Gets the model's name
*/
readonly Name: string;
/**
* READONLY: User can never pick the object
*/
readonly IsSelectable: boolean;
/**
* READONLY: Can see other objects
*/
readonly IsScanner: boolean;
/**
* READONLY: Send this object to a team when it is seen for the 1st time
*/
readonly IsPredictable: boolean;
/**
* READONLY: Need to track its visibility with regard to side
*/
readonly IsScanRequired: boolean;
/**
* READONLY: Can not move
*/
readonly IsStatic: boolean;
/**
* READONLY: Can take damage
*/
readonly IsDamagable: boolean;
/**
* READONLY: Goes into the collision KD tree
*/
readonly IsHitable: boolean;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCModels Interface
/**
* IAGCModels Interface
*/
interface IAGCModels extends IAGCCollection
{
/**
* Returns an AGCModel from the collection, or NULL if the item does not exist. Takes an argument, index, which must be the index into the collection.
*/
Item(pvIndex: object): IAGCModel;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCBuyable Interface
/**
* Properties of an object that is buyable.
*/
interface IAGCBuyable extends IAGCBase
{
/**
* READONLY: Gets the name of the object.
*/
readonly Name: string;
/**
* READONLY: Gets the description of the object.
*/
readonly Description: string;
/**
* READONLY: Gets the name of the model that buying this creates.
*/
readonly ModelName: string;
/**
* READONLY: Gets price of the object.
*/
readonly Price: AGCMoney;
/**
* READONLY: Gets time to build the object.
*/
readonly TimeToBuild: number;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCHullType Interface
/**
* Interface to an AGC Hull Type object.
*/
interface IAGCHullType extends IAGCBuyable
{
/**
* READONLY: Gets the Length.
*/
readonly Length: number;
/**
* READONLY: Gets the MaxSpeed.
*/
readonly MaxSpeed: number;
/**
* Gets the MaxTurnRate.
*/
MaxTurnRate(eAxis: Enums.AGCAxis): number;
/**
* Gets the TurnTorque.
*/
TurnTorque(eAxis: Enums.AGCAxis): number;
/**
* READONLY: Gets the Thrust.
*/
readonly Thrust: number;
/**
* READONLY: Gets the SideMultiplier.
*/
readonly SideMultiplier: number;
/**
* READONLY: Gets the BackMultiplier.
*/
readonly BackMultiplier: number;
/**
* READONLY: Gets the ScannerRange.
*/
readonly ScannerRange: number;
/**
* READONLY: Gets the MaxEnergy.
*/
readonly MaxEnergy: number;
/**
* READONLY: Gets the RechargeRate.
*/
readonly RechargeRate: number;
/**
* READONLY: Gets the HitPoints.
*/
readonly HitPoints: AGCHitPoints;
/**
* Gets the PartMask.
*/
PartMask(et: Enums.AGCEquipmentType, mountID: AGCMount): AGCPartMask;
/**
* READONLY: Gets the MaxWeapons.
*/
readonly MaxWeapons: AGCMount;
/**
* READONLY: Gets the MaxFixedWeapons.
*/
readonly MaxFixedWeapons: AGCMount;
/**
* READONLY: Gets the CanMount.
*/
readonly Mass: number;
/**
* READONLY: Gets the Signature.
*/
readonly Signature: number;
/**
* READONLY: Gets the Capabilities.
*/
readonly Capabilities: AGCHullAbilityBitMask;
/**
* Determines if the object has the specified capabilities..
*/
HasCapability(habm: AGCHullAbilityBitMask): boolean;
/**
* READONLY: Gets the MaxAmmo.
*/
readonly MaxAmmo: number;
/**
* READONLY: Gets the MaxFuel.
*/
readonly MaxFuel: number;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCTreasure Interface
/**
*
*/
interface IAGCTreasure extends IAGCModel
{
/**
* READONLY:
*/
readonly Type: Enums.AGCTreasureType;
/**
* READONLY:
*/
readonly Amount: number;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCTreasures Interface
/**
* IAGCTreasures Interface
*/
interface IAGCTreasures extends IAGCCollection
{
/**
* Returns an AGCTreasure from the collection, or NULL if the game does not exist. Takes an argument, index, which must be the index into the collection.
*/
Item(pvIndex: object): IAGCTreasure;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCDamage Interface
/**
* IAGCDamage Interface
*/
interface IAGCDamage extends IAGCModel
{
/**
* READONLY:
*/
readonly Fraction: number;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCScanner Interface
/**
* IAGCScanner Interface
*/
interface IAGCScanner extends IAGCDamage
{
/**
*
*/
InScannerRange(pModel: IAGCModel): boolean;
/**
*
*/
CanSee(pModel: IAGCModel): boolean;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCProbe Interface
/**
* IAGCProbe Interface
*/
interface IAGCProbe extends IAGCScanner
{
/**
* READONLY: Gets the type of projectiles fired, if any.
*/
readonly EmissionPoint: IAGCVector;
/**
* READONLY: Gets the lifespan.
*/
readonly Lifespan: number;
/**
* READONLY: Gets the weapon burst rate(?).
*/
readonly DtBurst: number;
/**
* READONLY: Gets the weapon firing accuracy.
*/
readonly Accuracy: number;
/**
* READONLY: Gets the indicator of the probe being a ripcord destination.
*/
readonly IsRipcord: boolean;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCProbes Interface
/**
* IAGCProbes Interface
*/
interface IAGCProbes extends IAGCCollection
{
/**
* Returns an AGCProbe from the collection, or NULL if the item does not exist. Takes an argument, index, which must be the index into the collection.
*/
Item(pvIndex: object): IAGCProbe;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCGame Interface
/**
* IAGCGame Interface
*/
interface IAGCGame extends IAGCCommon
{
/**
* READONLY: Gets the game's name
*/
readonly Name: string;
/**
* READONLY: Gets the collection of sectors in the game.
*/
readonly Sectors: IAGCSectors;
/**
* READONLY: Gets the collection of teams in the game.
*/
readonly Teams: IAGCTeams;
/**
* Gets the Ship associated with specified AGC ID.
*/
LookupShip(idAGC: AGCUniqueID): IAGCShip;
/**
* READONLY: Gets the collection of the ships in the game.
*/
readonly Ships: IAGCShips;
/**
* READONLY: Gets the collection of alephs in the game.
*/
readonly Alephs: IAGCAlephs;
/**
* READONLY: Gets the collection of asteroids in the game.
*/
readonly Asteroids: IAGCAsteroids;
/**
* READONLY: Gets the parameters used to create the game.
*/
readonly GameParameters: IAGCGameParameters;
/**
* READONLY: Gets unique mission id.
*/
readonly GameID: AGCGameID;
/**
* Gets the team associated with specified AGC ID.
*/
LookupTeam(idAGC: AGCObjectID): IAGCTeam;
/**
* Sends the specified chat text to everyone in the Game.
*/
SendChat(bstrText: string, idSound: AGCSoundID): void;
/**
* Sends the specified command to everyone in the Game.
*/
SendCommand(bstrCommand: string, pModelTarget: IAGCModel, idSound: AGCSoundID): void;
/**
* READONLY: Gets the stage of the game.
*/
readonly GameStage: Enums.AGCGameStage;
/**
* READONLY: Gets the collection of probes in the game.
*/
readonly Probes: IAGCProbes;
/**
* READONLY: Gets the collection of buoys in the game.
*/
readonly Buoys: IAGCModels;
/**
* READONLY: Gets the collection of treasures in the game.
*/
readonly Treasures: IAGCModels;
/**
* READONLY: Gets the collection of mines in the game.
*/
readonly Mines: IAGCModels;
/**
* READONLY: Gets the number of times this game has been 'reused'.
*/
readonly ReplayCount: number;
/**
* READONLY: Gets a string that uniquely identifies the game context, within the game server.
*/
readonly ContextName: string;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCShip Interface
/**
* IAGCShip Interface
*/
interface IAGCShip extends IAGCScanner
{
/**
* Amount of ammo the ship has.
*/
Ammo(Val: number): void;
/**
* Amount of fuel the ship has.
*/
Fuel(Val: number): void;
/**
* Amount of energy the ship has.
*/
Energy(Val: number): void;
/**
* Ship's Wing ID.
*/
WingID(Val: number): void;
/**
* Sends the specified chat text to the ship.
*/
SendChat(bstrText: string, idSound: AGCSoundID): void;
/**
* Sends the specified command to the ship.
*/
SendCommand(bstrCommand: string, pModelTarget: IAGCModel, idSound: AGCSoundID): void;
/**
* Gets/sets the AutoDonate ship.
*/
AutoDonate(pShip: IAGCShip): void;
/**
* Gets/sets the ship's ShieldFraction
*/
ShieldFraction(pVal: number): void;
/**
* READONLY: Gets the ship's Hull type.
*/
readonly HullType: IAGCHullType;
/**
* READONLY: Gets the ship's base hull type.
*/
readonly BaseHullType: IAGCHullType;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCShips Interface
/**
* IAGCShips Interface
*/
interface IAGCShips extends IAGCCollection
{
/**
* Returns a AGCShip from the collection, or NULL if the item does not exist. Takes an argument, index, which must be the index into the collection.
*/
Item(pvIndex: object): IAGCShip;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCStation Interface
/**
* IAGCStation Interface
*/
interface IAGCStation extends IAGCScanner
{
/**
* Gets/sets the station's ShieldFraction
*/
ShieldFraction(pVal: number): void;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCStations Interface
/**
* IAGCStations Interface
*/
interface IAGCStations extends IAGCCollection
{
/**
* Returns a AGCStation from the collection, or NULL if the item does not exist. Takes an argument, index, which must be the index into the collection.
*/
Item(pvIndex: object): IAGCStation;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCAleph Interface
/**
* IAGCAleph Interface
*/
interface IAGCAleph extends IAGCModel
{
/**
* READONLY: Gets the destination aleph.
*/
readonly Destination: IAGCAleph;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCAlephs Interface
/**
* IAGCAlephs Interface
*/
interface IAGCAlephs extends IAGCCollection
{
/**
* Returns a AGCAleph from the collection, or NULL if the AGCAleph does not exist. Takes an argument, index, which must be the index into the collection.
*/
Item(pvIndex: object): IAGCAleph;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCSector Interface
/**
* IAGCSector Interface
*/
interface IAGCSector extends IAGCBase
{
/**
* READONLY: Gets the AGCSector's name
*/
readonly Name: string;
/**
* Gets the collection of stations in the sector.
*/
Stations: IAGCStations;
/**
* READONLY: Gets the collection of ships in the sector.
*/
readonly Ships: IAGCShips;
/**
* READONLY: Gets the collection of alephs in the sector.
*/
readonly Alephs: IAGCAlephs;
/**
* READONLY: Gets the collection of asteroids in the sector.
*/
readonly Asteroids: IAGCAsteroids;
/**
* Sends the specified chat text to everyone in the Sector.
*/
SendChat(bstrText: string, bIncludeEnemies: boolean, idSound: AGCSoundID): void;
/**
* Sends the specified command to everyone in the Sector.
*/
SendCommand(bstrCommand: string, pModelTarget: IAGCModel, bIncludeEnemies: boolean, idSound: AGCSoundID): void;
/**
* READONLY: Gets sector's X position relative to other sectors. This is used in the sector overview display. This value never changes.
*/
readonly ScreenX: number;
/**
* READONLY: Gets sector's Y position relative to other sectors. This is used in the sector overview display. This value never changes.
*/
readonly ScreenY: number;
/**
* READONLY: Gets the collection of mines in the sector.
*/
readonly Mines: IAGCModels;
/**
* READONLY: Gets the collection of missiles in the sector.
*/
readonly Missiles: IAGCModels;
/**
* READONLY: Gets the collection of probes in the sector.
*/
readonly Probes: IAGCProbes;
/**
* READONLY: Gets the collection of models in the sector.
*/
readonly Models: IAGCModels;
/**
* READONLY: Gets the collection of selectable models in the sector.
*/
readonly SelectableModels: IAGCModels;
/**
* READONLY: Gets the collection of treasures in the sector.
*/
readonly Treasures: IAGCModels;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCSectors Interface
/**
* IAGCSectors Interface
*/
interface IAGCSectors extends IAGCCollection
{
/**
* Returns a AGCSector from the collection, or NULL if the sector does not exist. Takes an argument, index, which must be the index into the collection.
*/
Item(pvIndex: object): IAGCSector;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCTeam Interface
/**
* IAGCTeam Interface
*/
interface IAGCTeam extends IAGCBase
{
/**
* READONLY: Gets the team's name
*/
readonly Name: string;
/**
* Returns a collection of stations that belong to the team.
*/
Stations: IAGCStations;
/**
* READONLY: Returns a Ships collection of the ships in the team.
*/
readonly Ships: IAGCShips;
/**
* READONLY: Returns name of civ for team.
*/
readonly Civ: string;
/**
* Sends the specified chat text to everyone on the Team.
*/
SendChat(bstrText: string, idWing: number, idSound: AGCSoundID): void;
/**
* Sends the specified command to everyone on the Team.
*/
SendCommand(bstrCommand: string, pModelTarget: IAGCModel, idWing: number, idSound: AGCSoundID): void;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCTeams Interface
/**
* IAGCTeams Interface
*/
interface IAGCTeams extends IAGCCollection
{
/**
* Returns a AGCTeam from the collection, or NULL if the game does not exist. Takes an argument, index, which must be the index into the collection.
*/
Item(pvIndex: object): IAGCTeam;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCAsteroid Interface
/**
* IAGCAsteroid Interface
*/
interface IAGCAsteroid extends IAGCDamage
{
/**
* READONLY: Gets the amount of ore remaining on the asteroid.
*/
readonly Ore: number;
/**
* READONLY: Gets the Capabilities bit mask of the object.
*/
readonly Capabilities: AGCAsteroidAbilityBitMask;
/**
* Determines if the object has the specified capabilities.
*/
HasCapability(aabm: AGCAsteroidAbilityBitMask): boolean;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IAGCAsteroids Interface
/**
* IAGCAsteroids Interface
*/
interface IAGCAsteroids extends IAGCCollection
{
/**
* Returns an AGCAsteroid from the collection, or NULL if the game does not exist. Takes an argument, index, which must be the index into the collection.
*/
Item(pvIndex: object): IAGCAsteroid;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IPigBehaviorType Interface
/**
* Interface to a pig behavior type object.
*/
interface IPigBehaviorType extends IDispatch
{
/**
* READONLY: Gets the collection of command strings that will invoke this behavior.
*/
readonly InvokeCommands: ITCStrings;
/**
* READONLY: Gets the name of this behavior type.
*/
readonly Name: string;
/**
* READONLY: Gets the description of this behavior type.
*/
readonly Description: string;
/**
* READONLY: Gets the collection of pig behavior objects currently referencing this behavior type.
*/
readonly Behaviors: IPigBehaviors;
/**
* READONLY: Gets the indicator of whether or not this object is based on a script or not.
*/
readonly IsScript: boolean;
/**
* READONLY: Gets the behavior type that serves as this one's base class.
*/
readonly BaseBehaviorType: IPigBehaviorType;
/**
* Gets/sets the flag indicating whether or not the script has encountered an error yet.
*/
AppearsValid(bAppearsValid: boolean): void;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IPigBehaviorTypes Interface
/**
* Interface to a collection of pig behavior script objects.
*/
interface IPigBehaviorTypes extends ITCCollection
{
/**
* Gets an item from the collection. Takes an argument, index, that is either the 0-relative index into the collection, the name of the behavior, or one of the invoke commands of the behavior.
*/
Item(pvIndex: object): IPigBehaviorType;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IPigBehaviorScriptType Interface
/**
* Interface to a pig behavior script object.
*/
interface IPigBehaviorScriptType extends IPigBehaviorType
{
/**
* READONLY: Gets the path and name of the script file that defines this behavior.
*/
readonly FilePathName: string;
/**
* READONLY: Gets the name of the script file that defines this behavior.
*/
readonly FileName: string;
/**
* READONLY: Gets the time (UTC) that the script file was last modified.
*/
readonly FileModifiedTime: Date;
/**
* READONLY: Gets the attributes of the script file.
*/
readonly FileAttributes: Enums.FileAttributes;
/**
* READONLY: Gets the text of the entire script file.
*/
readonly FileText: string;
/**
* READONLY: Gets the text of the script sections within the file.
*/
readonly ScriptText: ITCStrings;
/**
* READONLY: Gets the Prog ID of the Active Scripting engine used to parse/execute this script.
*/
readonly ScriptEngineProgID: string;
/**
* READONLY: Gets the CLSID of the Active Scripting engine used to parse/execute this script.
*/
readonly ScriptEngineCLSID: string;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IPigBehaviorHost Interface
/**
* Interface to a pig behavior host object.
*/
interface IPigBehaviorHost extends IDispatch
{
/**
* Useful test method that beeps as specified.
*/
Beep(nFrequency: number, nDuration: number): void;
/**
* Creates a new pig object with the specified behavior type.
*/
CreatePig(bstrType: string, bstrCommandLine: string): IPig;
/**
* Useful test method that echoes the specified text to the debugger output.
*/
Trace(bstrText: string): void;
/**
* Gets the textual name of the specified pig state.
*/
StateName(ePigState: Enums.PigState): string;
/**
* Generates a random integer between 0 and 32,767.
*/
Random(): number;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IPigBehavior Interface
/**
* Interface to a pig behavior object.
*/
interface IPigBehavior extends IDispatch
{
/**
* READONLY: Gets the object that describes this class of behavior.
*/
readonly BehaviorType: IPigBehaviorType;
/**
* READONLY: Get the behavior, if any, that serve's as the this one's base class.
*/
readonly BaseBehavior: IDispatch;
/**
* READONLY: Gets the pig player object using this behavior instance.
*/
readonly Pig: IPig;
/**
* READONLY: Gets the object used to access the rest of the Pigs object model.
*/
readonly Host: IPigBehaviorHost;
/**
* READONLY: Gets the indicator of whether or not this behaior is the one currently active for the pig player object.
*/
readonly IsActive: boolean;
/**
* READONLY: Gets the dictionary containing the behavior-defined properties.
*/
readonly Properties: IDictionary;
/**
* READONLY: Gets the timer for which the event expression is currently executing, if any
*/
readonly Timer: IPigTimer;
/**
* READONLY: Gets the command line text used to activate the behvaior, if any.
*/
readonly CommandLine: string;
/**
* Creates a new timer object.
*/
CreateTimer(fInterval: number, bstrEventExpression: string, nRepetitions: number, bstrName: string): IPigTimer;
/**
* Called when this behavior becomes a pig's active behavior.
*/
OnActivate(pPigDeactived: IPigBehavior): void;
/**
* Called when this behavior is deactivated as a pig's active behavior.
*/
OnDeactivate(pPigActivated: IPigBehavior): void;
/**
* Called when the state of the pig has changed to PigState_NonExistant.
*/
OnStateNonExistant(eStatePrevious: Enums.PigState): void;
/**
* Called when the state of the pig has changed to PigState_LoggingOn.
*/
OnStateLoggingOn(eStatePrevious: Enums.PigState): void;
/**
* Called when the state of the pig has changed to PigState_LoggingOff.
*/
OnStateLoggingOff(eStatePrevious: Enums.PigState): void;
/**
* Called when the state of the pig has changed to PigState_MissionList.
*/
OnStateMissionList(eStatePrevious: Enums.PigState): void;
/**
* Called when the state of the pig has changed to PigState_CreatingMission.
*/
OnStateCreatingMission(eStatePrevious: Enums.PigState): void;
/**
* Called when the state of the pig has changed to PigState_JoiningMission.
*/
OnStateJoiningMission(eStatePrevious: Enums.PigState): void;
/**
* Called when the state of the pig has changed to PigState_QuittingMission.
*/
OnStateQuittingMission(eStatePrevious: Enums.PigState): void;
/**
* Called when the state of the pig has changed to PigState_TeamList.
*/
OnStateTeamList(eStatePrevious: Enums.PigState): void;
/**
* Called when the state of the pig has changed to PigState_JoiningTeam.
*/
OnStateJoiningTeam(eStatePrevious: Enums.PigState): void;
/**
* Called when the state of the pig has changed to PigState_WaitingForMission.
*/
OnStateWaitingForMission(eStatePrevious: Enums.PigState): void;
/**
* Called when the state of the pig has changed to PigState_Docked.
*/
OnStateDocked(eStatePrevious: Enums.PigState): void;
/**
* Called when the state of the pig has changed to PigState_Launching.
*/
OnStateLaunching(eStatePrevious: Enums.PigState): void;
/**
* Called when the state of the pig has changed to PigState_Flying.
*/
OnStateFlying(eStatePrevious: Enums.PigState): void;
/**
* Called when the state of the pig has changed to PigState_Terminated.
*/
OnStateTerminated(eStatePrevious: Enums.PigState): void;
/**
* Called when the Pig's current mission begins.
*/
OnMissionStarted(): void;
/**
* Called when the Pig receives chat text.
*/
OnReceiveChat(bstrText: string, pShipSender: IAGCShip): boolean;
/**
* Called when any ship takes damage.
*/
OnShipDamaged(pShip: IAGCShip, pModelLauncher: IAGCModel, fAmount: number, fLeakage: number, pVector1: IAGCVector, pVector2: IAGCVector): void;
/**
* Called when any ship is killed.
*/
OnShipKilled(pShip: IAGCShip, pModelLauncher: IAGCModel, fAmount: number, pVector1: IAGCVector, pVector2: IAGCVector): void;
/**
* Called when the Pig ship is transported to a new Sector.
*/
OnSectorChange(pSectorOld: IAGCSector, pSectorNew: IAGCSector): void;
/**
* Called when the Pig ship hits an Aleph.
*/
OnAlephHit(pAleph: IAGCAleph): void;
}
/**
* These are global objects that are injected by COM into the javascript space. Both IPig and IPigBehavior are available,
* but because you can get a Pig object from IPigBehavior, I am not going to make constants for those here.
*/
/**
* READONLY: Gets the object that describes this class of behavior.
*/
declare const BehaviorType: IPigBehaviorType;
/**
* READONLY: Get the behavior, if any, that serve's as the this one's base class.
*/
declare const BaseBehavior: IDispatch;
/**
* READONLY: Gets the pig player object using this behavior instance.
*/
declare const Pig: IPig;
/**
* READONLY: Gets the object used to access the rest of the Pigs object model.
*/
declare const Host: IPigBehaviorHost;
/**
* READONLY: Gets the indicator of whether or not this behaior is the one currently active for the pig player object.
*/
declare const IsActive: boolean;
/**
* READONLY: Gets the dictionary containing the behavior-defined properties.
*/
declare const Properties: IDictionary;
/**
* READONLY: Gets the timer for which the event expression is currently executing, if any
*/
declare const Timer: IPigTimer;
/**
* READONLY: Gets the command line text used to activate the behvaior, if any.
*/
declare const CommandLine: string;
/**
* Creates a new timer object.
*/
declare function CreateTimer(fInterval: number, bstrEventExpression: string, nRepetitions: number, bstrName: string): IPigTimer;
/**
* Called when this behavior becomes a pig's active behavior.
*/
declare function OnActivate(pPigDeactived: IPigBehavior): void;
/**
* Called when this behavior is deactivated as a pig's active behavior.
*/
declare function OnDeactivate(pPigActivated: IPigBehavior): void;
/**
* Called when the state of the pig has changed to PigState_NonExistant.
*/
declare function OnStateNonExistant(eStatePrevious: Enums.PigState): void;
/**
* Called when the state of the pig has changed to PigState_LoggingOn.
*/
declare function OnStateLoggingOn(eStatePrevious: Enums.PigState): void;
/**
* Called when the state of the pig has changed to PigState_LoggingOff.
*/
declare function OnStateLoggingOff(eStatePrevious: Enums.PigState): void;
/**
* Called when the state of the pig has changed to PigState_MissionList.
*/
declare function OnStateMissionList(eStatePrevious: Enums.PigState): void;
/**
* Called when the state of the pig has changed to PigState_CreatingMission.
*/
declare function OnStateCreatingMission(eStatePrevious: Enums.PigState): void;
/**
* Called when the state of the pig has changed to PigState_JoiningMission.
*/
declare function OnStateJoiningMission(eStatePrevious: Enums.PigState): void;
/**
* Called when the state of the pig has changed to PigState_QuittingMission.
*/
declare function OnStateQuittingMission(eStatePrevious: Enums.PigState): void;
/**
* Called when the state of the pig has changed to PigState_TeamList.
*/
declare function OnStateTeamList(eStatePrevious: Enums.PigState): void;
/**
* Called when the state of the pig has changed to PigState_JoiningTeam.
*/
declare function OnStateJoiningTeam(eStatePrevious: Enums.PigState): void;
/**
* Called when the state of the pig has changed to PigState_WaitingForMission.
*/
declare function OnStateWaitingForMission(eStatePrevious: Enums.PigState): void;
/**
* Called when the state of the pig has changed to PigState_Docked.
*/
declare function OnStateDocked(eStatePrevious: Enums.PigState): void;
/**
* Called when the state of the pig has changed to PigState_Launching.
*/
declare function OnStateLaunching(eStatePrevious: Enums.PigState): void;
/**
* Called when the state of the pig has changed to PigState_Flying.
*/
declare function OnStateFlying(eStatePrevious: Enums.PigState): void;
/**
* Called when the state of the pig has changed to PigState_Terminated.
*/
declare function OnStateTerminated(eStatePrevious: Enums.PigState): void;
/**
* Called when the Pig's current mission begins.
*/
declare function OnMissionStarted(): void;
/**
* Called when the Pig receives chat text.
*/
declare function OnReceiveChat(bstrText: string, pShipSender: IAGCShip): boolean;
/**
* Called when any ship takes damage.
*/
declare function OnShipDamaged(pShip: IAGCShip, pModelLauncher: IAGCModel, fAmount: number, fLeakage: number, pVector1: IAGCVector, pVector2: IAGCVector): void;
/**
* Called when any ship is killed.
*/
declare function OnShipKilled(pShip: IAGCShip, pModelLauncher: IAGCModel, fAmount: number, pVector1: IAGCVector, pVector2: IAGCVector): void;
/**
* Called when the Pig ship is transported to a new Sector.
*/
declare function OnSectorChange(pSectorOld: IAGCSector, pSectorNew: IAGCSector): void;
/**
* Called when the Pig ship hits an Aleph.
*/
declare function OnAlephHit(pAleph: IAGCAleph): void;
////////////////////////////////////////////////////////////////////////////////////////////////////
// IPigBehaviors Interface
/**
* Interface to a collection of pig behavior objects.
*/
interface IPigBehaviors extends ITCCollection
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IPigBehaviorStack Interface
/**
* Interface to a stack of pig behavior objects.
*/
interface IPigBehaviorStack extends ITCCollection
{
/**
* Creates a new behavior of the specified type and pushes it onto the top of the behavior stack.
*/
Push(bstrType: string, bstrCommandLine: string): IPigBehavior;
/**
* Pops the top-most behavior off the stack, unless there is only one behavior remaining on the stack.
*/
Pop(): void;
/**
* Gets a reference to a behavior on the stack without removing it from the stack.
*/
Top(nFromTop: number): IPigBehavior;
/**
* READONLY: Gets the pig object which owns this behavior stack.
*/
readonly Pig: IPig;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IPig Interface
/**
* Interface to a pig player object.
*/
interface IPig extends IDispatch
{
/**
* READONLY: Gets the current state of the pig.
*/
readonly PigState: Enums.PigState;
/**
* READONLY: Gets the textual name of the state of the pig.
*/
readonly PigStateName: string;
/**
* READONLY: Gets the stack of behaviors associated with this pig.
*/
readonly Stack: IPigBehaviorStack;
/**
* READONLY: Gets the character name of the pig.
*/
readonly Name: string;
/**
* READONLY: Gets the ship object of the pig.
*/
readonly Ship: IPigShip;
/**
* Gets/sets the number of times per second that the IGC layer is updated.
*/
UpdatesPerSecond(nPerSecond: number): void;
/**
* READONLY: Gets the collection of hull types available to this pig.
*/
readonly HullTypes: IPigHullTypes;
/**
* READONLY: Gets this pig's liquid worth.
*/
readonly Money: AGCMoney;
/**
* Logs on to the mission server.
*/
Logon(): void;
/**
* Logs off from the lobby server.
*/
Logoff(): void;
/**
* Creates (and joins) a new mission with the specified parameters.
*/
CreateMission(bstrServerName: string, bstrServerAddr: string, pMissionParams: IPigMissionParams): void;
/**
* Joins a mission, which may be specified by name, by a buddy player, or not at all.
*/
JoinMission(bstrMissionOrPlayer: string): void;
/**
* Requests a position on a team, which may be specified by name, by a buddy player, or not at all.
*/
JoinTeam(bstrCivName: string, bstrTeamOrPlayer: string): void;
/**
* Quits the current game.
*/
QuitGame(): void;
/**
* Undocks from the station and enters space.
*/
Launch(): void;
/**
* Forces the pig to exit the game.
*/
Shutdown(): void;
/**
* Returns true if player has game control
*/
IsMissionOwner(): boolean;
/**
* Returns true if player is the team leader
*/
IsTeamLeader(): boolean;
/**
* Sets the shoot, turn and goto skills
*/
SetSkills(fShoot: number, fTurn: number, fGoto: number): void;
/**
* READONLY: Gets the AGCGame object that the Pig is a member of, if any.
*/
readonly Game: IAGCGame;
/**
* READONLY: Gets the AGCShip object that sent the current chat. NULL if chat was from HQ or Pig is not currently processing chat text.
*/
readonly Me: IAGCShip;
/**
* READONLY: Gets the target of the current chat. AGCChat_NoSelection if Pig is not currently processing chat text.
*/
readonly ChatTarget: Enums.AGCChatTarget;
/**
* READONLY: Gets the object used to access the rest of the Pigs object model.
*/
readonly Host: IPigBehaviorHost;
/**
* Sets mission params then starts the game.
*/
StartCustomGame(pMissionParams: IPigMissionParams): void;
/**
* Starts the game.
*/
StartGame(): void;
/**
* Contains a threshold value, representing an angle in radians, to which each ship's movement is compared.
*/
ShipAngleThreshold1(rRadians: number): void;
/**
* Contains a threshold value, representing an angle in radians, to which each ship's movement is compared.
*/
ShipAngleThreshold2(rRadians: number): void;
/**
* Contains a threshold value, representing an angle in radians, to which each ship's movement is compared.
*/
ShipAngleThreshold3(rRadians: number): void;
/**
* Contains a threshold value, representing a distance, to which each ship's movement is compared.
*/
ShipDistanceThreshold1(rDistance: number): void;
/**
* Contains a threshold value, representing a distance, to which each ship's movement is compared.
*/
ShipDistanceThreshold2(rDistance: number): void;
/**
* Contains a threshold value, representing a distance, to which each ship's movement is compared.
*/
ShipDistanceThreshold3(rDistance: number): void;
/**
* Contains a threshold value, representing ZTime, to which the (heavy_update_time - client_time) is compared.
*/
ShipsUpdateLatencyThreshold1(nMilliseconds: number): void;
/**
* Contains a threshold value, representing ZTime, to which the (heavy_update_time - client_time) is compared.
*/
ShipsUpdateLatencyThreshold2(nMilliseconds: number): void;
/**
* Contains a threshold value, representing ZTime, to which the (heavy_update_time - client_time) is compared.
*/
ShipsUpdateLatencyThreshold3(nMilliseconds: number): void;
/**
* Sends the bytes specified to the connected lobby server, if any. pvBytes is either the name of a file, or a SAFEARRAY of bytes.
*/
SendBytesToLobby(pvBytes: object, bGuaranteed: boolean): void;
/**
* Sends the bytes specified to the connected game server, if any. pvBytes is either the name of a file, or a SAFEARRAY of bytes.
*/
SendBytesToGame(pvBytes: object, bGuaranteed: boolean): void;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IPigs Interface
/**
* Interface to a collection of pig player objects.
*/
interface IPigs extends ITCCollection
{
/**
* Returns an IPig* from the collection or NULL if the specified named pig does not exist in the collection. Takes an argument, index, which must be the name of a pig in the collection.
*/
Item(pvIndex: object): IPig;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IPigTeam Interface
/**
* Interface to a Team object.
*/
interface IPigTeam extends IDispatch
{
/**
* READONLY: Gets the name of the team.
*/
readonly Name: string;
/**
* READONLY: Gets/sets the civilization of the team.
*/
readonly PlayersMaximum: number;
/**
* READONLY: Gets the current number of players on this team.
*/
readonly PlayerCount: number;
/**
* Gets the collection of players on this team.
*/
IsAutoAccept(bAutoAccept: boolean): void;
/**
* Gets/sets the 'ready' flag of this team.
*/
IsReady(bReady: boolean): void;
/**
* Gets/sets the 'force-ready' flag of this team.
*/
IsForceReady(bForceReady: boolean): void;
/**
* Gets/sets the 'active' flag of this team.
*/
IsActive(bActive: boolean): void;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IPigTeams Interface
/**
* Interface to a collection of Team objects.
*/
interface IPigTeams extends ITCCollection
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IPigMissionParams Interface
/**
* Interface to a MissionParams object.
*/
interface IPigMissionParams extends IDispatch
{
/**
* Validates the properties of the object.
*/
Validate(): void;
/**
* Gets/sets the number of teams for the mission.
*/
TeamCount(nTeamCount: number): void;
/**
* Gets/sets the maximum number of players allowed on a team.
*/
MaxTeamPlayers(nMaxTeamPlayers: number): void;
/**
* Gets/sets the minimum number of players allowed on a team.
*/
MinTeamPlayers(nMinTeamPlayers: number): void;
/**
* Gets/sets the map type for the mission.
*/
MapType(eMapType: Enums.PigMapType): void;
/**
* Gets/sets the death match goal.
*/
TeamKills(nGoalTeamKills: number): void;
/**
* Gets/sets the game name for the mission.
*/
GameName(bstrGameName: string): void;
/**
* Gets/sets the core for the mission.
*/
CoreName(bstrCoreName: string): void;
/**
* Gets/sets the KB Level.
*/
KillBonus(KBLevel: number): void;
/**
* Gets/sets Defections allowed.
*/
Defections(Defections: boolean): void;
/**
* Gets/sets the number of starting miners.
*/
Miners(Miners: number): void;
/**
* Gets/sets Developments allowed.
*/
Developments(Developments: boolean): void;
/**
* Gets/sets the Conquest goal.
*/
Conquest(Conquest: number): void;
/**
* Gets/sets the Flags goal.
*/
Flags(Flags: number): void;
/**
* Gets/sets the Artifacts goal.
*/
Artifacts(Artifacts: number): void;
/**
* Gets/sets Pods allowed.
*/
Pods(Pods: boolean): void;
/**
* Gets/sets Experimental allowed.
*/
Experimental(Experimental: boolean): void;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IPigMissionParamsPrivate Interface
/**
* Private interface to a MissionParams object.
*/
interface IPigMissionParamsPrivate extends IUnknown
{
/**
* Gets a stream containing the length-prefixed data structure.
*/
GetData(): IStream;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IPigMission Interface
/**
* Interface to a Mission object.
*/
interface IPigMission extends IDispatch
{
/**
* READONLY: Gets the collection of (pig) players.
*/
readonly Pigs: IPigs;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IPigMissions Interface
/**
* Interface to a collection of Mission objects.
*/
interface IPigMissions extends ITCCollection
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IPigLobby Interface
/**
* Interface to a Lobby object.
*/
interface IPigLobby extends IDispatch
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IPigLobbies Interface
/**
* Interface to a collection of Lobby objects.
*/
interface IPigLobbies extends ITCCollection
{
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IPigSession Interface
/**
* IPigSession Interface
*/
interface IPigSession extends IDispatch
{
/**
* Gets/sets the session information object.
*/
SessionInfo(pSessionInfo: ITCSessionInfo): void;
/**
* READONLY: Gets the collection of connected sessions.
*/
readonly SessionInfos: ITCSessionInfos;
/**
* Gets/sets the directory for script files.
*/
ScriptDir(bstrScriptDir: string): void;
/**
* Gets/sets the directory for artwork files.
*/
ArtPath(bstrArtPath: string): void;
/**
* READONLY: Gets the collection of behavior scripts.
*/
readonly BehaviorTypes: IPigBehaviorTypes;
/**
* READONLY: Gets the collection of game lobby servers.
*/
readonly Lobbies: IPigLobbies;
/**
* READONLY: Gets the collection of all (pig) players.
*/
readonly Pigs: IPigs;
/**
* Creates a new pig object with the specified behavior type.
*/
CreatePig(bstrType: string, bstrCommandLine: string): IPig;
/**
* Gets/sets the server on which all pigs will be created.
*/
MissionServer(bstrServer: string): void;
/**
* Gets/sets maximum number of pigs that can be created on this server.
*/
MaxPigs(nMaxPigs: number): void;
/**
* READONLY: Gets the object that dispenses pig accounts.
*/
readonly AccountDispenser: IPigAccountDispenser;
/**
* READONLY: Gets the version information of the Pig server.
*/
readonly Version: IAGCVersionInfo;
/**
* READONLY: Gets the process ID of the server, meaningful only on the local machine.
*/
readonly ProcessID: number;
/**
* Enables the firing of all available events from this session.
*/
ActivateAllEvents(): void;
/**
* Disables the firing of all available events from this session.
*/
DeactivateAllEvents(): void;
/**
* READONLY: Gets the event log object.
*/
readonly EventLog: IAGCEventLogger;
/**
* Contains the server from which pig accounts will be dispensed. When empty, the MissionServer is used. When this property is a period character, the local machine is used.
*/
AccountServer(bstrServer: string): void;
/**
* Contains the server on which the pig accounts will be authenticated. When empty, no authentication is performed.
*/
ZoneAuthServer(bstrServer: string): void;
/**
* Contains the maximum amount of time allowed for authentication of pig accounts. Ignored when ZoneAuthServer is an empty string.
*/
ZoneAuthTimeout(nMilliseconds: number): void;
/**
* Specifies the mode of lobby connection that is used for server connections. Affects the usage of the MissionServer property.
*/
LobbyMode(eMode: Enums.PigLobbyMode): void;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IPigSessionEvents Interface
/**
* IPigSessionEvents Interface
*/
interface IPigSessionEvents extends IUnknown
{
/**
* Called when an event is fired for this session.
*/
OnEvent(pEvent: IAGCEvent): void;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IPigEvent Interface
/**
* Interface to a Pig Event object.
*/
interface IPigEvent extends IDispatch
{
/**
* Gets/sets the name of the object.
*/
Name(bstrName: string): void;
/**
* Gets/sets the expression to be evaluated on the normal expiration of this action.
*/
ExpirationExpression(bstrExpr: string): void;
/**
* READONLY: Gets whether or not the event has expired.
*/
readonly IsExpired: boolean;
/**
* Kills the event.
*/
Kill(): void;
/**
* Gets/sets the expression to be evaluated on the interrupted expiration of this action.
*/
InterruptionExpression(bstrExpr: string): void;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IPigTimer Interface
/**
* Interface to a Timer object.
*/
interface IPigTimer extends IPigEvent
{
/**
* Gets/sets the number of interval occurences remaining for this timer.
*/
RepetitionCount(nRepetitionCount: number): void;
/**
* Gets/sets the time, in seconds, of each timer interval.
*/
Interval(fInterval: number): void;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IPigShip Interface
/**
* Interface to a Pig Ship object.
*/
interface IPigShip extends IAGCShip
{
/**
* Sells all parts loaded onto the ship.
*/
SellAllParts(): void;
/**
* Buys the specified hull type.
*/
BuyHull(pHullType: IAGCHullType): void;
/**
* Buys the default loadout for the current hull type.
*/
BuyDefaultLoadout(): void;
/**
* Kills the ship.
*/
CommitSuicide(): string;
/**
* Stops all thrusting, throttling, axis turning, and action events.
*/
AllStop(): string;
/**
* Thrusts the ship in the specified direction(s).
*/
Thrust(e1: Enums.PigThrust, e2: Enums.PigThrust, e3: Enums.PigThrust, e4: Enums.PigThrust, e5: Enums.PigThrust, e6: Enums.PigThrust, e7: Enums.PigThrust): string;
/**
* Turns afterburner on/off.
*/
Boost(bOn: boolean): string;
/**
* Begins/ends the firing of the active weapon.
*/
FireWeapon(bBegin: boolean): string;
/**
* Begins/ends the firing of the missile launcher.
*/
FireMissile(bBegin: boolean): string;
/**
* Begins/ends the dropping of mines (or probes).
*/
DropMine(bBegin: boolean): string;
/**
* Activates/deactivates the vector lock.
*/
LockVector(bLockVector: boolean): string;
/**
* Activates/deactivates the rip cording action.
*/
RipCord(pvParam: object): string;
/**
* Cloaks/decloaks the ship.
*/
Cloak(bCloak: boolean): string;
/**
* Accepts the queued command.
*/
AcceptCommand(): string;
/**
* Clears the accepted command.
*/
ClearCommand(): string;
/**
* Turns the ship the specified number of positive degrees upward.
*/
PitchUp(fDegrees: number): string;
/**
* Turns the ship the specified number of positive degrees downward.
*/
PitchDown(fDegrees: number): string;
/**
* Turns the ship the specified number of positive degrees to the left.
*/
YawLeft(fDegrees: number): string;
/**
* Turns the ship the specified number of positive degrees to the right.
*/
YawRight(fDegrees: number): string;
/**
* Rolls the ship the specified number of positive degrees to the left
*/
RollLeft(fDegrees: number): string;
/**
* Rolls the ship the specified number of positive degrees to the right.
*/
RollRight(fDegrees: number): string;
/**
* Turns the ship to face the vector, specified by either an object name (VT_BSTR) or an IAGCVector* or IAGCModel* (VT_DISPATCH).
*/
Face(pvarObject: object, bstrCompletionExpr: string, bstrInterruptionExpr: string, bMatchUpVector: boolean): string;
/**
* Defends the specified target.
*/
Defend(bstrObject: string): string;
/**
* Attacks the specified target ship.
*/
AttackShip(pTarget: IAGCShip): string;
/**
* Attacks the specified target station.
*/
AttackStation(pTarget: IAGCStation): string;
/**
* Goto the specified target.
*/
Goto(bstrObject: string, bFriendly: boolean): string;
/**
* Goto the specified station ID.
*/
GotoStationID(oid: number): string;
/**
* Gets/sets the AutoPilot state.
*/
AutoPilot(bEngage: boolean): void;
/**
* READONLY: Gets the Pig Ship action event object for this ship.
*/
readonly AutoAction: IPigShipEvent;
/**
* Indicates whether the ship is thrusting in the specified direction.
*/
IsThrusting(eThrust: Enums.PigThrust): boolean;
/**
* Gets/sets the weapon that is active. This must be 0 thru 3, or -1 for the default of 'all weapons'.
*/
ActiveWeapon(iWeapon: number): void;
/**
* READONLY: Indicates whether the ship is firing the active weapon.
*/
readonly IsFiringWeapon: boolean;
/**
* READONLY: Indicates whether the ship is firing the missile launcher.
*/
readonly IsFiringMissile: boolean;
/**
* READONLY: Indicates whether the ship is dropping a mine (or probe).
*/
readonly IsDroppingMine: boolean;
/**
* READONLY: Indicates whether the ship's vector lock is active.
*/
readonly IsVectorLocked: boolean;
/**
* READONLY: Indicates whether the ship is rip-cording.
*/
readonly IsRipCording: boolean;
/**
* READONLY: Indicates whether the ship is cloaked.
*/
readonly IsCloaked: boolean;
/**
* READONLY: Gets the max range of the current missile
*/
readonly MissileRange: number;
/**
* READONLY: Gets the currnt missile lock 0.0 to 1.0
*/
readonly MissileLock: number;
/**
* Gets/sets the ship's throttle. The valid range is 0 to 100.
*/
Throttle(fThrottle: number): void;
/**
* Gets/sets the ship's pitch speed. The valid range is -100 to 100.
*/
Pitch(fPitch: number): void;
/**
* Gets/sets the ship's yaw speed. The valid range is -100 to 100.
*/
Yaw(fYaw: number): void;
/**
* Gets/sets the ship's roll speed. The valid range is -100 to 100.
*/
Roll(fRoll: number): void;
/**
* READONLY: Gets the queued command.
*/
readonly QueuedCommand: IAGCCommand;
/**
* READONLY: Gets the accepted command.
*/
readonly AcceptedCommand: IAGCCommand;
/**
* Gets/sets whether the ship automatically accepts queued commands.
*/
AutoAcceptCommands(bAutoAccept: boolean): void;
/**
* READONLY: Gets the amount of time left until the ripcordind action completes.
*/
readonly RipCordTimeLeft: number;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IPigShipEvent Interface
/**
* Interface to a Pig Ship Event object.
*/
interface IPigShipEvent extends IPigEvent
{
/**
* READONLY: Gets name of the action in progress.
*/
readonly Action: string;
/**
* READONLY: Gets the name of the target object for the action in progress.
*/
readonly Target: string;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IPigVector Interface
/**
* Interface to a Pig Vector object.
*/
interface IPigVector extends IDispatch
{
/**
* Gets/sets the x coordinate of the vector.
*/
X(xArg: number): void;
/**
* Gets/sets the y coordinate of the vector.
*/
Y(yArg: number): void;
/**
* Gets/sets the z coordinate of the vector.
*/
Z(zArg: number): void;
/**
* Sets the x, y, and z coordinates of the vector.
*/
SetXYZ(xArg: number, yArg: number, zArg: number): void;
/**
* READONLY: Gets the displayable string representation of the vector.
*/
readonly DisplayString: string;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IPigAccount Interface
/**
* Interface to a Pig Account object.
*/
interface IPigAccount extends IDispatch
{
/**
* READONLY: Gets the account name.
*/
readonly Name: string;
/**
* READONLY: Gets the account password.
*/
readonly Password: string;
/**
* READONLY: Gets the account CDKEY.
*/
readonly CdKey: string;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IPigAccountDispenser Interface
/**
* Interface to a Pig Account Dispenser object.
*/
interface IPigAccountDispenser extends IDispatch
{
/**
* READONLY: Gets an available account and marks it 'in-use'.
*/
readonly NextAvailable: IPigAccount;
/**
* READONLY: Gets a collection of all the managed user names.
*/
readonly Names: ITCStrings;
/**
* READONLY: Gets a collection of the available user names.
*/
readonly NamesAvailable: ITCStrings;
/**
* READONLY: Gets a collection of the user names in use.
*/
readonly NamesInUse: ITCStrings;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// IPigHullTypes Interface
/**
* Interface to a collection of hull type objects.
*/
interface IPigHullTypes extends ITCCollection
{
/**
* Returns an IAGCHullType* from the collection or NULL if the specified named hull type does not exist in the collection. Takes an argument, index, which must be either the name of a hull type in the collection or a 0-based index into the collection.
*/
Item(pvIndex: object): IAGCHullType;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// These declarations enable you to convert your JS objects into COM Interfaces so that you can
// get intellisense for event handler parameters.
declare class CType {
/**
* Casts the passed object to IAGCEventSink - Interface implemented by the hosting application to receive triggered events. Intended for use ONLY by host applications.
*/
IAGCEventSink(o: any): IAGCEventSink;
/**
* Casts the passed object to IAGCEventSinkSynchronous - Interface implemented by the hosting application to receive triggered events. Intended for use ONLY by host applications.
*/
IAGCEventSinkSynchronous(o: any): IAGCEventSinkSynchronous;
/**
* Casts the passed object to IAGCDebugHook - Implemented by an AGC host to hook debug events.
*/
IAGCDebugHook(o: any): IAGCDebugHook;
/**
* Casts the passed object to IAGCGlobal - Interface to the AGC Global object. Intended for use ONLY by host applications that deal directly with Igc.
*/
IAGCGlobal(o: any): IAGCGlobal;
/**
* Casts the passed object to IAGCVector - Interface to a AGC Vector object.
*/
IAGCVector(o: any): IAGCVector;
/**
* Casts the passed object to IAGCVectorPrivate - Private interface to an AGC Vector object.
*/
IAGCVectorPrivate(o: any): IAGCVectorPrivate;
/**
* Casts the passed object to IAGCOrientation - Interface to an AGC Orientation object.
*/
IAGCOrientation(o: any): IAGCOrientation;
/**
* Casts the passed object to IAGCOrientationPrivate - Private interface to an AGC Orientation object.
*/
IAGCOrientationPrivate(o: any): IAGCOrientationPrivate;
/**
* Casts the passed object to IAGCEventType - IAGCEventType Interface
*/
IAGCEventType(o: any): IAGCEventType;
/**
* Casts the passed object to IAGCEvent - IAGCEvent Interface
*/
IAGCEvent(o: any): IAGCEvent;
/**
* Casts the passed object to IAGCEventCreate - IAGCEventCreate Interface
*/
IAGCEventCreate(o: any): IAGCEventCreate;
/**
* Casts the passed object to IAGCGameParameters - IAGCGameParameters Interface
*/
IAGCGameParameters(o: any): IAGCGameParameters;
/**
* Casts the passed object to IAGCCommand - Interface to an AGC Command object.
*/
IAGCCommand(o: any): IAGCCommand;
/**
* Casts the passed object to IAGCCommandPrivate - Private interface to an AGC Command object.
*/
IAGCCommandPrivate(o: any): IAGCCommandPrivate;
/**
* Casts the passed object to IAGCVersionInfo - IAGCVersionInfo Interface
*/
IAGCVersionInfo(o: any): IAGCVersionInfo;
/**
* Casts the passed object to IAGCDBParams - IAGCDBParams Interface
*/
IAGCDBParams(o: any): IAGCDBParams;
/**
* Casts the passed object to IAGCEventLogger - IAGCEventLogger Interface
*/
IAGCEventLogger(o: any): IAGCEventLogger;
/**
* Casts the passed object to IAGCEventLoggerHook - Implemented by an AGC host to hook event logging.
*/
IAGCEventLoggerHook(o: any): IAGCEventLoggerHook;
/**
* Casts the passed object to IAGCEventLoggerPrivate - IAGCEventLoggerPrivate Interface
*/
IAGCEventLoggerPrivate(o: any): IAGCEventLoggerPrivate;
/**
* Casts the passed object to IAGCRangePrivate - Private interface to an AGC Range object.
*/
IAGCRangePrivate(o: any): IAGCRangePrivate;
/**
* Casts the passed object to IAGCRangesPrivate - Private interface to an AGC Ranges object.
*/
IAGCRangesPrivate(o: any): IAGCRangesPrivate;
/**
* Casts the passed object to IAGCEventIDRange - IAGCEventIDRange Interface
*/
IAGCEventIDRange(o: any): IAGCEventIDRange;
/**
* Casts the passed object to IAGCEventIDRanges - IAGCEventIDRanges Interface
*/
IAGCEventIDRanges(o: any): IAGCEventIDRanges;
/**
* Casts the passed object to ITCCollection - Base interface for most collection interfaces.
*/
ITCCollection(o: any): ITCCollection;
/**
* Casts the passed object to ITCStrings - Interface to a collection of strings.
*/
ITCStrings(o: any): ITCStrings;
/**
* Casts the passed object to ITCPropBagOnRegKey - Interface to create a property bag on a registry key.
*/
ITCPropBagOnRegKey(o: any): ITCPropBagOnRegKey;
/**
* Casts the passed object to ITCSessionInfo - ITCSessionInfo Interface
*/
ITCSessionInfo(o: any): ITCSessionInfo;
/**
* Casts the passed object to ITCSessionInfos - ITCSessionInfos interface
*/
ITCSessionInfos(o: any): ITCSessionInfos;
/**
* Casts the passed object to ITCCollectionPersistHelper - ITCCollectionPersistHelper interface
*/
ITCCollectionPersistHelper(o: any): ITCCollectionPersistHelper;
/**
* Casts the passed object to ITCUtility - ITCUtility interface
*/
ITCUtility(o: any): ITCUtility;
/**
* Casts the passed object to IAdminSessionHelper - IAdminSessionHelper interface
*/
IAdminSessionHelper(o: any): IAdminSessionHelper;
/**
* Casts the passed object to IAGCPrivate - Internally-used interface on an AGC object.
*/
IAGCPrivate(o: any): IAGCPrivate;
/**
* Casts the passed object to IAGCCommon - IAGCCommon Interface
*/
IAGCCommon(o: any): IAGCCommon;
/**
* Casts the passed object to IAGCCollection - Base interface for AGC collection interfaces.
*/
IAGCCollection(o: any): IAGCCollection;
/**
* Casts the passed object to IAGCBase - IAGCBase Interface
*/
IAGCBase(o: any): IAGCBase;
/**
* Casts the passed object to IAGCModel - IAGCModel Interface
*/
IAGCModel(o: any): IAGCModel;
/**
* Casts the passed object to IAGCModels - IAGCModels Interface
*/
IAGCModels(o: any): IAGCModels;
/**
* Casts the passed object to IAGCBuyable - Properties of an object that is buyable.
*/
IAGCBuyable(o: any): IAGCBuyable;
/**
* Casts the passed object to IAGCHullType - Interface to an AGC Hull Type object.
*/
IAGCHullType(o: any): IAGCHullType;
/**
* Casts the passed object to IAGCTreasure -
*/
IAGCTreasure(o: any): IAGCTreasure;
/**
* Casts the passed object to IAGCTreasures - IAGCTreasures Interface
*/
IAGCTreasures(o: any): IAGCTreasures;
/**
* Casts the passed object to IAGCDamage - IAGCDamage Interface
*/
IAGCDamage(o: any): IAGCDamage;
/**
* Casts the passed object to IAGCScanner - IAGCScanner Interface
*/
IAGCScanner(o: any): IAGCScanner;
/**
* Casts the passed object to IAGCProbe - IAGCProbe Interface
*/
IAGCProbe(o: any): IAGCProbe;
/**
* Casts the passed object to IAGCProbes - IAGCProbes Interface
*/
IAGCProbes(o: any): IAGCProbes;
/**
* Casts the passed object to IAGCGame - IAGCGame Interface
*/
IAGCGame(o: any): IAGCGame;
/**
* Casts the passed object to IAGCShip - IAGCShip Interface
*/
IAGCShip(o: any): IAGCShip;
/**
* Casts the passed object to IAGCShips - IAGCShips Interface
*/
IAGCShips(o: any): IAGCShips;
/**
* Casts the passed object to IAGCStation - IAGCStation Interface
*/
IAGCStation(o: any): IAGCStation;
/**
* Casts the passed object to IAGCStations - IAGCStations Interface
*/
IAGCStations(o: any): IAGCStations;
/**
* Casts the passed object to IAGCAleph - IAGCAleph Interface
*/
IAGCAleph(o: any): IAGCAleph;
/**
* Casts the passed object to IAGCAlephs - IAGCAlephs Interface
*/
IAGCAlephs(o: any): IAGCAlephs;
/**
* Casts the passed object to IAGCSector - IAGCSector Interface
*/
IAGCSector(o: any): IAGCSector;
/**
* Casts the passed object to IAGCSectors - IAGCSectors Interface
*/
IAGCSectors(o: any): IAGCSectors;
/**
* Casts the passed object to IAGCTeam - IAGCTeam Interface
*/
IAGCTeam(o: any): IAGCTeam;
/**
* Casts the passed object to IAGCTeams - IAGCTeams Interface
*/
IAGCTeams(o: any): IAGCTeams;
/**
* Casts the passed object to IAGCAsteroid - IAGCAsteroid Interface
*/
IAGCAsteroid(o: any): IAGCAsteroid;
/**
* Casts the passed object to IAGCAsteroids - IAGCAsteroids Interface
*/
IAGCAsteroids(o: any): IAGCAsteroids;
/**
* Casts the passed object to IPigBehaviorType - Interface to a pig behavior type object.
*/
IPigBehaviorType(o: any): IPigBehaviorType;
/**
* Casts the passed object to IPigBehaviorTypes - Interface to a collection of pig behavior script objects.
*/
IPigBehaviorTypes(o: any): IPigBehaviorTypes;
/**
* Casts the passed object to IPigBehaviorScriptType - Interface to a pig behavior script object.
*/
IPigBehaviorScriptType(o: any): IPigBehaviorScriptType;
/**
* Casts the passed object to IPigBehaviorHost - Interface to a pig behavior host object.
*/
IPigBehaviorHost(o: any): IPigBehaviorHost;
/**
* Casts the passed object to IPigBehavior - Interface to a pig behavior object.
*/
IPigBehavior(o: any): IPigBehavior;
/**
* Casts the passed object to IPigBehaviors - Interface to a collection of pig behavior objects.
*/
IPigBehaviors(o: any): IPigBehaviors;
/**
* Casts the passed object to IPigBehaviorStack - Interface to a stack of pig behavior objects.
*/
IPigBehaviorStack(o: any): IPigBehaviorStack;
/**
* Casts the passed object to IPig - Interface to a pig player object.
*/
IPig(o: any): IPig;
/**
* Casts the passed object to IPigs - Interface to a collection of pig player objects.
*/
IPigs(o: any): IPigs;
/**
* Casts the passed object to IPigTeam - Interface to a Team object.
*/
IPigTeam(o: any): IPigTeam;
/**
* Casts the passed object to IPigTeams - Interface to a collection of Team objects.
*/
IPigTeams(o: any): IPigTeams;
/**
* Casts the passed object to IPigMissionParams - Interface to a MissionParams object.
*/
IPigMissionParams(o: any): IPigMissionParams;
/**
* Casts the passed object to IPigMissionParamsPrivate - Private interface to a MissionParams object.
*/
IPigMissionParamsPrivate(o: any): IPigMissionParamsPrivate;
/**
* Casts the passed object to IPigMission - Interface to a Mission object.
*/
IPigMission(o: any): IPigMission;
/**
* Casts the passed object to IPigMissions - Interface to a collection of Mission objects.
*/
IPigMissions(o: any): IPigMissions;
/**
* Casts the passed object to IPigLobby - Interface to a Lobby object.
*/
IPigLobby(o: any): IPigLobby;
/**
* Casts the passed object to IPigLobbies - Interface to a collection of Lobby objects.
*/
IPigLobbies(o: any): IPigLobbies;
/**
* Casts the passed object to IPigSession - IPigSession Interface
*/
IPigSession(o: any): IPigSession;
/**
* Casts the passed object to IPigSessionEvents - IPigSessionEvents Interface
*/
IPigSessionEvents(o: any): IPigSessionEvents;
/**
* Casts the passed object to IPigEvent - Interface to a Pig Event object.
*/
IPigEvent(o: any): IPigEvent;
/**
* Casts the passed object to IPigTimer - Interface to a Timer object.
*/
IPigTimer(o: any): IPigTimer;
/**
* Casts the passed object to IPigShip - Interface to a Pig Ship object.
*/
IPigShip(o: any): IPigShip;
/**
* Casts the passed object to IPigShipEvent - Interface to a Pig Ship Event object.
*/
IPigShipEvent(o: any): IPigShipEvent;
/**
* Casts the passed object to IPigVector - Interface to a Pig Vector object.
*/
IPigVector(o: any): IPigVector;
/**
* Casts the passed object to IPigAccount - Interface to a Pig Account object.
*/
IPigAccount(o: any): IPigAccount;
/**
* Casts the passed object to IPigAccountDispenser - Interface to a Pig Account Dispenser object.
*/
IPigAccountDispenser(o: any): IPigAccountDispenser;
/**
* Casts the passed object to IPigHullTypes - Interface to a collection of hull type objects.
*/
IPigHullTypes(o: any): IPigHullTypes;
} | the_stack |
'use strict';
/** @hidden */
const debug = require('debug')('wicked-sdk');
/** @hidden */
const qs = require('querystring');
/** @hidden */
const uuid = require('node-uuid');
import {
WickedInitOptions,
Callback,
WickedGlobals,
ErrorCallback,
WickedAwaitOptions,
WickedApiCollection,
WickedApi,
WickedCollection,
WickedSubscription,
WickedApiPlan,
WickedApiPlanCollection,
WickedGroupCollection,
WickedUserShortInfo,
WickedGetOptions,
WickedUserCreateInfo,
WickedUserInfo,
WickedGetCollectionOptions,
WickedApplicationCreateInfo,
WickedApplication,
WickedApplicationRole,
WickedApplicationRoleType,
WickedSubscriptionPatchInfo,
WickedApproval,
WickedVerification,
WickedComponentHealth,
WickedChatbotTemplates,
WickedEmailTemplateType,
WickedAuthServer,
WickedWebhookListener,
WickedEvent,
WickedPoolMap,
WickedPool,
WickedNamespace,
WickedGetRegistrationOptions,
WickedRegistration,
WickedRegistrationMap,
WickedGrant,
ExpressHandler,
WickedSubscriptionInfo,
WickedSubscriptionCreateInfo,
OidcProfile,
PassthroughScopeRequest,
PassthroughScopeResponse,
WickedSessionStoreType,
WickedApiScopes,
WickedApiSettings,
WickedScopeGrant,
WickedPasswordStrategy,
ExternalRefreshRequest,
ExternalRefreshResponse,
ExternalUserPassRequest,
ExternalUserPassResponse,
ScopeLookupResponse,
WickedSubscriptionScopeModeType,
WickedClientType,
} from "./interfaces";
export {
WickedInitOptions,
Callback,
WickedGlobals,
ErrorCallback,
WickedAwaitOptions,
WickedApiCollection,
WickedApi,
WickedCollection,
WickedSubscription,
WickedApiPlan,
WickedApiPlanCollection,
WickedGroupCollection,
WickedUserShortInfo,
WickedGetOptions,
WickedUserCreateInfo,
WickedUserInfo,
WickedGetCollectionOptions,
WickedApplicationCreateInfo,
WickedApplication,
WickedApplicationRole,
WickedApplicationRoleType,
WickedSubscriptionPatchInfo,
WickedApproval,
WickedVerification,
WickedComponentHealth,
WickedChatbotTemplates,
WickedEmailTemplateType,
WickedAuthServer,
WickedWebhookListener,
WickedEvent,
WickedPoolMap,
WickedPool,
WickedNamespace,
WickedGetRegistrationOptions,
WickedRegistration,
WickedRegistrationMap,
WickedGrant,
ExpressHandler,
WickedSubscriptionInfo,
WickedSubscriptionCreateInfo,
OidcProfile,
PassthroughScopeRequest,
PassthroughScopeResponse,
WickedSessionStoreType,
WickedApiScopes,
WickedApiSettings,
WickedScopeGrant,
WickedPasswordStrategy,
ExternalRefreshRequest,
ExternalRefreshResponse,
ExternalUserPassRequest,
ExternalUserPassResponse,
ScopeLookupResponse,
WickedSubscriptionScopeModeType,
WickedClientType,
} from "./interfaces";
export { WickedError } from './wicked-error';
export {
KongApi,
KongPlugin,
KongService,
KongRoute,
ProtocolType,
KongCollection,
KongConsumer,
KongGlobals,
KongProxyListener,
KongHttpDirective,
KongStatus,
KongPluginCorrelationId,
KongPluginCors,
KongPluginBotDetection,
KongPluginCorrelationIdGeneratorType,
KongPluginOAuth2,
KongPluginRateLimiting,
KongPluginRequestTransformer,
KongPluginResponseTransformer,
KongPluginWhiteBlackList,
KongApiConfig,
KongPluginHmacAuth
} from './kong-interfaces';
export {
kongServiceRouteToApi,
kongApiToServiceRoute,
kongApiToServiceAndRoutes,
kongServiceAndRoutesToApi
} from './kong';
/** @hidden */
import * as implementation from './implementation';
// ======= INITIALIZATION =======
/**
* Initialize the wicked node SDK.
*
* @param options SDK global options
* @param callback Returns an error or the content of the `globals.json` file (as second argument)
*/
export function initialize(options: WickedInitOptions): Promise<WickedGlobals>;
export function initialize(options: WickedInitOptions, callback: Callback<WickedGlobals>);
export function initialize(options: WickedInitOptions, callback?: Callback<WickedGlobals>) {
return implementation._initialize(options, callback);
}
/**
* Returns true if the wicked SDK is currently able to reach the wicked API.
*/
export function isApiReachable(): boolean {
return implementation._isApiReachable();
}
/**
* Returns true if the system is in "development mode". This usually means that transport is not secure
* (not via https).
*/
export function isDevelopmentMode(): boolean {
return implementation._isDevelopmentMode();
};
/**
* Create a machine administrator user for a given service. This method can be used to get "backdoor"
* access to the wicked API on behalf of a machine user. If you call this method, the machine user ID
* will be stored internally in the SDK and will be used for any API calls using the SDK.
*
* @param serviceId A unique service ID for the service to create a machine user for
* @param callback Returns `null` if succeeded, or an error.
*/
export function initMachineUser(serviceId: string): Promise<any>;
export function initMachineUser(serviceId: string, callback: ErrorCallback);
export function initMachineUser(serviceId: string, callback?: ErrorCallback) {
return implementation._initMachineUser(serviceId, callback);
};
/**
* Awaits return code `200` for the specified URL.
*
* @param url The URL to wait for to return `200`
* @param options Await options (see interface)
* @param callback Returns `null` plus the returned content of the URL, or an error
*/
export function awaitUrl(url: string, options: WickedAwaitOptions): Promise<any>;
export function awaitUrl(url: string, options: WickedAwaitOptions, callback: Callback<any>);
export function awaitUrl(url: string, options: WickedAwaitOptions, callback?: Callback<any>) {
return implementation._awaitUrl(url, options, callback);
};
/**
* Convenience function to make sure the Kong Adapter is up and running.
*
* @param awaitOptions Await options
* @param callback Returns `null` plus the returned content of the URL, or an error
*/
export function awaitKongAdapter(awaitOptions: WickedAwaitOptions): Promise<any>;
export function awaitKongAdapter(awaitOptions: WickedAwaitOptions, callback: Callback<any>);
export function awaitKongAdapter(awaitOptions: WickedAwaitOptions, callback?: Callback<any>) {
return implementation._awaitKongAdapter(awaitOptions, callback);
};
// ======= INFORMATION RETRIEVAL =======
/**
* Returns the content of the `globals.json` file, with resolved environment variables, if applicable.
*/
export function getGlobals(): WickedGlobals {
return implementation._getGlobals();
};
/**
* Returns the current hash of the static configuration. This is used to check whether the static
* configuration has changed, and if so, decide to restart/stop components like the mailer or the kong
* adapter.
*/
export function getConfigHash(): string {
return implementation._getConfigHash();
};
/**
* Return the currently configured user facing schema (`http` or `https`). This information is contained
* in the `globals.json`.
*/
export function getSchema(): string {
return implementation._getSchema();
};
/**
* Returns the external portal host for the currently configured environment, e.g. `developer.mycompany.com`
*/
export function getExternalPortalHost(): string {
return implementation._getExternalPortalHost();
};
/**
* Returns the complete URL to the wicked portal UI, as seen from outside the deployment, e.g. `https://developer.mycompany.com`
*/
export function getExternalPortalUrl(): string {
return implementation._getExternalPortalUrl();
};
/**
* Returns the host name for the API Gateway for the currently configured environment, e.g. `api.mycompany.com`
*/
export function getExternalApiHost(): string {
return implementation._getExternalGatewayHost();
};
/**
* Returns the complete base URL to the API Gateway, as seen from outside the deployment. E.g., `https://api.mycompany.com`
*/
export function getExternalApiUrl(): string {
return implementation._getExternalGatewayUrl();
};
/**
* Returns the URL to the wicked API, as seen from *inside* the deployment
*/
export function getInternalApiUrl(): string {
return implementation._getInternalApiUrl();
};
/**
* Returns the full scope to the wicked API (all scope strings, space separated).
*/
export function getPortalApiScope(): string {
return implementation._getPortalApiScope();
};
/**
* Returns the full URL to the portal UI instance, e.g. `http://portal:3000`, as seen from inside the deployment.
*/
export function getInternalPortalUrl(): string {
return implementation._getInternalPortalUrl();
}
/**
* Returns the full URL to the admin port of the Kong instance(s), as seen from inside the deployment. E.g., `http://kong:8001`.
*/
export function getInternalKongAdminUrl(): string {
return implementation._getInternalKongAdminUrl();
};
/**
* Returns the full URL to the proxy port of the Kong instance(s), as seen from inside the deployment. E.g., `http://kong:8000`.
*/
export function getInternalKongProxyUrl(): string {
return implementation._getInternalKongProxyUrl();
};
/**
* Returns the full URL to the Kong Adapter, as seen from inside the deployment, e.g. `http://portal-kong-adapter:3002`
*/
export function getInternalKongAdapterUrl(): string {
return implementation._getInternalKongAdapterUrl();
};
/**
* Returns the full URL to the chatbot, as seen from inside the deployment, e.g. `http://portal-chatbot:3004`
*/
export function getInternalChatbotUrl(): string {
return implementation._getInternalChatbotUrl();
};
/**
* Returns the full URL to the mailer, as seen from inside the deployment, e.g. `http://portal-mailer:3003`
*/
export function getInternalMailerUrl(): string {
return implementation._getInternalMailerUrl();
};
export function getInternalUrl(globalSettingsProperty: string): string {
return implementation._getInternalUrl(globalSettingsProperty, null, 0);
};
/**
* Returns the list of Kong plugins which the Kong Adapter will not touch.
*/
export function getKongAdapterIgnoreList(): string[] {
return implementation._getKongAdapterIgnoreList();
}
/**
* Returns the header name to use for key auth purposes. Defaults to `X-ApiKey`.
*/
export function getApiKeyHeader(): string {
return implementation._getApiKeyHeader();
}
/**
* Returns the selected password validation strategy identifier.
*/
export function getPasswordStrategy(): string {
return implementation._getPasswordStrategy();
}
// ======= API FUNCTIONALITY =======
/**
* General purpose `GET` operation on the wicked API; you do not use this directly usually, but use one of
* the dedicated SDK functions.
*
* @param urlPath relative URL path
* @param userIdOrCallback user ID to perform the `GET` operation as, or `callback`
* @param callback Callback containing an `err` (or `null` if success) and the `GET` returned content.
*/
export function apiGet(urlPath: string, userIdOrCallback, callback) {
let userId = userIdOrCallback;
if (!callback && typeof (userIdOrCallback) === 'function') {
callback = userIdOrCallback;
userId = null;
}
return implementation._apiGet(urlPath, userId, null, callback);
};
/**
* General purpose `POST` operation on the wicked API; you do not use this directly usually, but use one of
* the dedicated SDK functions.
*
* @param urlPath relative URL path
* @param postBody Body to post
* @param userIdOrCallback user ID to perform the `GET` operation as, or `callback`
* @param callback Callback containing an `err` (or `null` if success) and the `GET` returned content.
*/
export function apiPost(urlPath: string, postBody: object, userIdOrCallback, callback) {
let userId = userIdOrCallback;
if (!callback && typeof (userIdOrCallback) === 'function') {
callback = userIdOrCallback;
userId = null;
}
return implementation._apiPost(urlPath, postBody, userId, callback);
};
/**
* General purpose `PUT` operation on the wicked API; you do not use this directly usually, but use one of
* the dedicated SDK functions.
*
* @param urlPath relative URL path
* @param putBody Body to post
* @param userIdOrCallback user ID to perform the `GET` operation as, or `callback`
* @param callback Callback containing an `err` (or `null` if success) and the `GET` returned content.
*/
export function apiPut(urlPath: string, putBody: object, userIdOrCallback, callback) {
let userId = userIdOrCallback;
if (!callback && typeof (userIdOrCallback) === 'function') {
callback = userIdOrCallback;
userId = null;
}
return implementation._apiPut(urlPath, putBody, userId, callback);
};
/**
* General purpose `PATCH` operation on the wicked API; you do not use this directly usually, but use one of
* the dedicated SDK functions.
*
* @param urlPath relative URL path
* @param putBody Body to patch
* @param userIdOrCallback user ID to perform the `GET` operation as, or `callback`
* @param callback Callback containing an `err` (or `null` if success) and the `GET` returned content.
*/
export function apiPatch(urlPath: string, patchBody: object, userIdOrCallback, callback) {
let userId = userIdOrCallback;
if (!callback && typeof (userIdOrCallback) === 'function') {
callback = userIdOrCallback;
userId = null;
}
return implementation._apiPatch(urlPath, patchBody, userId, callback);
};
/**
* General purpose `DELETE` operation on the wicked API; you do not use this directly usually, but use one of
* the dedicated SDK functions.
*
* @param urlPath relative URL path
* @param userIdOrCallback user ID to perform the `GET` operation as, or `callback`
* @param callback Callback containing an `err` (or `null` if success) and the `GET` returned content.
*/
export function apiDelete(urlPath: string, userIdOrCallback, callback) {
let userId = userIdOrCallback;
if (!callback && typeof (userIdOrCallback) === 'function') {
callback = userIdOrCallback;
userId = null;
}
return implementation._apiDelete(urlPath, userId, callback);
};
// ======= API CONVENIENCE FUNCTIONS =======
// APIS
/**
* Returns a collection of API definitions (corresponds to the `apis.json`).
* @param callback
* @category APIs
*/
export function getApis(): Promise<WickedApiCollection>;
export function getApis(callback: Callback<WickedApiCollection>);
export function getApis(callback?: Callback<WickedApiCollection>) {
return getApisAs(null, callback);
}
export function getApisAs(asUserId: string): Promise<WickedApiCollection>;
export function getApisAs(asUserId: string, callback: Callback<WickedApiCollection>);
export function getApisAs(asUserId: string, callback?: Callback<WickedApiCollection>) {
return apiGet('apis', asUserId, callback);
}
/**
* Return the generic APIs description (for all APIs). Returns markdown code.
* @param callback
*/
export function getApisDescription(): Promise<string>;
export function getApisDescription(callback: Callback<string>);
export function getApisDescription(callback?: Callback<string>) {
return getApisDescriptionAs(null, callback);
}
export function getApisDescriptionAs(asUserId: string): Promise<string>;
export function getApisDescriptionAs(asUserId: string, callback: Callback<string>);
export function getApisDescriptionAs(asUserId: string, callback?: Callback<string>) {
return apiGet(`apis/desc`, asUserId, callback);
}
/**
* Returns the API definition for a specific API.
*
* @param apiId The id of the API to retrieve
* @param callback
*/
export function getApi(apiId: string): Promise<WickedApi>;
export function getApi(apiId: string, callback: Callback<WickedApi>);
export function getApi(apiId: string, callback?: Callback<WickedApi>) {
return getApiAs(apiId, null, callback);
}
export function getApiAs(apiId: string, asUserId: string): Promise<WickedApi>;
export function getApiAs(apiId: string, asUserId: string, callback: Callback<WickedApi>);
export function getApiAs(apiId: string, asUserId: string, callback?: Callback<WickedApi>) {
return apiGet(`apis/${apiId}`, asUserId, callback);
}
/**
* Retrieve the (markdown) API description of a specific API.
*
* @param apiId The id of the API to retrieve the description for
* @param callback
*/
export function getApiDescription(apiId: string): Promise<string>;
export function getApiDescription(apiId: string, callback: Callback<string>);
export function getApiDescription(apiId: string, callback?: Callback<string>) {
return getApiDescriptionAs(apiId, null, callback);
}
export function getApiDescriptionAs(apiId: string, asUserId: string): Promise<string>;
export function getApiDescriptionAs(apiId: string, asUserId: string, callback: Callback<string>);
export function getApiDescriptionAs(apiId: string, asUserId: string, callback?: Callback<string>) {
return apiGet(`apis/${apiId}/desc`, asUserId, callback);
}
/**
* Retrieve the API specific Kong configuration for a specific API.
*
* @param apiId The id of the API to retrieve the Kong config for
* @param callback
*/
export function getApiConfig(apiId: string): Promise<any>;
export function getApiConfig(apiId: string, callback: Callback<any>);
export function getApiConfig(apiId: string, callback?: Callback<any>) {
return getApiConfigAs(apiId, null, callback);
}
export function getApiConfigAs(apiId: string, asUserId: string): Promise<any>;
export function getApiConfigAs(apiId: string, asUserId: string, callback: Callback<any>);
export function getApiConfigAs(apiId: string, asUserId: string, callback?: Callback<any>) {
return apiGet(`apis/${apiId}/config`, asUserId, callback);
}
/**
* Retrieve a JSON representation of the Swagger information for a specific API; contains authorization information (injected).
*
* @param apiId The id of the API to retrieve the Swagger JSON for
* @param callback
*/
export function getApiSwagger(apiId: string): Promise<object>;
export function getApiSwagger(apiId: string, callback: Callback<object>);
export function getApiSwagger(apiId: string, callback?: Callback<object>) {
return getApiSwaggerAs(apiId, null, callback);
}
export function getApiSwaggerAs(apiId: string, asUserId: string): Promise<object>;
export function getApiSwaggerAs(apiId: string, asUserId: string, callback: Callback<object>);
export function getApiSwaggerAs(apiId: string, asUserId: string, callback?: Callback<object>) {
return apiGet(`apis/${apiId}/swagger`, asUserId, callback);
}
/**
* Retrieve a list of subscriptions to a specific API.
*
* @param apiId The id of the API to retrieve subscriptions for.
* @param callback
*/
export function getApiSubscriptions(apiId: string): Promise<WickedCollection<WickedSubscription>>;
export function getApiSubscriptions(apiId: string, callback: Callback<WickedCollection<WickedSubscription>>);
export function getApiSubscriptions(apiId: string, callback?: Callback<WickedCollection<WickedSubscription>>) {
return getApiSubscriptionsAs(apiId, null, callback);
}
export function getApiSubscriptionsAs(apiId: string, asUserId: string): Promise<WickedCollection<WickedSubscription>>;
export function getApiSubscriptionsAs(apiId: string, asUserId: string, callback: Callback<WickedCollection<WickedSubscription>>);
export function getApiSubscriptionsAs(apiId: string, asUserId: string, callback?: Callback<WickedCollection<WickedSubscription>>) {
return apiGet(`apis/${apiId}/subscriptions`, asUserId, callback);
}
// PLANS
/**
* Retrieve a list of API Plans for a specific API.
*
* @param apiId The id of the API to retrieve the associated plans for
* @param callback
*/
export function getApiPlans(apiId: string): Promise<WickedApiPlan[]>;
export function getApiPlans(apiId: string, callback: Callback<WickedApiPlan[]>);
export function getApiPlans(apiId: string, callback?: Callback<WickedApiPlan[]>) {
return getApiPlansAs(apiId, null, callback);
}
export function getApiPlansAs(apiId: string, asUserId: string): Promise<WickedApiPlan[]>;
export function getApiPlansAs(apiId: string, asUserId: string, callback: Callback<WickedApiPlan[]>);
export function getApiPlansAs(apiId: string, asUserId: string, callback?: Callback<WickedApiPlan[]>) {
return apiGet(`apis/${apiId}/plans`, asUserId, callback);
}
/**
* Return a collection of all API plans, disregarding their association with APIs or not. This is an open
* endpoint, so there is no `As` alternative.
* @param callback
*/
export function getPlans(): Promise<WickedApiPlanCollection>;
export function getPlans(callback: Callback<WickedApiPlanCollection>);
export function getPlans(callback?: Callback<WickedApiPlanCollection>) {
return apiGet('plans', null, callback);
}
// GROUPS
/**
* Retrieve a collection of all wicked user groups. This is an open
* endpoint, so there is no `As` alternative.
* @param callback
*/
export function getGroups(): Promise<WickedGroupCollection>;
export function getGroups(callback: Callback<WickedGroupCollection>);
export function getGroups(callback?: Callback<WickedGroupCollection>) {
return apiGet('groups', null, callback);
}
// USERS
/**
* Retrieves user short info by custom id.
*
* @param customId The custom id of the user to retrieve
* @param callback
*/
export function getUserByCustomId(customId: string): Promise<WickedUserShortInfo[]>;
export function getUserByCustomId(customId: string, callback: Callback<WickedUserShortInfo[]>);
export function getUserByCustomId(customId: string, callback?: Callback<WickedUserShortInfo[]>) {
return apiGet(`users?customId=${qs.escape(customId)}`, null, callback);
}
/**
* Retrieves user short info by email address.
*
* @param email The email address of the user to retrieve
* @param callback
*/
export function getUserByEmail(email: string): Promise<WickedUserShortInfo[]>;
export function getUserByEmail(email: string, callback: Callback<WickedUserShortInfo[]>);
export function getUserByEmail(email: string, callback?: Callback<WickedUserShortInfo[]>) {
return apiGet(`users?email=${qs.escape(email)}`, null, callback);
}
/**
* Retrieve list of users matching the given options. Chances are good you will rather want to use
* getRegistrations().
*
* @param options Collection get options
* @param callback
*/
export function getUsers(options: WickedGetOptions): Promise<WickedUserShortInfo[]>;
export function getUsers(options: WickedGetOptions, callback: Callback<WickedUserShortInfo[]>);
export function getUsers(options: WickedGetOptions, callback?: Callback<WickedUserShortInfo[]>) {
return getUsersAs(options, null, callback);
}
export function getUsersAs(options: WickedGetOptions, asUserId: string): Promise<WickedUserShortInfo[]>;
export function getUsersAs(options: WickedGetOptions, asUserId: string, callback: Callback<WickedUserShortInfo[]>);
export function getUsersAs(options: WickedGetOptions, asUserId: string, callback?: Callback<WickedUserShortInfo[]>) {
let o = implementation.validateGetOptions(options);
let url = implementation.buildUrl('users', o);
return apiGet(url, asUserId, callback);
}
/**
* Creates a new user from the given information. Returns a user information object also containing
* the new internal ID of the user.
*
* @param userCreateInfo The basic user info needed to create a user
* @param callback
*/
export function createUser(userCreateInfo: WickedUserCreateInfo): Promise<WickedUserInfo>;
export function createUser(userCreateInfo: WickedUserCreateInfo, callback: Callback<WickedUserInfo>);
export function createUser(userCreateInfo: WickedUserCreateInfo, callback?: Callback<WickedUserInfo>) {
return createUserAs(userCreateInfo, null, callback);
}
export function createUserAs(userCreateInfo: WickedUserCreateInfo, asUserId: string): Promise<WickedUserInfo>;
export function createUserAs(userCreateInfo: WickedUserCreateInfo, asUserId: string, callback: Callback<WickedUserInfo>);
export function createUserAs(userCreateInfo: WickedUserCreateInfo, asUserId: string, callback?: Callback<WickedUserInfo>) {
return apiPost('users', userCreateInfo, asUserId, callback);
}
/**
* Patches a user. Returns the updated user information.
*
* @param userPatchInfo The information of the user to update (password, groups...)
* @param callback
*/
export function patchUser(userId: string, userPatchInfo: WickedUserCreateInfo): Promise<WickedUserInfo>;
export function patchUser(userId: string, userPatchInfo: WickedUserCreateInfo, callback: Callback<WickedUserInfo>);
export function patchUser(userId: string, userPatchInfo: WickedUserCreateInfo, callback?: Callback<WickedUserInfo>) {
return patchUserAs(userId, userPatchInfo, null, callback);
}
export function patchUserAs(userId: string, userPatchInfo: WickedUserCreateInfo, asUserId: string): Promise<WickedUserInfo>;
export function patchUserAs(userId: string, userPatchInfo: WickedUserCreateInfo, asUserId: string, callback: Callback<WickedUserInfo>);
export function patchUserAs(userId: string, userPatchInfo: WickedUserCreateInfo, asUserId: string, callback?: Callback<WickedUserInfo>) {
return apiPatch(`users/${userId}`, userPatchInfo, asUserId, callback);
}
/**
* Deletes a user. This function will only succeed if the user does not have any associated applications.
* If the user has applications, these have to be deleted or re-owned first.
*
* @param userId ID of user to delete
* @param callback
*/
export function deleteUser(userId: string): Promise<any>;
export function deleteUser(userId: string, callback: ErrorCallback);
export function deleteUser(userId: string, callback?: ErrorCallback) {
return deleteUserAs(userId, null, callback);
}
export function deleteUserAs(userId: string, asUserId: string): Promise<any>;
export function deleteUserAs(userId: string, asUserId: string, callback: ErrorCallback);
export function deleteUserAs(userId: string, asUserId: string, callback?: ErrorCallback) {
return apiDelete(`users/${userId}`, asUserId, callback);
}
/**
* Retrieves user information for a specific user.
*
* @param userId ID of user to retrieve
* @param callback
*/
export function getUser(userId: string): Promise<WickedUserInfo>;
export function getUser(userId: string, callback: Callback<WickedUserInfo>): void;
export function getUser(userId: string, callback?: Callback<WickedUserInfo>) {
return getUserAs(userId, null, callback);
}
export function getUserAs(userId: string, asUserId: string): Promise<WickedUserInfo>;
export function getUserAs(userId: string, asUserId: string, callback: Callback<WickedUserInfo>);
export function getUserAs(userId: string, asUserId: string, callback?: Callback<WickedUserInfo>) {
return apiGet(`users/${userId}`, asUserId, callback);
}
/**
* Special function which deletes the password for a specific user; this user will no longer be able to
* log in using username and password anymore.
*
* @param userId ID of user to delete password for.
* @param callback
*/
export function deleteUserPassword(userId: string): Promise<any>;
export function deleteUserPassword(userId: string, callback: ErrorCallback);
export function deleteUserPassword(userId: string, callback?: ErrorCallback) {
return deleteUserPasswordAs(userId, null, callback);
}
export function deleteUserPasswordAs(userId: string, asUserId: string): Promise<any>;
export function deleteUserPasswordAs(userId: string, asUserId: string, callback: ErrorCallback);
export function deleteUserPasswordAs(userId: string, asUserId: string, callback?: ErrorCallback) {
return apiDelete(`users/${userId}/password`, asUserId, callback);
}
// APPLICATIONS
/**
* Retrieves all registered wicked applications.
*
* @param options Get options (filtering, paging)
* @param callback
*/
export function getApplications(options: WickedGetCollectionOptions): Promise<WickedCollection<WickedApplication>>;
export function getApplications(options: WickedGetCollectionOptions, callback: Callback<WickedCollection<WickedApplication>>);
export function getApplications(options: WickedGetCollectionOptions, callback?: Callback<WickedCollection<WickedApplication>>) {
return getApplicationsAs(options, null, callback);
}
export function getApplicationsAs(options: WickedGetCollectionOptions, asUserId: string): Promise<WickedCollection<WickedApplication>>;
export function getApplicationsAs(options: WickedGetCollectionOptions, asUserId: string, callback: Callback<WickedCollection<WickedApplication>>);
export function getApplicationsAs(options: WickedGetCollectionOptions, asUserId: string, callback?: Callback<WickedCollection<WickedApplication>>) {
const o = implementation.validateGetCollectionOptions(options);
const url = implementation.buildUrl('applications', o);
return apiGet(url, asUserId, callback);
}
/**
* Creates a new wicked application based on the given information. Please note that the `clientType` takes precedence over
* the `confidential` property. Using only `clientType` is recommended. If none is passed in, `clientType` defaults to `public_spa`,
* which is the least secure option.
*
* @param appCreateInfo Application information for new application
* @param callback
*/
export function createApplication(appCreateInfo: WickedApplicationCreateInfo): Promise<WickedApplication>;
export function createApplication(appCreateInfo: WickedApplicationCreateInfo, callback: Callback<WickedApplication>);
export function createApplication(appCreateInfo: WickedApplicationCreateInfo, callback?: Callback<WickedApplication>) {
return createApplicationAs(appCreateInfo, null, callback);
}
export function createApplicationAs(appCreateInfo: WickedApplicationCreateInfo, asUserId: string): Promise<WickedApplication>;
export function createApplicationAs(appCreateInfo: WickedApplicationCreateInfo, asUserId: string, callback: Callback<WickedApplication>);
export function createApplicationAs(appCreateInfo: WickedApplicationCreateInfo, asUserId: string, callback?: Callback<WickedApplication>) {
return apiPost('applications', appCreateInfo, asUserId, callback);
}
/**
* Retrieves the list of (predefined) application roles.
*
* @param callback
*/
export function getApplicationRoles(): Promise<WickedApplicationRole[]>;
export function getApplicationRoles(callback: Callback<WickedApplicationRole[]>);
export function getApplicationRoles(callback?: Callback<WickedApplicationRole[]>) {
return apiGet('applications/roles', null, callback);
}
/**
* Retrieve information on the given application.
*
* @param appId ID of application to retrieve
* @param callback
*/
export function getApplication(appId: string): Promise<WickedApplication>;
export function getApplication(appId: string, callback: Callback<WickedApplication>);
export function getApplication(appId: string, callback?: Callback<WickedApplication>) {
return getApplicationAs(appId, null, callback);
}
export function getApplicationAs(appId: string, asUserId: string): Promise<WickedApplication>;
export function getApplicationAs(appId: string, asUserId: string, callback: Callback<WickedApplication>);
export function getApplicationAs(appId: string, asUserId: string, callback?: Callback<WickedApplication>) {
return apiGet(`applications/${appId}`, asUserId, callback);
}
/**
* Patch an application, e.g. change it's name, redirect URL or `clientType`.
*
* @param appId ID of application to patch
* @param appPatchInfo Patch body
* @param callback
*/
export function patchApplication(appId: string, appPatchInfo: WickedApplicationCreateInfo): Promise<WickedApplication>;
export function patchApplication(appId: string, appPatchInfo: WickedApplicationCreateInfo, callback: Callback<WickedApplication>);
export function patchApplication(appId: string, appPatchInfo: WickedApplicationCreateInfo, callback?: Callback<WickedApplication>) {
return patchApplicationAs(appId, appPatchInfo, null, callback);
}
export function patchApplicationAs(appId: string, appPatchInfo: WickedApplicationCreateInfo, asUserId: string): Promise<WickedApplication>;
export function patchApplicationAs(appId: string, appPatchInfo: WickedApplicationCreateInfo, asUserId: string, callback: Callback<WickedApplication>);
export function patchApplicationAs(appId: string, appPatchInfo: WickedApplicationCreateInfo, asUserId: string, callback?: Callback<WickedApplication>) {
return apiPatch(`applications/${appId}`, appPatchInfo, asUserId, callback);
}
/**
* Delete an application entirely.
*
* @param appId ID of application to delete
* @param callback
*/
export function deleteApplication(appId: string): Promise<any>;
export function deleteApplication(appId: string, callback: ErrorCallback);
export function deleteApplication(appId: string, callback?: ErrorCallback) {
return deleteApplicationAs(appId, null, callback);
}
export function deleteApplicationAs(appId: string, asUserId): Promise<any>;
export function deleteApplicationAs(appId: string, asUserId: string, callback: ErrorCallback);
export function deleteApplicationAs(appId: string, asUserId: string, callback?: ErrorCallback) {
return apiDelete(`applications/${appId}`, asUserId, callback);
}
/**
* Add an owner to a specific application.
*
* @param appId ID of application to add an owner for
* @param email Email address of additional owner
* @param role The role of the additional owner
* @param callback
*/
export function addApplicationOwner(appId: string, email: string, role: WickedApplicationRoleType): Promise<WickedApplication>;
export function addApplicationOwner(appId: string, email: string, role: WickedApplicationRoleType, callback: Callback<WickedApplication>);
export function addApplicationOwner(appId: string, email: string, role: WickedApplicationRoleType, callback?: Callback<WickedApplication>) {
return addApplicationOwnerAs(appId, email, role, null, callback);
}
export function addApplicationOwnerAs(appId: string, email: string, role: WickedApplicationRoleType, asUserId: string): Promise<WickedApplication>;
export function addApplicationOwnerAs(appId: string, email: string, role: WickedApplicationRoleType, asUserId: string, callback: Callback<WickedApplication>);
export function addApplicationOwnerAs(appId: string, email: string, role: WickedApplicationRoleType, asUserId: string, callback?: Callback<WickedApplication>) {
const body = {
email: email,
role: role
};
return apiPost(`applications/${appId}/owners`, body, asUserId, callback);
}
/**
* Delete an owner from an application.
*
* @param appId ID of application to delete the owner from
* @param email Email address of owner to delete from application
* @param callback
*/
export function deleteApplicationOwner(appId: string, email: string): Promise<WickedApplication>;
export function deleteApplicationOwner(appId: string, email: string, callback: Callback<WickedApplication>);
export function deleteApplicationOwner(appId: string, email: string, callback?: Callback<WickedApplication>) {
return deleteApplicationOwnerAs(appId, email, null, callback);
}
export function deleteApplicationOwnerAs(appId: string, email: string, asUserId: string): Promise<WickedApplication>;
export function deleteApplicationOwnerAs(appId: string, email: string, asUserId: string, callback: Callback<WickedApplication>);
export function deleteApplicationOwnerAs(appId: string, email: string, asUserId: string, callback?: Callback<WickedApplication>) {
return apiDelete(`applications/${appId}/owners?email=${qs.escape(email)}`, asUserId, callback);
}
// SUBSCRIPTIONS
/**
* Retrieve all API subscriptions for a specific application.
*
* @param appId ID of application to retrieve subscriptions for
* @param callback
*/
export function getSubscriptions(appId: string): Promise<WickedSubscription[]>;
export function getSubscriptions(appId: string, callback: Callback<WickedSubscription[]>);
export function getSubscriptions(appId: string, callback?: Callback<WickedSubscription[]>) {
return getSubscriptionsAs(appId, null, callback);
}
export function getSubscriptionsAs(appId: string, asUserId: string): Promise<WickedSubscription[]>;
export function getSubscriptionsAs(appId: string, asUserId: string, callback: Callback<WickedSubscription[]>);
export function getSubscriptionsAs(appId: string, asUserId: string, callback?: Callback<WickedSubscription[]>) {
return apiGet(`applications/${appId}/subscriptions`, asUserId, callback);
}
/**
* Retrieve subscription information for an application based on an OAuth2 client ID and a given API.
*
* @param clientId OAuth2 client ID of application
* @param apiId ID of API
* @param callback
*/
export function getSubscriptionByClientId(clientId: string, apiId: string): Promise<WickedSubscriptionInfo>;
export function getSubscriptionByClientId(clientId: string, apiId: string, callback: Callback<WickedSubscriptionInfo>);
export function getSubscriptionByClientId(clientId: string, apiId: string, callback?: Callback<WickedSubscriptionInfo>) {
return getSubscriptionByClientIdAs(clientId, apiId, null, callback);
}
export function getSubscriptionByClientIdAs(clientId: string, apiId: string, asUserId: string): Promise<WickedSubscriptionInfo>;
export function getSubscriptionByClientIdAs(clientId: string, apiId: string, asUserId: string, callback: Callback<WickedSubscriptionInfo>);
export function getSubscriptionByClientIdAs(clientId: string, apiId: string, asUserId: string, callback?: Callback<WickedSubscriptionInfo>) {
return implementation._getSubscriptionByClientId(clientId, apiId, asUserId, callback);
}
/**
* Create a new API subscription for an application.
*
* @param appId ID of application to create a subscription for
* @param subsCreateInfo Subscription create info (see type)
* @param callback
*/
export function createSubscription(appId: string, subsCreateInfo: WickedSubscriptionCreateInfo): Promise<WickedSubscription>;
export function createSubscription(appId: string, subsCreateInfo: WickedSubscriptionCreateInfo, callback: Callback<WickedSubscription>);
export function createSubscription(appId: string, subsCreateInfo: WickedSubscriptionCreateInfo, callback?: Callback<WickedSubscription>) {
return createSubscriptionAs(appId, subsCreateInfo, null, callback);
}
export function createSubscriptionAs(appId: string, subsCreateInfo: WickedSubscriptionCreateInfo, asUserId: string): Promise<WickedSubscription>;
export function createSubscriptionAs(appId: string, subsCreateInfo: WickedSubscriptionCreateInfo, asUserId: string, callback: Callback<WickedSubscription>);
export function createSubscriptionAs(appId: string, subsCreateInfo: WickedSubscriptionCreateInfo, asUserId: string, callback?: Callback<WickedSubscription>) {
return apiPost(`applications/${appId}/subscriptions`, subsCreateInfo, asUserId, callback);
}
/**
* Retrieve a specific application API subscription.
*
* @param appId ID of application to retrieve subscription for
* @param apiId ID of API to which the subscription applies
* @param callback
*/
export function getSubscription(appId: string, apiId: string): Promise<WickedSubscription>;
export function getSubscription(appId: string, apiId: string, callback: Callback<WickedSubscription>);
export function getSubscription(appId: string, apiId: string, callback?: Callback<WickedSubscription>) {
return getSubscriptionAs(appId, apiId, null, callback);
}
export function getSubscriptionAs(appId: string, apiId: string, asUserId: string): Promise<WickedSubscription>;
export function getSubscriptionAs(appId: string, apiId: string, asUserId: string, callback: Callback<WickedSubscription>);
export function getSubscriptionAs(appId: string, apiId: string, asUserId: string, callback?: Callback<WickedSubscription>) {
return apiGet(`applications/${appId}/subscriptions/${apiId}`, asUserId, callback);
}
/**
* Patch a subscription. This function is only used for approval workflows: Use this
* to patch the subscription to be approved.
*
* @param appId ID of application of which to patch the subscription
* @param apiId ID of API
* @param patchInfo Patch information (see type)
* @param callback
*/
export function patchSubscription(appId: string, apiId: string, patchInfo: WickedSubscriptionPatchInfo): Promise<WickedSubscription>;
export function patchSubscription(appId: string, apiId: string, patchInfo: WickedSubscriptionPatchInfo, callback: Callback<WickedSubscription>);
export function patchSubscription(appId: string, apiId: string, patchInfo: WickedSubscriptionPatchInfo, callback?: Callback<WickedSubscription>) {
return patchSubscriptionAs(appId, apiId, patchInfo, null, callback);
}
export function patchSubscriptionAs(appId: string, apiId: string, patchInfo: WickedSubscriptionPatchInfo, asUserId: string): Promise<WickedSubscription>;
export function patchSubscriptionAs(appId: string, apiId: string, patchInfo: WickedSubscriptionPatchInfo, asUserId: string, callback: Callback<WickedSubscription>);
export function patchSubscriptionAs(appId: string, apiId: string, patchInfo: WickedSubscriptionPatchInfo, asUserId: string, callback?: Callback<WickedSubscription>) {
return apiPatch(`applications/${appId}/subscriptions/${apiId}`, patchInfo, asUserId, callback);
}
/**
* Deletes a subscription to an API for an application.
*
* @param appId ID of application to delete the subscription for
* @param apiId ID of API to delete subscription for
*/
export function deleteSubscription(appId: string, apiId: string): Promise<any>;
export function deleteSubscription(appId: string, apiId: string, callback: ErrorCallback);
export function deleteSubscription(appId: string, apiId: string, callback?: ErrorCallback) {
return deleteSubscriptionAs(appId, apiId, null, callback);
}
export function deleteSubscriptionAs(appId: string, apiId: string, asUserId: string): Promise<any>;
export function deleteSubscriptionAs(appId: string, apiId: string, asUserId: string, callback: ErrorCallback);
export function deleteSubscriptionAs(appId: string, apiId: string, asUserId: string, callback?: ErrorCallback) {
return apiDelete(`applications/${appId}/subscriptions/${apiId}`, asUserId, callback);
}
// APPROVALS
/**
* Retrieve a list of all pending subscription approvals.
*
* @param callback
*/
export function getApprovals(): Promise<WickedApproval[]>;
export function getApprovals(callback: Callback<WickedApproval[]>);
export function getApprovals(callback?: Callback<WickedApproval[]>) {
return getApprovalsAs(null, callback);
}
export function getApprovalsAs(asUserId: string): Promise<WickedApproval[]>;
export function getApprovalsAs(asUserId: string, callback: Callback<WickedApproval[]>);
export function getApprovalsAs(asUserId: string, callback?: Callback<WickedApproval[]>) {
return apiGet('approvals', asUserId, callback);
}
/**
* Retrieve a specific approval request by ID.
*
* @param approvalId ID of approval to retrieve
* @param callback
*/
export function getApproval(approvalId: string): Promise<WickedApproval>;
export function getApproval(approvalId: string, callback: Callback<WickedApproval>);
export function getApproval(approvalId: string, callback?: Callback<WickedApproval>) {
return getApprovalAs(approvalId, null, callback);
}
export function getApprovalAs(approvalId: string, asUserId: string): Promise<WickedApproval>;
export function getApprovalAs(approvalId: string, asUserId: string, callback: Callback<WickedApproval>);
export function getApprovalAs(approvalId: string, asUserId: string, callback?: Callback<WickedApproval>) {
return apiGet(`approvals/${approvalId}`, asUserId, callback);
}
// VERIFICATIONS
/**
* Creates a verification record; depending on the type of the verification record, this may trigger
* certain workflows, such as the "lost password" or "verify email address" workflow, given that the
* wicked mailer is correctly configured and deployed.
*
* @param verification Verification information to create a verification record for
* @param callback
*/
export function createVerification(verification: WickedVerification): Promise<any>;
export function createVerification(verification: WickedVerification, callback: ErrorCallback);
export function createVerification(verification: WickedVerification, callback?: ErrorCallback) {
return createVerificationAs(verification, null, callback);
}
export function createVerificationAs(verification: WickedVerification, asUserId: string): Promise<any>;
export function createVerificationAs(verification: WickedVerification, asUserId: string, callback: ErrorCallback);
export function createVerificationAs(verification: WickedVerification, asUserId: string, callback?: ErrorCallback) {
return apiPost('verifications', verification, asUserId, callback);
}
/**
* Retrieve all pending verifications.
*
* @param callback
*/
export function getVerifications(): Promise<WickedVerification[]>;
export function getVerifications(callback: Callback<WickedVerification[]>);
export function getVerifications(callback?: Callback<WickedVerification[]>) {
return getVerificationsAs(null, callback);
}
export function getVerificationsAs(asUserId: string): Promise<WickedVerification[]>;
export function getVerificationsAs(asUserId: string, callback: Callback<WickedVerification[]>);
export function getVerificationsAs(asUserId: string, callback?: Callback<WickedVerification[]>) {
return apiGet('verificaations', asUserId, callback);
}
/**
* Retrieve a specific verification by its ID.
*
* @param verificationId ID of verification to retrieve.
* @param callback
*/
export function getVerification(verificationId: string): Promise<WickedVerification>;
export function getVerification(verificationId: string, callback: Callback<WickedVerification>);
export function getVerification(verificationId: string, callback?: Callback<WickedVerification>) {
return getVerificationAs(verificationId, null, callback);
}
export function getVerificationAs(verificationId: string, asUserId: string): Promise<WickedVerification>;
export function getVerificationAs(verificationId: string, asUserId: string, callback: Callback<WickedVerification>);
export function getVerificationAs(verificationId: string, asUserId: string, callback?: Callback<WickedVerification>) {
return apiGet(`verifications/${verificationId}`, asUserId, callback);
}
/**
* Delete a verification by ID.
*
* @param verificationId ID of verification to delete.
* @param callback
*/
export function deleteVerification(verificationId: string): Promise<any>;
export function deleteVerification(verificationId: string, callback: ErrorCallback);
export function deleteVerification(verificationId: string, callback?: ErrorCallback) {
return deleteVerificationAs(verificationId, null, callback);
}
export function deleteVerificationAs(verificationId: string, asUserId: string): Promise<any>;
export function deleteVerificationAs(verificationId: string, asUserId: string, callback: ErrorCallback);
export function deleteVerificationAs(verificationId: string, asUserId: string, callback?: ErrorCallback) {
return apiDelete(`verifications/${verificationId}`, asUserId, callback);
}
// SYSTEM HEALTH
export function getSystemHealth(): Promise<WickedComponentHealth[]>;
export function getSystemHealth(callback: Callback<WickedComponentHealth[]>);
export function getSystemHealth(callback?: Callback<WickedComponentHealth[]>) {
return getSystemHealthAs(null, callback);
}
export function getSystemHealthAs(asUserId: string): Promise<WickedComponentHealth[]>;
export function getSystemHealthAs(asUserId: string, callback: Callback<WickedComponentHealth[]>);
export function getSystemHealthAs(asUserId: string, callback?: Callback<WickedComponentHealth[]>) {
return apiGet('systemhealth', asUserId, callback);
}
// TEMPLATES
export function getChatbotTemplates(): Promise<WickedChatbotTemplates>;
export function getChatbotTemplates(callback: Callback<WickedChatbotTemplates>);
export function getChatbotTemplates(callback?: Callback<WickedChatbotTemplates>) {
return getChatbotTemplatesAs(null, callback);
}
export function getChatbotTemplatesAs(asUserId: string): Promise<WickedChatbotTemplates>;
export function getChatbotTemplatesAs(asUserId: string, callback: Callback<WickedChatbotTemplates>);
export function getChatbotTemplatesAs(asUserId: string, callback?: Callback<WickedChatbotTemplates>) {
return apiGet('templates/chatbot', asUserId, callback);
}
export function getEmailTemplate(templateId: WickedEmailTemplateType): Promise<string>;
export function getEmailTemplate(templateId: WickedEmailTemplateType, callback: Callback<string>);
export function getEmailTemplate(templateId: WickedEmailTemplateType, callback?: Callback<string>) {
return getEmailTemplateAs(templateId, null, callback);
}
export function getEmailTemplateAs(templateId: WickedEmailTemplateType, asUserId: string): Promise<string>;
export function getEmailTemplateAs(templateId: WickedEmailTemplateType, asUserId: string, callback: Callback<string>);
export function getEmailTemplateAs(templateId: WickedEmailTemplateType, asUserId: string, callback?: Callback<string>) {
return apiGet(`templates/email/${templateId}`, asUserId, callback);
}
// AUTH-SERVERS
/**
* Retrieve a string list of registered authorization servers. This just returns a list of names, to
* get further information, use getAuthServer().
* @param callback
*/
export function getAuthServerNames(): Promise<string[]>;
export function getAuthServerNames(callback: Callback<string[]>);
export function getAuthServerNames(callback?: Callback<string[]>) {
return getAuthServerNamesAs(null, callback);
}
export function getAuthServerNamesAs(asUserId: string): Promise<string[]>;
export function getAuthServerNamesAs(asUserId: string, callback: Callback<string[]>);
export function getAuthServerNamesAs(asUserId: string, callback?: Callback<string[]>) {
return apiGet('auth-servers', asUserId, callback);
}
/**
* Retrieve information on a specific authorization server.
*
* @param serverId ID of authorization server to retrieve information on.
* @param callback
*/
export function getAuthServer(serverId: string): Promise<WickedAuthServer>;
export function getAuthServer(serverId: string, callback: Callback<WickedAuthServer>);
export function getAuthServer(serverId: string, callback?: Callback<WickedAuthServer>) {
return getAuthServerAs(serverId, null, callback);
}
export function getAuthServerAs(serverId: string, asUserId: string): Promise<WickedAuthServer>;
export function getAuthServerAs(serverId: string, asUserId: string, callback: Callback<WickedAuthServer>);
export function getAuthServerAs(serverId: string, asUserId: string, callback?: Callback<WickedAuthServer>) {
return apiGet(`auth-servers/${serverId}`, asUserId, callback);
}
// WEBHOOKS
/**
* Retrieve a list of all currently registered webhook listeners.
*
* @param callback
*/
export function getWebhookListeners(): Promise<WickedWebhookListener[]>;
export function getWebhookListeners(callback: Callback<WickedWebhookListener[]>);
export function getWebhookListeners(callback?: Callback<WickedWebhookListener[]>) {
return getWebhookListenersAs(null, callback);
}
export function getWebhookListenersAs(asUserId: string): Promise<WickedWebhookListener[]>;
export function getWebhookListenersAs(asUserId: string, callback: Callback<WickedWebhookListener[]>);
export function getWebhookListenersAs(asUserId: string, callback?: Callback<WickedWebhookListener[]>) {
return apiGet('webhooks/listeners', asUserId, callback);
}
/**
* Insert or update data of a specific webhook listener. After upserting the information of
* a new webhook listener, the wicked API will start to accumulate events for this webhook
* listener. These events can be retrieved using `getWebhookEvents` and deleted via
* `deleteWebhookEvents`.
*
* @param listenerId ID of listener to insert or update
* @param listener Data of listener to insert or update
* @param callback
*/
export function upsertWebhookListener(listenerId: string, listener: WickedWebhookListener): Promise<any>;
export function upsertWebhookListener(listenerId: string, listener: WickedWebhookListener, callback: ErrorCallback);
export function upsertWebhookListener(listenerId: string, listener: WickedWebhookListener, callback?: ErrorCallback) {
return upsertWebhookListenerAs(listenerId, listener, null, callback);
}
export function upsertWebhookListenerAs(listenerId: string, listener: WickedWebhookListener, asUserId: string): Promise<any>;
export function upsertWebhookListenerAs(listenerId: string, listener: WickedWebhookListener, asUserId: string, callback: ErrorCallback);
export function upsertWebhookListenerAs(listenerId: string, listener: WickedWebhookListener, asUserId: string, callback?: ErrorCallback) {
return apiPut(`webhooks/listeners/${listenerId}`, listener, asUserId, callback);
}
/**
* Delete a specific webhook listener.
*
* @param listenerId ID of webhook listener to delete
* @param callback
*/
export function deleteWebhookListener(listenerId: string): Promise<any>;
export function deleteWebhookListener(listenerId: string, callback: ErrorCallback);
export function deleteWebhookListener(listenerId: string, callback?: ErrorCallback) {
return deleteWebhookListenerAs(listenerId, null, callback);
}
export function deleteWebhookListenerAs(listenerId: string, asUserId: string): Promise<any>;
export function deleteWebhookListenerAs(listenerId: string, asUserId: string, callback: ErrorCallback);
export function deleteWebhookListenerAs(listenerId: string, asUserId: string, callback?: ErrorCallback) {
return apiDelete(`webhooks/listeners/${listenerId}`, asUserId, callback);
}
/**
* Retrieve all pending webhook events for a specific webhook listener. This operation is idempotent.
* To delete the webhook events, subsequently call deleteWebhookEvent.
*
* @param listenerId ID of webhook listener to retrieve pending events for
* @param callback
*/
export function getWebhookEvents(listenerId: string): Promise<WickedEvent[]>;
export function getWebhookEvents(listenerId: string, callback: Callback<WickedEvent[]>);
export function getWebhookEvents(listenerId: string, callback?: Callback<WickedEvent[]>) {
return getWebhookEventsAs(listenerId, null, callback);
}
export function getWebhookEventsAs(listenerId: string, asUserId: string): Promise<WickedEvent[]>;
export function getWebhookEventsAs(listenerId: string, asUserId: string, callback: Callback<WickedEvent[]>);
export function getWebhookEventsAs(listenerId: string, asUserId: string, callback?: Callback<WickedEvent[]>) {
return apiGet(`webhooks/events/${listenerId}`, asUserId, callback);
}
/**
* Flush/delete all pending webhook events for a specific webhook listener.
*
* @param listenerId ID of webhook listener to flush all events for.
* @param callback
*/
export function flushWebhookEvents(listenerId: string): Promise<any>;
export function flushWebhookEvents(listenerId: string, callback: ErrorCallback);
export function flushWebhookEvents(listenerId: string, callback?: ErrorCallback) {
return flushWebhookEventsAs(listenerId, null, callback);
}
export function flushWebhookEventsAs(listenerId: string, asUserId: string): Promise<any>;
export function flushWebhookEventsAs(listenerId: string, asUserId: string, callback: ErrorCallback);
export function flushWebhookEventsAs(listenerId: string, asUserId: string, callback?: ErrorCallback) {
return apiDelete(`webhooks/events/${listenerId}`, asUserId, callback);
}
/**
* Delete a specific webhook event for a specific webhook listener from the event queue.
*
* @param listenerId ID of webhook listener to delete an event for
* @param eventId ID of event to delete
* @param callback
*/
export function deleteWebhookEvent(listenerId: string, eventId: string): Promise<any>;
export function deleteWebhookEvent(listenerId: string, eventId: string, callback: ErrorCallback);
export function deleteWebhookEvent(listenerId: string, eventId: string, callback?: ErrorCallback) {
return deleteWebhookEventAs(listenerId, eventId, null, callback);
}
export function deleteWebhookEventAs(listenerId: string, eventId: string, asUserId: string): Promise<any>;
export function deleteWebhookEventAs(listenerId: string, eventId: string, asUserId: string, callback: ErrorCallback);
export function deleteWebhookEventAs(listenerId: string, eventId: string, asUserId: string, callback?: ErrorCallback) {
return apiDelete(`webhooks/events/${listenerId}/${eventId}`, asUserId, callback);
}
// REGISTRATION POOLS
/**
* Retrieve a map of registration pools and registration pool information.
*
* @param callback
*/
export function getRegistrationPools(): Promise<WickedPoolMap>;
export function getRegistrationPools(callback: Callback<WickedPoolMap>);
export function getRegistrationPools(callback?: Callback<WickedPoolMap>) {
return getRegistrationPoolsAs(null, callback);
}
export function getRegistrationPoolsAs(asUserId: string): Promise<WickedPoolMap>;
export function getRegistrationPoolsAs(asUserId: string, callback: Callback<WickedPoolMap>);
export function getRegistrationPoolsAs(asUserId: string, callback?: Callback<WickedPoolMap>) {
return apiGet('pools', asUserId, callback);
}
/**
* Retrieve information on a specific registration pool.
*
* @param poolId ID of pool to retrieve information on
* @param callback
*/
export function getRegistrationPool(poolId: string): Promise<WickedPool>;
export function getRegistrationPool(poolId: string, callback: Callback<WickedPool>);
export function getRegistrationPool(poolId: string, callback?: Callback<WickedPool>) {
return getRegistrationPoolAs(poolId, null, callback);
}
export function getRegistrationPoolAs(poolId: string, asUserId: string): Promise<WickedPool>;
export function getRegistrationPoolAs(poolId: string, asUserId: string, callback: Callback<WickedPool>);
export function getRegistrationPoolAs(poolId: string, asUserId: string, callback?: Callback<WickedPool>) {
return apiGet(`pools/${poolId}`, asUserId, callback);
}
// NAMESPACES
/**
* Retrieve a collection of namespaces for a given registration pool (`poolId`). **Note**: The registration pool
* must have the `requireNamespace` option set for the namespace functions to be valid to call.
*
* @param poolId ID of pool to retrieve namespaces for
* @param options Get retrieval options (paging, filtering)
* @param callback
*/
export function getPoolNamespaces(poolId: string, options: WickedGetCollectionOptions): Promise<WickedCollection<WickedNamespace>>;
export function getPoolNamespaces(poolId: string, options: WickedGetCollectionOptions, callback: Callback<WickedCollection<WickedNamespace>>);
export function getPoolNamespaces(poolId: string, options: WickedGetCollectionOptions, callback?: Callback<WickedCollection<WickedNamespace>>) {
return getPoolNamespacesAs(poolId, options, null, callback);
}
export function getPoolNamespacesAs(poolId: string, options: WickedGetCollectionOptions, asUserId: string): Promise<WickedCollection<WickedNamespace>>;
export function getPoolNamespacesAs(poolId: string, options: WickedGetCollectionOptions, asUserId: string, callback: Callback<WickedCollection<WickedNamespace>>);
export function getPoolNamespacesAs(poolId: string, options: WickedGetCollectionOptions, asUserId: string, callback?: Callback<WickedCollection<WickedNamespace>>) {
const o = implementation.validateGetCollectionOptions(options);
const url = implementation.buildUrl(`pools/${poolId}/namespaces`, options);
return apiGet(url, asUserId, callback);
}
/**
* Retrieve information on a specific namespace of a specific registration pool. Namespaces are usually
* mapped to things like "tenants", so the description of a namespace can be a tenant name or similar.
*
* @param poolId ID of pool to retrieve a namespace for
* @param namespaceId ID of namespace to retrieve
* @param callback
*/
export function getPoolNamespace(poolId: string, namespaceId: string): Promise<WickedNamespace>;
export function getPoolNamespace(poolId: string, namespaceId: string, callback: Callback<WickedNamespace>);
export function getPoolNamespace(poolId: string, namespaceId: string, callback?: Callback<WickedNamespace>) {
return getPoolNamespaceAs(poolId, namespaceId, null, callback);
}
export function getPoolNamespaceAs(poolId: string, namespaceId: string, asUserId: string): Promise<WickedNamespace>;
export function getPoolNamespaceAs(poolId: string, namespaceId: string, asUserId: string, callback: Callback<WickedNamespace>);
export function getPoolNamespaceAs(poolId: string, namespaceId: string, asUserId: string, callback?: Callback<WickedNamespace>) {
return apiGet(`pools/${poolId}/namespaces/${namespaceId}`, asUserId, callback);
}
/**
* Upsert a namespace in a specific registration pool. In order to create registrations for a specific
* namespace, this function has to have been called for the namespace which is to be used.
*
* @param poolId ID of pool to which the namespace to upsert belongs
* @param namespaceId Id of namespace to upsert
* @param namespaceInfo New namespace data to store for this namespace
* @param callback
*/
export function upsertPoolNamespace(poolId: string, namespaceId: string, namespaceInfo: WickedNamespace): Promise<any>;
export function upsertPoolNamespace(poolId: string, namespaceId: string, namespaceInfo: WickedNamespace, callback: ErrorCallback);
export function upsertPoolNamespace(poolId: string, namespaceId: string, namespaceInfo: WickedNamespace, callback?: ErrorCallback) {
return upsertPoolNamespaceAs(poolId, namespaceId, namespaceInfo, null, callback);
}
export function upsertPoolNamespaceAs(poolId: string, namespaceId: string, namespaceInfo: WickedNamespace, asUserId: string): Promise<any>;
export function upsertPoolNamespaceAs(poolId: string, namespaceId: string, namespaceInfo: WickedNamespace, asUserId: string, callback: ErrorCallback);
export function upsertPoolNamespaceAs(poolId: string, namespaceId: string, namespaceInfo: WickedNamespace, asUserId: string, callback?: ErrorCallback) {
return apiPut(`pools/${poolId}/namespaces/${namespaceId}`, namespaceInfo, asUserId, callback);
}
/**
* Delete a registration pool namespace. Subsequently, it cannot be used to create or enumerate
* registrations.
*
* @param poolId ID of pool to which the namespace to delete belongs
* @param namespaceId ID of namespace to delete
* @param callback
*/
export function deletePoolNamespace(poolId: string, namespaceId: string): Promise<any>;
export function deletePoolNamespace(poolId: string, namespaceId: string, callback: ErrorCallback);
export function deletePoolNamespace(poolId: string, namespaceId: string, callback?: ErrorCallback) {
return deletePoolNamespaceAs(poolId, namespaceId, null, callback);
}
export function deletePoolNamespaceAs(poolId: string, namespaceId: string, asUserId: string): Promise<any>;
export function deletePoolNamespaceAs(poolId: string, namespaceId: string, asUserId: string, callback: ErrorCallback);
export function deletePoolNamespaceAs(poolId: string, namespaceId: string, asUserId: string, callback?: ErrorCallback) {
return apiDelete(`pools/${poolId}/namespaces/${namespaceId}`, asUserId, callback);
}
// REGISTRATIONS
/**
* Retrieve all registrations for a specific registration pool; use the `namespace` filtering inside the `options`
* parameter to retrieve registrations for specific namespaces. Please note that the `namespace` option is required
* for registration pools which requires namespaces, and is forbidden for registration pools which do not require
* namespaces.
*
* @param poolId ID of registration pool to retrieve registrations for
* @param options Get options, e.g. namespace filtering, generic filtering and paging
* @param callback
*/
export function getPoolRegistrations(poolId: string, options: WickedGetRegistrationOptions): Promise<WickedCollection<WickedRegistration>>;
export function getPoolRegistrations(poolId: string, options: WickedGetRegistrationOptions, callback: Callback<WickedCollection<WickedRegistration>>);
export function getPoolRegistrations(poolId: string, options: WickedGetRegistrationOptions, callback?: Callback<WickedCollection<WickedRegistration>>) {
return getPoolRegistrationsAs(poolId, options, null, callback);
}
export function getPoolRegistrationsAs(poolId: string, options: WickedGetRegistrationOptions, asUserId: string): Promise<WickedCollection<WickedRegistration>>;
export function getPoolRegistrationsAs(poolId: string, options: WickedGetRegistrationOptions, asUserId: string, callback: Callback<WickedCollection<WickedRegistration>>);
export function getPoolRegistrationsAs(poolId: string, options: WickedGetRegistrationOptions, asUserId: string, callback?: Callback<WickedCollection<WickedRegistration>>) {
const o = implementation.validateGetCollectionOptions(options) as WickedGetRegistrationOptions;
if (options.namespace)
o.namespace = options.namespace;
const url = implementation.buildUrl(`registrations/pools/${poolId}`, o);
return apiGet(url, asUserId, callback);
}
/**
* Retrieve a collection of user registrations for a specific registration pool id. This can
* be a collection of 0 or more registration objects; it's valid for a user to have multiple
* registrations for a single registration pool in case the registration pool requires
* namespaces (but only one registration per namespace). In case the registration pool does not
* require/support namespaces, the result will be an array of eiher 0 or 1 elements.
*
* @param poolId ID of pool for which to retrieve a user's registrations
* @param userId ID of user to retrieve registrations for
* @param callback
*/
export function getUserRegistrations(poolId: string, userId: string): Promise<WickedCollection<WickedRegistration>>;
export function getUserRegistrations(poolId: string, userId: string, callback: Callback<WickedCollection<WickedRegistration>>);
export function getUserRegistrations(poolId: string, userId: string, callback?: Callback<WickedCollection<WickedRegistration>>) {
return getUserRegistrationsAs(poolId, userId, null, callback);
}
export function getUserRegistrationsAs(poolId: string, userId: string, asUserId: string): Promise<WickedCollection<WickedRegistration>>;
export function getUserRegistrationsAs(poolId: string, userId: string, asUserId: string, callback: Callback<WickedCollection<WickedRegistration>>);
export function getUserRegistrationsAs(poolId: string, userId: string, asUserId: string, callback?: Callback<WickedCollection<WickedRegistration>>) {
return apiGet(`registrations/pools/${poolId}/users/${userId}`, asUserId, callback);
}
/**
* Upsert a user registration. Note that if the registration pool requires the use of namespaces
* the `userRegistration` object **must** contain a `namespace` property. Vice versa, if the registration
* pool does not require/support namespaces, the `userRegistration` object must **not** contain
* a `namespace` property.
*
* @param poolId ID of pool to upsert a user registration for
* @param userId ID of user to upsert a registration for
* @param userRegistration User registration data.
* @param callback
*/
export function upsertUserRegistration(poolId: string, userId: string, userRegistration: WickedRegistration): Promise<any>;
export function upsertUserRegistration(poolId: string, userId: string, userRegistration: WickedRegistration, callback: ErrorCallback);
export function upsertUserRegistration(poolId: string, userId: string, userRegistration: WickedRegistration, callback?: ErrorCallback) {
return upsertUserRegistrationAs(poolId, userId, userRegistration, null, callback);
}
export function upsertUserRegistrationAs(poolId: string, userId: string, userRegistration: WickedRegistration, asUserId: string): Promise<any>;
export function upsertUserRegistrationAs(poolId: string, userId: string, userRegistration: WickedRegistration, asUserId: string, callback: ErrorCallback);
export function upsertUserRegistrationAs(poolId: string, userId: string, userRegistration: WickedRegistration, asUserId: string, callback?: ErrorCallback) {
return apiPut(`registrations/pools/${poolId}/users/${userId}`, userRegistration, asUserId, callback);
}
/**
* Delete a specific user registration for a given registration pool (and optionally namespace).
*
* @param poolId ID of registration pool to delete a user registration from
* @param userId ID of user to delete a registration for
* @param namespaceId Namespace to delete registration for; for registration pools not requiring a namespace, this must be `null`, otherwise it must be specified
* @param callback
*/
export function deleteUserRegistration(poolId: string, userId: string, namespaceId: string): Promise<any>;
export function deleteUserRegistration(poolId: string, userId: string, namespaceId: string, callback: ErrorCallback);
export function deleteUserRegistration(poolId: string, userId: string, namespaceId: string, callback?: ErrorCallback) {
return deleteUserRegistrationAs(poolId, userId, namespaceId, null, callback);
}
export function deleteUserRegistrationAs(poolId: string, userId: string, namespaceId: string, asUserId: string): Promise<any>;
export function deleteUserRegistrationAs(poolId: string, userId: string, namespaceId: string, asUserId: string, callback: ErrorCallback);
export function deleteUserRegistrationAs(poolId: string, userId: string, namespaceId: string, asUserId: string, callback?: ErrorCallback) {
const o = {} as any;
if (namespaceId)
o.namespace = namespaceId;
const url = implementation.buildUrl(`registrations/pools/${poolId}/users/${userId}`, o);
return apiDelete(url, asUserId, callback);
}
/**
* Retrieve a map of all registrations, across all registration pools, a user has.
*
* @param userId ID of user to retrieve all registrations for.
* @param callback
*/
export function getAllUserRegistrations(userId: string): Promise<WickedRegistrationMap>;
export function getAllUserRegistrations(userId: string, callback: Callback<WickedRegistrationMap>);
export function getAllUserRegistrations(userId: string, callback?: Callback<WickedRegistrationMap>) {
return getAllUserRegistrationsAs(userId, null, callback);
}
export function getAllUserRegistrationsAs(userId: string, asUserId: string): Promise<WickedRegistrationMap>;
export function getAllUserRegistrationsAs(userId: string, asUserId: string, callback: Callback<WickedRegistrationMap>);
export function getAllUserRegistrationsAs(userId: string, asUserId: string, callback?: Callback<WickedRegistrationMap>) {
return apiGet(`registrations/users/${userId}`, asUserId, callback);
}
// GRANTS
/**
* Retrieve all grants a user has allowed to any application for accessing any API.
*
* @param userId ID of user to retrieve grants for
* @param options Get options (filtering, paging,...)
* @param callback
*/
export function getUserGrants(userId: string, options: WickedGetOptions): Promise<WickedCollection<WickedGrant>>;
export function getUserGrants(userId: string, options: WickedGetOptions, callback: Callback<WickedCollection<WickedGrant>>);
export function getUserGrants(userId: string, options: WickedGetOptions, callback?: Callback<WickedCollection<WickedGrant>>) {
return getUserGrantsAs(userId, options, null, callback);
}
export function getUserGrantsAs(userId: string, options: WickedGetOptions, asUserId: string): Promise<WickedCollection<WickedGrant>>;
export function getUserGrantsAs(userId: string, options: WickedGetOptions, asUserId: string, callback: Callback<WickedCollection<WickedGrant>>);
export function getUserGrantsAs(userId: string, options: WickedGetOptions, asUserId: string, callback?: Callback<WickedCollection<WickedGrant>>) {
const o = implementation.validateGetOptions(options);
const url = implementation.buildUrl(`grants/${userId}`, o);
return apiGet(url, asUserId, callback);
}
/**
* Delete all grants a user has made to any application to access APIs on behalf of himself. After calling this
* method, any non-trusted application will need to ask permission to the user again to access the user's data on
* behalf of the user.
*
* @param userId ID of user to delete all grants for.
* @param callback
*/
export function deleteAllUserGrants(userId: string): Promise<any>;
export function deleteAllUserGrants(userId: string, callback: ErrorCallback);
export function deleteAllUserGrants(userId: string, callback?: ErrorCallback) {
return deleteAllUserGrantsAs(userId, null, callback);
}
export function deleteAllUserGrantsAs(userId: string, asUserId: string): Promise<any>;
export function deleteAllUserGrantsAs(userId: string, asUserId: string, callback: ErrorCallback);
export function deleteAllUserGrantsAs(userId: string, asUserId: string, callback?: ErrorCallback) {
return apiDelete(`grants/${userId}`, asUserId, callback);
}
/**
* Retrieve a specific access grant for a specific, user, application and API.
*
* @param userId ID of user to retrieve a grant for
* @param applicationId ID of application to retrieve a grant for
* @param apiId ID of API for which to retrieve the grant
* @param callback
*/
export function getUserGrant(userId: string, applicationId: string, apiId: string): Promise<WickedGrant>;
export function getUserGrant(userId: string, applicationId: string, apiId: string, callback: Callback<WickedGrant>);
export function getUserGrant(userId: string, applicationId: string, apiId: string, callback?: Callback<WickedGrant>) {
return getUserGrantAs(userId, applicationId, apiId, null, callback);
}
export function getUserGrantAs(userId: string, applicationId: string, apiId: string, asUserId: string): Promise<WickedGrant>;
export function getUserGrantAs(userId: string, applicationId: string, apiId: string, asUserId: string, callback: Callback<WickedGrant>);
export function getUserGrantAs(userId: string, applicationId: string, apiId: string, asUserId: string, callback?: Callback<WickedGrant>) {
return apiGet(`grants/${userId}/applications/${applicationId}/apis/${apiId}`, asUserId, callback);
}
/**
* Upsert a grant information for a user, so that a given application can access the given API
* with a specific set of scopes on the user's behalf. This method is foremost used automatically
* by the Authorization Server after it has asked the user whether a certain application is allowed
* to access the user's data on the user's behalf.
*
* @param userId ID of user to upsert a grant for
* @param applicationId ID of application to upsert a grant for
* @param apiId ID of API to upsert a grant for
* @param grantInfo Grant information to store
* @param callback
*/
export function upsertUserGrant(userId: string, applicationId: string, apiId: string, grantInfo: WickedGrant): Promise<any>;
export function upsertUserGrant(userId: string, applicationId: string, apiId: string, grantInfo: WickedGrant, callback: ErrorCallback);
export function upsertUserGrant(userId: string, applicationId: string, apiId: string, grantInfo: WickedGrant, callback?: ErrorCallback) {
return upsertUserGrantAs(userId, applicationId, apiId, grantInfo, null, callback);
}
export function upsertUserGrantAs(userId: string, applicationId: string, apiId: string, grantInfo: WickedGrant, asUserId: string): Promise<any>;
export function upsertUserGrantAs(userId: string, applicationId: string, apiId: string, grantInfo: WickedGrant, asUserId: string, callback: ErrorCallback);
export function upsertUserGrantAs(userId: string, applicationId: string, apiId: string, grantInfo: WickedGrant, asUserId: string, callback?: ErrorCallback) {
return apiPut(`grants/${userId}/applications/${applicationId}/apis/${apiId}`, grantInfo, asUserId, callback);
}
/**
* Delete a user's grant of access to a specific application and API.
*
* @param userId ID of user of which to delete a grant
* @param applicationId ID of application of which to delete a grant
* @param apiId ID of API to delete a grant for
* @param callback
*/
export function deleteUserGrant(userId: string, applicationId: string, apiId: string): Promise<any>;
export function deleteUserGrant(userId: string, applicationId: string, apiId: string, callback: ErrorCallback);
export function deleteUserGrant(userId: string, applicationId: string, apiId: string, callback?: ErrorCallback) {
return deleteUserGrantAs(userId, applicationId, apiId, null, callback);
}
export function deleteUserGrantAs(userId: string, applicationId: string, apiId: string, asUserId: string): Promise<any>;
export function deleteUserGrantAs(userId: string, applicationId: string, apiId: string, asUserId: string, callback: ErrorCallback);
export function deleteUserGrantAs(userId: string, applicationId: string, apiId: string, asUserId: string, callback?: ErrorCallback) {
return apiDelete(`grants/${userId}/applications/${applicationId}/apis/${apiId}`, asUserId, callback);
}
// ======= CORRELATION ID HANDLER =======
/**
* Express middleware implementation of a correlation ID handler; it inserts
* a header `Correlation-Id` if it's not already present and passes it on to the
* wicked API. In case a header is already present, it re-uses the content. The
* usual format of the correlation ID is a UUID.
*
* Usage: `app.use(wicked.correlationIdHandler());`
*/
export function correlationIdHandler(): ExpressHandler {
return function (req, res, next) {
const correlationId = req.get('correlation-id');
if (correlationId) {
debug('Picking up correlation id: ' + correlationId);
req.correlationId = correlationId;
} else {
req.correlationId = uuid.v4();
debug('Creating a new correlation id: ' + req.correlationId);
}
implementation.requestRuntime.correlationId = correlationId;
return next();
};
} | the_stack |
import BigNumber from 'bignumber.js'
import { EthValue } from '@app/core/models'
export enum FormattedNumberUnit {
ETH = 'eth',
GWEI = 'gwei',
WEI = 'wei',
PERCENT = '%',
USD = '$',
B = 'B',
T = 'T',
Q = 'Q',
M = 'M',
K = 'k'
}
export interface FormattedNumber {
value: string
unit?: FormattedNumberUnit
tooltipText?: string
}
/* Constants: */
const SmallUsdBreakpoint = 0.04
const SmallNumberBreakpoint = 0.0000001
const SmallGweiBreakpoint = 0.00001
const OneThousand = 1e3
const TenThousand = 1e4
const HundredThousand = 1e5
const OneMillion = 1e6
const OneBillion = 1e9
const HundredBillion = 1e11
const OneTrillion = 1e12
const OneQuadrillion = 1e15
export class NumberFormatHelper {
/**
* General: Formatted integers
* E.g. Block Number
* Numbers that do not need formating methods
*/
/**
* GROUP I: Formatted integers
* Converts an integer value to a FormattedNumber object, returns value in { billions, trillions, "> 1Q"} if > 1 billion
* @param value: BigNumber
* @return FormattedNumber
*/
public static formatIntegerValue(value: BigNumber, isSmaller = false): FormattedNumber {
/* Case I: value >= 1,000,000,000,000,000 */
if (value.isGreaterThanOrEqualTo(OneQuadrillion)) {
return this.convertToQuadrillion(value)
}
/* Case II: value >= 1,000,000,000,000 */
if (value.isGreaterThanOrEqualTo(OneTrillion)) {
return this.convertToTrillions(value)
}
/* Case III: value >= 1,000,000,000 */
if (value.isGreaterThanOrEqualTo(OneBillion)) {
return this.convertToBillions(value)
}
/* Case: need shorter string for over 1 thousand */
if (isSmaller) {
/* Case IV: value >= 1,000,000 */
if (value.isGreaterThanOrEqualTo(OneMillion)) {
return this.convertToMillions(value)
}
/* Case V: value >= 1,000 */
if (value.isGreaterThanOrEqualTo(OneThousand)) {
return this.convertToThousands(value)
}
}
/* Case IV: value < 1,000,000,000 and !isSmaller */
return { value: value.toFormat() }
}
/**
* GROUP II: Floating point values
* Converts a floating point value to a FormattedNumber object
* Use cases: Token Balances / Quantities / Non Detail page for floating numbers
* @param value BigNumber
* @returns Object FormattedNumber with value as formatted string, unit and tooltipText
*/
public static formatFloatingPointValue(value: BigNumber): FormattedNumber {
const dps = value.decimalPlaces()
/**
* Case I: value === 0
* Return: "0"
*/
if (value.isZero()) {
return { value: '0' }
}
/**
* Case II: value >= 1,000,000,000
* Return: formated integer value with tooltip
*/
if (value.isGreaterThanOrEqualTo(OneBillion)) {
return this.formatIntegerValue(value)
}
/**
* Case III: value >= 1,000,000
* Return: round number and tooltip with full value if there are decimal places
*/
if (value.isGreaterThanOrEqualTo(OneMillion)) {
return this.getRoundNumber(value, 0, dps)
}
/**
* Case IV: value >= 10,000
* Return: a number, rounded to 2 decimal points and tooltip with full value if > 2 decimal places
*/
if (value.isGreaterThanOrEqualTo(TenThousand)) {
return this.getRoundNumber(value, 2, dps)
}
/**
* Case IV: value >= 1
* Return: a number, rounded to 4 decimal points and tooltip with full value if > 4 decimal places
*/
if (value.isGreaterThanOrEqualTo(1)) {
return this.getRoundNumber(value, 4, dps)
}
/**
* Case V: value >= 0.0000001
* Return: a number, rounded up to 7 decimal places and tooltip with full value if > 7 decimal places
*/
if (value.isGreaterThanOrEqualTo(SmallNumberBreakpoint)) {
return this.getRoundNumber(value, 7, dps)
}
/**
* Case V: value < 0.0000001
* Return: string "< 0.0000001" and tooltip with full value
*/
return { value: '< 0.0000001', tooltipText: dps ? value.toFormat() : undefined }
}
/**
* GROUP III: Variable unit ETH values, used in details pages
* Converts a value from wei to a formatted string in an appropriate unit
* @param value BigNumber - must be original wei value (not already converted to Eth)
* @returns Object FormattedNumber with value as formatted string, unit and tooltipText
*/
public static formatVariableUnitEthValue(value: BigNumber): FormattedNumber {
/**
* Case I: value === 0
* Return: "0 ETH"
*/
if (value.isZero()) {
return { value: '0', unit: FormattedNumberUnit.ETH }
} else if (value.isLessThan(TenThousand)) {
/**
* Case II: value < 10,000 wei
* Return: small values in WEI (no conversion) and tooltip with ETH value
*/
return {
value: value.toFormat(),
unit: FormattedNumberUnit.WEI,
tooltipText: `${new EthValue(value).toEthBN().toFixed()}`
}
} else if (value.isLessThan(HundredBillion)) {
/**
* Case III: value < 100 Billion Wei OR value < 100 Gwei
* Return: Gwei value, using Group II
*/
const gweiBN = new EthValue(value).toGweiBN()
return {
value: this.formatFloatingPointValue(gweiBN).value,
unit: FormattedNumberUnit.GWEI,
tooltipText: `${new EthValue(value).toEthBN().toFixed()}`
}
}
const ethBN = new EthValue(value).toEthBN()
const unit = FormattedNumberUnit.ETH
const dps = ethBN.decimalPlaces()
/**
* Case IV: 0.0000001 Eth <= X < 1 Eth
* Return: rounded number to 12 dps
*/
if (ethBN.isLessThan(1)) {
return { ...this.getRoundNumber(ethBN, 12, dps), unit }
}
/**
* Case V: 1 Eth <= X < 100,000 Eth
* Return: rounded number to 6 dps
*/
if (ethBN.isLessThan(HundredThousand)) {
return { ...this.getRoundNumber(ethBN, 6, dps), unit }
}
/**
* Case VI: 100,000 <= X < 1 mill
* Return: rounded number to 4 dps
*/
if (ethBN.isLessThan(OneMillion)) {
return { ...this.getRoundNumber(ethBN, 4, dps), unit }
}
/**
* Case VII: 1 mill <= X < 1 Bill
* Return: rounded number to 0 dps
*/
if (ethBN.isLessThan(OneBillion)) {
return { ...this.getRoundNumber(ethBN, 0, dps), unit }
}
/**
* Case VIII: V >= 1 Billion
* Return: Group I formatted value
*/
return { ...this.formatIntegerValue(ethBN), unit }
}
/**
* GROUP IV: Non-variable ETH values
* Convert a value in WEI to ETH
* @param value: BigNumber (in wei)
* @return FormattedNumber with value converted to ETH and tooltip if maxDecimalPlaces was applied
*/
public static formatNonVariableEthValue(value: BigNumber): FormattedNumber {
/**
* Case I: value === 0
* Return: "0 ETH"
*/
if (value.isZero()) {
return { value: '0', unit: FormattedNumberUnit.ETH }
} else if (value.isLessThan(TenThousand)) {
/**
* Case II: value < 10,000 wei
* Return: small values in WEI (no conversion) and tooltip with ETH value
*/
return {
value: value.toFormat(),
unit: FormattedNumberUnit.WEI,
tooltipText: `${new EthValue(value).toEthBN().toFixed()}`
}
} else if (value.isLessThan(HundredBillion)) {
/**
* Case III: value < 100 Billion Wei OR value < 100 Gwei
* Return: Gwei value, using Group II
*/
const gweiBN = new EthValue(value).toGweiBN()
return {
value: this.formatFloatingPointValue(gweiBN).value,
unit: FormattedNumberUnit.GWEI,
tooltipText: `${new EthValue(value).toEthBN().toFixed()}`
}
}
const ethBN = new EthValue(value).toEthBN()
return { ...this.formatFloatingPointValue(ethBN), unit: FormattedNumberUnit.ETH }
}
/**
* GROUP V: Non-variable GWei values
* Convert a value from WEI to GWEI
* @param value BigNumber (in wei)
* @return FormattedNumber with value in GWei and unit
*/
public static formatNonVariableGWeiValue(value: BigNumber): FormattedNumber {
const gweiBN = new EthValue(value).toGweiBN()
const dps = gweiBN.decimalPlaces()
const unit = FormattedNumberUnit.GWEI
/**
* Case I: value === 0
* Return: "0 ETH"
*/
if (gweiBN.isZero()) {
return { value: '0', unit }
}
/**
* Case II: x < 0.00001
* Return: number in wei and show tooltip with Gwei value
*/
if (gweiBN.isLessThan(SmallGweiBreakpoint)) {
return {
value: value.toFormat(),
unit,
tooltipText: `${gweiBN.toFormat()} ${unit}`
}
}
/**
* Case III: x < 1 mill
* Return: number in Gwei using Group II
*/
if (gweiBN.isLessThan(OneMillion)) {
return { ...this.formatFloatingPointValue(gweiBN), unit, tooltipText: `${new EthValue(value).toEthBN().toFixed()}` }
}
/**
* Case IV: x >= 1 mill
* Return: number in eth and show tooltip with Gwei value
*/
return {
...this.formatNonVariableEthValue(value),
unit,
tooltipText: `${gweiBN.toFixed()} ${unit}`
}
}
/**
* GROUP VI: Percentage values
* Converts a percentage value to a FormattedNumber
* @param value: BigNumber already converted to a percentage e.g. < 100 (expect in special cases)
* @returns Object FormattedNumber with value as formatted string, unit and tooltipText
*/
public static formatPercentageValue(value: BigNumber | number): FormattedNumber {
// Convert to BigNumber if necessary
if (!(value instanceof BigNumber)) {
value = new BigNumber(value)
}
const unit = FormattedNumberUnit.PERCENT
/**
* Case I: value === 0
* Return: "0%"
*/
if (value.isZero()) {
return { value: '0', unit }
}
const isNegative = value.isNegative() // Record whether value is negative
const absoluteValue = value.absoluteValue() // Get Absolute value
const dps = value.decimalPlaces()
/**
* Case II: |value| >= 1000
* Return: >1000 or <-1000 and tooltip
*/
if (absoluteValue.isGreaterThanOrEqualTo(1000)) {
const result = isNegative ? '< -1000' : '> 1000'
return { value: result, unit, tooltipText: `${value.toFormat()}%` }
}
/**
* Case III: |value| >= 100
* Return: whole number and tooltips if has decimal points
*/
if (absoluteValue.isGreaterThanOrEqualTo(100)) {
return { value: value.toFormat(0), unit, tooltipText: dps ? `${value.toFormat()}%` : undefined }
}
/**
* Case IV: |value| >= 0.01
* Return: rounded to 2 decimal points number and tooltip if > 2 decimal points
*/
if (absoluteValue.isGreaterThanOrEqualTo(0.01)) {
return { ...this.getRoundNumber(value, 2, dps), unit, tooltipText: dps > 2 ? `${value.toFormat()}%` : undefined }
}
/**
* Case V: If -0.01 < |value| < 0.01
* Return: '>-0.01' '<0.01'r and tooltip
*/
const result = isNegative ? '> -0.01' : '< 0.01'
return { value: result, unit, tooltipText: `${value.toFormat()}%` }
}
/**
* GROUP VII: USD Values
* Converts a USD value to a FormattedNumber
* @param value: BigNumber
* @returns Object FormattedNumber with value as formatted string, unit and tooltipText
*/
public static formatUsdValue(value: BigNumber): FormattedNumber {
const unit = FormattedNumberUnit.USD
/**
* Case I: value === 0
* Return: "$0.00"
*/
if (value === undefined || value.isZero()) {
return { value: '$0.00', unit }
}
/**
* Case II: value >= 1 Quadrillion
* Return: value converted to Quadrillions"
*/
if (value.isGreaterThanOrEqualTo(OneQuadrillion)) {
const result = this.convertToQuadrillion(value)
return { value: `$${result.value}`, unit, tooltipText: result.tooltipText ? `$${result.tooltipText}` : undefined }
}
/**
* Case II: value >= 1 Trillion
* Return: value converted to trillions"
*/
if (value.isGreaterThanOrEqualTo(OneTrillion)) {
const result = this.convertToTrillions(value)
return { value: `$${result.value}`, unit, tooltipText: result.tooltipText ? `$${result.tooltipText}` : undefined }
}
/**
* Case III: value >= 1 Billion
* Return: value converted to billions"
*/
if (value.isGreaterThanOrEqualTo(OneBillion)) {
const result = this.convertToBillions(value)
return { value: `$${result.value}`, unit, tooltipText: result.tooltipText ? `$${result.tooltipText}` : undefined }
}
/**
* Case IV: value >= 1 Million.
* Return: rounded number and tolltip if has decimal points"
*/
if (value.isGreaterThanOrEqualTo(OneMillion)) {
const result = this.getRoundNumber(value, 0, value.decimalPlaces())
return { value: `$${result.value}`, unit, tooltipText: result.tooltipText ? `$${result.tooltipText}` : undefined }
}
/**
* Case V: value > 0.04
* Return: rounded number up to 2 decimal points and tolltip if > 2 decimal points"
*/
if (value.isGreaterThan(SmallUsdBreakpoint)) {
return { value: `$${value.toFormat(2)}`, unit, tooltipText: value.decimalPlaces() > 2 ? `$${value.toFormat()}` : undefined }
}
/**
* Case VI: 0.00001 <= value <= 0.04
* Return: rounded number up to 5 decimal points and tooltip if > 5 decimal points"
*/
if (value.isGreaterThanOrEqualTo(SmallGweiBreakpoint)) {
const formatted = value.toFormat(Math.min(5, value.decimalPlaces()))
return { value: `$${formatted}`, unit, tooltipText: value.decimalPlaces() > 5 ? `$${value.toFormat()}` : undefined }
}
/**
* Case V: value < 0.0000001
* Return: string "< $0.0000001" and tooltip with full value
*/
return { value: '< $0.0000001', unit, tooltipText: `$${value.toFixed()}` }
}
/* Helper functions */
private static convertToThousands(value: BigNumber): FormattedNumber {
const result = value.dividedBy(OneThousand)
return {
value: `${result.toFormat(Math.min(2, result.decimalPlaces()))}k`,
unit: FormattedNumberUnit.K,
tooltipText: value.toFormat()
}
}
private static convertToMillions(value: BigNumber): FormattedNumber {
const result = value.dividedBy(OneMillion)
return {
value: `${result.toFormat(Math.min(2, result.decimalPlaces()))}M`,
unit: FormattedNumberUnit.M,
tooltipText: value.toFormat()
}
}
private static convertToBillions(value: BigNumber): FormattedNumber {
const result = value.dividedBy(OneBillion)
return {
value: `${result.toFormat(Math.min(3, result.decimalPlaces()))}B`,
unit: FormattedNumberUnit.B,
tooltipText: value.toFormat()
}
}
private static convertToTrillions(value: BigNumber): FormattedNumber {
const result = value.dividedBy(OneTrillion)
return {
value: `${result.toFormat(Math.min(3, result.decimalPlaces()))}T`,
unit: FormattedNumberUnit.T,
tooltipText: value.toFormat()
}
}
private static convertToQuadrillion(value: BigNumber): FormattedNumber {
const result = value.dividedBy(OneQuadrillion)
return { value: '> 1Q', unit: FormattedNumberUnit.Q, tooltipText: value.toFormat() }
}
public static getRoundNumber(value: BigNumber, round: number, dp: number): FormattedNumber {
return { value: value.toFormat(Math.min(round, dp)), tooltipText: dp > round ? value.toFormat() : undefined }
}
} | the_stack |
import { BaseResource } from 'ms-rest-azure';
import { CloudError } from 'ms-rest-azure';
import * as moment from 'moment';
export { BaseResource } from 'ms-rest-azure';
export { CloudError } from 'ms-rest-azure';
/**
* @class
* Initializes a new instance of the ConsistencyPolicy class.
* @constructor
* The consistency policy for the Cosmos DB database account.
*
* @member {string} defaultConsistencyLevel The default consistency level and
* configuration settings of the Cosmos DB account. Possible values include:
* 'Eventual', 'Session', 'BoundedStaleness', 'Strong', 'ConsistentPrefix'
* @member {number} [maxStalenessPrefix] When used with the Bounded Staleness
* consistency level, this value represents the number of stale requests
* tolerated. Accepted range for this value is 1 – 2,147,483,647. Required when
* defaultConsistencyPolicy is set to 'BoundedStaleness'.
* @member {number} [maxIntervalInSeconds] When used with the Bounded Staleness
* consistency level, this value represents the time amount of staleness (in
* seconds) tolerated. Accepted range for this value is 5 - 86400. Required
* when defaultConsistencyPolicy is set to 'BoundedStaleness'.
*/
export interface ConsistencyPolicy {
defaultConsistencyLevel: string;
maxStalenessPrefix?: number;
maxIntervalInSeconds?: number;
}
/**
* @class
* Initializes a new instance of the Capability class.
* @constructor
* Cosmos DB capability object
*
* @member {string} [name] Name of the Cosmos DB capability. For example,
* "name": "EnableCassandra". Current values also include "EnableTable" and
* "EnableGremlin".
*/
export interface Capability {
name?: string;
}
/**
* @class
* Initializes a new instance of the Location class.
* @constructor
* A region in which the Azure Cosmos DB database account is deployed.
*
* @member {string} [id] The unique identifier of the region within the
* database account. Example: <accountName>-<locationName>.
* @member {string} [locationName] The name of the region.
* @member {string} [documentEndpoint] The connection endpoint for the specific
* region. Example:
* https://<accountName>-<locationName>.documents.azure.com:443/
* @member {string} [provisioningState]
* @member {number} [failoverPriority] The failover priority of the region. A
* failover priority of 0 indicates a write region. The maximum value for a
* failover priority = (total number of regions - 1). Failover priority values
* must be unique for each of the regions in which the database account exists.
*/
export interface Location {
readonly id?: string;
locationName?: string;
readonly documentEndpoint?: string;
provisioningState?: string;
failoverPriority?: number;
}
/**
* @class
* Initializes a new instance of the FailoverPolicy class.
* @constructor
* The failover policy for a given region of a database account.
*
* @member {string} [id] The unique identifier of the region in which the
* database account replicates to. Example:
* <accountName>-<locationName>.
* @member {string} [locationName] The name of the region in which the database
* account exists.
* @member {number} [failoverPriority] The failover priority of the region. A
* failover priority of 0 indicates a write region. The maximum value for a
* failover priority = (total number of regions - 1). Failover priority values
* must be unique for each of the regions in which the database account exists.
*/
export interface FailoverPolicy {
readonly id?: string;
locationName?: string;
failoverPriority?: number;
}
/**
* @class
* Initializes a new instance of the VirtualNetworkRule class.
* @constructor
* Virtual Network ACL Rule object
*
* @member {string} [id] Resource ID of a subnet, for example:
* /subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/subnets/{subnetName}.
* @member {boolean} [ignoreMissingVNetServiceEndpoint] Create firewall rule
* before the virtual network has vnet service endpoint enabled.
*/
export interface VirtualNetworkRule {
id?: string;
ignoreMissingVNetServiceEndpoint?: boolean;
}
/**
* @class
* Initializes a new instance of the Resource class.
* @constructor
* A database account resource.
*
* @member {string} [id] The unique resource identifier of the database
* account.
* @member {string} [name] The name of the database account.
* @member {string} [type] The type of Azure resource.
* @member {string} location The location of the resource group to which the
* resource belongs.
* @member {object} [tags]
*/
export interface Resource extends BaseResource {
readonly id?: string;
readonly name?: string;
readonly type?: string;
location: string;
tags?: { [propertyName: string]: string };
}
/**
* @class
* Initializes a new instance of the DatabaseAccount class.
* @constructor
* An Azure Cosmos DB database account.
*
* @member {string} [kind] Indicates the type of database account. This can
* only be set at database account creation. Possible values include:
* 'GlobalDocumentDB', 'MongoDB', 'Parse'. Default value: 'GlobalDocumentDB' .
* @member {string} [provisioningState]
* @member {string} [documentEndpoint] The connection endpoint for the Cosmos
* DB database account.
* @member {string} [databaseAccountOfferType] The offer type for the Cosmos DB
* database account. Default value: Standard. Possible values include:
* 'Standard'
* @member {string} [ipRangeFilter] Cosmos DB Firewall Support: This value
* specifies the set of IP addresses or IP address ranges in CIDR form to be
* included as the allowed list of client IPs for a given database account. IP
* addresses/ranges must be comma separated and must not contain any spaces.
* @member {boolean} [isVirtualNetworkFilterEnabled] Flag to indicate whether
* to enable/disable Virtual Network ACL rules.
* @member {boolean} [enableAutomaticFailover] Enables automatic failover of
* the write region in the rare event that the region is unavailable due to an
* outage. Automatic failover will result in a new write region for the account
* and is chosen based on the failover priorities configured for the account.
* @member {object} [consistencyPolicy] The consistency policy for the Cosmos
* DB database account.
* @member {string} [consistencyPolicy.defaultConsistencyLevel] The default
* consistency level and configuration settings of the Cosmos DB account.
* Possible values include: 'Eventual', 'Session', 'BoundedStaleness',
* 'Strong', 'ConsistentPrefix'
* @member {number} [consistencyPolicy.maxStalenessPrefix] When used with the
* Bounded Staleness consistency level, this value represents the number of
* stale requests tolerated. Accepted range for this value is 1 –
* 2,147,483,647. Required when defaultConsistencyPolicy is set to
* 'BoundedStaleness'.
* @member {number} [consistencyPolicy.maxIntervalInSeconds] When used with the
* Bounded Staleness consistency level, this value represents the time amount
* of staleness (in seconds) tolerated. Accepted range for this value is 5 -
* 86400. Required when defaultConsistencyPolicy is set to 'BoundedStaleness'.
* @member {array} [capabilities] List of Cosmos DB capabilities for the
* account
* @member {array} [writeLocations] An array that contains the write location
* for the Cosmos DB account.
* @member {array} [readLocations] An array that contains of the read locations
* enabled for the Cosmos DB account.
* @member {array} [failoverPolicies] An array that contains the regions
* ordered by their failover priorities.
* @member {array} [virtualNetworkRules] List of Virtual Network ACL rules
* configured for the Cosmos DB account.
* @member {boolean} [enableMultipleWriteLocations] Enables the account to
* write in multiple locations
*/
export interface DatabaseAccount extends Resource {
kind?: string;
provisioningState?: string;
readonly documentEndpoint?: string;
readonly databaseAccountOfferType?: string;
ipRangeFilter?: string;
isVirtualNetworkFilterEnabled?: boolean;
enableAutomaticFailover?: boolean;
consistencyPolicy?: ConsistencyPolicy;
capabilities?: Capability[];
readonly writeLocations?: Location[];
readonly readLocations?: Location[];
readonly failoverPolicies?: FailoverPolicy[];
virtualNetworkRules?: VirtualNetworkRule[];
enableMultipleWriteLocations?: boolean;
}
/**
* @class
* Initializes a new instance of the ErrorResponse class.
* @constructor
* Error Response.
*
* @member {string} [code] Error code.
* @member {string} [message] Error message indicating why the operation
* failed.
*/
export interface ErrorResponse {
code?: string;
message?: string;
}
/**
* @class
* Initializes a new instance of the FailoverPolicies class.
* @constructor
* The list of new failover policies for the failover priority change.
*
* @member {array} failoverPolicies List of failover policies.
*/
export interface FailoverPolicies {
failoverPolicies: FailoverPolicy[];
}
/**
* @class
* Initializes a new instance of the RegionForOnlineOffline class.
* @constructor
* Cosmos DB region to online or offline.
*
* @member {string} region Cosmos DB region, with spaces between words and each
* word capitalized.
*/
export interface RegionForOnlineOffline {
region: string;
}
/**
* @class
* Initializes a new instance of the DatabaseAccountCreateUpdateParameters class.
* @constructor
* Parameters to create and update Cosmos DB database accounts.
*
* @member {string} [kind] Indicates the type of database account. This can
* only be set at database account creation. Possible values include:
* 'GlobalDocumentDB', 'MongoDB', 'Parse'. Default value: 'GlobalDocumentDB' .
* @member {object} [consistencyPolicy] The consistency policy for the Cosmos
* DB account.
* @member {string} [consistencyPolicy.defaultConsistencyLevel] The default
* consistency level and configuration settings of the Cosmos DB account.
* Possible values include: 'Eventual', 'Session', 'BoundedStaleness',
* 'Strong', 'ConsistentPrefix'
* @member {number} [consistencyPolicy.maxStalenessPrefix] When used with the
* Bounded Staleness consistency level, this value represents the number of
* stale requests tolerated. Accepted range for this value is 1 –
* 2,147,483,647. Required when defaultConsistencyPolicy is set to
* 'BoundedStaleness'.
* @member {number} [consistencyPolicy.maxIntervalInSeconds] When used with the
* Bounded Staleness consistency level, this value represents the time amount
* of staleness (in seconds) tolerated. Accepted range for this value is 5 -
* 86400. Required when defaultConsistencyPolicy is set to 'BoundedStaleness'.
* @member {array} locations An array that contains the georeplication
* locations enabled for the Cosmos DB account.
* @member {string} [ipRangeFilter] Cosmos DB Firewall Support: This value
* specifies the set of IP addresses or IP address ranges in CIDR form to be
* included as the allowed list of client IPs for a given database account. IP
* addresses/ranges must be comma separated and must not contain any spaces.
* @member {boolean} [isVirtualNetworkFilterEnabled] Flag to indicate whether
* to enable/disable Virtual Network ACL rules.
* @member {boolean} [enableAutomaticFailover] Enables automatic failover of
* the write region in the rare event that the region is unavailable due to an
* outage. Automatic failover will result in a new write region for the account
* and is chosen based on the failover priorities configured for the account.
* @member {array} [capabilities] List of Cosmos DB capabilities for the
* account
* @member {array} [virtualNetworkRules] List of Virtual Network ACL rules
* configured for the Cosmos DB account.
* @member {boolean} [enableMultipleWriteLocations] Enables the account to
* write in multiple locations
*/
export interface DatabaseAccountCreateUpdateParameters extends Resource {
kind?: string;
consistencyPolicy?: ConsistencyPolicy;
locations: Location[];
ipRangeFilter?: string;
isVirtualNetworkFilterEnabled?: boolean;
enableAutomaticFailover?: boolean;
capabilities?: Capability[];
virtualNetworkRules?: VirtualNetworkRule[];
enableMultipleWriteLocations?: boolean;
}
/**
* @class
* Initializes a new instance of the DatabaseAccountPatchParameters class.
* @constructor
* Parameters for patching Azure Cosmos DB database account properties.
*
* @member {object} [tags]
* @member {array} [capabilities] List of Cosmos DB capabilities for the
* account
*/
export interface DatabaseAccountPatchParameters {
tags?: { [propertyName: string]: string };
capabilities?: Capability[];
}
/**
* @class
* Initializes a new instance of the DatabaseAccountListReadOnlyKeysResult class.
* @constructor
* The read-only access keys for the given database account.
*
* @member {string} [primaryReadonlyMasterKey] Base 64 encoded value of the
* primary read-only key.
* @member {string} [secondaryReadonlyMasterKey] Base 64 encoded value of the
* secondary read-only key.
*/
export interface DatabaseAccountListReadOnlyKeysResult {
readonly primaryReadonlyMasterKey?: string;
readonly secondaryReadonlyMasterKey?: string;
}
/**
* @class
* Initializes a new instance of the DatabaseAccountListKeysResult class.
* @constructor
* The access keys for the given database account.
*
* @member {string} [primaryMasterKey] Base 64 encoded value of the primary
* read-write key.
* @member {string} [secondaryMasterKey] Base 64 encoded value of the secondary
* read-write key.
* @member {string} [primaryReadonlyMasterKey] Base 64 encoded value of the
* primary read-only key.
* @member {string} [secondaryReadonlyMasterKey] Base 64 encoded value of the
* secondary read-only key.
*/
export interface DatabaseAccountListKeysResult {
readonly primaryMasterKey?: string;
readonly secondaryMasterKey?: string;
readonly primaryReadonlyMasterKey?: string;
readonly secondaryReadonlyMasterKey?: string;
}
/**
* @class
* Initializes a new instance of the DatabaseAccountConnectionString class.
* @constructor
* Connection string for the Cosmos DB account
*
* @member {string} [connectionString] Value of the connection string
* @member {string} [description] Description of the connection string
*/
export interface DatabaseAccountConnectionString {
readonly connectionString?: string;
readonly description?: string;
}
/**
* @class
* Initializes a new instance of the DatabaseAccountListConnectionStringsResult class.
* @constructor
* The connection strings for the given database account.
*
* @member {array} [connectionStrings] An array that contains the connection
* strings for the Cosmos DB account.
*/
export interface DatabaseAccountListConnectionStringsResult {
connectionStrings?: DatabaseAccountConnectionString[];
}
/**
* @class
* Initializes a new instance of the DatabaseAccountRegenerateKeyParameters class.
* @constructor
* Parameters to regenerate the keys within the database account.
*
* @member {string} keyKind The access key to regenerate. Possible values
* include: 'primary', 'secondary', 'primaryReadonly', 'secondaryReadonly'
*/
export interface DatabaseAccountRegenerateKeyParameters {
keyKind: string;
}
/**
* @class
* Initializes a new instance of the OperationDisplay class.
* @constructor
* The object that represents the operation.
*
* @member {string} [provider] Service provider: Microsoft.ResourceProvider
* @member {string} [resource] Resource on which the operation is performed:
* Profile, endpoint, etc.
* @member {string} [operation] Operation type: Read, write, delete, etc.
* @member {string} [description] Description of operation
*/
export interface OperationDisplay {
provider?: string;
resource?: string;
operation?: string;
description?: string;
}
/**
* @class
* Initializes a new instance of the Operation class.
* @constructor
* REST API operation
*
* @member {string} [name] Operation name: {provider}/{resource}/{operation}
* @member {object} [display] The object that represents the operation.
* @member {string} [display.provider] Service provider:
* Microsoft.ResourceProvider
* @member {string} [display.resource] Resource on which the operation is
* performed: Profile, endpoint, etc.
* @member {string} [display.operation] Operation type: Read, write, delete,
* etc.
* @member {string} [display.description] Description of operation
*/
export interface Operation {
name?: string;
display?: OperationDisplay;
}
/**
* @class
* Initializes a new instance of the MetricName class.
* @constructor
* A metric name.
*
* @member {string} [value] The name of the metric.
* @member {string} [localizedValue] The friendly name of the metric.
*/
export interface MetricName {
readonly value?: string;
readonly localizedValue?: string;
}
/**
* @class
* Initializes a new instance of the Usage class.
* @constructor
* The usage data for a usage request.
*
* @member {string} [unit] The unit of the metric. Possible values include:
* 'Count', 'Bytes', 'Seconds', 'Percent', 'CountPerSecond', 'BytesPerSecond',
* 'Milliseconds'
* @member {object} [name] The name information for the metric.
* @member {string} [name.value] The name of the metric.
* @member {string} [name.localizedValue] The friendly name of the metric.
* @member {string} [quotaPeriod] The quota period used to summarize the usage
* values.
* @member {number} [limit] Maximum value for this metric
* @member {number} [currentValue] Current value for this metric
*/
export interface Usage {
unit?: string;
readonly name?: MetricName;
readonly quotaPeriod?: string;
readonly limit?: number;
readonly currentValue?: number;
}
/**
* @class
* Initializes a new instance of the PartitionUsage class.
* @constructor
* The partition level usage data for a usage request.
*
* @member {string} [partitionId] The parition id (GUID identifier) of the
* usages.
* @member {string} [partitionKeyRangeId] The partition key range id (integer
* identifier) of the usages.
*/
export interface PartitionUsage extends Usage {
readonly partitionId?: string;
readonly partitionKeyRangeId?: string;
}
/**
* @class
* Initializes a new instance of the MetricAvailability class.
* @constructor
* The availability of the metric.
*
* @member {string} [timeGrain] The time grain to be used to summarize the
* metric values.
* @member {string} [retention] The retention for the metric values.
*/
export interface MetricAvailability {
readonly timeGrain?: string;
readonly retention?: string;
}
/**
* @class
* Initializes a new instance of the MetricDefinition class.
* @constructor
* The definition of a metric.
*
* @member {array} [metricAvailabilities] The list of metric availabilities for
* the account.
* @member {string} [primaryAggregationType] The primary aggregation type of
* the metric. Possible values include: 'None', 'Average', 'Total',
* 'Minimimum', 'Maximum', 'Last'
* @member {string} [unit] The unit of the metric. Possible values include:
* 'Count', 'Bytes', 'Seconds', 'Percent', 'CountPerSecond', 'BytesPerSecond',
* 'Milliseconds'
* @member {string} [resourceUri] The resource uri of the database.
* @member {object} [name] The name information for the metric.
* @member {string} [name.value] The name of the metric.
* @member {string} [name.localizedValue] The friendly name of the metric.
*/
export interface MetricDefinition {
readonly metricAvailabilities?: MetricAvailability[];
readonly primaryAggregationType?: string;
unit?: string;
readonly resourceUri?: string;
readonly name?: MetricName;
}
/**
* @class
* Initializes a new instance of the MetricValue class.
* @constructor
* Represents metrics values.
*
* @member {number} [_count] The number of values for the metric.
* @member {number} [average] The average value of the metric.
* @member {number} [maximum] The max value of the metric.
* @member {number} [minimum] The min value of the metric.
* @member {date} [timestamp] The metric timestamp (ISO-8601 format).
* @member {number} [total] The total value of the metric.
*/
export interface MetricValue {
readonly _count?: number;
readonly average?: number;
readonly maximum?: number;
readonly minimum?: number;
readonly timestamp?: Date;
readonly total?: number;
}
/**
* @class
* Initializes a new instance of the Metric class.
* @constructor
* Metric data
*
* @member {date} [startTime] The start time for the metric (ISO-8601 format).
* @member {date} [endTime] The end time for the metric (ISO-8601 format).
* @member {string} [timeGrain] The time grain to be used to summarize the
* metric values.
* @member {string} [unit] The unit of the metric. Possible values include:
* 'Count', 'Bytes', 'Seconds', 'Percent', 'CountPerSecond', 'BytesPerSecond',
* 'Milliseconds'
* @member {object} [name] The name information for the metric.
* @member {string} [name.value] The name of the metric.
* @member {string} [name.localizedValue] The friendly name of the metric.
* @member {array} [metricValues] The metric values for the specified time
* window and timestep.
*/
export interface Metric {
readonly startTime?: Date;
readonly endTime?: Date;
readonly timeGrain?: string;
unit?: string;
readonly name?: MetricName;
readonly metricValues?: MetricValue[];
}
/**
* @class
* Initializes a new instance of the PercentileMetricValue class.
* @constructor
* Represents percentile metrics values.
*
* @member {number} [p10] The 10th percentile value for the metric.
* @member {number} [p25] The 25th percentile value for the metric.
* @member {number} [p50] The 50th percentile value for the metric.
* @member {number} [p75] The 75th percentile value for the metric.
* @member {number} [p90] The 90th percentile value for the metric.
* @member {number} [p95] The 95th percentile value for the metric.
* @member {number} [p99] The 99th percentile value for the metric.
*/
export interface PercentileMetricValue extends MetricValue {
readonly p10?: number;
readonly p25?: number;
readonly p50?: number;
readonly p75?: number;
readonly p90?: number;
readonly p95?: number;
readonly p99?: number;
}
/**
* @class
* Initializes a new instance of the PercentileMetric class.
* @constructor
* Percentile Metric data
*
* @member {date} [startTime] The start time for the metric (ISO-8601 format).
* @member {date} [endTime] The end time for the metric (ISO-8601 format).
* @member {string} [timeGrain] The time grain to be used to summarize the
* metric values.
* @member {string} [unit] The unit of the metric. Possible values include:
* 'Count', 'Bytes', 'Seconds', 'Percent', 'CountPerSecond', 'BytesPerSecond',
* 'Milliseconds'
* @member {object} [name] The name information for the metric.
* @member {string} [name.value] The name of the metric.
* @member {string} [name.localizedValue] The friendly name of the metric.
* @member {array} [metricValues] The percentile metric values for the
* specified time window and timestep.
*/
export interface PercentileMetric {
readonly startTime?: Date;
readonly endTime?: Date;
readonly timeGrain?: string;
unit?: string;
readonly name?: MetricName;
readonly metricValues?: PercentileMetricValue[];
}
/**
* @class
* Initializes a new instance of the PartitionMetric class.
* @constructor
* The metric values for a single partition.
*
* @member {string} [partitionId] The parition id (GUID identifier) of the
* metric values.
* @member {string} [partitionKeyRangeId] The partition key range id (integer
* identifier) of the metric values.
*/
export interface PartitionMetric extends Metric {
readonly partitionId?: string;
readonly partitionKeyRangeId?: string;
}
/**
* @class
* Initializes a new instance of the DatabaseAccountsListResult class.
* @constructor
* The List operation response, that contains the database accounts and their
* properties.
*
*/
export interface DatabaseAccountsListResult extends Array<DatabaseAccount> {
}
/**
* @class
* Initializes a new instance of the MetricListResult class.
* @constructor
* The response to a list metrics request.
*
*/
export interface MetricListResult extends Array<Metric> {
}
/**
* @class
* Initializes a new instance of the UsagesResult class.
* @constructor
* The response to a list usage request.
*
*/
export interface UsagesResult extends Array<Usage> {
}
/**
* @class
* Initializes a new instance of the MetricDefinitionsListResult class.
* @constructor
* The response to a list metric definitions request.
*
*/
export interface MetricDefinitionsListResult extends Array<MetricDefinition> {
}
/**
* @class
* Initializes a new instance of the OperationListResult class.
* @constructor
* Result of the request to list Resource Provider operations. It contains a
* list of operations and a URL link to get the next set of results.
*
* @member {string} [nextLink] URL to get the next set of operation list
* results if there are any.
*/
export interface OperationListResult extends Array<Operation> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the PercentileMetricListResult class.
* @constructor
* The response to a list percentile metrics request.
*
*/
export interface PercentileMetricListResult extends Array<PercentileMetric> {
}
/**
* @class
* Initializes a new instance of the PartitionMetricListResult class.
* @constructor
* The response to a list partition metrics request.
*
*/
export interface PartitionMetricListResult extends Array<PartitionMetric> {
}
/**
* @class
* Initializes a new instance of the PartitionUsagesResult class.
* @constructor
* The response to a list partition level usage request.
*
*/
export interface PartitionUsagesResult extends Array<PartitionUsage> {
} | the_stack |
import { WlMessage, fileDescriptor, uint, int,
fixed, object, objectOptional, newObject, string, stringOptional,
array, arrayOptional, u, i, f, oOptional, o, n, sOptional, s, aOptional, a, h, WebFD, Fixed } from 'westfield-runtime-common'
import * as Westfield from '..'
/**
*
* Clients can handle the 'done' event to get notified when
* the related request is done.
*
*/
export class WlCallbackResource extends Westfield.Resource {
static readonly protocolName = 'wl_callback'
//@ts-ignore Should always be set when resource is created.
implementation: any
/**
*
* Notify the client when the related request is done.
*
*
* @param callbackData request-specific data for the callback
*
* @since 1
*
*/
done (callbackData: number) {
this.client.marshall(this.id, 0, [uint(callbackData)])
}
constructor (client: Westfield.Client, id: number, version: number) {
super(client, id, version)
}
}
/**
*
* A compositor. This object is a singleton global. The
* compositor is in charge of combining the contents of multiple
* surfaces into one displayable output.
*
*/
export class WlCompositorResource extends Westfield.Resource {
static readonly protocolName = 'wl_compositor'
//@ts-ignore Should always be set when resource is created.
implementation: WlCompositorRequests
constructor (client: Westfield.Client, id: number, version: number) {
super(client, id, version)
}
[0] (message: WlMessage) {
return this.implementation.createSurface(this, n(message))
}
[1] (message: WlMessage) {
return this.implementation.createRegion(this, n(message))
}
}
export interface WlCompositorRequests {
/**
*
* Ask the compositor to create a new surface.
*
*
* @param resource The protocol resource of this implementation.
* @param id the new surface
*
* @since 1
*
*/
createSurface(resource: WlCompositorResource, id: number): void
/**
*
* Ask the compositor to create a new region.
*
*
* @param resource The protocol resource of this implementation.
* @param id the new region
*
* @since 1
*
*/
createRegion(resource: WlCompositorResource, id: number): void
}
/**
*
* The wl_shm_pool object encapsulates a piece of memory shared
* between the compositor and client. Through the wl_shm_pool
* object, the client can allocate shared memory wl_buffer objects.
* All objects created through the same pool share the same
* underlying mapped memory. Reusing the mapped memory avoids the
* setup/teardown overhead and is useful when interactively resizing
* a surface or for many small buffers.
*
*/
export class WlShmPoolResource extends Westfield.Resource {
static readonly protocolName = 'wl_shm_pool'
//@ts-ignore Should always be set when resource is created.
implementation: WlShmPoolRequests
constructor (client: Westfield.Client, id: number, version: number) {
super(client, id, version)
}
[0] (message: WlMessage) {
return this.implementation.createBuffer(this, n(message), i(message), i(message), i(message), i(message), u(message))
}
[1] (message: WlMessage) {
return this.implementation.destroy(this)
}
[2] (message: WlMessage) {
return this.implementation.resize(this, i(message))
}
}
export interface WlShmPoolRequests {
/**
*
* Create a wl_buffer object from the pool.
*
* The buffer is created offset bytes into the pool and has
* width and height as specified. The stride argument specifies
* the number of bytes from the beginning of one row to the beginning
* of the next. The format is the pixel format of the buffer and
* must be one of those advertised through the wl_shm.format event.
*
* A buffer will keep a reference to the pool it was created from
* so it is valid to destroy the pool immediately after creating
* a buffer from it.
*
*
* @param resource The protocol resource of this implementation.
* @param id buffer to create
* @param offset buffer byte offset within the pool
* @param width buffer width, in pixels
* @param height buffer height, in pixels
* @param stride number of bytes from the beginning of one row to the beginning of the next row
* @param format buffer pixel format
*
* @since 1
*
*/
createBuffer(resource: WlShmPoolResource, id: number, offset: number, width: number, height: number, stride: number, format: number): void
/**
*
* Destroy the shared memory pool.
*
* The mmapped memory will be released when all
* buffers that have been created from this pool
* are gone.
*
*
* @param resource The protocol resource of this implementation.
*
* @since 1
*
*/
destroy(resource: WlShmPoolResource): void
/**
*
* This request will cause the server to remap the backing memory
* for the pool from the file descriptor passed when the pool was
* created, but using the new size. This request can only be
* used to make the pool bigger.
*
*
* @param resource The protocol resource of this implementation.
* @param size new size of the pool, in bytes
*
* @since 1
*
*/
resize(resource: WlShmPoolResource, size: number): void
}
/**
*
* A singleton global object that provides support for shared
* memory.
*
* Clients can create wl_shm_pool objects using the create_pool
* request.
*
* At connection setup time, the wl_shm object emits one or more
* format events to inform clients about the valid pixel formats
* that can be used for buffers.
*
*/
export class WlShmResource extends Westfield.Resource {
static readonly protocolName = 'wl_shm'
//@ts-ignore Should always be set when resource is created.
implementation: WlShmRequests
/**
*
* Informs the client about a valid pixel format that
* can be used for buffers. Known formats include
* argb8888 and xrgb8888.
*
*
* @param format buffer pixel format
*
* @since 1
*
*/
format (format: number) {
this.client.marshall(this.id, 0, [uint(format)])
}
constructor (client: Westfield.Client, id: number, version: number) {
super(client, id, version)
}
[0] (message: WlMessage) {
return this.implementation.createPool(this, n(message), h(message), i(message))
}
}
export interface WlShmRequests {
/**
*
* Create a new wl_shm_pool object.
*
* The pool can be used to create shared memory based buffer
* objects. The server will mmap size bytes of the passed file
* descriptor, to use as backing memory for the pool.
*
*
* @param resource The protocol resource of this implementation.
* @param id pool to create
* @param fd file descriptor for the pool
* @param size pool size, in bytes
*
* @since 1
*
*/
createPool(resource: WlShmResource, id: number, fd: WebFD, size: number): void
}
export enum WlShmError {
/**
* buffer format is not known
*/
invalidFormat = 0,
/**
* invalid size or stride during pool or buffer creation
*/
invalidStride = 1,
/**
* mmapping the file descriptor failed
*/
invalidFd = 2
}
export enum WlShmFormat {
/**
* 32-bit ARGB format, [31:0] A:R:G:B 8:8:8:8 little endian
*/
argb8888 = 0,
/**
* 32-bit RGB format, [31:0] x:R:G:B 8:8:8:8 little endian
*/
xrgb8888 = 1,
/**
* 8-bit color index format, [7:0] C
*/
c8 = 0x20203843,
/**
* 8-bit RGB format, [7:0] R:G:B 3:3:2
*/
rgb332 = 0x38424752,
/**
* 8-bit BGR format, [7:0] B:G:R 2:3:3
*/
bgr233 = 0x38524742,
/**
* 16-bit xRGB format, [15:0] x:R:G:B 4:4:4:4 little endian
*/
xrgb4444 = 0x32315258,
/**
* 16-bit xBGR format, [15:0] x:B:G:R 4:4:4:4 little endian
*/
xbgr4444 = 0x32314258,
/**
* 16-bit RGBx format, [15:0] R:G:B:x 4:4:4:4 little endian
*/
rgbx4444 = 0x32315852,
/**
* 16-bit BGRx format, [15:0] B:G:R:x 4:4:4:4 little endian
*/
bgrx4444 = 0x32315842,
/**
* 16-bit ARGB format, [15:0] A:R:G:B 4:4:4:4 little endian
*/
argb4444 = 0x32315241,
/**
* 16-bit ABGR format, [15:0] A:B:G:R 4:4:4:4 little endian
*/
abgr4444 = 0x32314241,
/**
* 16-bit RBGA format, [15:0] R:G:B:A 4:4:4:4 little endian
*/
rgba4444 = 0x32314152,
/**
* 16-bit BGRA format, [15:0] B:G:R:A 4:4:4:4 little endian
*/
bgra4444 = 0x32314142,
/**
* 16-bit xRGB format, [15:0] x:R:G:B 1:5:5:5 little endian
*/
xrgb1555 = 0x35315258,
/**
* 16-bit xBGR 1555 format, [15:0] x:B:G:R 1:5:5:5 little endian
*/
xbgr1555 = 0x35314258,
/**
* 16-bit RGBx 5551 format, [15:0] R:G:B:x 5:5:5:1 little endian
*/
rgbx5551 = 0x35315852,
/**
* 16-bit BGRx 5551 format, [15:0] B:G:R:x 5:5:5:1 little endian
*/
bgrx5551 = 0x35315842,
/**
* 16-bit ARGB 1555 format, [15:0] A:R:G:B 1:5:5:5 little endian
*/
argb1555 = 0x35315241,
/**
* 16-bit ABGR 1555 format, [15:0] A:B:G:R 1:5:5:5 little endian
*/
abgr1555 = 0x35314241,
/**
* 16-bit RGBA 5551 format, [15:0] R:G:B:A 5:5:5:1 little endian
*/
rgba5551 = 0x35314152,
/**
* 16-bit BGRA 5551 format, [15:0] B:G:R:A 5:5:5:1 little endian
*/
bgra5551 = 0x35314142,
/**
* 16-bit RGB 565 format, [15:0] R:G:B 5:6:5 little endian
*/
rgb565 = 0x36314752,
/**
* 16-bit BGR 565 format, [15:0] B:G:R 5:6:5 little endian
*/
bgr565 = 0x36314742,
/**
* 24-bit RGB format, [23:0] R:G:B little endian
*/
rgb888 = 0x34324752,
/**
* 24-bit BGR format, [23:0] B:G:R little endian
*/
bgr888 = 0x34324742,
/**
* 32-bit xBGR format, [31:0] x:B:G:R 8:8:8:8 little endian
*/
xbgr8888 = 0x34324258,
/**
* 32-bit RGBx format, [31:0] R:G:B:x 8:8:8:8 little endian
*/
rgbx8888 = 0x34325852,
/**
* 32-bit BGRx format, [31:0] B:G:R:x 8:8:8:8 little endian
*/
bgrx8888 = 0x34325842,
/**
* 32-bit ABGR format, [31:0] A:B:G:R 8:8:8:8 little endian
*/
abgr8888 = 0x34324241,
/**
* 32-bit RGBA format, [31:0] R:G:B:A 8:8:8:8 little endian
*/
rgba8888 = 0x34324152,
/**
* 32-bit BGRA format, [31:0] B:G:R:A 8:8:8:8 little endian
*/
bgra8888 = 0x34324142,
/**
* 32-bit xRGB format, [31:0] x:R:G:B 2:10:10:10 little endian
*/
xrgb2101010 = 0x30335258,
/**
* 32-bit xBGR format, [31:0] x:B:G:R 2:10:10:10 little endian
*/
xbgr2101010 = 0x30334258,
/**
* 32-bit RGBx format, [31:0] R:G:B:x 10:10:10:2 little endian
*/
rgbx1010102 = 0x30335852,
/**
* 32-bit BGRx format, [31:0] B:G:R:x 10:10:10:2 little endian
*/
bgrx1010102 = 0x30335842,
/**
* 32-bit ARGB format, [31:0] A:R:G:B 2:10:10:10 little endian
*/
argb2101010 = 0x30335241,
/**
* 32-bit ABGR format, [31:0] A:B:G:R 2:10:10:10 little endian
*/
abgr2101010 = 0x30334241,
/**
* 32-bit RGBA format, [31:0] R:G:B:A 10:10:10:2 little endian
*/
rgba1010102 = 0x30334152,
/**
* 32-bit BGRA format, [31:0] B:G:R:A 10:10:10:2 little endian
*/
bgra1010102 = 0x30334142,
/**
* packed YCbCr format, [31:0] Cr0:Y1:Cb0:Y0 8:8:8:8 little endian
*/
yuyv = 0x56595559,
/**
* packed YCbCr format, [31:0] Cb0:Y1:Cr0:Y0 8:8:8:8 little endian
*/
yvyu = 0x55595659,
/**
* packed YCbCr format, [31:0] Y1:Cr0:Y0:Cb0 8:8:8:8 little endian
*/
uyvy = 0x59565955,
/**
* packed YCbCr format, [31:0] Y1:Cb0:Y0:Cr0 8:8:8:8 little endian
*/
vyuy = 0x59555956,
/**
* packed AYCbCr format, [31:0] A:Y:Cb:Cr 8:8:8:8 little endian
*/
ayuv = 0x56555941,
/**
* 2 plane YCbCr Cr:Cb format, 2x2 subsampled Cr:Cb plane
*/
nv12 = 0x3231564e,
/**
* 2 plane YCbCr Cb:Cr format, 2x2 subsampled Cb:Cr plane
*/
nv21 = 0x3132564e,
/**
* 2 plane YCbCr Cr:Cb format, 2x1 subsampled Cr:Cb plane
*/
nv16 = 0x3631564e,
/**
* 2 plane YCbCr Cb:Cr format, 2x1 subsampled Cb:Cr plane
*/
nv61 = 0x3136564e,
/**
* 3 plane YCbCr format, 4x4 subsampled Cb (1) and Cr (2) planes
*/
yuv410 = 0x39565559,
/**
* 3 plane YCbCr format, 4x4 subsampled Cr (1) and Cb (2) planes
*/
yvu410 = 0x39555659,
/**
* 3 plane YCbCr format, 4x1 subsampled Cb (1) and Cr (2) planes
*/
yuv411 = 0x31315559,
/**
* 3 plane YCbCr format, 4x1 subsampled Cr (1) and Cb (2) planes
*/
yvu411 = 0x31315659,
/**
* 3 plane YCbCr format, 2x2 subsampled Cb (1) and Cr (2) planes
*/
yuv420 = 0x32315559,
/**
* 3 plane YCbCr format, 2x2 subsampled Cr (1) and Cb (2) planes
*/
yvu420 = 0x32315659,
/**
* 3 plane YCbCr format, 2x1 subsampled Cb (1) and Cr (2) planes
*/
yuv422 = 0x36315559,
/**
* 3 plane YCbCr format, 2x1 subsampled Cr (1) and Cb (2) planes
*/
yvu422 = 0x36315659,
/**
* 3 plane YCbCr format, non-subsampled Cb (1) and Cr (2) planes
*/
yuv444 = 0x34325559,
/**
* 3 plane YCbCr format, non-subsampled Cr (1) and Cb (2) planes
*/
yvu444 = 0x34325659
}
/**
*
* A buffer provides the content for a wl_surface. Buffers are
* created through factory interfaces such as wl_drm, wl_shm or
* similar. It has a width and a height and can be attached to a
* wl_surface, but the mechanism by which a client provides and
* updates the contents is defined by the buffer factory interface.
*
*/
export class WlBufferResource extends Westfield.Resource {
static readonly protocolName = 'wl_buffer'
//@ts-ignore Should always be set when resource is created.
implementation: WlBufferRequests
/**
*
* Sent when this wl_buffer is no longer used by the compositor.
* The client is now free to reuse or destroy this buffer and its
* backing storage.
*
* If a client receives a release event before the frame callback
* requested in the same wl_surface.commit that attaches this
* wl_buffer to a surface, then the client is immediately free to
* reuse the buffer and its backing storage, and does not need a
* second buffer for the next surface content update. Typically
* this is possible, when the compositor maintains a copy of the
* wl_surface contents, e.g. as a GL texture. This is an important
* optimization for GL(ES) compositors with wl_shm clients.
*
* @since 1
*
*/
release () {
this.client.marshall(this.id, 0, [])
}
constructor (client: Westfield.Client, id: number, version: number) {
super(client, id, version)
}
[0] (message: WlMessage) {
return this.implementation.destroy(this)
}
}
export interface WlBufferRequests {
/**
*
* Destroy a buffer. If and how you need to release the backing
* storage is defined by the buffer factory interface.
*
* For possible side-effects to a surface, see wl_surface.attach.
*
*
* @param resource The protocol resource of this implementation.
*
* @since 1
*
*/
destroy(resource: WlBufferResource): void
}
/**
*
* A wl_data_offer represents a piece of data offered for transfer
* by another client (the source client). It is used by the
* copy-and-paste and drag-and-drop mechanisms. The offer
* describes the different mime types that the data can be
* converted to and provides the mechanism for transferring the
* data directly from the source client.
*
*/
export class WlDataOfferResource extends Westfield.Resource {
static readonly protocolName = 'wl_data_offer'
//@ts-ignore Should always be set when resource is created.
implementation: WlDataOfferRequests
/**
*
* Sent immediately after creating the wl_data_offer object. One
* event per offered mime type.
*
*
* @param mimeType offered mime type
*
* @since 1
*
*/
offer (mimeType: string) {
this.client.marshall(this.id, 0, [string(mimeType)])
}
/**
*
* This event indicates the actions offered by the data source. It
* will be sent right after wl_data_device.enter, or anytime the source
* side changes its offered actions through wl_data_source.set_actions.
*
*
* @param sourceActions actions offered by the data source
*
* @since 3
*
*/
sourceActions (sourceActions: number) {
this.client.marshall(this.id, 1, [uint(sourceActions)])
}
/**
*
* This event indicates the action selected by the compositor after
* matching the source/destination side actions. Only one action (or
* none) will be offered here.
*
* This event can be emitted multiple times during the drag-and-drop
* operation in response to destination side action changes through
* wl_data_offer.set_actions.
*
* This event will no longer be emitted after wl_data_device.drop
* happened on the drag-and-drop destination, the client must
* honor the last action received, or the last preferred one set
* through wl_data_offer.set_actions when handling an "ask" action.
*
* Compositors may also change the selected action on the fly, mainly
* in response to keyboard modifier changes during the drag-and-drop
* operation.
*
* The most recent action received is always the valid one. Prior to
* receiving wl_data_device.drop, the chosen action may change (e.g.
* due to keyboard modifiers being pressed). At the time of receiving
* wl_data_device.drop the drag-and-drop destination must honor the
* last action received.
*
* Action changes may still happen after wl_data_device.drop,
* especially on "ask" actions, where the drag-and-drop destination
* may choose another action afterwards. Action changes happening
* at this stage are always the result of inter-client negotiation, the
* compositor shall no longer be able to induce a different action.
*
* Upon "ask" actions, it is expected that the drag-and-drop destination
* may potentially choose a different action and/or mime type,
* based on wl_data_offer.source_actions and finally chosen by the
* user (e.g. popping up a menu with the available options). The
* final wl_data_offer.set_actions and wl_data_offer.accept requests
* must happen before the call to wl_data_offer.finish.
*
*
* @param dndAction action selected by the compositor
*
* @since 3
*
*/
action (dndAction: number) {
this.client.marshall(this.id, 2, [uint(dndAction)])
}
constructor (client: Westfield.Client, id: number, version: number) {
super(client, id, version)
}
[0] (message: WlMessage) {
return this.implementation.accept(this, u(message), sOptional(message))
}
[1] (message: WlMessage) {
return this.implementation.receive(this, s(message), h(message))
}
[2] (message: WlMessage) {
return this.implementation.destroy(this)
}
[3] (message: WlMessage) {
return this.implementation.finish(this)
}
[4] (message: WlMessage) {
return this.implementation.setActions(this, u(message), u(message))
}
}
export interface WlDataOfferRequests {
/**
*
* Indicate that the client can accept the given mime type, or
* NULL for not accepted.
*
* For objects of version 2 or older, this request is used by the
* client to give feedback whether the client can receive the given
* mime type, or NULL if none is accepted; the feedback does not
* determine whether the drag-and-drop operation succeeds or not.
*
* For objects of version 3 or newer, this request determines the
* final result of the drag-and-drop operation. If the end result
* is that no mime types were accepted, the drag-and-drop operation
* will be cancelled and the corresponding drag source will receive
* wl_data_source.cancelled. Clients may still use this event in
* conjunction with wl_data_source.action for feedback.
*
*
* @param resource The protocol resource of this implementation.
* @param serial serial number of the accept request
* @param mimeType mime type accepted by the client
*
* @since 1
*
*/
accept(resource: WlDataOfferResource, serial: number, mimeType: string|undefined): void
/**
*
* To transfer the offered data, the client issues this request
* and indicates the mime type it wants to receive. The transfer
* happens through the passed file descriptor (typically created
* with the pipe system call). The source client writes the data
* in the mime type representation requested and then closes the
* file descriptor.
*
* The receiving client reads from the read end of the pipe until
* EOF and then closes its end, at which point the transfer is
* complete.
*
* This request may happen multiple times for different mime types,
* both before and after wl_data_device.drop. Drag-and-drop destination
* clients may preemptively fetch data or examine it more closely to
* determine acceptance.
*
*
* @param resource The protocol resource of this implementation.
* @param mimeType mime type desired by receiver
* @param fd file descriptor for data transfer
*
* @since 1
*
*/
receive(resource: WlDataOfferResource, mimeType: string, fd: WebFD): void
/**
*
* Destroy the data offer.
*
*
* @param resource The protocol resource of this implementation.
*
* @since 1
*
*/
destroy(resource: WlDataOfferResource): void
/**
*
* Notifies the compositor that the drag destination successfully
* finished the drag-and-drop operation.
*
* Upon receiving this request, the compositor will emit
* wl_data_source.dnd_finished on the drag source client.
*
* It is a client error to perform other requests than
* wl_data_offer.destroy after this one. It is also an error to perform
* this request after a NULL mime type has been set in
* wl_data_offer.accept or no action was received through
* wl_data_offer.action.
*
*
* @param resource The protocol resource of this implementation.
*
* @since 3
*
*/
finish(resource: WlDataOfferResource): void
/**
*
* Sets the actions that the destination side client supports for
* this operation. This request may trigger the emission of
* wl_data_source.action and wl_data_offer.action events if the compositor
* needs to change the selected action.
*
* This request can be called multiple times throughout the
* drag-and-drop operation, typically in response to wl_data_device.enter
* or wl_data_device.motion events.
*
* This request determines the final result of the drag-and-drop
* operation. If the end result is that no action is accepted,
* the drag source will receive wl_drag_source.cancelled.
*
* The dnd_actions argument must contain only values expressed in the
* wl_data_device_manager.dnd_actions enum, and the preferred_action
* argument must only contain one of those values set, otherwise it
* will result in a protocol error.
*
* While managing an "ask" action, the destination drag-and-drop client
* may perform further wl_data_offer.receive requests, and is expected
* to perform one last wl_data_offer.set_actions request with a preferred
* action other than "ask" (and optionally wl_data_offer.accept) before
* requesting wl_data_offer.finish, in order to convey the action selected
* by the user. If the preferred action is not in the
* wl_data_offer.source_actions mask, an error will be raised.
*
* If the "ask" action is dismissed (e.g. user cancellation), the client
* is expected to perform wl_data_offer.destroy right away.
*
* This request can only be made on drag-and-drop offers, a protocol error
* will be raised otherwise.
*
*
* @param resource The protocol resource of this implementation.
* @param dndActions actions supported by the destination client
* @param preferredAction action preferred by the destination client
*
* @since 3
*
*/
setActions(resource: WlDataOfferResource, dndActions: number, preferredAction: number): void
}
export enum WlDataOfferError {
/**
* finish request was called untimely
*/
invalidFinish = 0,
/**
* action mask contains invalid values
*/
invalidActionMask = 1,
/**
* action argument has an invalid value
*/
invalidAction = 2,
/**
* offer doesn't accept this request
*/
invalidOffer = 3
}
/**
*
* The wl_data_source object is the source side of a wl_data_offer.
* It is created by the source client in a data transfer and
* provides a way to describe the offered data and a way to respond
* to requests to transfer the data.
*
*/
export class WlDataSourceResource extends Westfield.Resource {
static readonly protocolName = 'wl_data_source'
//@ts-ignore Should always be set when resource is created.
implementation: WlDataSourceRequests
/**
*
* Sent when a target accepts pointer_focus or motion events. If
* a target does not accept any of the offered types, type is NULL.
*
* Used for feedback during drag-and-drop.
*
*
* @param mimeType mime type accepted by the target
*
* @since 1
*
*/
target (mimeType: string|undefined) {
this.client.marshall(this.id, 0, [stringOptional(mimeType)])
}
/**
*
* Request for data from the client. Send the data as the
* specified mime type over the passed file descriptor, then
* close it.
*
*
* @param mimeType mime type for the data
* @param fd file descriptor for the data
*
* @since 1
*
*/
send (mimeType: string, fd: WebFD) {
this.client.marshall(this.id, 1, [string(mimeType), fileDescriptor(fd)])
}
/**
*
* This data source is no longer valid. There are several reasons why
* this could happen:
*
* - The data source has been replaced by another data source.
* - The drag-and-drop operation was performed, but the drop destination
* did not accept any of the mime types offered through
* wl_data_source.target.
* - The drag-and-drop operation was performed, but the drop destination
* did not select any of the actions present in the mask offered through
* wl_data_source.action.
* - The drag-and-drop operation was performed but didn't happen over a
* surface.
* - The compositor cancelled the drag-and-drop operation (e.g. compositor
* dependent timeouts to avoid stale drag-and-drop transfers).
*
* The client should clean up and destroy this data source.
*
* For objects of version 2 or older, wl_data_source.cancelled will
* only be emitted if the data source was replaced by another data
* source.
*
* @since 1
*
*/
cancelled () {
this.client.marshall(this.id, 2, [])
}
/**
*
* The user performed the drop action. This event does not indicate
* acceptance, wl_data_source.cancelled may still be emitted afterwards
* if the drop destination does not accept any mime type.
*
* However, this event might however not be received if the compositor
* cancelled the drag-and-drop operation before this event could happen.
*
* Note that the data_source may still be used in the future and should
* not be destroyed here.
*
* @since 3
*
*/
dndDropPerformed () {
this.client.marshall(this.id, 3, [])
}
/**
*
* The drop destination finished interoperating with this data
* source, so the client is now free to destroy this data source and
* free all associated data.
*
* If the action used to perform the operation was "move", the
* source can now delete the transferred data.
*
* @since 3
*
*/
dndFinished () {
this.client.marshall(this.id, 4, [])
}
/**
*
* This event indicates the action selected by the compositor after
* matching the source/destination side actions. Only one action (or
* none) will be offered here.
*
* This event can be emitted multiple times during the drag-and-drop
* operation, mainly in response to destination side changes through
* wl_data_offer.set_actions, and as the data device enters/leaves
* surfaces.
*
* It is only possible to receive this event after
* wl_data_source.dnd_drop_performed if the drag-and-drop operation
* ended in an "ask" action, in which case the final wl_data_source.action
* event will happen immediately before wl_data_source.dnd_finished.
*
* Compositors may also change the selected action on the fly, mainly
* in response to keyboard modifier changes during the drag-and-drop
* operation.
*
* The most recent action received is always the valid one. The chosen
* action may change alongside negotiation (e.g. an "ask" action can turn
* into a "move" operation), so the effects of the final action must
* always be applied in wl_data_offer.dnd_finished.
*
* Clients can trigger cursor surface changes from this point, so
* they reflect the current action.
*
*
* @param dndAction action selected by the compositor
*
* @since 3
*
*/
action (dndAction: number) {
this.client.marshall(this.id, 5, [uint(dndAction)])
}
constructor (client: Westfield.Client, id: number, version: number) {
super(client, id, version)
}
[0] (message: WlMessage) {
return this.implementation.offer(this, s(message))
}
[1] (message: WlMessage) {
return this.implementation.destroy(this)
}
[2] (message: WlMessage) {
return this.implementation.setActions(this, u(message))
}
}
export interface WlDataSourceRequests {
/**
*
* This request adds a mime type to the set of mime types
* advertised to targets. Can be called several times to offer
* multiple types.
*
*
* @param resource The protocol resource of this implementation.
* @param mimeType mime type offered by the data source
*
* @since 1
*
*/
offer(resource: WlDataSourceResource, mimeType: string): void
/**
*
* Destroy the data source.
*
*
* @param resource The protocol resource of this implementation.
*
* @since 1
*
*/
destroy(resource: WlDataSourceResource): void
/**
*
* Sets the actions that the source side client supports for this
* operation. This request may trigger wl_data_source.action and
* wl_data_offer.action events if the compositor needs to change the
* selected action.
*
* The dnd_actions argument must contain only values expressed in the
* wl_data_device_manager.dnd_actions enum, otherwise it will result
* in a protocol error.
*
* This request must be made once only, and can only be made on sources
* used in drag-and-drop, so it must be performed before
* wl_data_device.start_drag. Attempting to use the source other than
* for drag-and-drop will raise a protocol error.
*
*
* @param resource The protocol resource of this implementation.
* @param dndActions actions supported by the data source
*
* @since 3
*
*/
setActions(resource: WlDataSourceResource, dndActions: number): void
}
export enum WlDataSourceError {
/**
* action mask contains invalid values
*/
invalidActionMask = 0,
/**
* source doesn't accept this request
*/
invalidSource = 1
}
/**
*
* There is one wl_data_device per seat which can be obtained
* from the global wl_data_device_manager singleton.
*
* A wl_data_device provides access to inter-client data transfer
* mechanisms such as copy-and-paste and drag-and-drop.
*
*/
export class WlDataDeviceResource extends Westfield.Resource {
static readonly protocolName = 'wl_data_device'
//@ts-ignore Should always be set when resource is created.
implementation: WlDataDeviceRequests
/**
*
* The data_offer event introduces a new wl_data_offer object,
* which will subsequently be used in either the
* data_device.enter event (for drag-and-drop) or the
* data_device.selection event (for selections). Immediately
* following the data_device_data_offer event, the new data_offer
* object will send out data_offer.offer events to describe the
* mime types it offers.
*
*
* @return resource id. the new data_offer object
*
* @since 1
*
*/
dataOffer () {
return this.client.marshallConstructor(this.id, 0, [newObject()])
}
/**
*
* This event is sent when an active drag-and-drop pointer enters
* a surface owned by the client. The position of the pointer at
* enter time is provided by the x and y arguments, in surface-local
* coordinates.
*
*
* @param serial serial number of the enter event
* @param surface client surface entered
* @param x surface-local x coordinate
* @param y surface-local y coordinate
* @param id source data_offer object
*
* @since 1
*
*/
enter (serial: number, surface: Westfield.WlSurfaceResource, x: Fixed, y: Fixed, id: Westfield.WlDataOfferResource|undefined) {
this.client.marshall(this.id, 1, [uint(serial), object(surface), fixed(x), fixed(y), objectOptional(id)])
}
/**
*
* This event is sent when the drag-and-drop pointer leaves the
* surface and the session ends. The client must destroy the
* wl_data_offer introduced at enter time at this point.
*
* @since 1
*
*/
leave () {
this.client.marshall(this.id, 2, [])
}
/**
*
* This event is sent when the drag-and-drop pointer moves within
* the currently focused surface. The new position of the pointer
* is provided by the x and y arguments, in surface-local
* coordinates.
*
*
* @param time timestamp with millisecond granularity
* @param x surface-local x coordinate
* @param y surface-local y coordinate
*
* @since 1
*
*/
motion (time: number, x: Fixed, y: Fixed) {
this.client.marshall(this.id, 3, [uint(time), fixed(x), fixed(y)])
}
/**
*
* The event is sent when a drag-and-drop operation is ended
* because the implicit grab is removed.
*
* The drag-and-drop destination is expected to honor the last action
* received through wl_data_offer.action, if the resulting action is
* "copy" or "move", the destination can still perform
* wl_data_offer.receive requests, and is expected to end all
* transfers with a wl_data_offer.finish request.
*
* If the resulting action is "ask", the action will not be considered
* final. The drag-and-drop destination is expected to perform one last
* wl_data_offer.set_actions request, or wl_data_offer.destroy in order
* to cancel the operation.
*
* @since 1
*
*/
drop () {
this.client.marshall(this.id, 4, [])
}
/**
*
* The selection event is sent out to notify the client of a new
* wl_data_offer for the selection for this device. The
* data_device.data_offer and the data_offer.offer events are
* sent out immediately before this event to introduce the data
* offer object. The selection event is sent to a client
* immediately before receiving keyboard focus and when a new
* selection is set while the client has keyboard focus. The
* data_offer is valid until a new data_offer or NULL is received
* or until the client loses keyboard focus. The client must
* destroy the previous selection data_offer, if any, upon receiving
* this event.
*
*
* @param id selection data_offer object
*
* @since 1
*
*/
selection (id: Westfield.WlDataOfferResource|undefined) {
this.client.marshall(this.id, 5, [objectOptional(id)])
}
constructor (client: Westfield.Client, id: number, version: number) {
super(client, id, version)
}
[0] (message: WlMessage) {
return this.implementation.startDrag(this, oOptional<Westfield.WlDataSourceResource>(message, this.client.connection), o<Westfield.WlSurfaceResource>(message, this.client.connection), oOptional<Westfield.WlSurfaceResource>(message, this.client.connection), u(message))
}
[1] (message: WlMessage) {
return this.implementation.setSelection(this, oOptional<Westfield.WlDataSourceResource>(message, this.client.connection), u(message))
}
[2] (message: WlMessage) {
return this.implementation.release(this)
}
}
export interface WlDataDeviceRequests {
/**
*
* This request asks the compositor to start a drag-and-drop
* operation on behalf of the client.
*
* The source argument is the data source that provides the data
* for the eventual data transfer. If source is NULL, enter, leave
* and motion events are sent only to the client that initiated the
* drag and the client is expected to handle the data passing
* internally.
*
* The origin surface is the surface where the drag originates and
* the client must have an active implicit grab that matches the
* serial.
*
* The icon surface is an optional (can be NULL) surface that
* provides an icon to be moved around with the cursor. Initially,
* the top-left corner of the icon surface is placed at the cursor
* hotspot, but subsequent wl_surface.attach request can move the
* relative position. Attach requests must be confirmed with
* wl_surface.commit as usual. The icon surface is given the role of
* a drag-and-drop icon. If the icon surface already has another role,
* it raises a protocol error.
*
* The current and pending input regions of the icon wl_surface are
* cleared, and wl_surface.set_input_region is ignored until the
* wl_surface is no longer used as the icon surface. When the use
* as an icon ends, the current and pending input regions become
* undefined, and the wl_surface is unmapped.
*
*
* @param resource The protocol resource of this implementation.
* @param source data source for the eventual transfer
* @param origin surface where the drag originates
* @param icon drag-and-drop icon surface
* @param serial serial number of the implicit grab on the origin
*
* @since 1
*
*/
startDrag(resource: WlDataDeviceResource, source: Westfield.WlDataSourceResource|undefined, origin: Westfield.WlSurfaceResource, icon: Westfield.WlSurfaceResource|undefined, serial: number): void
/**
*
* This request asks the compositor to set the selection
* to the data from the source on behalf of the client.
*
* To unset the selection, set the source to NULL.
*
*
* @param resource The protocol resource of this implementation.
* @param source data source for the selection
* @param serial serial number of the event that triggered this request
*
* @since 1
*
*/
setSelection(resource: WlDataDeviceResource, source: Westfield.WlDataSourceResource|undefined, serial: number): void
/**
*
* This request destroys the data device.
*
*
* @param resource The protocol resource of this implementation.
*
* @since 2
*
*/
release(resource: WlDataDeviceResource): void
}
export enum WlDataDeviceError {
/**
* given wl_surface has another role
*/
role = 0
}
/**
*
* The wl_data_device_manager is a singleton global object that
* provides access to inter-client data transfer mechanisms such as
* copy-and-paste and drag-and-drop. These mechanisms are tied to
* a wl_seat and this interface lets a client get a wl_data_device
* corresponding to a wl_seat.
*
* Depending on the version bound, the objects created from the bound
* wl_data_device_manager object will have different requirements for
* functioning properly. See wl_data_source.set_actions,
* wl_data_offer.accept and wl_data_offer.finish for details.
*
*/
export class WlDataDeviceManagerResource extends Westfield.Resource {
static readonly protocolName = 'wl_data_device_manager'
//@ts-ignore Should always be set when resource is created.
implementation: WlDataDeviceManagerRequests
constructor (client: Westfield.Client, id: number, version: number) {
super(client, id, version)
}
[0] (message: WlMessage) {
return this.implementation.createDataSource(this, n(message))
}
[1] (message: WlMessage) {
return this.implementation.getDataDevice(this, n(message), o<Westfield.WlSeatResource>(message, this.client.connection))
}
}
export interface WlDataDeviceManagerRequests {
/**
*
* Create a new data source.
*
*
* @param resource The protocol resource of this implementation.
* @param id data source to create
*
* @since 1
*
*/
createDataSource(resource: WlDataDeviceManagerResource, id: number): void
/**
*
* Create a new data device for a given seat.
*
*
* @param resource The protocol resource of this implementation.
* @param id data device to create
* @param seat seat associated with the data device
*
* @since 1
*
*/
getDataDevice(resource: WlDataDeviceManagerResource, id: number, seat: Westfield.WlSeatResource): void
}
export enum WlDataDeviceManagerDndAction {
/**
* no action
*/
none = 0,
/**
* copy action
*/
copy = 1,
/**
* move action
*/
move = 2,
/**
* ask action
*/
ask = 4
}
/**
*
* This interface is implemented by servers that provide
* desktop-style user interfaces.
*
* It allows clients to associate a wl_shell_surface with
* a basic surface.
*
*/
export class WlShellResource extends Westfield.Resource {
static readonly protocolName = 'wl_shell'
//@ts-ignore Should always be set when resource is created.
implementation: WlShellRequests
constructor (client: Westfield.Client, id: number, version: number) {
super(client, id, version)
}
[0] (message: WlMessage) {
return this.implementation.getShellSurface(this, n(message), o<Westfield.WlSurfaceResource>(message, this.client.connection))
}
}
export interface WlShellRequests {
/**
*
* Create a shell surface for an existing surface. This gives
* the wl_surface the role of a shell surface. If the wl_surface
* already has another role, it raises a protocol error.
*
* Only one shell surface can be associated with a given surface.
*
*
* @param resource The protocol resource of this implementation.
* @param id shell surface to create
* @param surface surface to be given the shell surface role
*
* @since 1
*
*/
getShellSurface(resource: WlShellResource, id: number, surface: Westfield.WlSurfaceResource): void
}
export enum WlShellError {
/**
* given wl_surface has another role
*/
role = 0
}
/**
*
* An interface that may be implemented by a wl_surface, for
* implementations that provide a desktop-style user interface.
*
* It provides requests to treat surfaces like toplevel, fullscreen
* or popup windows, move, resize or maximize them, associate
* metadata like title and class, etc.
*
* On the server side the object is automatically destroyed when
* the related wl_surface is destroyed. On the client side,
* wl_shell_surface_destroy() must be called before destroying
* the wl_surface object.
*
*/
export class WlShellSurfaceResource extends Westfield.Resource {
static readonly protocolName = 'wl_shell_surface'
//@ts-ignore Should always be set when resource is created.
implementation: WlShellSurfaceRequests
/**
*
* Ping a client to check if it is receiving events and sending
* requests. A client is expected to reply with a pong request.
*
*
* @param serial serial number of the ping
*
* @since 1
*
*/
ping (serial: number) {
this.client.marshall(this.id, 0, [uint(serial)])
}
/**
*
* The configure event asks the client to resize its surface.
*
* The size is a hint, in the sense that the client is free to
* ignore it if it doesn't resize, pick a smaller size (to
* satisfy aspect ratio or resize in steps of NxM pixels).
*
* The edges parameter provides a hint about how the surface
* was resized. The client may use this information to decide
* how to adjust its content to the new size (e.g. a scrolling
* area might adjust its content position to leave the viewable
* content unmoved).
*
* The client is free to dismiss all but the last configure
* event it received.
*
* The width and height arguments specify the size of the window
* in surface-local coordinates.
*
*
* @param edges how the surface was resized
* @param width new width of the surface
* @param height new height of the surface
*
* @since 1
*
*/
configure (edges: number, width: number, height: number) {
this.client.marshall(this.id, 1, [uint(edges), int(width), int(height)])
}
/**
*
* The popup_done event is sent out when a popup grab is broken,
* that is, when the user clicks a surface that doesn't belong
* to the client owning the popup surface.
*
* @since 1
*
*/
popupDone () {
this.client.marshall(this.id, 2, [])
}
constructor (client: Westfield.Client, id: number, version: number) {
super(client, id, version)
}
[0] (message: WlMessage) {
return this.implementation.pong(this, u(message))
}
[1] (message: WlMessage) {
return this.implementation.move(this, o<Westfield.WlSeatResource>(message, this.client.connection), u(message))
}
[2] (message: WlMessage) {
return this.implementation.resize(this, o<Westfield.WlSeatResource>(message, this.client.connection), u(message), u(message))
}
[3] (message: WlMessage) {
return this.implementation.setToplevel(this)
}
[4] (message: WlMessage) {
return this.implementation.setTransient(this, o<Westfield.WlSurfaceResource>(message, this.client.connection), i(message), i(message), u(message))
}
[5] (message: WlMessage) {
return this.implementation.setFullscreen(this, u(message), u(message), oOptional<Westfield.WlOutputResource>(message, this.client.connection))
}
[6] (message: WlMessage) {
return this.implementation.setPopup(this, o<Westfield.WlSeatResource>(message, this.client.connection), u(message), o<Westfield.WlSurfaceResource>(message, this.client.connection), i(message), i(message), u(message))
}
[7] (message: WlMessage) {
return this.implementation.setMaximized(this, oOptional<Westfield.WlOutputResource>(message, this.client.connection))
}
[8] (message: WlMessage) {
return this.implementation.setTitle(this, s(message))
}
[9] (message: WlMessage) {
return this.implementation.setClass(this, s(message))
}
}
export interface WlShellSurfaceRequests {
/**
*
* A client must respond to a ping event with a pong request or
* the client may be deemed unresponsive.
*
*
* @param resource The protocol resource of this implementation.
* @param serial serial number of the ping event
*
* @since 1
*
*/
pong(resource: WlShellSurfaceResource, serial: number): void
/**
*
* Start a pointer-driven move of the surface.
*
* This request must be used in response to a button press event.
* The server may ignore move requests depending on the state of
* the surface (e.g. fullscreen or maximized).
*
*
* @param resource The protocol resource of this implementation.
* @param seat seat whose pointer is used
* @param serial serial number of the implicit grab on the pointer
*
* @since 1
*
*/
move(resource: WlShellSurfaceResource, seat: Westfield.WlSeatResource, serial: number): void
/**
*
* Start a pointer-driven resizing of the surface.
*
* This request must be used in response to a button press event.
* The server may ignore resize requests depending on the state of
* the surface (e.g. fullscreen or maximized).
*
*
* @param resource The protocol resource of this implementation.
* @param seat seat whose pointer is used
* @param serial serial number of the implicit grab on the pointer
* @param edges which edge or corner is being dragged
*
* @since 1
*
*/
resize(resource: WlShellSurfaceResource, seat: Westfield.WlSeatResource, serial: number, edges: number): void
/**
*
* Map the surface as a toplevel surface.
*
* A toplevel surface is not fullscreen, maximized or transient.
*
*
* @param resource The protocol resource of this implementation.
*
* @since 1
*
*/
setToplevel(resource: WlShellSurfaceResource): void
/**
*
* Map the surface relative to an existing surface.
*
* The x and y arguments specify the location of the upper left
* corner of the surface relative to the upper left corner of the
* parent surface, in surface-local coordinates.
*
* The flags argument controls details of the transient behaviour.
*
*
* @param resource The protocol resource of this implementation.
* @param parent parent surface
* @param x surface-local x coordinate
* @param y surface-local y coordinate
* @param flags transient surface behavior
*
* @since 1
*
*/
setTransient(resource: WlShellSurfaceResource, parent: Westfield.WlSurfaceResource, x: number, y: number, flags: number): void
/**
*
* Map the surface as a fullscreen surface.
*
* If an output parameter is given then the surface will be made
* fullscreen on that output. If the client does not specify the
* output then the compositor will apply its policy - usually
* choosing the output on which the surface has the biggest surface
* area.
*
* The client may specify a method to resolve a size conflict
* between the output size and the surface size - this is provided
* through the method parameter.
*
* The framerate parameter is used only when the method is set
* to "driver", to indicate the preferred framerate. A value of 0
* indicates that the client does not care about framerate. The
* framerate is specified in mHz, that is framerate of 60000 is 60Hz.
*
* A method of "scale" or "driver" implies a scaling operation of
* the surface, either via a direct scaling operation or a change of
* the output mode. This will override any kind of output scaling, so
* that mapping a surface with a buffer size equal to the mode can
* fill the screen independent of buffer_scale.
*
* A method of "fill" means we don't scale up the buffer, however
* any output scale is applied. This means that you may run into
* an edge case where the application maps a buffer with the same
* size of the output mode but buffer_scale 1 (thus making a
* surface larger than the output). In this case it is allowed to
* downscale the results to fit the screen.
*
* The compositor must reply to this request with a configure event
* with the dimensions for the output on which the surface will
* be made fullscreen.
*
*
* @param resource The protocol resource of this implementation.
* @param method method for resolving size conflict
* @param framerate framerate in mHz
* @param output output on which the surface is to be fullscreen
*
* @since 1
*
*/
setFullscreen(resource: WlShellSurfaceResource, method: number, framerate: number, output: Westfield.WlOutputResource|undefined): void
/**
*
* Map the surface as a popup.
*
* A popup surface is a transient surface with an added pointer
* grab.
*
* An existing implicit grab will be changed to owner-events mode,
* and the popup grab will continue after the implicit grab ends
* (i.e. releasing the mouse button does not cause the popup to
* be unmapped).
*
* The popup grab continues until the window is destroyed or a
* mouse button is pressed in any other client's window. A click
* in any of the client's surfaces is reported as normal, however,
* clicks in other clients' surfaces will be discarded and trigger
* the callback.
*
* The x and y arguments specify the location of the upper left
* corner of the surface relative to the upper left corner of the
* parent surface, in surface-local coordinates.
*
*
* @param resource The protocol resource of this implementation.
* @param seat seat whose pointer is used
* @param serial serial number of the implicit grab on the pointer
* @param parent parent surface
* @param x surface-local x coordinate
* @param y surface-local y coordinate
* @param flags transient surface behavior
*
* @since 1
*
*/
setPopup(resource: WlShellSurfaceResource, seat: Westfield.WlSeatResource, serial: number, parent: Westfield.WlSurfaceResource, x: number, y: number, flags: number): void
/**
*
* Map the surface as a maximized surface.
*
* If an output parameter is given then the surface will be
* maximized on that output. If the client does not specify the
* output then the compositor will apply its policy - usually
* choosing the output on which the surface has the biggest surface
* area.
*
* The compositor will reply with a configure event telling
* the expected new surface size. The operation is completed
* on the next buffer attach to this surface.
*
* A maximized surface typically fills the entire output it is
* bound to, except for desktop elements such as panels. This is
* the main difference between a maximized shell surface and a
* fullscreen shell surface.
*
* The details depend on the compositor implementation.
*
*
* @param resource The protocol resource of this implementation.
* @param output output on which the surface is to be maximized
*
* @since 1
*
*/
setMaximized(resource: WlShellSurfaceResource, output: Westfield.WlOutputResource|undefined): void
/**
*
* Set a short title for the surface.
*
* This string may be used to identify the surface in a task bar,
* window list, or other user interface elements provided by the
* compositor.
*
* The string must be encoded in UTF-8.
*
*
* @param resource The protocol resource of this implementation.
* @param title surface title
*
* @since 1
*
*/
setTitle(resource: WlShellSurfaceResource, title: string): void
/**
*
* Set a class for the surface.
*
* The surface class identifies the general class of applications
* to which the surface belongs. A common convention is to use the
* file name (or the full path if it is a non-standard location) of
* the application's .desktop file as the class.
*
*
* @param resource The protocol resource of this implementation.
* @param clazz surface class
*
* @since 1
*
*/
setClass(resource: WlShellSurfaceResource, clazz: string): void
}
export enum WlShellSurfaceResize {
/**
* no edge
*/
none = 0,
/**
* top edge
*/
top = 1,
/**
* bottom edge
*/
bottom = 2,
/**
* left edge
*/
left = 4,
/**
* top and left edges
*/
topLeft = 5,
/**
* bottom and left edges
*/
bottomLeft = 6,
/**
* right edge
*/
right = 8,
/**
* top and right edges
*/
topRight = 9,
/**
* bottom and right edges
*/
bottomRight = 10
}
export enum WlShellSurfaceTransient {
/**
* do not set keyboard focus
*/
inactive = 0x1
}
export enum WlShellSurfaceFullscreenMethod {
/**
* no preference, apply default policy
*/
default = 0,
/**
* scale, preserve the surface's aspect ratio and center on output
*/
scale = 1,
/**
* switch output mode to the smallest mode that can fit the surface, add black borders to compensate size mismatch
*/
driver = 2,
/**
* no upscaling, center on output and add black borders to compensate size mismatch
*/
fill = 3
}
/**
*
* A surface is a rectangular area that is displayed on the screen.
* It has a location, size and pixel contents.
*
* The size of a surface (and relative positions on it) is described
* in surface-local coordinates, which may differ from the buffer
* coordinates of the pixel content, in case a buffer_transform
* or a buffer_scale is used.
*
* A surface without a "role" is fairly useless: a compositor does
* not know where, when or how to present it. The role is the
* purpose of a wl_surface. Examples of roles are a cursor for a
* pointer (as set by wl_pointer.set_cursor), a drag icon
* (wl_data_device.start_drag), a sub-surface
* (wl_subcompositor.get_subsurface), and a window as defined by a
* shell protocol (e.g. wl_shell.get_shell_surface).
*
* A surface can have only one role at a time. Initially a
* wl_surface does not have a role. Once a wl_surface is given a
* role, it is set permanently for the whole lifetime of the
* wl_surface object. Giving the current role again is allowed,
* unless explicitly forbidden by the relevant interface
* specification.
*
* Surface roles are given by requests in other interfaces such as
* wl_pointer.set_cursor. The request should explicitly mention
* that this request gives a role to a wl_surface. Often, this
* request also creates a new protocol object that represents the
* role and adds additional functionality to wl_surface. When a
* client wants to destroy a wl_surface, they must destroy this 'role
* object' before the wl_surface.
*
* Destroying the role object does not remove the role from the
* wl_surface, but it may stop the wl_surface from "playing the role".
* For instance, if a wl_subsurface object is destroyed, the wl_surface
* it was created for will be unmapped and forget its position and
* z-order. It is allowed to create a wl_subsurface for the same
* wl_surface again, but it is not allowed to use the wl_surface as
* a cursor (cursor is a different role than sub-surface, and role
* switching is not allowed).
*
*/
export class WlSurfaceResource extends Westfield.Resource {
static readonly protocolName = 'wl_surface'
//@ts-ignore Should always be set when resource is created.
implementation: WlSurfaceRequests
/**
*
* This is emitted whenever a surface's creation, movement, or resizing
* results in some part of it being within the scanout region of an
* output.
*
* Note that a surface may be overlapping with zero or more outputs.
*
*
* @param output output entered by the surface
*
* @since 1
*
*/
enter (output: Westfield.WlOutputResource) {
this.client.marshall(this.id, 0, [object(output)])
}
/**
*
* This is emitted whenever a surface's creation, movement, or resizing
* results in it no longer having any part of it within the scanout region
* of an output.
*
*
* @param output output left by the surface
*
* @since 1
*
*/
leave (output: Westfield.WlOutputResource) {
this.client.marshall(this.id, 1, [object(output)])
}
constructor (client: Westfield.Client, id: number, version: number) {
super(client, id, version)
}
[0] (message: WlMessage) {
return this.implementation.destroy(this)
}
[1] (message: WlMessage) {
return this.implementation.attach(this, oOptional<Westfield.WlBufferResource>(message, this.client.connection), i(message), i(message))
}
[2] (message: WlMessage) {
return this.implementation.damage(this, i(message), i(message), i(message), i(message))
}
[3] (message: WlMessage) {
return this.implementation.frame(this, n(message))
}
[4] (message: WlMessage) {
return this.implementation.setOpaqueRegion(this, oOptional<Westfield.WlRegionResource>(message, this.client.connection))
}
[5] (message: WlMessage) {
return this.implementation.setInputRegion(this, oOptional<Westfield.WlRegionResource>(message, this.client.connection))
}
[6] (message: WlMessage) {
return this.implementation.commit(this, u(message))
}
[7] (message: WlMessage) {
return this.implementation.setBufferTransform(this, i(message))
}
[8] (message: WlMessage) {
return this.implementation.setBufferScale(this, i(message))
}
[9] (message: WlMessage) {
return this.implementation.damageBuffer(this, i(message), i(message), i(message), i(message))
}
}
export interface WlSurfaceRequests {
/**
*
* Deletes the surface and invalidates its object ID.
*
*
* @param resource The protocol resource of this implementation.
*
* @since 1
*
*/
destroy(resource: WlSurfaceResource): void
/**
*
* Set a buffer as the content of this surface.
*
* The new size of the surface is calculated based on the buffer
* size transformed by the inverse buffer_transform and the
* inverse buffer_scale. This means that the supplied buffer
* must be an integer multiple of the buffer_scale.
*
* The x and y arguments specify the location of the new pending
* buffer's upper left corner, relative to the current buffer's upper
* left corner, in surface-local coordinates. In other words, the
* x and y, combined with the new surface size define in which
* directions the surface's size changes.
*
* Surface contents are double-buffered state, see wl_surface.commit.
*
* The initial surface contents are void; there is no content.
* wl_surface.attach assigns the given wl_buffer as the pending
* wl_buffer. wl_surface.commit makes the pending wl_buffer the new
* surface contents, and the size of the surface becomes the size
* calculated from the wl_buffer, as described above. After commit,
* there is no pending buffer until the next attach.
*
* Committing a pending wl_buffer allows the compositor to read the
* pixels in the wl_buffer. The compositor may access the pixels at
* any time after the wl_surface.commit request. When the compositor
* will not access the pixels anymore, it will send the
* wl_buffer.release event. Only after receiving wl_buffer.release,
* the client may reuse the wl_buffer. A wl_buffer that has been
* attached and then replaced by another attach instead of committed
* will not receive a release event, and is not used by the
* compositor.
*
* Destroying the wl_buffer after wl_buffer.release does not change
* the surface contents. However, if the client destroys the
* wl_buffer before receiving the wl_buffer.release event, the surface
* contents become undefined immediately.
*
* If wl_surface.attach is sent with a NULL wl_buffer, the
* following wl_surface.commit will remove the surface content.
*
*
* @param resource The protocol resource of this implementation.
* @param buffer buffer of surface contents
* @param x surface-local x coordinate
* @param y surface-local y coordinate
*
* @since 1
*
*/
attach(resource: WlSurfaceResource, buffer: Westfield.WlBufferResource|undefined, x: number, y: number): void
/**
*
* This request is used to describe the regions where the pending
* buffer is different from the current surface contents, and where
* the surface therefore needs to be repainted. The compositor
* ignores the parts of the damage that fall outside of the surface.
*
* Damage is double-buffered state, see wl_surface.commit.
*
* The damage rectangle is specified in surface-local coordinates,
* where x and y specify the upper left corner of the damage rectangle.
*
* The initial value for pending damage is empty: no damage.
* wl_surface.damage adds pending damage: the new pending damage
* is the union of old pending damage and the given rectangle.
*
* wl_surface.commit assigns pending damage as the current damage,
* and clears pending damage. The server will clear the current
* damage as it repaints the surface.
*
* Alternatively, damage can be posted with wl_surface.damage_buffer
* which uses buffer coordinates instead of surface coordinates,
* and is probably the preferred and intuitive way of doing this.
*
*
* @param resource The protocol resource of this implementation.
* @param x surface-local x coordinate
* @param y surface-local y coordinate
* @param width width of damage rectangle
* @param height height of damage rectangle
*
* @since 1
*
*/
damage(resource: WlSurfaceResource, x: number, y: number, width: number, height: number): void
/**
*
* Request a notification when it is a good time to start drawing a new
* frame, by creating a frame callback. This is useful for throttling
* redrawing operations, and driving animations.
*
* When a client is animating on a wl_surface, it can use the 'frame'
* request to get notified when it is a good time to draw and commit the
* next frame of animation. If the client commits an update earlier than
* that, it is likely that some updates will not make it to the display,
* and the client is wasting resources by drawing too often.
*
* The frame request will take effect on the next wl_surface.commit.
* The notification will only be posted for one frame unless
* requested again. For a wl_surface, the notifications are posted in
* the order the frame requests were committed.
*
* The server must send the notifications so that a client
* will not send excessive updates, while still allowing
* the highest possible update rate for clients that wait for the reply
* before drawing again. The server should give some time for the client
* to draw and commit after sending the frame callback events to let it
* hit the next output refresh.
*
* A server should avoid signaling the frame callbacks if the
* surface is not visible in any way, e.g. the surface is off-screen,
* or completely obscured by other opaque surfaces.
*
* The object returned by this request will be destroyed by the
* compositor after the callback is fired and as such the client must not
* attempt to use it after that point.
*
* The callback_data passed in the callback is the current time, in
* milliseconds, with an undefined base.
*
*
* @param resource The protocol resource of this implementation.
* @param callback callback object for the frame request
*
* @since 1
*
*/
frame(resource: WlSurfaceResource, callback: number): void
/**
*
* This request sets the region of the surface that contains
* opaque content.
*
* The opaque region is an optimization hint for the compositor
* that lets it optimize the redrawing of content behind opaque
* regions. Setting an opaque region is not required for correct
* behaviour, but marking transparent content as opaque will result
* in repaint artifacts.
*
* The opaque region is specified in surface-local coordinates.
*
* The compositor ignores the parts of the opaque region that fall
* outside of the surface.
*
* Opaque region is double-buffered state, see wl_surface.commit.
*
* wl_surface.set_opaque_region changes the pending opaque region.
* wl_surface.commit copies the pending region to the current region.
* Otherwise, the pending and current regions are never changed.
*
* The initial value for an opaque region is empty. Setting the pending
* opaque region has copy semantics, and the wl_region object can be
* destroyed immediately. A NULL wl_region causes the pending opaque
* region to be set to empty.
*
*
* @param resource The protocol resource of this implementation.
* @param region opaque region of the surface
*
* @since 1
*
*/
setOpaqueRegion(resource: WlSurfaceResource, region: Westfield.WlRegionResource|undefined): void
/**
*
* This request sets the region of the surface that can receive
* pointer and touch events.
*
* Input events happening outside of this region will try the next
* surface in the server surface stack. The compositor ignores the
* parts of the input region that fall outside of the surface.
*
* The input region is specified in surface-local coordinates.
*
* Input region is double-buffered state, see wl_surface.commit.
*
* wl_surface.set_input_region changes the pending input region.
* wl_surface.commit copies the pending region to the current region.
* Otherwise the pending and current regions are never changed,
* except cursor and icon surfaces are special cases, see
* wl_pointer.set_cursor and wl_data_device.start_drag.
*
* The initial value for an input region is infinite. That means the
* whole surface will accept input. Setting the pending input region
* has copy semantics, and the wl_region object can be destroyed
* immediately. A NULL wl_region causes the input region to be set
* to infinite.
*
*
* @param resource The protocol resource of this implementation.
* @param region input region of the surface
*
* @since 1
*
*/
setInputRegion(resource: WlSurfaceResource, region: Westfield.WlRegionResource|undefined): void
/**
*
* Surface state (input, opaque, and damage regions, attached buffers,
* etc.) is double-buffered. Protocol requests modify the pending state,
* as opposed to the current state in use by the compositor. A commit
* request atomically applies all pending state, replacing the current
* state. After commit, the new pending state is as documented for each
* related request.
*
* On commit, a pending wl_buffer is applied first, and all other state
* second. This means that all coordinates in double-buffered state are
* relative to the new wl_buffer coming into use, except for
* wl_surface.attach itself. If there is no pending wl_buffer, the
* coordinates are relative to the current surface contents.
*
* All requests that need a commit to become effective are documented
* to affect double-buffered state.
*
* Other interfaces may add further double-buffered surface state.
*
*
* @param resource The protocol resource of this implementation.
* @param serial serial number of the commit
*
* @since 1
*
*/
commit(resource: WlSurfaceResource, serial: number): void
/**
*
* This request sets an optional transformation on how the compositor
* interprets the contents of the buffer attached to the surface. The
* accepted values for the transform parameter are the values for
* wl_output.transform.
*
* Buffer transform is double-buffered state, see wl_surface.commit.
*
* A newly created surface has its buffer transformation set to normal.
*
* wl_surface.set_buffer_transform changes the pending buffer
* transformation. wl_surface.commit copies the pending buffer
* transformation to the current one. Otherwise, the pending and current
* values are never changed.
*
* The purpose of this request is to allow clients to render content
* according to the output transform, thus permitting the compositor to
* use certain optimizations even if the display is rotated. Using
* hardware overlays and scanning out a client buffer for fullscreen
* surfaces are examples of such optimizations. Those optimizations are
* highly dependent on the compositor implementation, so the use of this
* request should be considered on a case-by-case basis.
*
* Note that if the transform value includes 90 or 270 degree rotation,
* the width of the buffer will become the surface height and the height
* of the buffer will become the surface width.
*
* If transform is not one of the values from the
* wl_output.transform enum the invalid_transform protocol error
* is raised.
*
*
* @param resource The protocol resource of this implementation.
* @param transform transform for interpreting buffer contents
*
* @since 2
*
*/
setBufferTransform(resource: WlSurfaceResource, transform: number): void
/**
*
* This request sets an optional scaling factor on how the compositor
* interprets the contents of the buffer attached to the window.
*
* Buffer scale is double-buffered state, see wl_surface.commit.
*
* A newly created surface has its buffer scale set to 1.
*
* wl_surface.set_buffer_scale changes the pending buffer scale.
* wl_surface.commit copies the pending buffer scale to the current one.
* Otherwise, the pending and current values are never changed.
*
* The purpose of this request is to allow clients to supply higher
* resolution buffer data for use on high resolution outputs. It is
* intended that you pick the same buffer scale as the scale of the
* output that the surface is displayed on. This means the compositor
* can avoid scaling when rendering the surface on that output.
*
* Note that if the scale is larger than 1, then you have to attach
* a buffer that is larger (by a factor of scale in each dimension)
* than the desired surface size.
*
* If scale is not positive the invalid_scale protocol error is
* raised.
*
*
* @param resource The protocol resource of this implementation.
* @param scale positive scale for interpreting buffer contents
*
* @since 3
*
*/
setBufferScale(resource: WlSurfaceResource, scale: number): void
/**
*
* This request is used to describe the regions where the pending
* buffer is different from the current surface contents, and where
* the surface therefore needs to be repainted. The compositor
* ignores the parts of the damage that fall outside of the surface.
*
* Damage is double-buffered state, see wl_surface.commit.
*
* The damage rectangle is specified in buffer coordinates,
* where x and y specify the upper left corner of the damage rectangle.
*
* The initial value for pending damage is empty: no damage.
* wl_surface.damage_buffer adds pending damage: the new pending
* damage is the union of old pending damage and the given rectangle.
*
* wl_surface.commit assigns pending damage as the current damage,
* and clears pending damage. The server will clear the current
* damage as it repaints the surface.
*
* This request differs from wl_surface.damage in only one way - it
* takes damage in buffer coordinates instead of surface-local
* coordinates. While this generally is more intuitive than surface
* coordinates, it is especially desirable when using wp_viewport
* or when a drawing library (like EGL) is unaware of buffer scale
* and buffer transform.
*
* Note: Because buffer transformation changes and damage requests may
* be interleaved in the protocol stream, it is impossible to determine
* the actual mapping between surface and buffer damage until
* wl_surface.commit time. Therefore, compositors wishing to take both
* kinds of damage into account will have to accumulate damage from the
* two requests separately and only transform from one to the other
* after receiving the wl_surface.commit.
*
*
* @param resource The protocol resource of this implementation.
* @param x buffer-local x coordinate
* @param y buffer-local y coordinate
* @param width width of damage rectangle
* @param height height of damage rectangle
*
* @since 4
*
*/
damageBuffer(resource: WlSurfaceResource, x: number, y: number, width: number, height: number): void
}
export enum WlSurfaceError {
/**
* buffer scale value is invalid
*/
invalidScale = 0,
/**
* buffer transform value is invalid
*/
invalidTransform = 1
}
/**
*
* A seat is a group of keyboards, pointer and touch devices. This
* object is published as a global during start up, or when such a
* device is hot plugged. A seat typically has a pointer and
* maintains a keyboard focus and a pointer focus.
*
*/
export class WlSeatResource extends Westfield.Resource {
static readonly protocolName = 'wl_seat'
//@ts-ignore Should always be set when resource is created.
implementation: WlSeatRequests
/**
*
* This is emitted whenever a seat gains or loses the pointer,
* keyboard or touch capabilities. The argument is a capability
* enum containing the complete set of capabilities this seat has.
*
* When the pointer capability is added, a client may create a
* wl_pointer object using the wl_seat.get_pointer request. This object
* will receive pointer events until the capability is removed in the
* future.
*
* When the pointer capability is removed, a client should destroy the
* wl_pointer objects associated with the seat where the capability was
* removed, using the wl_pointer.release request. No further pointer
* events will be received on these objects.
*
* In some compositors, if a seat regains the pointer capability and a
* client has a previously obtained wl_pointer object of version 4 or
* less, that object may start sending pointer events again. This
* behavior is considered a misinterpretation of the intended behavior
* and must not be relied upon by the client. wl_pointer objects of
* version 5 or later must not send events if created before the most
* recent event notifying the client of an added pointer capability.
*
* The above behavior also applies to wl_keyboard and wl_touch with the
* keyboard and touch capabilities, respectively.
*
*
* @param capabilities capabilities of the seat
*
* @since 1
*
*/
capabilities (capabilities: number) {
this.client.marshall(this.id, 0, [uint(capabilities)])
}
/**
*
* In a multiseat configuration this can be used by the client to help
* identify which physical devices the seat represents. Based on
* the seat configuration used by the compositor.
*
*
* @param name seat identifier
*
* @since 2
*
*/
name (name: string) {
this.client.marshall(this.id, 1, [string(name)])
}
constructor (client: Westfield.Client, id: number, version: number) {
super(client, id, version)
}
[0] (message: WlMessage) {
return this.implementation.getPointer(this, n(message))
}
[1] (message: WlMessage) {
return this.implementation.getKeyboard(this, n(message))
}
[2] (message: WlMessage) {
return this.implementation.getTouch(this, n(message))
}
[3] (message: WlMessage) {
return this.implementation.release(this)
}
}
export interface WlSeatRequests {
/**
*
* The ID provided will be initialized to the wl_pointer interface
* for this seat.
*
* This request only takes effect if the seat has the pointer
* capability, or has had the pointer capability in the past.
* It is a protocol violation to issue this request on a seat that has
* never had the pointer capability.
*
*
* @param resource The protocol resource of this implementation.
* @param id seat pointer
*
* @since 1
*
*/
getPointer(resource: WlSeatResource, id: number): void
/**
*
* The ID provided will be initialized to the wl_keyboard interface
* for this seat.
*
* This request only takes effect if the seat has the keyboard
* capability, or has had the keyboard capability in the past.
* It is a protocol violation to issue this request on a seat that has
* never had the keyboard capability.
*
*
* @param resource The protocol resource of this implementation.
* @param id seat keyboard
*
* @since 1
*
*/
getKeyboard(resource: WlSeatResource, id: number): void
/**
*
* The ID provided will be initialized to the wl_touch interface
* for this seat.
*
* This request only takes effect if the seat has the touch
* capability, or has had the touch capability in the past.
* It is a protocol violation to issue this request on a seat that has
* never had the touch capability.
*
*
* @param resource The protocol resource of this implementation.
* @param id seat touch interface
*
* @since 1
*
*/
getTouch(resource: WlSeatResource, id: number): void
/**
*
* Using this request a client can tell the server that it is not going to
* use the seat object anymore.
*
*
* @param resource The protocol resource of this implementation.
*
* @since 5
*
*/
release(resource: WlSeatResource): void
}
export enum WlSeatCapability {
/**
* the seat has pointer devices
*/
pointer = 1,
/**
* the seat has one or more keyboards
*/
keyboard = 2,
/**
* the seat has touch devices
*/
touch = 4
}
/**
*
* The wl_pointer interface represents one or more input devices,
* such as mice, which control the pointer location and pointer_focus
* of a seat.
*
* The wl_pointer interface generates motion, enter and leave
* events for the surfaces that the pointer is located over,
* and button and axis events for button presses, button releases
* and scrolling.
*
*/
export class WlPointerResource extends Westfield.Resource {
static readonly protocolName = 'wl_pointer'
//@ts-ignore Should always be set when resource is created.
implementation: WlPointerRequests
/**
*
* Notification that this seat's pointer is focused on a certain
* surface.
*
* When a seat's focus enters a surface, the pointer image
* is undefined and a client should respond to this event by setting
* an appropriate pointer image with the set_cursor request.
*
*
* @param serial serial number of the enter event
* @param surface surface entered by the pointer
* @param surfaceX surface-local x coordinate
* @param surfaceY surface-local y coordinate
*
* @since 1
*
*/
enter (serial: number, surface: Westfield.WlSurfaceResource, surfaceX: Fixed, surfaceY: Fixed) {
this.client.marshall(this.id, 0, [uint(serial), object(surface), fixed(surfaceX), fixed(surfaceY)])
}
/**
*
* Notification that this seat's pointer is no longer focused on
* a certain surface.
*
* The leave notification is sent before the enter notification
* for the new focus.
*
*
* @param serial serial number of the leave event
* @param surface surface left by the pointer
*
* @since 1
*
*/
leave (serial: number, surface: Westfield.WlSurfaceResource) {
this.client.marshall(this.id, 1, [uint(serial), object(surface)])
}
/**
*
* Notification of pointer location change. The arguments
* surface_x and surface_y are the location relative to the
* focused surface.
*
*
* @param time timestamp with millisecond granularity
* @param surfaceX surface-local x coordinate
* @param surfaceY surface-local y coordinate
*
* @since 1
*
*/
motion (time: number, surfaceX: Fixed, surfaceY: Fixed) {
this.client.marshall(this.id, 2, [uint(time), fixed(surfaceX), fixed(surfaceY)])
}
/**
*
* Mouse button click and release notifications.
*
* The location of the click is given by the last motion or
* enter event.
* The time argument is a timestamp with millisecond
* granularity, with an undefined base.
*
* The button is a button code as defined in the Linux kernel's
* linux/input-event-codes.h header file, e.g. BTN_LEFT.
*
* Any 16-bit button code value is reserved for future additions to the
* kernel's event code list. All other button codes above 0xFFFF are
* currently undefined but may be used in future versions of this
* protocol.
*
*
* @param serial serial number of the button event
* @param time timestamp with millisecond granularity
* @param button button that produced the event
* @param state physical state of the button
*
* @since 1
*
*/
button (serial: number, time: number, button: number, state: number) {
this.client.marshall(this.id, 3, [uint(serial), uint(time), uint(button), uint(state)])
}
/**
*
* Scroll and other axis notifications.
*
* For scroll events (vertical and horizontal scroll axes), the
* value parameter is the length of a vector along the specified
* axis in a coordinate space identical to those of motion events,
* representing a relative movement along the specified axis.
*
* For devices that support movements non-parallel to axes multiple
* axis events will be emitted.
*
* When applicable, for example for touch pads, the server can
* choose to emit scroll events where the motion vector is
* equivalent to a motion event vector.
*
* When applicable, a client can transform its content relative to the
* scroll distance.
*
*
* @param time timestamp with millisecond granularity
* @param axis axis type
* @param value length of vector in surface-local coordinate space
*
* @since 1
*
*/
axis (time: number, axis: number, value: Fixed) {
this.client.marshall(this.id, 4, [uint(time), uint(axis), fixed(value)])
}
/**
*
* Indicates the end of a set of events that logically belong together.
* A client is expected to accumulate the data in all events within the
* frame before proceeding.
*
* All wl_pointer events before a wl_pointer.frame event belong
* logically together. For example, in a diagonal scroll motion the
* compositor will send an optional wl_pointer.axis_source event, two
* wl_pointer.axis events (horizontal and vertical) and finally a
* wl_pointer.frame event. The client may use this information to
* calculate a diagonal vector for scrolling.
*
* When multiple wl_pointer.axis events occur within the same frame,
* the motion vector is the combined motion of all events.
* When a wl_pointer.axis and a wl_pointer.axis_stop event occur within
* the same frame, this indicates that axis movement in one axis has
* stopped but continues in the other axis.
* When multiple wl_pointer.axis_stop events occur within the same
* frame, this indicates that these axes stopped in the same instance.
*
* A wl_pointer.frame event is sent for every logical event group,
* even if the group only contains a single wl_pointer event.
* Specifically, a client may get a sequence: motion, frame, button,
* frame, axis, frame, axis_stop, frame.
*
* The wl_pointer.enter and wl_pointer.leave events are logical events
* generated by the compositor and not the hardware. These events are
* also grouped by a wl_pointer.frame. When a pointer moves from one
* surface to another, a compositor should group the
* wl_pointer.leave event within the same wl_pointer.frame.
* However, a client must not rely on wl_pointer.leave and
* wl_pointer.enter being in the same wl_pointer.frame.
* Compositor-specific policies may require the wl_pointer.leave and
* wl_pointer.enter event being split across multiple wl_pointer.frame
* groups.
*
* @since 5
*
*/
frame () {
this.client.marshall(this.id, 5, [])
}
/**
*
* Source information for scroll and other axes.
*
* This event does not occur on its own. It is sent before a
* wl_pointer.frame event and carries the source information for
* all events within that frame.
*
* The source specifies how this event was generated. If the source is
* wl_pointer.axis_source.finger, a wl_pointer.axis_stop event will be
* sent when the user lifts the finger off the device.
*
* If the source is wl_pointer.axis_source.wheel,
* wl_pointer.axis_source.wheel_tilt or
* wl_pointer.axis_source.continuous, a wl_pointer.axis_stop event may
* or may not be sent. Whether a compositor sends an axis_stop event
* for these sources is hardware-specific and implementation-dependent;
* clients must not rely on receiving an axis_stop event for these
* scroll sources and should treat scroll sequences from these scroll
* sources as unterminated by default.
*
* This event is optional. If the source is unknown for a particular
* axis event sequence, no event is sent.
* Only one wl_pointer.axis_source event is permitted per frame.
*
* The order of wl_pointer.axis_discrete and wl_pointer.axis_source is
* not guaranteed.
*
*
* @param axisSource source of the axis event
*
* @since 5
*
*/
axisSource (axisSource: number) {
this.client.marshall(this.id, 6, [uint(axisSource)])
}
/**
*
* Stop notification for scroll and other axes.
*
* For some wl_pointer.axis_source types, a wl_pointer.axis_stop event
* is sent to notify a client that the axis sequence has terminated.
* This enables the client to implement kinetic scrolling.
* See the wl_pointer.axis_source documentation for information on when
* this event may be generated.
*
* Any wl_pointer.axis events with the same axis_source after this
* event should be considered as the start of a new axis motion.
*
* The timestamp is to be interpreted identical to the timestamp in the
* wl_pointer.axis event. The timestamp value may be the same as a
* preceding wl_pointer.axis event.
*
*
* @param time timestamp with millisecond granularity
* @param axis the axis stopped with this event
*
* @since 5
*
*/
axisStop (time: number, axis: number) {
this.client.marshall(this.id, 7, [uint(time), uint(axis)])
}
/**
*
* Discrete step information for scroll and other axes.
*
* This event carries the axis value of the wl_pointer.axis event in
* discrete steps (e.g. mouse wheel clicks).
*
* This event does not occur on its own, it is coupled with a
* wl_pointer.axis event that represents this axis value on a
* continuous scale. The protocol guarantees that each axis_discrete
* event is always followed by exactly one axis event with the same
* axis number within the same wl_pointer.frame. Note that the protocol
* allows for other events to occur between the axis_discrete and
* its coupled axis event, including other axis_discrete or axis
* events.
*
* This event is optional; continuous scrolling devices
* like two-finger scrolling on touchpads do not have discrete
* steps and do not generate this event.
*
* The discrete value carries the directional information. e.g. a value
* of -2 is two steps towards the negative direction of this axis.
*
* The axis number is identical to the axis number in the associated
* axis event.
*
* The order of wl_pointer.axis_discrete and wl_pointer.axis_source is
* not guaranteed.
*
*
* @param axis axis type
* @param discrete number of steps
*
* @since 5
*
*/
axisDiscrete (axis: number, discrete: number) {
this.client.marshall(this.id, 8, [uint(axis), int(discrete)])
}
constructor (client: Westfield.Client, id: number, version: number) {
super(client, id, version)
}
[0] (message: WlMessage) {
return this.implementation.setCursor(this, u(message), oOptional<Westfield.WlSurfaceResource>(message, this.client.connection), i(message), i(message))
}
[1] (message: WlMessage) {
return this.implementation.release(this)
}
}
export interface WlPointerRequests {
/**
*
* Set the pointer surface, i.e., the surface that contains the
* pointer image (cursor). This request gives the surface the role
* of a cursor. If the surface already has another role, it raises
* a protocol error.
*
* The cursor actually changes only if the pointer
* focus for this device is one of the requesting client's surfaces
* or the surface parameter is the current pointer surface. If
* there was a previous surface set with this request it is
* replaced. If surface is NULL, the pointer image is hidden.
*
* The parameters hotspot_x and hotspot_y define the position of
* the pointer surface relative to the pointer location. Its
* top-left corner is always at (x, y) - (hotspot_x, hotspot_y),
* where (x, y) are the coordinates of the pointer location, in
* surface-local coordinates.
*
* On surface.attach requests to the pointer surface, hotspot_x
* and hotspot_y are decremented by the x and y parameters
* passed to the request. Attach must be confirmed by
* wl_surface.commit as usual.
*
* The hotspot can also be updated by passing the currently set
* pointer surface to this request with new values for hotspot_x
* and hotspot_y.
*
* The current and pending input regions of the wl_surface are
* cleared, and wl_surface.set_input_region is ignored until the
* wl_surface is no longer used as the cursor. When the use as a
* cursor ends, the current and pending input regions become
* undefined, and the wl_surface is unmapped.
*
*
* @param resource The protocol resource of this implementation.
* @param serial serial number of the enter event
* @param surface pointer surface
* @param hotspotX surface-local x coordinate
* @param hotspotY surface-local y coordinate
*
* @since 1
*
*/
setCursor(resource: WlPointerResource, serial: number, surface: Westfield.WlSurfaceResource|undefined, hotspotX: number, hotspotY: number): void
/**
*
* Using this request a client can tell the server that it is not going to
* use the pointer object anymore.
*
* This request destroys the pointer proxy object, so clients must not call
* wl_pointer_destroy() after using this request.
*
*
* @param resource The protocol resource of this implementation.
*
* @since 3
*
*/
release(resource: WlPointerResource): void
}
export enum WlPointerError {
/**
* given wl_surface has another role
*/
role = 0
}
export enum WlPointerButtonState {
/**
* the button is not pressed
*/
released = 0,
/**
* the button is pressed
*/
pressed = 1
}
export enum WlPointerAxis {
/**
* vertical axis
*/
verticalScroll = 0,
/**
* horizontal axis
*/
horizontalScroll = 1
}
export enum WlPointerAxisSource {
/**
* a physical wheel rotation
*/
wheel = 0,
/**
* finger on a touch surface
*/
finger = 1,
/**
* continuous coordinate space
*/
continuous = 2,
/**
* a physical wheel tilt
*/
wheelTilt = 3
}
/**
*
* The wl_keyboard interface represents one or more keyboards
* associated with a seat.
*
*/
export class WlKeyboardResource extends Westfield.Resource {
static readonly protocolName = 'wl_keyboard'
//@ts-ignore Should always be set when resource is created.
implementation: WlKeyboardRequests
/**
*
* This event provides a file descriptor to the client which can be
* memory-mapped to provide a keyboard mapping description.
*
*
* @param format keymap format
* @param fd keymap file descriptor
* @param size keymap size, in bytes
*
* @since 1
*
*/
keymap (format: number, fd: WebFD, size: number) {
this.client.marshall(this.id, 0, [uint(format), fileDescriptor(fd), uint(size)])
}
/**
*
* Notification that this seat's keyboard focus is on a certain
* surface.
*
*
* @param serial serial number of the enter event
* @param surface surface gaining keyboard focus
* @param keys the currently pressed keys
*
* @since 1
*
*/
enter (serial: number, surface: Westfield.WlSurfaceResource, keys: ArrayBufferView) {
this.client.marshall(this.id, 1, [uint(serial), object(surface), array(keys)])
}
/**
*
* Notification that this seat's keyboard focus is no longer on
* a certain surface.
*
* The leave notification is sent before the enter notification
* for the new focus.
*
*
* @param serial serial number of the leave event
* @param surface surface that lost keyboard focus
*
* @since 1
*
*/
leave (serial: number, surface: Westfield.WlSurfaceResource) {
this.client.marshall(this.id, 2, [uint(serial), object(surface)])
}
/**
*
* A key was pressed or released.
* The time argument is a timestamp with millisecond
* granularity, with an undefined base.
*
*
* @param serial serial number of the key event
* @param time timestamp with millisecond granularity
* @param key key that produced the event
* @param state physical state of the key
*
* @since 1
*
*/
key (serial: number, time: number, key: number, state: number) {
this.client.marshall(this.id, 3, [uint(serial), uint(time), uint(key), uint(state)])
}
/**
*
* Notifies clients that the modifier and/or group state has
* changed, and it should update its local state.
*
*
* @param serial serial number of the modifiers event
* @param modsDepressed depressed modifiers
* @param modsLatched latched modifiers
* @param modsLocked locked modifiers
* @param group keyboard layout
*
* @since 1
*
*/
modifiers (serial: number, modsDepressed: number, modsLatched: number, modsLocked: number, group: number) {
this.client.marshall(this.id, 4, [uint(serial), uint(modsDepressed), uint(modsLatched), uint(modsLocked), uint(group)])
}
/**
*
* Informs the client about the keyboard's repeat rate and delay.
*
* This event is sent as soon as the wl_keyboard object has been created,
* and is guaranteed to be received by the client before any key press
* event.
*
* Negative values for either rate or delay are illegal. A rate of zero
* will disable any repeating (regardless of the value of delay).
*
* This event can be sent later on as well with a new value if necessary,
* so clients should continue listening for the event past the creation
* of wl_keyboard.
*
*
* @param rate the rate of repeating keys in characters per second
* @param delay delay in milliseconds since key down until repeating starts
*
* @since 4
*
*/
repeatInfo (rate: number, delay: number) {
this.client.marshall(this.id, 5, [int(rate), int(delay)])
}
constructor (client: Westfield.Client, id: number, version: number) {
super(client, id, version)
}
[0] (message: WlMessage) {
return this.implementation.release(this)
}
}
export interface WlKeyboardRequests {
/**
*
* @param resource The protocol resource of this implementation.
*
* @since 3
*
*/
release(resource: WlKeyboardResource): void
}
export enum WlKeyboardKeymapFormat {
/**
* no keymap; client must understand how to interpret the raw keycode
*/
noKeymap = 0,
/**
* libxkbcommon compatible; to determine the xkb keycode, clients must add 8 to the key event keycode
*/
xkbV1 = 1
}
export enum WlKeyboardKeyState {
/**
* key is not pressed
*/
released = 0,
/**
* key is pressed
*/
pressed = 1
}
/**
*
* The wl_touch interface represents a touchscreen
* associated with a seat.
*
* Touch interactions can consist of one or more contacts.
* For each contact, a series of events is generated, starting
* with a down event, followed by zero or more motion events,
* and ending with an up event. Events relating to the same
* contact point can be identified by the ID of the sequence.
*
*/
export class WlTouchResource extends Westfield.Resource {
static readonly protocolName = 'wl_touch'
//@ts-ignore Should always be set when resource is created.
implementation: WlTouchRequests
/**
*
* A new touch point has appeared on the surface. This touch point is
* assigned a unique ID. Future events from this touch point reference
* this ID. The ID ceases to be valid after a touch up event and may be
* reused in the future.
*
*
* @param serial serial number of the touch down event
* @param time timestamp with millisecond granularity
* @param surface surface touched
* @param id the unique ID of this touch point
* @param x surface-local x coordinate
* @param y surface-local y coordinate
*
* @since 1
*
*/
down (serial: number, time: number, surface: Westfield.WlSurfaceResource, id: number, x: Fixed, y: Fixed) {
this.client.marshall(this.id, 0, [uint(serial), uint(time), object(surface), int(id), fixed(x), fixed(y)])
}
/**
*
* The touch point has disappeared. No further events will be sent for
* this touch point and the touch point's ID is released and may be
* reused in a future touch down event.
*
*
* @param serial serial number of the touch up event
* @param time timestamp with millisecond granularity
* @param id the unique ID of this touch point
*
* @since 1
*
*/
up (serial: number, time: number, id: number) {
this.client.marshall(this.id, 1, [uint(serial), uint(time), int(id)])
}
/**
*
* A touch point has changed coordinates.
*
*
* @param time timestamp with millisecond granularity
* @param id the unique ID of this touch point
* @param x surface-local x coordinate
* @param y surface-local y coordinate
*
* @since 1
*
*/
motion (time: number, id: number, x: Fixed, y: Fixed) {
this.client.marshall(this.id, 2, [uint(time), int(id), fixed(x), fixed(y)])
}
/**
*
* Indicates the end of a set of events that logically belong together.
* A client is expected to accumulate the data in all events within the
* frame before proceeding.
*
* A wl_touch.frame terminates at least one event but otherwise no
* guarantee is provided about the set of events within a frame. A client
* must assume that any state not updated in a frame is unchanged from the
* previously known state.
*
* @since 1
*
*/
frame () {
this.client.marshall(this.id, 3, [])
}
/**
*
* Sent if the compositor decides the touch stream is a global
* gesture. No further events are sent to the clients from that
* particular gesture. Touch cancellation applies to all touch points
* currently active on this client's surface. The client is
* responsible for finalizing the touch points, future touch points on
* this surface may reuse the touch point ID.
*
* @since 1
*
*/
cancel () {
this.client.marshall(this.id, 4, [])
}
/**
*
* Sent when a touchpoint has changed its shape.
*
* This event does not occur on its own. It is sent before a
* wl_touch.frame event and carries the new shape information for
* any previously reported, or new touch points of that frame.
*
* Other events describing the touch point such as wl_touch.down,
* wl_touch.motion or wl_touch.orientation may be sent within the
* same wl_touch.frame. A client should treat these events as a single
* logical touch point update. The order of wl_touch.shape,
* wl_touch.orientation and wl_touch.motion is not guaranteed.
* A wl_touch.down event is guaranteed to occur before the first
* wl_touch.shape event for this touch ID but both events may occur within
* the same wl_touch.frame.
*
* A touchpoint shape is approximated by an ellipse through the major and
* minor axis length. The major axis length describes the longer diameter
* of the ellipse, while the minor axis length describes the shorter
* diameter. Major and minor are orthogonal and both are specified in
* surface-local coordinates. The center of the ellipse is always at the
* touchpoint location as reported by wl_touch.down or wl_touch.move.
*
* This event is only sent by the compositor if the touch device supports
* shape reports. The client has to make reasonable assumptions about the
* shape if it did not receive this event.
*
*
* @param id the unique ID of this touch point
* @param major length of the major axis in surface-local coordinates
* @param minor length of the minor axis in surface-local coordinates
*
* @since 6
*
*/
shape (id: number, major: Fixed, minor: Fixed) {
this.client.marshall(this.id, 5, [int(id), fixed(major), fixed(minor)])
}
/**
*
* Sent when a touchpoint has changed its orientation.
*
* This event does not occur on its own. It is sent before a
* wl_touch.frame event and carries the new shape information for
* any previously reported, or new touch points of that frame.
*
* Other events describing the touch point such as wl_touch.down,
* wl_touch.motion or wl_touch.shape may be sent within the
* same wl_touch.frame. A client should treat these events as a single
* logical touch point update. The order of wl_touch.shape,
* wl_touch.orientation and wl_touch.motion is not guaranteed.
* A wl_touch.down event is guaranteed to occur before the first
* wl_touch.orientation event for this touch ID but both events may occur
* within the same wl_touch.frame.
*
* The orientation describes the clockwise angle of a touchpoint's major
* axis to the positive surface y-axis and is normalized to the -180 to
* +180 degree range. The granularity of orientation depends on the touch
* device, some devices only support binary rotation values between 0 and
* 90 degrees.
*
* This event is only sent by the compositor if the touch device supports
* orientation reports.
*
*
* @param id the unique ID of this touch point
* @param orientation angle between major axis and positive surface y-axis in degrees
*
* @since 6
*
*/
orientation (id: number, orientation: Fixed) {
this.client.marshall(this.id, 6, [int(id), fixed(orientation)])
}
constructor (client: Westfield.Client, id: number, version: number) {
super(client, id, version)
}
[0] (message: WlMessage) {
return this.implementation.release(this)
}
}
export interface WlTouchRequests {
/**
*
* @param resource The protocol resource of this implementation.
*
* @since 3
*
*/
release(resource: WlTouchResource): void
}
/**
*
* An output describes part of the compositor geometry. The
* compositor works in the 'compositor coordinate system' and an
* output corresponds to a rectangular area in that space that is
* actually visible. This typically corresponds to a monitor that
* displays part of the compositor space. This object is published
* as global during start up, or when a monitor is hotplugged.
*
*/
export class WlOutputResource extends Westfield.Resource {
static readonly protocolName = 'wl_output'
//@ts-ignore Should always be set when resource is created.
implementation: WlOutputRequests
/**
*
* The geometry event describes geometric properties of the output.
* The event is sent when binding to the output object and whenever
* any of the properties change.
*
*
* @param x x position within the global compositor space
* @param y y position within the global compositor space
* @param physicalWidth width in millimeters of the output
* @param physicalHeight height in millimeters of the output
* @param subpixel subpixel orientation of the output
* @param make textual description of the manufacturer
* @param model textual description of the model
* @param transform transform that maps framebuffer to output
*
* @since 1
*
*/
geometry (x: number, y: number, physicalWidth: number, physicalHeight: number, subpixel: number, make: string, model: string, transform: number) {
this.client.marshall(this.id, 0, [int(x), int(y), int(physicalWidth), int(physicalHeight), int(subpixel), string(make), string(model), int(transform)])
}
/**
*
* The mode event describes an available mode for the output.
*
* The event is sent when binding to the output object and there
* will always be one mode, the current mode. The event is sent
* again if an output changes mode, for the mode that is now
* current. In other words, the current mode is always the last
* mode that was received with the current flag set.
*
* The size of a mode is given in physical hardware units of
* the output device. This is not necessarily the same as
* the output size in the global compositor space. For instance,
* the output may be scaled, as described in wl_output.scale,
* or transformed, as described in wl_output.transform.
*
*
* @param flags bitfield of mode flags
* @param width width of the mode in hardware units
* @param height height of the mode in hardware units
* @param refresh vertical refresh rate in mHz
*
* @since 1
*
*/
mode (flags: number, width: number, height: number, refresh: number) {
this.client.marshall(this.id, 1, [uint(flags), int(width), int(height), int(refresh)])
}
/**
*
* This event is sent after all other properties have been
* sent after binding to the output object and after any
* other property changes done after that. This allows
* changes to the output properties to be seen as
* atomic, even if they happen via multiple events.
*
* @since 2
*
*/
done () {
this.client.marshall(this.id, 2, [])
}
/**
*
* This event contains scaling geometry information
* that is not in the geometry event. It may be sent after
* binding the output object or if the output scale changes
* later. If it is not sent, the client should assume a
* scale of 1.
*
* A scale larger than 1 means that the compositor will
* automatically scale surface buffers by this amount
* when rendering. This is used for very high resolution
* displays where applications rendering at the native
* resolution would be too small to be legible.
*
* It is intended that scaling aware clients track the
* current output of a surface, and if it is on a scaled
* output it should use wl_surface.set_buffer_scale with
* the scale of the output. That way the compositor can
* avoid scaling the surface, and the client can supply
* a higher detail image.
*
*
* @param factor scaling factor of output
*
* @since 2
*
*/
scale (factor: number) {
this.client.marshall(this.id, 3, [int(factor)])
}
constructor (client: Westfield.Client, id: number, version: number) {
super(client, id, version)
}
[0] (message: WlMessage) {
return this.implementation.release(this)
}
}
export interface WlOutputRequests {
/**
*
* Using this request a client can tell the server that it is not going to
* use the output object anymore.
*
*
* @param resource The protocol resource of this implementation.
*
* @since 3
*
*/
release(resource: WlOutputResource): void
}
export enum WlOutputSubpixel {
/**
* unknown geometry
*/
unknown = 0,
/**
* no geometry
*/
none = 1,
/**
* horizontal RGB
*/
horizontalRgb = 2,
/**
* horizontal BGR
*/
horizontalBgr = 3,
/**
* vertical RGB
*/
verticalRgb = 4,
/**
* vertical BGR
*/
verticalBgr = 5
}
export enum WlOutputTransform {
/**
* no transform
*/
normal = 0,
/**
* 90 degrees counter-clockwise
*/
_90 = 1,
/**
* 180 degrees counter-clockwise
*/
_180 = 2,
/**
* 270 degrees counter-clockwise
*/
_270 = 3,
/**
* 180 degree flip around a vertical axis
*/
flipped = 4,
/**
* flip and rotate 90 degrees counter-clockwise
*/
flipped90 = 5,
/**
* flip and rotate 180 degrees counter-clockwise
*/
flipped180 = 6,
/**
* flip and rotate 270 degrees counter-clockwise
*/
flipped270 = 7
}
export enum WlOutputMode {
/**
* indicates this is the current mode
*/
current = 0x1,
/**
* indicates this is the preferred mode
*/
preferred = 0x2
}
/**
*
* A region object describes an area.
*
* Region objects are used to describe the opaque and input
* regions of a surface.
*
*/
export class WlRegionResource extends Westfield.Resource {
static readonly protocolName = 'wl_region'
//@ts-ignore Should always be set when resource is created.
implementation: WlRegionRequests
constructor (client: Westfield.Client, id: number, version: number) {
super(client, id, version)
}
[0] (message: WlMessage) {
return this.implementation.destroy(this)
}
[1] (message: WlMessage) {
return this.implementation.add(this, i(message), i(message), i(message), i(message))
}
[2] (message: WlMessage) {
return this.implementation.subtract(this, i(message), i(message), i(message), i(message))
}
}
export interface WlRegionRequests {
/**
*
* Destroy the region. This will invalidate the object ID.
*
*
* @param resource The protocol resource of this implementation.
*
* @since 1
*
*/
destroy(resource: WlRegionResource): void
/**
*
* Add the specified rectangle to the region.
*
*
* @param resource The protocol resource of this implementation.
* @param x region-local x coordinate
* @param y region-local y coordinate
* @param width rectangle width
* @param height rectangle height
*
* @since 1
*
*/
add(resource: WlRegionResource, x: number, y: number, width: number, height: number): void
/**
*
* Subtract the specified rectangle from the region.
*
*
* @param resource The protocol resource of this implementation.
* @param x region-local x coordinate
* @param y region-local y coordinate
* @param width rectangle width
* @param height rectangle height
*
* @since 1
*
*/
subtract(resource: WlRegionResource, x: number, y: number, width: number, height: number): void
}
/**
*
* The global interface exposing sub-surface compositing capabilities.
* A wl_surface, that has sub-surfaces associated, is called the
* parent surface. Sub-surfaces can be arbitrarily nested and create
* a tree of sub-surfaces.
*
* The root surface in a tree of sub-surfaces is the main
* surface. The main surface cannot be a sub-surface, because
* sub-surfaces must always have a parent.
*
* A main surface with its sub-surfaces forms a (compound) window.
* For window management purposes, this set of wl_surface objects is
* to be considered as a single window, and it should also behave as
* such.
*
* The aim of sub-surfaces is to offload some of the compositing work
* within a window from clients to the compositor. A prime example is
* a video player with decorations and video in separate wl_surface
* objects. This should allow the compositor to pass YUV video buffer
* processing to dedicated overlay hardware when possible.
*
*/
export class WlSubcompositorResource extends Westfield.Resource {
static readonly protocolName = 'wl_subcompositor'
//@ts-ignore Should always be set when resource is created.
implementation: WlSubcompositorRequests
constructor (client: Westfield.Client, id: number, version: number) {
super(client, id, version)
}
[0] (message: WlMessage) {
return this.implementation.destroy(this)
}
[1] (message: WlMessage) {
return this.implementation.getSubsurface(this, n(message), o<Westfield.WlSurfaceResource>(message, this.client.connection), o<Westfield.WlSurfaceResource>(message, this.client.connection))
}
}
export interface WlSubcompositorRequests {
/**
*
* Informs the server that the client will not be using this
* protocol object anymore. This does not affect any other
* objects, wl_subsurface objects included.
*
*
* @param resource The protocol resource of this implementation.
*
* @since 1
*
*/
destroy(resource: WlSubcompositorResource): void
/**
*
* Create a sub-surface interface for the given surface, and
* associate it with the given parent surface. This turns a
* plain wl_surface into a sub-surface.
*
* The to-be sub-surface must not already have another role, and it
* must not have an existing wl_subsurface object. Otherwise a protocol
* error is raised.
*
*
* @param resource The protocol resource of this implementation.
* @param id the new sub-surface object ID
* @param surface the surface to be turned into a sub-surface
* @param parent the parent surface
*
* @since 1
*
*/
getSubsurface(resource: WlSubcompositorResource, id: number, surface: Westfield.WlSurfaceResource, parent: Westfield.WlSurfaceResource): void
}
export enum WlSubcompositorError {
/**
* the to-be sub-surface is invalid
*/
badSurface = 0
}
/**
*
* An additional interface to a wl_surface object, which has been
* made a sub-surface. A sub-surface has one parent surface. A
* sub-surface's size and position are not limited to that of the parent.
* Particularly, a sub-surface is not automatically clipped to its
* parent's area.
*
* A sub-surface becomes mapped, when a non-NULL wl_buffer is applied
* and the parent surface is mapped. The order of which one happens
* first is irrelevant. A sub-surface is hidden if the parent becomes
* hidden, or if a NULL wl_buffer is applied. These rules apply
* recursively through the tree of surfaces.
*
* The behaviour of a wl_surface.commit request on a sub-surface
* depends on the sub-surface's mode. The possible modes are
* synchronized and desynchronized, see methods
* wl_subsurface.set_sync and wl_subsurface.set_desync. Synchronized
* mode caches the wl_surface state to be applied when the parent's
* state gets applied, and desynchronized mode applies the pending
* wl_surface state directly. A sub-surface is initially in the
* synchronized mode.
*
* Sub-surfaces have also other kind of state, which is managed by
* wl_subsurface requests, as opposed to wl_surface requests. This
* state includes the sub-surface position relative to the parent
* surface (wl_subsurface.set_position), and the stacking order of
* the parent and its sub-surfaces (wl_subsurface.place_above and
* .place_below). This state is applied when the parent surface's
* wl_surface state is applied, regardless of the sub-surface's mode.
* As the exception, set_sync and set_desync are effective immediately.
*
* The main surface can be thought to be always in desynchronized mode,
* since it does not have a parent in the sub-surfaces sense.
*
* Even if a sub-surface is in desynchronized mode, it will behave as
* in synchronized mode, if its parent surface behaves as in
* synchronized mode. This rule is applied recursively throughout the
* tree of surfaces. This means, that one can set a sub-surface into
* synchronized mode, and then assume that all its child and grand-child
* sub-surfaces are synchronized, too, without explicitly setting them.
*
* If the wl_surface associated with the wl_subsurface is destroyed, the
* wl_subsurface object becomes inert. Note, that destroying either object
* takes effect immediately. If you need to synchronize the removal
* of a sub-surface to the parent surface update, unmap the sub-surface
* first by attaching a NULL wl_buffer, update parent, and then destroy
* the sub-surface.
*
* If the parent wl_surface object is destroyed, the sub-surface is
* unmapped.
*
*/
export class WlSubsurfaceResource extends Westfield.Resource {
static readonly protocolName = 'wl_subsurface'
//@ts-ignore Should always be set when resource is created.
implementation: WlSubsurfaceRequests
constructor (client: Westfield.Client, id: number, version: number) {
super(client, id, version)
}
[0] (message: WlMessage) {
return this.implementation.destroy(this)
}
[1] (message: WlMessage) {
return this.implementation.setPosition(this, i(message), i(message))
}
[2] (message: WlMessage) {
return this.implementation.placeAbove(this, o<Westfield.WlSurfaceResource>(message, this.client.connection))
}
[3] (message: WlMessage) {
return this.implementation.placeBelow(this, o<Westfield.WlSurfaceResource>(message, this.client.connection))
}
[4] (message: WlMessage) {
return this.implementation.setSync(this)
}
[5] (message: WlMessage) {
return this.implementation.setDesync(this)
}
}
export interface WlSubsurfaceRequests {
/**
*
* The sub-surface interface is removed from the wl_surface object
* that was turned into a sub-surface with a
* wl_subcompositor.get_subsurface request. The wl_surface's association
* to the parent is deleted, and the wl_surface loses its role as
* a sub-surface. The wl_surface is unmapped.
*
*
* @param resource The protocol resource of this implementation.
*
* @since 1
*
*/
destroy(resource: WlSubsurfaceResource): void
/**
*
* This schedules a sub-surface position change.
* The sub-surface will be moved so that its origin (top left
* corner pixel) will be at the location x, y of the parent surface
* coordinate system. The coordinates are not restricted to the parent
* surface area. Negative values are allowed.
*
* The scheduled coordinates will take effect whenever the state of the
* parent surface is applied. When this happens depends on whether the
* parent surface is in synchronized mode or not. See
* wl_subsurface.set_sync and wl_subsurface.set_desync for details.
*
* If more than one set_position request is invoked by the client before
* the commit of the parent surface, the position of a new request always
* replaces the scheduled position from any previous request.
*
* The initial position is 0, 0.
*
*
* @param resource The protocol resource of this implementation.
* @param x x coordinate in the parent surface
* @param y y coordinate in the parent surface
*
* @since 1
*
*/
setPosition(resource: WlSubsurfaceResource, x: number, y: number): void
/**
*
* This sub-surface is taken from the stack, and put back just
* above the reference surface, changing the z-order of the sub-surfaces.
* The reference surface must be one of the sibling surfaces, or the
* parent surface. Using any other surface, including this sub-surface,
* will cause a protocol error.
*
* The z-order is double-buffered. Requests are handled in order and
* applied immediately to a pending state. The final pending state is
* copied to the active state the next time the state of the parent
* surface is applied. When this happens depends on whether the parent
* surface is in synchronized mode or not. See wl_subsurface.set_sync and
* wl_subsurface.set_desync for details.
*
* A new sub-surface is initially added as the top-most in the stack
* of its siblings and parent.
*
*
* @param resource The protocol resource of this implementation.
* @param sibling the reference surface
*
* @since 1
*
*/
placeAbove(resource: WlSubsurfaceResource, sibling: Westfield.WlSurfaceResource): void
/**
*
* The sub-surface is placed just below the reference surface.
* See wl_subsurface.place_above.
*
*
* @param resource The protocol resource of this implementation.
* @param sibling the reference surface
*
* @since 1
*
*/
placeBelow(resource: WlSubsurfaceResource, sibling: Westfield.WlSurfaceResource): void
/**
*
* Change the commit behaviour of the sub-surface to synchronized
* mode, also described as the parent dependent mode.
*
* In synchronized mode, wl_surface.commit on a sub-surface will
* accumulate the committed state in a cache, but the state will
* not be applied and hence will not change the compositor output.
* The cached state is applied to the sub-surface immediately after
* the parent surface's state is applied. This ensures atomic
* updates of the parent and all its synchronized sub-surfaces.
* Applying the cached state will invalidate the cache, so further
* parent surface commits do not (re-)apply old state.
*
* See wl_subsurface for the recursive effect of this mode.
*
*
* @param resource The protocol resource of this implementation.
*
* @since 1
*
*/
setSync(resource: WlSubsurfaceResource): void
/**
*
* Change the commit behaviour of the sub-surface to desynchronized
* mode, also described as independent or freely running mode.
*
* In desynchronized mode, wl_surface.commit on a sub-surface will
* apply the pending state directly, without caching, as happens
* normally with a wl_surface. Calling wl_surface.commit on the
* parent surface has no effect on the sub-surface's wl_surface
* state. This mode allows a sub-surface to be updated on its own.
*
* If cached state exists when wl_surface.commit is called in
* desynchronized mode, the pending state is added to the cached
* state, and applied as a whole. This invalidates the cache.
*
* Note: even if a sub-surface is set to desynchronized, a parent
* sub-surface may override it to behave as synchronized. For details,
* see wl_subsurface.
*
* If a surface's parent surface behaves as desynchronized, then
* the cached state is applied on set_desync.
*
*
* @param resource The protocol resource of this implementation.
*
* @since 1
*
*/
setDesync(resource: WlSubsurfaceResource): void
}
export enum WlSubsurfaceError {
/**
* wl_surface is not a sibling or the parent
*/
badSurface = 0
} | the_stack |
* Tooltip spec
*/
import { isVisible } from '@syncfusion/ej2-base';
import { Kanban, KanbanModel } from '../../src/kanban/index';
import { kanbanData } from './common/kanban-data.spec';
import { profile, inMB, getMemoryProfile } from './common/common.spec';
import * as util from './common/util.spec';
import { Query } from '@syncfusion/ej2-data';
describe('Kanban tooltip module', () => {
beforeAll(() => {
const isDef: (o: any) => boolean = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
// eslint-disable-next-line no-console
console.log('Unsupported environment, window.performance.memory is unavailable');
(this as any).skip(); //Skips test (in Chai)
return;
}
});
describe('Check tooltip on default content', () => {
let kanbanObj: Kanban;
beforeAll((done: DoneFn) => {
const model: KanbanModel = { enableTooltip: true };
kanbanObj = util.createKanban(model, kanbanData, done);
util.disableTooltipAnimation((kanbanObj.tooltipModule as any).tooltipObj);
});
afterAll(() => {
util.destroy(kanbanObj);
});
it('mouse hover open tooltip', () => {
const target: HTMLElement = kanbanObj.element.querySelector('.e-card .e-card-header-title.e-tooltip-text') as HTMLElement;
expect(document.querySelector('.e-kanban-tooltip')).toBeNull();
util.triggerMouseEvent(target, 'mouseover');
const tooltipEle: HTMLElement = document.querySelector('.e-kanban-tooltip') as HTMLElement;
expect(isVisible(tooltipEle)).toBe(true);
expect(tooltipEle.innerText).toEqual('1');
util.triggerMouseEvent(target, 'mouseleave');
expect(document.querySelector('.e-kanban-tooltip')).toBeNull();
const content: HTMLElement = kanbanObj.element.querySelector('.e-card .e-card-content') as HTMLElement;
expect(document.querySelector('.e-kanban-tooltip')).toBeNull();
util.triggerMouseEvent(content, 'mouseover');
const tooltipElement: HTMLElement = document.querySelector('.e-kanban-tooltip') as HTMLElement;
expect(isVisible(tooltipElement)).toBe(true);
expect(tooltipElement.innerText).toEqual('Analyze the new requirements gathered from the customer.');
util.triggerMouseEvent(content, 'mouseleave');
expect(document.querySelector('.e-kanban-tooltip')).toBeNull();
});
});
describe('Check tooltip template', () => {
let kanbanObj: Kanban;
beforeAll((done: DoneFn) => {
const model: KanbanModel = {
enableTooltip: true,
tooltipTemplate: '<div class="template" style="padding:5px;"><div>Assignee: ${Assignee}</div></div>'
};
kanbanObj = util.createKanban(model, kanbanData, done);
util.disableTooltipAnimation((kanbanObj.tooltipModule as any).tooltipObj);
});
afterAll(() => {
util.destroy(kanbanObj);
});
it('mouse hover open tooltip', () => {
const target: HTMLElement = kanbanObj.element.querySelector('.e-card .e-card-header-title.e-tooltip-text') as HTMLElement;
expect(document.querySelector('.e-kanban-tooltip')).toBeNull();
util.triggerMouseEvent(target, 'mouseover');
const tooltipEle: HTMLElement = document.querySelector('.e-kanban-tooltip') as HTMLElement;
expect(isVisible(tooltipEle)).toBe(true);
expect([].slice.call(tooltipEle.querySelectorAll('.template')).length).toEqual(1);
util.triggerMouseEvent(target, 'mouseleave');
expect(document.querySelector('.e-kanban-tooltip')).toBeNull();
});
it('change tooltip template through set model', () => {
kanbanObj.tooltipTemplate = '<div class="template1" style="padding:5px;"><div>Assignee: ${Assignee}</div></div>';
kanbanObj.dataBind();
const target: HTMLElement = kanbanObj.element.querySelector('.e-card .e-card-header-title.e-tooltip-text') as HTMLElement;
expect(document.querySelector('.e-kanban-tooltip')).toBeNull();
util.triggerMouseEvent(target, 'mouseover');
const tooltipEle: HTMLElement = document.querySelector('.e-kanban-tooltip') as HTMLElement;
expect(isVisible(tooltipEle)).toBe(true);
expect([].slice.call(tooltipEle.querySelectorAll('.template')).length).toEqual(0);
expect([].slice.call(tooltipEle.querySelectorAll('.template1')).length).toEqual(1);
util.triggerMouseEvent(target, 'mouseleave');
expect(document.querySelector('.e-kanban-tooltip')).toBeNull();
});
});
describe('Check tooltip and checking e-control class on kanban element', () => {
let kanbanObj: Kanban;
beforeAll((done: DoneFn) => {
const model: KanbanModel = { enableTooltip: false };
kanbanObj = util.createKanban(model, kanbanData, done);
});
afterAll(() => {
util.destroy(kanbanObj);
});
it('hide tooltip on mouse hover', () => {
const target: HTMLElement = kanbanObj.element.querySelector('.e-card .e-card-header-title') as HTMLElement;
expect(document.querySelector('.e-kanban-tooltip')).toBeNull();
util.triggerMouseEvent(target, 'mouseover');
expect(document.querySelector('.e-kanban-tooltip')).toBeNull();
util.triggerMouseEvent(target, 'mouseleave');
expect(document.querySelector('.e-kanban-tooltip')).toBeNull();
});
it('show tooltip through set model on mouse hover', () => {
kanbanObj.enableTooltip = true;
kanbanObj.dataBind();
util.disableTooltipAnimation((kanbanObj.tooltipModule as any).tooltipObj);
const target: HTMLElement = kanbanObj.element.querySelector('.e-card .e-card-header-title.e-tooltip-text') as HTMLElement;
expect(document.querySelector('.e-kanban-tooltip')).toBeNull();
util.triggerMouseEvent(target, 'mouseover');
const tooltipEle: HTMLElement = document.querySelector('.e-kanban-tooltip') as HTMLElement;
expect(isVisible(tooltipEle)).toBe(true);
util.triggerMouseEvent(target, 'mouseleave');
expect(document.querySelector('.e-kanban-tooltip')).toBeNull();
});
it('hide tooltip through set model on mouse hover and checking e-control class on kanban element', () => {
kanbanObj.enableTooltip = false;
kanbanObj.dataBind();
expect(kanbanObj.element.classList.contains('e-control')).toEqual(true);
const target: HTMLElement = kanbanObj.element.querySelector('.e-card .e-card-header-title.e-tooltip-text') as HTMLElement;
expect(document.querySelector('.e-kanban-tooltip')).toBeNull();
util.triggerMouseEvent(target, 'mouseover');
expect(document.querySelector('.e-kanban-tooltip')).toBeNull();
util.triggerMouseEvent(target, 'mouseleave');
expect(document.querySelector('.e-kanban-tooltip')).toBeNull();
});
});
describe('covering sortBy without keyField', () => {
let kanbanObj: Kanban;
beforeAll((done: DoneFn) => {
let model: KanbanModel = {
columns: [
{ headerText: 'Backlog', keyField: 'Open', allowToggle: true, showAddButton: true },
{ headerText: 'In Progress', keyField: 'InProgress', allowToggle: true, showAddButton: true },
{ headerText: 'Testing', keyField: 'Testing', allowToggle: true, showAddButton: true },
{ headerText: 'Done', keyField: 'Close', allowToggle: true, showAddButton: true }
],
allowKeyboard: true,
query: new Query().take(10),
sortSettings: {
sortBy: 'Custom',
field: 'Summary',
direction: 'Descending'
},
cardSettings: {
selectionType: 'Multiple'
}
};
kanbanObj = util.createKanban(model, kanbanData, done);
});
afterAll(() => {
util.destroy(kanbanObj);
});
it('Add new card', () => {
expect(kanbanObj.kanbanData.length).toBe(10);
let addButton: HTMLElement = kanbanObj.element.querySelector('.e-show-add-button');
expect(addButton.classList.contains('e-show-add-focus')).toBe(false);
util.triggerMouseEvent(addButton, 'click');
});
it('Save new card', () => {
let saveEle: HTMLElement = document.querySelector('.e-dialog-add');
let popupEle: HTMLElement = document.querySelector('.e-dialog.e-kanban-dialog.e-popup');
expect(popupEle.classList.contains('e-popup-close')).toBe(false);
expect(popupEle.classList.contains('e-popup-open')).toBe(true);
util.triggerMouseEvent(saveEle, 'click');
expect(popupEle.classList.contains('e-popup-open')).toBe(false);
});
});
describe('Enable tooltip drag the card', () => {
let kanbanObj: Kanban;
let dragElement: HTMLElement;
beforeAll((done: DoneFn) => {
kanbanObj = util.createKanban({ enableTooltip: true }, kanbanData, done);
});
afterAll(() => {
util.destroy(kanbanObj);
});
it('Card Dragging to particular area', () => {
dragElement = (kanbanObj.element.querySelectorAll('.e-card[data-id="2"]') as NodeListOf<Element>).item(0) as HTMLElement;
util.triggerMouseEvent(dragElement, 'mousedown');
util.triggerMouseEvent(dragElement, 'mousemove', 100, 100);
expect(dragElement.classList.contains('e-kanban-dragged-card')).toBeTruthy();
expect(dragElement.nextElementSibling.classList.contains('e-target-dragged-clone')).toBeTruthy();
expect(kanbanObj.element.querySelectorAll('.e-target-dragged-clone').length).toBe(1);
});
it('Dragging card and mouseOvering to another card', () => {
const element: Element = (kanbanObj.element.querySelectorAll('.e-card[data-id="5"]').item(0)).querySelector('.e-card-content');
util.triggerMouseEvent(element, 'mousemove', 200, 140);
util.triggerMouseEvent(element, 'mouseover');
});
it('check the tooltip not showing', () => {
let ele: HTMLElement = kanbanObj.element.querySelector('.e-tooltip-wrap.e-popup.e-kanban-tooltip.e-popup-open');
expect(ele).toBe(null);
});
});
it('memory leak', () => {
profile.sample();
const average: number = inMB(profile.averageChange);
expect(average).toBeLessThan(10); //Check average change in memory samples to not be over 10MB
const memory: number = 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 {execSync} from 'child_process';
import * as dgram from 'dgram';
import * as dns from 'dns';
import {powerMonitor} from 'electron';
import * as net from 'net';
import {platform} from 'os';
import * as path from 'path';
import * as process from 'process';
import * as socks from 'socks';
import {ShadowsocksConfig} from '../www/app/config';
import {TunnelStatus} from '../www/app/tunnel';
import * as errors from '../www/model/errors';
import {isServerReachable} from './connectivity';
import {ChildProcessHelper} from './process';
import {RoutingDaemon} from './routing_service';
import {pathToEmbeddedBinary} from './util';
import {VpnTunnel} from './vpn_tunnel';
const isLinux = platform() === 'linux';
const isWindows = platform() === 'win32';
const TUN2SOCKS_TAP_DEVICE_NAME = isLinux ? 'outline-tun0' : 'outline-tap0';
const TUN2SOCKS_TAP_DEVICE_IP = '10.0.85.2';
const TUN2SOCKS_VIRTUAL_ROUTER_IP = '10.0.85.1';
const TUN2SOCKS_TAP_DEVICE_NETWORK = '10.0.85.0';
const TUN2SOCKS_VIRTUAL_ROUTER_NETMASK = '255.255.255.0';
// ss-local will almost always start, and fast: short timeouts, fast retries.
const SSLOCAL_CONNECTION_TIMEOUT = 10;
const SSLOCAL_MAX_ATTEMPTS = 30;
const SSLOCAL_PROXY_HOST = '127.0.0.1';
const SSLOCAL_PROXY_PORT = 1081;
const SSLOCAL_RETRY_INTERVAL_MS = 100;
const CREDENTIALS_TEST_DOMAINS = ['example.com', 'ietf.org', 'wikipedia.org'];
const DNS_LOOKUP_TIMEOUT_MS = 10000;
const UDP_FORWARDING_TEST_TIMEOUT_MS = 5000;
const UDP_FORWARDING_TEST_RETRY_INTERVAL_MS = 1000;
// Raises an error if:
// - the TAP device does not exist
// - the TAP device does not have the expected IP/subnet
//
// Note that this will *also* throw if netsh is not on the PATH. If that's the case then the
// installer should have failed, too.
//
// Only works on Windows!
function testTapDevice(tapDeviceName: string, tapDeviceIp: string) {
// Sample output:
// =============
// $ netsh interface ipv4 dump
// # ----------------------------------
// # IPv4 Configuration
// # ----------------------------------
// pushd interface ipv4
//
// reset
// set global icmpredirects=disabled
// set interface interface="Ethernet" forwarding=enabled advertise=enabled nud=enabled
// ignoredefaultroutes=disabled set interface interface="outline-tap0" forwarding=enabled
// advertise=enabled nud=enabled ignoredefaultroutes=disabled add address name="outline-tap0"
// address=10.0.85.2 mask=255.255.255.0
//
// popd
// # End of IPv4 configuration
const lines = execSync(`netsh interface ipv4 dump`).toString().split('\n');
// Find lines containing the TAP device name.
const tapLines = lines.filter(s => s.indexOf(tapDeviceName) !== -1);
if (tapLines.length < 1) {
throw new errors.SystemConfigurationException(`TAP device not found`);
}
// Within those lines, search for the expected IP.
if (tapLines.filter(s => s.indexOf(tapDeviceIp) !== -1).length < 1) {
throw new errors.SystemConfigurationException(`TAP device has wrong IP`);
}
}
async function isSsLocalReachable() {
await isServerReachable(
SSLOCAL_PROXY_HOST, SSLOCAL_PROXY_PORT, SSLOCAL_CONNECTION_TIMEOUT, SSLOCAL_MAX_ATTEMPTS,
SSLOCAL_RETRY_INTERVAL_MS);
}
// Establishes a full-system VPN with the help of Outline's routing daemon and child processes
// ss-local and badvpn-tun2socks. ss-local listens on a local SOCKS server and forwards TCP and UDP
// traffic through Shadowsocks. badvpn-tun2socks processes traffic from a TAP device and relays to
// a SOCKS proxy. The routing service modifies the routing table so that the TAP device receives all
// device traffic.
//
// |TAP| <-> |badvpn-tun2socks| <-> |ss-local| <-> |Shadowsocks proxy|
//
// In addition to the basic lifecycle of the three helper processes, this handles a few special
// situations:
// - repeat the UDP test when the network changes and restart tun2socks if the result has changed
// - silently restart tun2socks when the system is about to suspend (Windows only)
//
// Follows the Mediator pattern in that none of the three "helpers" know
// anything about the others.
export class ShadowsocksLibevBadvpnTunnel implements VpnTunnel {
private readonly ssLocal = new SsLocal(SSLOCAL_PROXY_PORT);
private readonly tun2socks = new BadvpnTun2socks(SSLOCAL_PROXY_HOST, SSLOCAL_PROXY_PORT);
// Extracted out to an instance variable because in certain situations, notably a change in UDP
// support, we need to stop and restart tun2socks *without notifying the client* and this allows
// us swap the listener in and out.
private tun2socksExitListener?: () => void | undefined;
// See #resumeListener.
private terminated = false;
private isUdpEnabled = false;
private readonly onAllHelpersStopped: Promise<void>;
private reconnectingListener?: () => void;
private reconnectedListener?: () => void;
constructor(private readonly routing: RoutingDaemon, private config: ShadowsocksConfig) {
// This trio of Promises, each tied to a helper process' exit, is key to the instance's
// lifecycle:
// - once any helper fails or exits, stop them all
// - once *all* helpers have stopped, we're done
const ssLocalExit = new Promise<void>((resolve) => {
this.ssLocal.onExit = (code?: number, signal?: string) => {
resolve();
};
});
const tun2socksExit = new Promise<void>((resolve) => {
this.tun2socksExitListener = resolve;
this.tun2socks.onExit = this.tun2socksExitListener;
});
const exits = [this.routing.onceDisconnected, ssLocalExit, tun2socksExit];
Promise.race(exits).then(() => {
console.log('a helper has exited, disconnecting');
this.disconnect();
});
this.onAllHelpersStopped = Promise.all(exits).then(() => {
console.log('all helpers have exited');
this.terminated = true;
});
}
/**
* Turns on verbose logging for the managed processes. Must be called before launching the
* processes
*/
enableDebugMode() {
this.ssLocal.enableDebugMode();
this.tun2socks.enableDebugMode();
}
// Fulfills once all three helpers have started successfully.
async connect(checkProxyConnectivity: boolean) {
if (isWindows) {
testTapDevice(TUN2SOCKS_TAP_DEVICE_NAME, TUN2SOCKS_TAP_DEVICE_IP);
// Windows: when the system suspends, tun2socks terminates due to the TAP device getting
// closed.
powerMonitor.on('suspend', this.suspendListener.bind(this));
powerMonitor.on('resume', this.resumeListener.bind((this)));
}
// ss-local must be up in order to test UDP support and validate credentials.
this.ssLocal.start(this.config);
await isSsLocalReachable();
if (checkProxyConnectivity) {
await validateServerCredentials(SSLOCAL_PROXY_HOST, SSLOCAL_PROXY_PORT);
this.isUdpEnabled = await checkUdpForwardingEnabled(SSLOCAL_PROXY_HOST, SSLOCAL_PROXY_PORT);
}
console.log(`UDP support: ${this.isUdpEnabled}`);
this.tun2socks.start(this.isUdpEnabled);
await this.routing.start();
}
networkChanged(status: TunnelStatus) {
if (status === TunnelStatus.CONNECTED) {
if (this.reconnectedListener) {
this.reconnectedListener();
}
// Test whether UDP availability has changed; since it won't change 99% of the time, do this
// *after* we've informed the client we've reconnected.
this.retestUdp();
} else if (status === TunnelStatus.RECONNECTING) {
if (this.reconnectingListener) {
this.reconnectingListener();
}
} else {
console.error(`unknown network change status ${status} from routing daemon`);
}
}
private suspendListener() {
// Swap out the current listener, restart once the system resumes.
this.tun2socks.onExit = () => {
console.log('stopped tun2socks in preparation for suspend');
};
}
private resumeListener() {
if (this.terminated) {
// NOTE: Cannot remove resume listeners - Electron bug?
console.error('resume event invoked but this tunnel is terminated - doing nothing');
return;
}
console.log('restarting tun2socks after resume');
this.tun2socks.onExit = this.tun2socksExitListener;
this.tun2socks.start(this.isUdpEnabled);
// Check if UDP support has changed; if so, silently restart.
this.retestUdp();
}
private async retestUdp() {
const wasUdpEnabled = this.isUdpEnabled;
try {
// Possibly over-cautious, though we have seen occasional failures immediately after network
// changes: ensure ss-local is reachable first.
await isSsLocalReachable();
this.isUdpEnabled = await checkUdpForwardingEnabled(SSLOCAL_PROXY_HOST, SSLOCAL_PROXY_PORT);
} catch (e) {
console.error(`UDP test failed: ${e.message}`);
return;
}
if (this.isUdpEnabled === wasUdpEnabled) {
return;
}
console.log(`UDP support change: now ${this.isUdpEnabled}`);
// Swap out the current listener, restart once the current process exits.
this.tun2socks.onExit = () => {
console.log('restarting tun2socks');
this.tun2socks.onExit = this.tun2socksExitListener;
this.tun2socks.start(this.isUdpEnabled);
};
this.tun2socks.stop();
}
// Use #onceDisconnected to be notified when the tunnel terminates.
async disconnect() {
powerMonitor.removeListener('suspend', this.suspendListener.bind(this));
powerMonitor.removeListener('resume', this.resumeListener.bind(this));
// This is the clean shutdown order, but to minimize delay, we don't
// wait for each shutdown step to complete. They may therefore complete
// out of order. This will cause tun2socks to print error messages in
// the console, but is otherwise harmless.
this.tun2socks.stop();
this.ssLocal.stop();
try {
await this.routing.stop();
} catch (e) {
// This can happen for several reasons, e.g. the daemon may have stopped while we were
// connected.
console.error(`could not stop routing: ${e.message}`);
}
}
// Fulfills once all three helper processes have stopped.
//
// When this happens, *as many changes made to the system in order to establish the full-system
// VPN as possible* will have been reverted.
get onceDisconnected() {
return this.onAllHelpersStopped;
}
// Sets an optional callback for when the routing daemon is attempting to re-connect.
onReconnecting(newListener: () => void|undefined) {
this.reconnectingListener = newListener;
}
// Sets an optional callback for when the routing daemon successfully reconnects.
onReconnected(newListener: () => void|undefined) {
this.reconnectedListener = newListener;
}
}
class SsLocal extends ChildProcessHelper {
constructor(private readonly proxyPort: number) {
super(pathToEmbeddedBinary('shadowsocks-libev', 'ss-local'));
}
start(config: ShadowsocksConfig) {
// ss-local -s x.x.x.x -p 65336 -k mypassword -m chacha20-ietf-poly1035 -l 1081 -u
const args = ['-l', this.proxyPort.toString()];
args.push('-s', config.host || '');
args.push('-p', `${config.port}`);
args.push('-k', config.password || '');
args.push('-m', config.method || '');
args.push('-u');
if (this.isInDebugMode) {
args.push('-v');
}
this.launch(args);
}
}
class BadvpnTun2socks extends ChildProcessHelper {
constructor(private proxyAddress: string, private proxyPort: number) {
super(pathToEmbeddedBinary('badvpn', 'badvpn-tun2socks'));
}
start(isUdpEnabled: boolean) {
// ./badvpn-tun2socks.exe \
// --tundev "tap0901:outline-tap0:10.0.85.2:10.0.85.0:255.255.255.0" \
// --netif-ipaddr 10.0.85.1 --netif-netmask 255.255.255.0 \
// --socks-server-addr 127.0.0.1:1081 \
// --socks5-udp --udp-relay-addr 127.0.0.1:1081 \
// --transparent-dns
const args: string[] = [];
args.push(
'--tundev',
isLinux ? TUN2SOCKS_TAP_DEVICE_NAME :
`tap0901:${TUN2SOCKS_TAP_DEVICE_NAME}:${TUN2SOCKS_TAP_DEVICE_IP}:${
TUN2SOCKS_TAP_DEVICE_NETWORK}:${TUN2SOCKS_VIRTUAL_ROUTER_NETMASK}`);
args.push('--netif-ipaddr', TUN2SOCKS_VIRTUAL_ROUTER_IP);
args.push('--netif-netmask', TUN2SOCKS_VIRTUAL_ROUTER_NETMASK);
args.push('--socks-server-addr', `${this.proxyAddress}:${this.proxyPort}`);
args.push('--transparent-dns');
if (isUdpEnabled) {
args.push('--socks5-udp');
args.push('--udp-relay-addr', `${this.proxyAddress}:${this.proxyPort}`);
}
args.push('--loglevel', this.isInDebugMode ? 'info' : 'error');
this.launch(args);
}
}
// Resolves with true iff a response can be received from a semi-randomly-chosen website through the
// Shadowsocks proxy.
//
// This has the same function as ShadowsocksConnectivity.validateServerCredentials in
// cordova-plugin-outline.
function validateServerCredentials(proxyAddress: string, proxyIp: number) {
return new Promise<void>((fulfill, reject) => {
const testDomain =
CREDENTIALS_TEST_DOMAINS[Math.floor(Math.random() * CREDENTIALS_TEST_DOMAINS.length)];
socks.createConnection(
{
proxy: {ipaddress: proxyAddress, port: proxyIp, type: 5},
target: {host: testDomain, port: 80}
},
(e, socket) => {
if (e) {
reject(new errors.InvalidServerCredentials(
`could not connect to remote test website: ${e.message}`));
return;
}
socket.write(`HEAD / HTTP/1.1\r\nHost: ${testDomain}\r\n\r\n`);
socket.on('data', (data) => {
if (data.toString().startsWith('HTTP/1.1')) {
socket.end();
fulfill();
} else {
socket.end();
reject(new errors.InvalidServerCredentials(
`unexpected response from remote test website`));
}
});
socket.on('close', () => {
reject(new errors.InvalidServerCredentials(`could not connect to remote test website`));
});
// Sockets must be resumed before any data will come in, as they are paused right before
// this callback is fired.
socket.resume();
});
});
}
// DNS request to google.com.
const DNS_REQUEST = Buffer.from([
0, 0, // [0-1] query ID
1, 0, // [2-3] flags; byte[2] = 1 for recursion desired (RD).
0, 1, // [4-5] QDCOUNT (number of queries)
0, 0, // [6-7] ANCOUNT (number of answers)
0, 0, // [8-9] NSCOUNT (number of name server records)
0, 0, // [10-11] ARCOUNT (number of additional records)
6, 103, 111, 111, 103, 108, 101, // google
3, 99, 111, 109, // com
0, // null terminator of FQDN (root TLD)
0, 1, // QTYPE, set to A
0, 1 // QCLASS, set to 1 = IN (Internet)
]);
// Verifies that the remote server has enabled UDP forwarding by sending a DNS request through it.
function checkUdpForwardingEnabled(proxyAddress: string, proxyIp: number): Promise<boolean> {
return new Promise((resolve, reject) => {
socks.createConnection(
{
proxy: {ipaddress: proxyAddress, port: proxyIp, type: 5, command: 'associate'},
target: {host: '0.0.0.0', port: 0}, // Specify the actual target once we get a response.
},
(err, socket, info) => {
if (err) {
reject(new errors.RemoteUdpForwardingDisabled(`could not connect to local proxy`));
return;
}
const packet = socks.createUDPFrame({host: '1.1.1.1', port: 53}, DNS_REQUEST);
const udpSocket = dgram.createSocket('udp4');
udpSocket.on('error', (e) => {
reject(new errors.RemoteUdpForwardingDisabled('UDP socket failure'));
});
udpSocket.on('message', (msg, info) => {
stopUdp();
resolve(true);
});
// Retry sending the query every second.
// TODO: logging here is a bit verbose
const intervalId = setInterval(() => {
try {
udpSocket.send(packet, info.port, info.host, (err) => {
if (err) {
console.error(`Failed to send data through UDP: ${err}`);
}
});
} catch (e) {
console.error(`Failed to send data through UDP ${e}`);
}
}, UDP_FORWARDING_TEST_RETRY_INTERVAL_MS);
const stopUdp = () => {
try {
clearInterval(intervalId);
udpSocket.close();
} catch (e) {
// Ignore; there may be multiple calls to this function.
}
};
// Give up after the timeout elapses.
setTimeout(() => {
stopUdp();
resolve(false);
}, UDP_FORWARDING_TEST_TIMEOUT_MS);
});
});
} | the_stack |
'use strict';
import { EventEmitter } from 'events';
import { errors, ErrorCallback, Callback, callbackToPromise, errorCallbackToPromise } from 'azure-iot-common';
import * as machina from 'machina';
import { ProvisioningDeviceConstants } from './constants';
import { PollingTransport, RegistrationRequest, DeviceRegistrationResult } from './interfaces';
import * as dbg from 'debug';
const debug = dbg('azure-iot-provisioning-device:PollingStateMachine');
const debugErrors = dbg('azure-iot-provisioning-device:PollingStateMachine:Errors');
/**
* @private
*/
export class PollingStateMachine extends EventEmitter {
private _fsm: machina.Fsm;
private _pollingTimer: any;
private _queryTimer: any;
private _transport: PollingTransport;
private _currentOperationCallback: any;
constructor(transport: PollingTransport) {
super();
this._transport = transport;
this._fsm = new machina.Fsm({
namespace: 'provisioning-client-polling',
initialState: 'disconnected',
states: {
disconnected: {
_onEnter: (err, result, response, callback) => {
if (callback) {
callback(err, result, response);
}
},
register: (request, callback) => this._fsm.transition('sendingRegistrationRequest', request, callback),
/* Codes_SRS_NODE_PROVISIONING_TRANSPORT_STATE_MACHINE_18_025: [ If `cancel` is called while disconnected, it shall immediately call its `callback`. ] */
cancel: (_cancelledOpErr, callback) => callback(),
/* Codes_SRS_NODE_PROVISIONING_TRANSPORT_STATE_MACHINE_18_031: [ If `disconnect` is called while disconnected, it shall immediately call its `callback`. ] */
disconnect: (callback) => callback()
},
idle: {
_onEnter: (err, result, response, callback) => callback(err, result, response),
/* Codes_SRS_NODE_PROVISIONING_TRANSPORT_STATE_MACHINE_18_030: [ If `cancel` is called while the transport is connected but idle, it shall immediately call its `callback`. ] */
cancel: (_cancelledOpErr, callback) => callback(),
/* Codes_SRS_NODE_PROVISIONING_TRANSPORT_STATE_MACHINE_18_032: [ If `disconnect` is called while while the transport is connected but idle, it shall call `PollingTransport.disconnect` and call it's `callback` passing the results of the transport operation. ] */
disconnect: (callback) => this._fsm.transition('disconnecting', callback),
register: (request, callback) => this._fsm.transition('sendingRegistrationRequest', request, callback)
},
sendingRegistrationRequest: {
_onEnter: (request, callback) => {
this._queryTimer = setTimeout(() => {
/* Codes_SRS_NODE_PROVISIONING_TRANSPORT_STATE_MACHINE_18_036: [ If `PollingTransport.registrationRequest` does not call its callback within `ProvisioningDeviceConstants.defaultTimeoutInterval` ms, register shall with with a `TimeoutError` error. ] */
if (this._currentOperationCallback === callback) {
debugErrors('timeout while sending request');
/* tslint:disable:no-empty */
this._fsm.handle('cancel', new errors.TimeoutError(), () => { });
}
}, ProvisioningDeviceConstants.defaultTimeoutInterval);
/* Codes_SRS_NODE_PROVISIONING_TRANSPORT_STATE_MACHINE_18_012: [ `register` shall call `PollingTransport.registrationRequest`. ] */
this._currentOperationCallback = callback;
this._transport.registrationRequest(request, (err, result, response, pollingInterval) => {
clearTimeout(this._queryTimer);
// Check if the operation is still pending before transitioning. We might be in a different state now and we don't want to mess that up.
if (this._currentOperationCallback === callback) {
this._fsm.transition('responseReceived', err, request, result, response, pollingInterval, callback);
} else if (this._currentOperationCallback) {
debugErrors('Unexpected: received unexpected response for cancelled operation');
}
});
},
cancel: (cancelledOpErr, callback) => this._fsm.transition('cancelling', cancelledOpErr, callback),
/* Codes_SRS_NODE_PROVISIONING_TRANSPORT_STATE_MACHINE_18_033: [ If `disconnect` is called while in the middle of a `registrationRequest` operation, the operation shall be cancelled and the transport shall be disconnected. ] */
disconnect: (callback) => {
this._fsm.handle('cancel', new errors.OperationCancelledError(''), (_err) => {
this._fsm.handle('disconnect', callback);
});
},
/* Codes_SRS_NODE_PROVISIONING_TRANSPORT_STATE_MACHINE_18_024: [ If `register` is called while a different request is in progress, it shall fail with an `InvalidOperationError`. ] */
register: (_request, callback) => callback(new errors.InvalidOperationError('another operation is in progress'))
},
responseReceived: {
_onEnter: (err, request, result, response, pollingInterval, callback) => {
if (err) {
/* Codes_SRS_NODE_PROVISIONING_TRANSPORT_STATE_MACHINE_18_013: [ If `PollingTransport.registrationRequest` fails, `register` shall fail. ] */
/* Codes_SRS_NODE_PROVISIONING_TRANSPORT_STATE_MACHINE_18_019: [ If `PollingTransport.queryOperationStatus` fails, `register` shall fail. ] */
this._fsm.transition('responseError', err, result, response, callback);
} else {
debug('received response from service:' + JSON.stringify(result));
switch (result.status.toLowerCase()) {
case 'registering': {
/*Codes_SRS_NODE_PROVISIONING_TRANSPORT_STATE_MACHINE_06_001: [If `PollingTransport.registrationRequest` succeeds with status==registering, `register` shall wait, then attempt `PollingTransport.registrationRequest` again.] */
this._fsm.transition('waitingToPoll', request, null, pollingInterval, callback);
break;
}
case 'assigned': {
this._fsm.transition('responseComplete', result, response, callback);
break;
}
case 'assigning': {
/* Codes_SRS_NODE_PROVISIONING_TRANSPORT_STATE_MACHINE_18_015: [ If `PollingTransport.registrationRequest` succeeds with status==Assigning, it shall begin polling for operation status requests. ] */
/* Codes_SRS_NODE_PROVISIONING_TRANSPORT_STATE_MACHINE_18_021: [ If `PollingTransport.queryOperationStatus` succeeds with status==Assigning, `register` shall begin polling for operation status requests. ] */
this._fsm.transition('waitingToPoll', request, result.operationId, pollingInterval, callback);
break;
}
case 'failed': {
/* Codes_SRS_NODE_PROVISIONING_TRANSPORT_STATE_MACHINE_18_028: [ If `TransportHandlers.registrationRequest` succeeds with status==Failed, it shall fail with a `DeviceRegistrationFailedError` error ] */
/* Codes_SRS_NODE_PROVISIONING_TRANSPORT_STATE_MACHINE_18_029: [ If `TransportHandlers.queryOperationStatus` succeeds with status==Failed, it shall fail with a `DeviceRegistrationFailedError` error ] */
let err = new errors.DeviceRegistrationFailedError('registration failed');
(err as any).result = result;
(err as any).response = response;
this._fsm.transition('responseError', err, result, response, callback);
break;
}
default: {
/* Codes_SRS_NODE_PROVISIONING_TRANSPORT_STATE_MACHINE_18_016: [ If `PollingTransport.registrationRequest` succeeds returns with an unknown status, `register` shall fail with a `SyntaxError` and pass the response body and the protocol-specific result to the `callback`. ] */
/* Codes_SRS_NODE_PROVISIONING_TRANSPORT_STATE_MACHINE_18_022: [ If `PollingTransport.queryOperationStatus` succeeds with an unknown status, `register` shall fail with a `SyntaxError` and pass the response body and the protocol-specific result to the `callback`. ] */
let err = new SyntaxError('status is ' + result.status);
(err as any).result = result;
(err as any).response = response;
this._fsm.transition('responseError', err, result, response, callback);
break;
}
}
}
},
'*': () => this._fsm.deferUntilTransition()
},
responseComplete: {
_onEnter: (result, response, callback) => {
this._currentOperationCallback = null;
/* Codes_SRS_NODE_PROVISIONING_TRANSPORT_STATE_MACHINE_18_014: [ If `PollingTransport.registrationRequest` succeeds with status==Assigned, it shall call `callback` with null, the response body, and the protocol-specific result. ] */
/* Codes_SRS_NODE_PROVISIONING_TRANSPORT_STATE_MACHINE_18_020: [ If `PollingTransport.queryOperationStatus` succeeds with status==Assigned, `register` shall complete and pass the body of the response and the protocol-specific result to the `callback`. ] */
this._fsm.transition('idle', null, result, response, callback);
},
'*': () => this._fsm.deferUntilTransition()
},
responseError: {
_onEnter: (err, result, response, callback) => {
debugErrors('Response error: ' + err);
this._currentOperationCallback = null;
this._fsm.transition('idle', err, result, response, callback);
},
'*': () => this._fsm.deferUntilTransition()
},
waitingToPoll: {
_onEnter: (request, operationId, pollingInterval, callback) => {
debug('waiting for ' + pollingInterval + ' ms');
this._pollingTimer = setTimeout(() => {
if (operationId) {
this._fsm.transition('polling', request, operationId, pollingInterval, callback);
} else {
//
// retrying registration must necessarily have a falsy operation id. If they had
// an operation id they wouldn't need to retry!
//
this._fsm.transition('sendingRegistrationRequest', request, callback);
}
}, pollingInterval);
},
cancel: (cancelledOpErr, callback) => {
/* Codes_SRS_NODE_PROVISIONING_TRANSPORT_STATE_MACHINE_18_027: [ If a registration is in progress, `cancel` shall cause that registration to fail with an `OperationCancelledError`. ] */
clearTimeout(this._pollingTimer);
this._pollingTimer = null;
this._fsm.transition('cancelling', cancelledOpErr, callback);
},
/* Codes_SRS_NODE_PROVISIONING_TRANSPORT_STATE_MACHINE_18_034: [ If `disconnect` is called while the state machine is waiting to poll, the current operation shall be cancelled and the transport shall be disconnected. ] */
disconnect: (callback) => {
this._fsm.handle('cancel', new errors.OperationCancelledError(''), (_err) => {
this._fsm.handle('disconnect', callback);
});
},
register: (_request, callback) => callback(new errors.InvalidOperationError('another operation is in progress'))
},
polling: {
_onEnter: (request, operationId, _pollingInterval, callback) => {
/* Codes_SRS_NODE_PROVISIONING_TRANSPORT_STATE_MACHINE_18_037: [ If `PollingTransport.queryOperationStatus` does not call its callback within `ProvisioningDeviceConstants.defaultTimeoutInterval` ms, register shall with with a `TimeoutError` error. ] */
this._queryTimer = setTimeout(() => {
debug('timeout while query');
if (this._currentOperationCallback === callback) {
/* tslint:disable:no-empty */
this._fsm.handle('cancel', new errors.TimeoutError(), () => { });
}
}, ProvisioningDeviceConstants.defaultTimeoutInterval);
/* Codes_SRS_NODE_PROVISIONING_TRANSPORT_STATE_MACHINE_18_018: [ When the polling interval elapses, `register` shall call `PollingTransport.queryOperationStatus`. ] */
this._transport.queryOperationStatus(request, operationId, (err, result, response, pollingInterval) => {
clearTimeout(this._queryTimer);
// Check if the operation is still pending before transitioning. We might be in a different state now and we don't want to mess that up.
if (this._currentOperationCallback === callback) {
this._fsm.transition('responseReceived', err, request, result, response, pollingInterval, callback);
} else if (this._currentOperationCallback) {
debugErrors('Unexpected: received unexpected response for cancelled operation');
}
});
},
cancel: (cancelledOpErr, callback) => this._fsm.transition('cancelling', cancelledOpErr, callback),
/* Codes_SRS_NODE_PROVISIONING_TRANSPORT_STATE_MACHINE_18_035: [ If `disconnect` is called while in the middle of a `queryOperationStatus` operation, the operation shall be cancelled and the transport shall be disconnected. ] */
disconnect: (callback) => {
this._fsm.handle('cancel', new errors.OperationCancelledError(''), (_err) => {
this._fsm.handle('disconnect', callback);
});
},
/* Codes_SRS_NODE_PROVISIONING_TRANSPORT_STATE_MACHINE_18_024: [ If `register` is called while a different request is in progress, it shall fail with an `InvalidOperationError`. ] */
register: (_request, callback) => callback(new errors.InvalidOperationError('another operation is in progress'))
},
cancelling: {
_onEnter: (cancelledOpErr, callback) => {
/* Codes_SRS_NODE_PROVISIONING_TRANSPORT_STATE_MACHINE_18_027: [ If a registration is in progress, `cancel` shall cause that registration to fail with an `OperationCancelledError`. ] */
if (this._currentOperationCallback) {
let _callback = this._currentOperationCallback;
this._currentOperationCallback = null;
process.nextTick(() => _callback(cancelledOpErr));
}
this._transport.cancel((cancelErr) => {
if (cancelErr) {
debugErrors('error received from transport during cancel: ' + cancelErr);
}
this._fsm.transition('idle', cancelErr, null, null, callback);
});
},
'*': () => this._fsm.deferUntilTransition()
},
disconnecting: {
_onEnter: (callback) => {
if (this._pollingTimer) {
debug('cancelling polling timer');
clearTimeout(this._pollingTimer);
}
if (this._queryTimer) {
debug('cancelling query timer');
clearTimeout(this._queryTimer);
}
this._transport.disconnect((err) => {
this._fsm.transition('disconnected', err, null, null, callback);
});
},
'*': () => this._fsm.deferUntilTransition()
}
}
});
this._fsm.on('transition', (data) => {
debug('completed transition from ' + data.fromState + ' to ' + data.toState);
});
}
register(request: RegistrationRequest, callback: Callback<DeviceRegistrationResult>): void;
register(request: RegistrationRequest): Promise<DeviceRegistrationResult>;
register(request: RegistrationRequest, callback?: Callback<DeviceRegistrationResult>): Promise<DeviceRegistrationResult> | void {
return callbackToPromise((_callback) => {
debug('register called for registrationId "' + request.registrationId + '"');
this._fsm.handle('register', request, _callback);
}, callback);
}
cancel(callback: ErrorCallback): void;
cancel(): Promise<void>;
cancel(callback?: ErrorCallback): Promise<void> | void {
return errorCallbackToPromise((_callback) => {
debug('cancel called');
this._fsm.handle('cancel', new errors.OperationCancelledError(''), _callback);
}, callback);
}
disconnect(callback: ErrorCallback): void;
disconnect(): Promise<void>;
disconnect(callback?: ErrorCallback): Promise<void> | void {
return errorCallbackToPromise((_callback) => {
debug('disconnect called');
this._fsm.handle('disconnect', _callback);
}, callback);
}
} | the_stack |
import request from 'request';
import _ from 'lodash';
import CONFIG from '../../config';
import { logger } from '../logger';
export const statusSMS = async (SMSID: string): Promise<{ succeeded: boolean; code: number }> => {
if (CONFIG.SMS_SIMULATE) {
return { succeeded: true, code: 1 };
}
const url = 'https://www.smsflatrate.net/status.php';
const qs = {
id: SMSID,
};
return new Promise<{ succeeded: boolean; code: number }>((resolve, reject) => {
request({ url, qs }, (err, response, body) => {
if (err) {
logger.error(JSON.stringify(err));
reject(err);
}
const code = parseInt(body, 10);
switch (code) {
case 100:
// Standard Rückgabewert // Standard return value
// SMS erfolgreich an das Gateway übertragen
// SMS successfully transferred to the gateway
resolve({ succeeded: true, code });
break;
// Zustellberichte / Return values (101-109)
// Return values 101 - 109 for sms with status request only
case 101:
// SMS wurde zugestellt // SMS successfully dispatched
resolve({ succeeded: true, code });
break;
case 102:
// SMS wurde noch nicht zugestellt(z.B.Handy aus oder temporär nicht erreichbar)
// SMS not delivered yet(for example mobile phone is off or network temporarily
// unavailable)
resolve({ succeeded: false, code });
break;
case 103:
// SMS konnte vermutlich nicht zugestellt werden(Rufnummer falsch, SIM nicht aktiv)
// SMS probably not delivered(wrong number, SIMcard not active)
resolve({ succeeded: false, code });
break;
case 104:
// SMS konnte nach Ablauf von 48 Stunden noch immer nicht zugestellt werden.
// Aus dem Rückgabewert 102 wird nach Ablauf von 2 Tagen der Status 104.
// SMS could not be delivered within 48 hours.
// The return value 102 changes to 104 after the 48 hours have passed.
resolve({ succeeded: false, code });
break;
case 109:
// SMS ID abgelaufen oder ungültig(manuelle Status - Abfrage)
// SMS ID expired or is invalid(for using manual status request)
resolve({ succeeded: false, code });
break;
// Zusätzliche Rückgabewerte
case 110:
// Falscher Schnittstellen - Key oder Ihr Account ist gesperrt
// Wrong Gateway - Key or your account is locked
resolve({ succeeded: false, code });
break;
case 120:
// Guthaben reicht nicht aus // Not enough credits
resolve({ succeeded: false, code });
break;
case 130:
// Falsche Datenübergabe(z.B.Absender fehlt)
// Incorrect data transfer(for example the Sender - ID is missing)
resolve({ succeeded: false, code });
break;
case 131:
// Empfänger nicht korrekt // Receiver number is not correct
resolve({ succeeded: false, code });
break;
case 132:
// Absender nicht korrekt // Sender-ID is not correct
resolve({ succeeded: false, code });
break;
case 133:
// Nachrichtentext nicht korrekt // Text message not correct
resolve({ succeeded: false, code });
break;
case 140:
// Falscher AppKey oder Ihr Account ist gesperrt
// Wrong AppKey or your account is locked
resolve({ succeeded: false, code });
break;
case 150:
// Sie haben versucht an eine internationale Handynummer eines Gateways, das
// ausschließlich für den Versand nach Deutschland bestimmt ist, zu senden.
// Bitte internationales Gateway oder Auto - Type - Funktion verwenden.
// You have tried to send to an international phone number through a gateway determined to
// handle german receivers only.Please use an international Gateway - Type or Auto - Type.
resolve({ succeeded: false, code });
break;
case 170:
// Parameter „time =“ ist nicht korrekt.Bitte im Format: TT.MM.JJJJ - SS: MM oder
// Parameter entfernen für sofortigen Versand.
// Parameter "time =" is not correct.Please use the format: TT.MM.YYYY - SS: MM or delete
// parameter for immediately dispatch.
resolve({ succeeded: false, code });
break;
case 171:
// Parameter „time =“ ist zu weit in der Zukunft terminiert(max. 360 Tage)
// Parameter "time =" is too far in the future(max. 360 days).
resolve({ succeeded: false, code });
break;
case 180:
// Account noch nicht komplett freigeschaltet / Volumen - Beschränkung noch aktiv
// Bitte im Kundencenter die Freischaltung beantragen, damit unbeschränkter
// Nachrichtenversand möglich ist.
resolve({ succeeded: false, code });
break;
case 231:
// Keine smsflatrate.net Gruppe vorhanden oder nicht korrekt
// smsflatrate.net group is not available or not correct
resolve({ succeeded: false, code });
break;
case 404:
// Unbekannter Fehler.Bitte dringend Support(ticket@smsflatrate.net) kontaktieren.
// Unknown error.Please urgently contact support(ticket@smsflatrate.net).
resolve({ succeeded: false, code });
break;
default:
resolve({ succeeded: false, code });
}
});
});
};
export const sendSMS = async (
phone: string,
code: string,
): Promise<{
status: boolean;
statusCode: number;
SMSID: string;
}> => {
if (CONFIG.SMS_SIMULATE) {
return { status: true, statusCode: 100, SMSID: _.uniqueId() };
}
const url = 'https://www.smsflatrate.net/schnittstelle.php';
const qs = {
key: CONFIG.SMS_PROVIDER_KEY,
from: 'DEMOCRACY',
to: phone,
text: `Hallo von DEMOCRACY. Dein Code lautet: ${code}`,
type: 'auto10or11',
status: '1',
};
return new Promise((resolve, reject) => {
request({ url, qs }, (err, response, body) => {
let status = false;
let statusCode = null;
let SMSID = null;
if (err) {
reject(err);
}
const bodyResult = body.split(',');
statusCode = parseInt(bodyResult[0], 10);
SMSID = bodyResult[1]; // eslint-disable-line
switch (statusCode) {
case 100:
// Standard Rückgabewert // Standard return value
// SMS erfolgreich an das Gateway übertragen
// SMS successfully transferred to the gateway
status = true;
break;
// Zustellberichte / Return values (101-109)
// Return values 101 - 109 for sms with status request only
case 101:
// SMS wurde zugestellt // SMS successfully dispatched
status = true;
break;
case 102:
// SMS wurde noch nicht zugestellt(z.B.Handy aus oder temporär nicht erreichbar)
// SMS not delivered yet(for example mobile phone is off or network temporarily
// unavailable)
status = false;
break;
case 103:
// SMS konnte vermutlich nicht zugestellt werden(Rufnummer falsch, SIM nicht aktiv)
// SMS probably not delivered(wrong number, SIMcard not active)
status = false;
break;
case 104:
// SMS konnte nach Ablauf von 48 Stunden noch immer nicht zugestellt werden.
// Aus dem Rückgabewert 102 wird nach Ablauf von 2 Tagen der Status 104.
// SMS could not be delivered within 48 hours.
// The return value 102 changes to 104 after the 48 hours have passed.
status = false;
break;
case 109:
// SMS ID abgelaufen oder ungültig(manuelle Status - Abfrage)
// SMS ID expired or is invalid(for using manual status request)
status = false;
break;
// Zusätzliche Rückgabewerte
case 110:
// Falscher Schnittstellen - Key oder Ihr Account ist gesperrt
// Wrong Gateway - Key or your account is locked
status = false;
break;
case 120:
// Guthaben reicht nicht aus // Not enough credits
status = false;
break;
case 130:
// Falsche Datenübergabe(z.B.Absender fehlt)
// Incorrect data transfer(for example the Sender - ID is missing)
status = false;
break;
case 131:
// Empfänger nicht korrekt // Receiver number is not correct
status = false;
break;
case 132:
// Absender nicht korrekt // Sender-ID is not correct
status = false;
break;
case 133:
// Nachrichtentext nicht korrekt // Text message not correct
status = false;
break;
case 140:
// Falscher AppKey oder Ihr Account ist gesperrt
// Wrong AppKey or your account is locked
status = false;
break;
case 150:
// Sie haben versucht an eine internationale Handynummer eines Gateways, das
// ausschließlich für den Versand nach Deutschland bestimmt ist, zu senden.
// Bitte internationales Gateway oder Auto - Type - Funktion verwenden.
// You have tried to send to an international phone number through a gateway determined to
// handle german receivers only.Please use an international Gateway - Type or Auto - Type.
status = false;
break;
case 170:
// Parameter „time =“ ist nicht korrekt.Bitte im Format: TT.MM.JJJJ - SS: MM oder
// Parameter entfernen für sofortigen Versand.
// Parameter "time =" is not correct.Please use the format: TT.MM.YYYY - SS: MM or delete
// parameter for immediately dispatch.
status = false;
break;
case 171:
// Parameter „time =“ ist zu weit in der Zukunft terminiert(max. 360 Tage)
// Parameter "time =" is too far in the future(max. 360 days).
status = false;
break;
case 180:
// Account noch nicht komplett freigeschaltet / Volumen - Beschränkung noch aktiv
// Bitte im Kundencenter die Freischaltung beantragen, damit unbeschränkter
// Nachrichtenversand möglich ist.
status = false;
break;
case 231:
// Keine smsflatrate.net Gruppe vorhanden oder nicht korrekt
// smsflatrate.net group is not available or not correct
status = false;
break;
case 404:
// Unbekannter Fehler.Bitte dringend Support(ticket@smsflatrate.net) kontaktieren.
// Unknown error.Please urgently contact support(ticket@smsflatrate.net).
status = false;
break;
default:
status = false;
}
if (!status) {
console.error('SMS Error', bodyResult);
}
resolve({ status, statusCode, SMSID });
});
});
}; | the_stack |
import * as ts from "../../../modules/typescript";
import * as WorkerProcessTypes from "./workerprocess/workerProcessTypes";
import ClientExtensionEventNames from "../../ClientExtensionEventNames";
import * as tsLanguageSupport from "./tsLanguageSupport";
/**
* Resource extension that handles compiling or transpling typescript on file save.
*/
export default class TypescriptLanguageExtension implements Editor.ClientExtensions.WebViewServiceEventListener {
name: string = "ClientTypescriptLanguageExtension";
description: string = "This extension handles typescript language features such as completion, compilation, etc.";
/**
* current filename
* @type {string}
*/
filename: string;
/**
* Is this instance of the extension active? Only true if the current editor
* is a typescript file.
* @type {Boolean}
*/
private active = false;
private serviceLocator: Editor.ClientExtensions.ClientServiceLocator;
private worker: SharedWorker.SharedWorker;
private editor: monaco.editor.IStandaloneCodeEditor;
/**
* Perform a full compile on save, or just transpile the current file
* @type {boolean}
*/
fullCompile: boolean = true;
/**
* Inject this language service into the registry
* @param {Editor.ClientExtensions.ClientServiceLocator} serviceLocator
*/
initialize(serviceLocator: Editor.ClientExtensions.ClientServiceLocator) {
// initialize the language service
this.serviceLocator = serviceLocator;
serviceLocator.clientServices.register(this);
}
/**
* Determines if the file name/path provided is something we care about
* @param {string} path
* @return {boolean}
*/
private isValidFiletype(path: string): boolean {
let ext = path.split(".").pop();
return ext == "ts" || ext == "js";
}
/**
* Returns true if this is a javascript file
* @param {string} path
* @return {boolean}
*/
private isJsFile(path: string): boolean {
let ext = path.split(".").pop();
return ext == "js";
}
/**
* Checks to see if this is a transpiled Javascript file
* @param {string} path
* @param {[type]} tsconfig
* @return {boolean}
*/
private isTranspiledJsFile(path: string, tsconfig): boolean {
if (this.isJsFile(path)) {
const tsFilename = path.replace(/\.js$/, ".ts");
return tsconfig.files.find(f => f.endsWith(tsFilename)) != null;
}
return false;
}
/**
* Utility function that handles sending a request to the worker process and then when
* a response is received pass it back to the caller. Since this is all handled async,
* it will be facilitated by passing back a promise
* @param {string} responseChannel The unique string name of the response message channel
* @param {any} message
* @return {PromiseLike}
*/
workerRequest(responseChannel: string, message: any): PromiseLike<{}> {
let worker = this.worker;
return new Promise((resolve, reject) => {
const responseCallback = function(e: WorkerProcessTypes.WorkerProcessMessage<any>) {
if (e.data.command == responseChannel) {
worker.port.removeEventListener("message", responseCallback);
resolve(e.data);
}
};
this.worker.port.addEventListener("message", responseCallback);
this.worker.port.postMessage(message);
});
}
/**
* Called when the editor needs to be configured for a particular file
* @param {Editor.ClientExtensions.EditorFileEvent} ev
*/
configureEditor(ev: Editor.ClientExtensions.EditorFileEvent) {
if (this.isValidFiletype(ev.filename)) {
let editor = ev.editor as monaco.editor.IStandaloneCodeEditor;
this.editor = editor; // cache this so that we can reference it later
this.active = true;
this.overrideBuiltinServiceProviders();
// Hook in the routine to allow the host to perform a full compile
this.serviceLocator.clientServices.getHostInterop().addCustomHostRoutine("TypeScript_DoFullCompile", (jsonTsConfig: string) => {
let tsConfig = JSON.parse(jsonTsConfig);
this.doFullCompile(tsConfig);
});
this.filename = ev.filename;
// Let's turn some things off in the editor. These will be provided by the shared web worker
if (this.isJsFile(ev.filename)) {
monaco.languages.typescript.javascriptDefaults.setCompilerOptions({
noEmit: true,
noResolve: true,
allowNonTsExtensions: true,
noLib: true,
target: monaco.languages.typescript.ScriptTarget.ES5
});
monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
noSemanticValidation: true,
noSyntaxValidation: true
});
// Register editor feature providers
monaco.languages.registerCompletionItemProvider("javascript", new CustomCompletionProvider(this));
monaco.languages.registerHoverProvider("javascript", new CustomHoverProvider(this));
monaco.languages.registerSignatureHelpProvider("javascript", new CustomSignatureProvider(this));
} else {
monaco.languages.register({
id: "atomic-ts"
});
monaco.languages.typescript.typescriptDefaults.setCompilerOptions({
noEmit: true,
noResolve: true,
noLib: true,
target: monaco.languages.typescript.ScriptTarget.ES5
});
monaco.languages.typescript.typescriptDefaults.setDiagnosticsOptions({
noSemanticValidation: true,
noSyntaxValidation: true
});
// Register editor feature providers
monaco.languages.registerCompletionItemProvider("typescript", new CustomCompletionProvider(this));
monaco.languages.registerSignatureHelpProvider("typescript", new CustomSignatureProvider(this));
monaco.languages.registerHoverProvider("typescript", new CustomHoverProvider(this));
}
}
}
/**
* Monkeypatch the TypeScript language provider so that our service providers get loaded
* and not the built-in ones. Ours use a shared web worker so that state can be shared
* across tabs.
*/
private overrideBuiltinServiceProviders() {
monaco.languages.registerSignatureHelpProvider = ((original) => {
return function(languageId: string, provider: monaco.languages.SignatureHelpProvider): monaco.IDisposable {
if (provider["isOverride"]) {
return original(languageId, provider);
}
};
})(monaco.languages.registerSignatureHelpProvider);
monaco.languages.registerCompletionItemProvider = ((original) => {
return function(languageId: string, provider: monaco.languages.CompletionItemProvider): monaco.IDisposable {
if (provider["isOverride"]) {
return original(languageId, provider);
}
};
})(monaco.languages.registerCompletionItemProvider);
monaco.languages.registerHoverProvider = ((original) => {
return function(languageId: string, provider: monaco.languages.HoverProvider): monaco.IDisposable {
if (provider["isOverride"]) {
return original(languageId, provider);
}
};
})(monaco.languages.registerHoverProvider);
}
/**
* Called when code is first loaded into the editor
* @param {CodeLoadedEvent} ev
*/
codeLoaded(ev: Editor.ClientExtensions.CodeLoadedEvent) {
if (this.isValidFiletype(ev.filename)) {
// Build our worker
this.buildWorker();
// Initial load, so the TSConfig on the window object should be the most current
let tsConfig = JSON.parse(window["TypeScriptLanguageExtension"]["tsConfig"]);
let model = this.editor.getModel();
let handle: number;
model.onDidChangeContent(() => {
clearTimeout(handle);
handle = setTimeout(() => this.getAnnotations(), 500);
});
// post a message to the shared web worker
this.worker.port.postMessage({
command: WorkerProcessTypes.Connect,
sender: "Typescript Language Extension",
filename: ev.filename,
tsConfig: tsConfig,
code: ev.code
});
// Configure based on prefs
this.preferencesChanged();
}
}
/**
* Handler for any messages initiated by the worker process
* @param {WorkerProcessTypes.WorkerProcessMessage} e
*/
handleWorkerMessage(e: WorkerProcessTypes.WorkerProcessMessage<any>) {
switch (e.data.command) {
case WorkerProcessTypes.Message:
console.log(e.data.message);
break;
case WorkerProcessTypes.Alert:
alert(e.data.message);
break;
case WorkerProcessTypes.AnnotationsUpdated:
this.setAnnotations(e.data);
break;
case WorkerProcessTypes.SaveFile:
this.saveFile(e.data);
break;
case WorkerProcessTypes.DisplayFullCompileResults:
this.displayFullCompileResults(e.data);
break;
}
}
/**
* Saves a compiled file sent across from the worker service
* @param {WorkerProcessTypes.SaveMessageData} event
*/
saveFile(event: WorkerProcessTypes.SaveMessageData) {
if (this.active) {
this.serviceLocator.clientServices.getHostInterop().saveFile(event.filename, event.code);
}
}
/**
* Format the code
*/
formatCode() {
if (this.active) {
const action = this.editor.getAction("editor.action.format");
if (action && action.isSupported()) {
let wasEmpty = false;
let cursorPosition;
if (this.editor.getSelection().isEmpty()) {
wasEmpty = true;
cursorPosition = this.editor.getPosition();
this.editor.setSelection(this.editor.getModel().getFullModelRange());
}
action.run().then(() => {
// Make sure we put the cursor back to where it was
if (wasEmpty && cursorPosition) {
this.editor.setPosition(cursorPosition);
}
});
}
}
}
/**
* Request the markers to display
*/
getAnnotations() {
const message: WorkerProcessTypes.GetAnnotationsMessageData = {
command: WorkerProcessTypes.GetAnnotations,
code: this.editor.getModel().getValue(),
filename: this.filename,
fileExt: null,
editor: null // cannot send editor across the boundary
};
this.worker.port.postMessage(message);
}
/**
* Set annotations based upon issues reported by the typescript language service
* @param {WorkerProcessTypes.GetAnnotationsResponseMessageData} event
*/
setAnnotations(event: WorkerProcessTypes.GetAnnotationsResponseMessageData) {
let model = this.editor.getModel();
let markers = event.annotations
.filter(ann => ann.start != undefined)
.map(ann => {
return {
code: ann.code,
severity: monaco.Severity.Error,
message: ann.message,
//source?: string;
startLineNumber: model.getPositionAt(ann.start).lineNumber,
startColumn: model.getPositionAt(ann.start).column,
endLineNumber: model.getPositionAt(ann.start + ann.length).lineNumber,
endColumn: model.getPositionAt(ann.start + ann.length).column
};
});
monaco.editor.setModelMarkers(this.editor.getModel(), "typescript", markers);
}
/**
* Build/Attach to the shared web worker
*/
buildWorker() {
if (!this.worker) {
this.worker = new SharedWorker("./source/editorCore/clientExtensions/languageExtensions/typescript/workerprocess/workerLoader.js");
// hook up the event listener
this.worker.port.addEventListener("message", this.handleWorkerMessage.bind(this), false);
// Tell the SharedWorker we're closing
addEventListener("beforeunload", () => {
this.worker.port.postMessage({ command: WorkerProcessTypes.Disconnect });
});
this.worker.port.start();
}
}
/**
* Called once a resource has been saved
* @param {Editor.ClientExtensions.SaveResourceEvent} ev
*/
save(ev: Editor.ClientExtensions.CodeSavedEvent) {
if (this.active && this.isValidFiletype(ev.filename)) {
const message: WorkerProcessTypes.SaveMessageData = {
command: ClientExtensionEventNames.CodeSavedEvent,
filename: ev.filename,
fileExt: ev.fileExt,
code: ev.code,
editor: null // cannot send editor across the boundary
};
this.worker.port.postMessage(message);
}
}
/**
* Handle the delete. This should delete the corresponding javascript file
* @param {Editor.ClientExtensions.DeleteResourceEvent} ev
*/
delete(ev: Editor.ClientExtensions.DeleteResourceEvent) {
if (this.active && this.isValidFiletype(ev.path)) {
// notify the typescript language service that the file has been deleted
const message: WorkerProcessTypes.DeleteMessageData = {
command: ClientExtensionEventNames.ResourceDeletedEvent,
path: ev.path
};
this.worker.port.postMessage(message);
}
}
/**
* Handle the rename. Should rename the corresponding .js file
* @param {Editor.ClientExtensions.RenameResourceEvent} ev
*/
rename(ev: Editor.ClientExtensions.RenameResourceEvent) {
if (this.active && this.isValidFiletype(ev.path)) {
// notify the typescript language service that the file has been renamed
const message: WorkerProcessTypes.RenameMessageData = {
command: ClientExtensionEventNames.ResourceRenamedEvent,
path: ev.path,
newPath: ev.newPath
};
this.worker.port.postMessage(message);
}
}
/**
* Called when the user preferences have been changed (or initially loaded)
* @return {[type]}
*/
preferencesChanged() {
if (this.active) {
let compileOnSave = this.serviceLocator.clientServices.getUserPreference("HostTypeScriptLanguageExtension", "CompileOnSave", true);
const message: WorkerProcessTypes.SetPreferencesMessageData = {
command: WorkerProcessTypes.SetPreferences,
preferences: {
compileOnSave: compileOnSave
}
};
this.worker.port.postMessage(message);
}
}
/**
* Tell the language service to perform a full compile
*/
doFullCompile(tsConfig: any) {
if (this.active) {
const message: WorkerProcessTypes.FullCompileMessageData = {
command: WorkerProcessTypes.DoFullCompile,
tsConfig: tsConfig
};
this.worker.port.postMessage(message);
}
}
/**
* Displays the results from a full compile
* @param {WorkerProcessTypes.FullCompileResultsMessageData} results
*/
displayFullCompileResults(results: WorkerProcessTypes.FullCompileResultsMessageData) {
let messageArray = results.annotations.map((result) => {
return `${result.text} at line ${result.row} col ${result.column} in ${result.file}`;
});
window.atomicQueryPromise("TypeScript.DisplayCompileResults", results);
}
}
/**
* Class used as a base for our custom providers to let the patched loader
* know to allow this through.
*/
class BuiltinServiceProviderOverride {
constructor(extension: TypescriptLanguageExtension) {
this.extension = extension;
}
protected extension: TypescriptLanguageExtension;
/**
* Used to tell the loader that we want to load this extension. Others will be skipped
* @type {Boolean}
*/
public isOverride = true;
}
/**
* Customized completion provider that will delegate to the shared web worker for it's completions
*/
class CustomCompletionProvider extends BuiltinServiceProviderOverride implements monaco.languages.CompletionItemProvider {
get triggerCharacters(): string[] {
return ["."];
}
provideCompletionItems(model: monaco.editor.IReadOnlyModel, position: monaco.Position, token: monaco.CancellationToken): monaco.languages.CompletionItem[] | monaco.Thenable<monaco.languages.CompletionItem[]> | monaco.languages.CompletionList | monaco.Thenable<monaco.languages.CompletionList> {
const message: WorkerProcessTypes.MonacoProvideCompletionItemsMessageData = {
command: WorkerProcessTypes.MonacoProvideCompletionItems,
uri: this.extension.filename,
source: model.getValue(),
positionOffset: model.getOffsetAt(position)
};
return this.extension.workerRequest(WorkerProcessTypes.MonacoProvideCompletionItemsResponse, message)
.then((e: WorkerProcessTypes.MonacoProvideCompletionItemsResponseMessageData) => {
// Need to map the TS completion kind to the monaco completion kind
return e.completions.map(completion => {
completion.kind = tsLanguageSupport.Kind.convertKind(completion.completionKind);
return completion;
}).filter(completion => {
// Filter out built-in keywords since most of them don't apply to Atomic
return completion.kind != monaco.languages.CompletionItemKind.Keyword;
});
});
}
resolveCompletionItem(item: monaco.languages.CompletionItem, token: monaco.CancellationToken): monaco.languages.CompletionItem | monaco.Thenable<monaco.languages.CompletionItem> {
const message: WorkerProcessTypes.MonacoResolveCompletionItemMessageData = {
command: WorkerProcessTypes.MonacoResolveCompletionItem,
item: item as WorkerProcessTypes.MonacoWordCompletion
};
return this.extension.workerRequest(WorkerProcessTypes.MonacoResolveCompletionItemResponse, message)
.then((e: WorkerProcessTypes.MonacoResolveCompletionItemResponseMessageData) => {
return e;
});
}
}
class CustomHoverProvider extends BuiltinServiceProviderOverride implements monaco.languages.HoverProvider {
protected _offsetToPosition(uri: monaco.Uri, offset: number): monaco.IPosition {
let model = monaco.editor.getModel(uri);
return model.getPositionAt(offset);
}
protected _textSpanToRange(uri: monaco.Uri, span: ts.TextSpan): monaco.IRange {
let p1 = this._offsetToPosition(uri, span.start);
let p2 = this._offsetToPosition(uri, span.start + span.length);
let {lineNumber: startLineNumber, column: startColumn} = p1;
let {lineNumber: endLineNumber, column: endColumn} = p2;
return { startLineNumber, startColumn, endLineNumber, endColumn };
}
provideHover(model: monaco.editor.IReadOnlyModel, position: monaco.IPosition) {
let resource = model.uri;
const message: WorkerProcessTypes.MonacoGetQuickInfoMessageData = {
command: WorkerProcessTypes.MonacoGetQuickInfo,
uri: this.extension.filename,
source: model.getValue(),
positionOffset: model.getOffsetAt(position)
};
return this.extension.workerRequest(WorkerProcessTypes.MonacoGetQuickInfoResponse, message)
.then((e: WorkerProcessTypes.MonacoGetQuickInfoResponseMessageData) => {
if (e.contents) {
return {
range: this._textSpanToRange(resource, e.textSpan),
contents: [e.documentation, { language: "typescript", value: e.contents }]
};
}
});
}
}
export class CustomSignatureProvider extends BuiltinServiceProviderOverride implements monaco.languages.SignatureHelpProvider {
public signatureHelpTriggerCharacters = ["(", ","];
provideSignatureHelp(model: monaco.editor.IReadOnlyModel, position: monaco.Position) {
let resource = model.uri;
const message: WorkerProcessTypes.MonacoGetSignatureMessageData = {
command: WorkerProcessTypes.MonacoGetSignature,
uri: this.extension.filename,
source: model.getValue(),
positionOffset: model.getOffsetAt(position)
};
return this.extension.workerRequest(WorkerProcessTypes.MonacoGetSignatureResponse, message)
.then((e: WorkerProcessTypes.MonacoGetSignatureMessageDataResponse) => {
if (e.signatures) {
let result: monaco.languages.SignatureHelp = {
signatures: e.signatures,
activeSignature: e.selectedItemIndex,
activeParameter: e.argumentIndex
};
return result;
}
});
}
} | the_stack |
import { isPresent, global, stringify } from '../../facade/lang';
import { GetterFn, SetterFn, MethodFn } from './types';
import { PlatformReflectionCapabilities } from './platform_reflection_capabilities';
import { ListWrapper } from '../../facade/collections';
import { Type } from '../../facade/type';
// import {BaseException} from 'angular2/src/facade/exceptions';
// This will be needed when we will used Reflect APIs
const Reflect = global.Reflect;
if ( !isReflectMetadata(Reflect) ) {
throw `
Reflect.*metadata shim is required when using class decorators.
You can use one of:
- "reflect-metadata" (https://www.npmjs.com/package/reflect-metadata)
- "core-js/es7/reflect" (https://github.com/zloirock/core-js)
`;
}
/**
* @internal
*/
export const CLASS_META_KEY = 'annotations';
/**
* @internal
*/
export const PARAM_META_KEY = 'parameters';
/**
* @internal
*/
export const PARAM_REFLECT_META_KEY = 'design:paramtypes';
/**
* @internal
*/
export const PROP_META_KEY = 'propMetadata';
/**
* @internal
*/
export const DOWNGRADED_COMPONENT_NAME_KEY = 'downgradeComponentName';
function isReflectMetadata( reflect: any ): boolean {
return isPresent( reflect ) && isPresent( reflect.getMetadata );
}
export class ReflectionCapabilities implements PlatformReflectionCapabilities {
private _reflect: any;
constructor( reflect=global.Reflect ) {
this._reflect = reflect;
}
isReflectionEnabled(): boolean { return true; }
factory( t: Type ): Function {
switch ( t.length ) {
case 0:
return () => new t();
case 1:
return ( a1: any ) => new t( a1 );
case 2:
return ( a1: any, a2: any ) => new t( a1, a2 );
case 3:
return ( a1: any, a2: any, a3: any ) => new t( a1, a2, a3 );
case 4:
return ( a1: any, a2: any, a3: any, a4: any ) => new t( a1, a2, a3, a4 );
case 5:
return ( a1: any, a2: any, a3: any, a4: any, a5: any ) => new t( a1, a2, a3, a4, a5 );
case 6:
return ( a1: any, a2: any, a3: any, a4: any, a5: any, a6: any ) =>
new t( a1, a2, a3, a4, a5, a6 );
case 7:
return ( a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any ) =>
new t( a1, a2, a3, a4, a5, a6, a7 );
case 8:
return ( a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any ) =>
new t( a1, a2, a3, a4, a5, a6, a7, a8 );
case 9:
return ( a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any ) =>
new t( a1, a2, a3, a4, a5, a6, a7, a8, a9 );
case 10:
return (
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any,
a10: any
) => new t( a1, a2, a3, a4, a5, a6, a7, a8, a9, a10 );
case 11:
return (
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any,
a10: any, a11: any
) => new t( a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11 );
case 12:
return (
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any,
a10: any, a11: any, a12: any
) =>
new t( a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12 );
case 13:
return (
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any,
a10: any, a11: any, a12: any, a13: any
) =>
new t( a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13 );
case 14:
return (
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any,
a10: any, a11: any, a12: any, a13: any, a14: any
) =>
new t( a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14 );
case 15:
return (
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any,
a10: any, a11: any, a12: any, a13: any, a14: any, a15: any
) =>
new t( a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15 );
case 16:
return (
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any,
a10: any, a11: any, a12: any, a13: any, a14: any, a15: any, a16: any
) =>
new t( a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16 );
case 17:
return (
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any,
a10: any, a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any
) =>
new t( a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16,
a17 );
case 18:
return (
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any,
a10: any, a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any,
a18: any
) => new t( a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15,
a16, a17, a18 );
case 19:
return (
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any,
a10: any, a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any,
a18: any, a19: any
) => new t( a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13,
a14, a15, a16, a17, a18, a19 );
case 20:
return (
a1: any, a2: any, a3: any, a4: any, a5: any, a6: any, a7: any, a8: any, a9: any,
a10: any, a11: any, a12: any, a13: any, a14: any, a15: any, a16: any, a17: any,
a18: any, a19: any, a20: any
) => new t( a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11,
a12, a13, a14, a15, a16, a17, a18, a19, a20 );
}
throw new Error(
`Cannot create a factory for '${stringify( t )}' because its constructor has more than 20 arguments`
);
}
/** @internal */
_zipTypesAndAnnotations( paramTypes: any[], paramAnnotations: any[] ): any[][] {
var result;
if ( typeof paramTypes === 'undefined' ) {
result = new Array( paramAnnotations.length );
} else {
result = new Array( paramTypes.length );
}
for ( var i = 0; i < result.length; i++ ) {
// TS outputs Object for parameters without types, while Traceur omits
// the annotations. For now we preserve the Traceur behavior to aid
// migration, but this can be revisited.
if ( typeof paramTypes === 'undefined' ) {
result[ i ] = [];
} else if ( paramTypes[ i ] != Object ) {
result[ i ] = [ paramTypes[ i ] ];
} else {
result[ i ] = [];
}
if ( isPresent( paramAnnotations ) && isPresent( paramAnnotations[ i ] ) ) {
result[ i ] = result[ i ].concat( paramAnnotations[ i ] );
}
}
return result;
}
parameters( typeOrFunc: Type ): any[][] {
// // Prefer the direct API.
// if (isPresent((<any>typeOrFunc).parameters)) {
// return (<any>typeOrFunc).parameters;
// }
if ( isReflectMetadata( this._reflect ) ) {
// get parameter created with @Inject()
const paramAnnotations = this._reflect.getMetadata( PARAM_META_KEY, typeOrFunc );
// get parameter created via TS type annotations
const paramTypes = this._reflect.getMetadata( PARAM_REFLECT_META_KEY, typeOrFunc );
if ( isPresent( paramTypes ) || isPresent( paramAnnotations ) ) {
return this._zipTypesAndAnnotations( paramTypes, paramAnnotations );
}
}
// The array has to be filled with `undefined` because holes would be skipped by `some`
const parameters = new Array( (<any>typeOrFunc.length) );
ListWrapper.fill( parameters, undefined );
// parameters.fill(undefined);
return parameters;
}
rawParameters( typeOrFunc: Type ): any[][] {
return this._reflect.getMetadata( PARAM_META_KEY, typeOrFunc );
}
registerParameters( parameters, type: Type ): void {
this._reflect.defineMetadata( PARAM_META_KEY, parameters, type );
}
annotations( typeOrFunc: Type ): any[] {
// // Prefer the direct API.
// if (isPresent((<any>typeOrFunc).annotations)) {
// var annotations = (<any>typeOrFunc).annotations;
// if (isFunction(annotations) && annotations.annotations) {
// annotations = annotations.annotations;
// }
// return annotations;
// }
if ( isReflectMetadata( this._reflect ) ) {
const annotations = this._reflect.getMetadata( CLASS_META_KEY, typeOrFunc );
if ( isPresent( annotations ) ) return annotations;
}
return [];
}
ownAnnotations( typeOrFunc: Type ): any[] {
return this._reflect.getOwnMetadata( CLASS_META_KEY, typeOrFunc );
}
registerAnnotations( annotations, typeOrFunc: Type ): void {
this._reflect.defineMetadata( CLASS_META_KEY, annotations, typeOrFunc );
}
propMetadata( typeOrFunc: any ): {[key: string]: any[]} {
// // Prefer the direct API.
// if (isPresent((<any>typeOrFunc).propMetadata)) {
// var propMetadata = (<any>typeOrFunc).propMetadata;
// if (isFunction(propMetadata) && propMetadata.propMetadata) {
// propMetadata = propMetadata.propMetadata;
// }
// return propMetadata;
// }
if ( isReflectMetadata( this._reflect ) ) {
const propMetadata = this._reflect.getMetadata( PROP_META_KEY, typeOrFunc );
if ( isPresent( propMetadata ) ) return propMetadata;
}
return {};
}
ownPropMetadata( typeOrFunc: Type ): {[key: string]: any[]} {
return this._reflect.getOwnMetadata( PROP_META_KEY, typeOrFunc );
}
registerPropMetadata( propMetadata, typeOrFunc: Type|Function ): void {
this._reflect.defineMetadata( PROP_META_KEY, propMetadata, typeOrFunc );
}
registerDowngradedNg2ComponentName( componentName: string, typeOrFunc: Type|Function ): void {
this._reflect.defineMetadata( DOWNGRADED_COMPONENT_NAME_KEY, componentName, typeOrFunc );
}
downgradedNg2ComponentName( typeOrFunc: Type|Function ): string {
return this._reflect.getOwnMetadata( DOWNGRADED_COMPONENT_NAME_KEY, typeOrFunc );
}
interfaces( type: Type ): any[] {
// throw new BaseException("JavaScript does not support interfaces");
throw new Error( 'JavaScript does not support interfaces' );
}
getter( name: string ): GetterFn { return <GetterFn>new Function( 'o', 'return o.' + name + ';' ); }
setter( name: string ): SetterFn {
return <SetterFn>new Function( 'o', 'v', 'return o.' + name + ' = v;' );
}
method( name: string ): MethodFn {
let functionBody = `if (!o.${name}) throw new Error('"${name}" is undefined');
return o.${name}.apply(o, args);`;
return <MethodFn>new Function( 'o', 'args', functionBody );
}
} | the_stack |
import {
PLUGIN_COMPONENT,
PLUGIN_TOOLBAR_BUTTONS,
GALLERY_SETTINGS,
GALLERY_IMAGE_SETTINGS,
GIPHY_PLUGIN,
IMAGE_SETTINGS,
VIDEO_SETTINGS,
ACTION_BUTTONS,
STATIC_TOOLBAR_BUTTONS,
} from '../cypress/dataHooks';
import { DEFAULT_DESKTOP_BROWSERS } from './settings';
import { usePlugins, plugins, usePluginsConfig } from '../cypress/testAppConfig';
const eyesOpen = ({
test: {
parent: { title },
},
}: Mocha.Context) =>
cy.eyesOpen({
appName: 'Plugins',
testName: title,
browser: DEFAULT_DESKTOP_BROWSERS,
});
describe('plugins', () => {
afterEach(() => cy.matchContentSnapshot());
context('viewerToolbar', () => {
before(function() {
eyesOpen(this);
cy.on('window:before:load', win => {
cy.stub(win, 'open').as('windowOpen');
});
});
after(() => {
cy.eyesClose();
});
const shouldHaveOpenedTwitter = () => {
const text =
// eslint-disable-next-line max-len
'text=%E2%80%9Crunway%20heading%20towards%20a%20streamlined%20cloud%20solution.%20%20User%E2%80%A6%E2%80%9C%E2%80%94';
// TODO: fix test, it is not running the checks
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore: function should not be passed as argument but to `then` chained function
cy.url(url => {
const originUrl = 'url=' + encodeURI(url.toString());
const twitterUrl = `https://twitter.com/intent/tweet?${text}&${originUrl}`;
cy.get('@windowOpen').should('be.calledWith', twitterUrl);
});
};
it('render viewer toolbar and tweet', function() {
cy.loadRicosEditorAndViewer('nested-lists');
cy.getViewer().trigger('mouseover');
cy.setViewerSelection(476, 98);
cy.getTwitterButton().should('be.visible');
cy.eyesCheckWindow(this.test.title);
cy.getTwitterButton().click();
shouldHaveOpenedTwitter();
});
});
context('image', () => {
before(function() {
eyesOpen(this);
});
beforeEach('load editor', () => {
cy.switchToDesktop();
});
after(() => cy.eyesClose());
it('render image toolbar and settings', function() {
cy.loadRicosEditorAndViewer('images');
cy.openPluginToolbar(PLUGIN_COMPONENT.IMAGE);
cy.openSettings();
cy.eyesCheckWindow({ tag: this.test.title + ' - settings', target: 'window', fully: false });
cy.addImageTitle();
cy.eyesCheckWindow(this.test.title + ' - add image title');
cy.editImageTitle();
cy.eyesCheckWindow(this.test.title + ' - in plugin editing');
cy.openSettings().deleteImageTitle();
cy.eyesCheckWindow(this.test.title + ' - delete image title');
cy.addImageLink();
cy.eyesCheckWindow(this.test.title + ' - add a link');
cy.openPluginToolbar(PLUGIN_COMPONENT.IMAGE).pluginSizeOriginal();
cy.eyesCheckWindow(this.test.title + ' - plugin original size');
cy.openPluginToolbar(PLUGIN_COMPONENT.IMAGE).shrinkPlugin(PLUGIN_COMPONENT.IMAGE);
cy.eyesCheckWindow(this.test.title + ' - plugin toolbar');
cy.openPluginToolbar(PLUGIN_COMPONENT.IMAGE).pluginSizeBestFit();
cy.eyesCheckWindow(this.test.title + ' - plugin content size');
cy.openPluginToolbar(PLUGIN_COMPONENT.IMAGE).pluginSizeFullWidth();
cy.eyesCheckWindow(this.test.title + ' - plugin full width size');
});
it('render image with link', () => {
cy.loadRicosEditorAndViewer('image-with-link');
cy.getImageLink();
});
it('render image with loader - loading in component data', () => {
cy.loadRicosEditorAndViewer('image-with-loader-percent');
cy.get(`[data-hook=loader]`).should('to.be.visible');
});
it('should disable image expand', () => {
cy.loadRicosEditorAndViewer('images');
cy.openPluginToolbar(PLUGIN_COMPONENT.IMAGE);
cy.openSettings();
cy.eyesCheckWindow();
cy.get(`[data-hook=${IMAGE_SETTINGS.IMAGE_EXPAND_TOGGLE}]`).click();
cy.wait(200);
cy.eyesCheckWindow();
cy.get(`[data-hook=${ACTION_BUTTONS.SAVE}]`).click();
cy.wait(200);
cy.get(`[data-hook=${PLUGIN_COMPONENT.IMAGE}]`)
.eq(2)
.parent()
.click();
cy.eyesCheckWindow();
});
});
context('full screen', () => {
before(function() {
eyesOpen(this);
});
beforeEach('load editor', () => cy.switchToDesktop());
after(() => cy.eyesClose());
context('image full screen', () => {
beforeEach('load editor', () => cy.loadRicosEditorAndViewer('images'));
it('expand image on full screen', function() {
cy.get(`[data-hook=${PLUGIN_COMPONENT.IMAGE}]:last`)
.parent()
.click();
cy.loadOutOfViewImagesInGallery();
cy.waitForGalleryImagesToLoad();
cy.eyesCheckWindow({ tag: this.test.title, target: 'window', fully: false });
});
});
context('image full screen in hebrew', () => {
beforeEach('load editor', () => {
cy.switchToHebrew();
cy.loadRicosEditorAndViewer('images');
});
afterEach(() => {
cy.switchToEnglish();
});
it('expand image on full screen in hebrew', function() {
cy.get(`[data-hook=${PLUGIN_COMPONENT.IMAGE}]:last`)
.parent()
.click();
cy.loadOutOfViewImagesInGallery();
cy.waitForGalleryImagesToLoad();
cy.eyesCheckWindow({ tag: this.test.title, target: 'window', fully: false });
});
});
context('innerRCE images full screen', () => {
beforeEach('load editor', () =>
cy.loadRicosEditorAndViewer('inner-rce-images', usePlugins(plugins.all))
);
it('expand inner-rce images on full screen', function() {
cy.get(`[data-hook=${PLUGIN_COMPONENT.IMAGE}]`)
.eq(2)
.parent()
.click();
cy.loadOutOfViewImagesInGallery();
cy.waitForGalleryImagesToLoad();
cy.get('img[data-idx="0"]', {
timeout: 10000,
}).should('be.visible');
cy.eyesCheckWindow({ tag: this.test.title, target: 'window', fully: false });
cy.get('[data-hook=nav-arrow-next]').click({ force: true });
cy.get('[data-hook=nav-arrow-back]').should('be.visible');
cy.get('img[data-idx="1"]', {
timeout: 10000,
}).should('be.visible');
});
});
context('gallery full screen', () => {
beforeEach('load editor', () =>
cy.loadRicosEditorAndViewer('gallery').waitForGalleryImagesToLoad()
);
it('expand gallery image on full screen', () => {
cy.get('[data-hook=ricos-viewer] [data-hook=item-wrapper]', {
timeout: 10000,
})
.eq(1)
.click({ force: true });
cy.get('[data-hook=fullscreen-root] [data-hook=image-item]', {
timeout: 10000,
}).should('be.visible');
// cy.eyesCheckWindow({
// tag: 'gallery fullscreen open on second image',
// target: 'window',
// fully: false,
// });
cy.get(`[data-hook=${'nav-arrow-back'}]`).click({ force: true });
cy.get('[data-hook=fullscreen-root] [data-hook=image-item]', {
timeout: 10000,
}).should('be.visible');
// cy.eyesCheckWindow({
// tag: 'gallery fullscreen previous image',
// target: 'window',
// fully: false,
// });
cy.get(`[data-hook=${'fullscreen-close-button'}]`).click();
});
});
});
context('gallery', () => {
before(function() {
eyesOpen(this);
});
beforeEach('load editor', () => {
cy.switchToDesktop();
});
after(() => cy.eyesClose());
it('render gallery plugin', function() {
cy.loadRicosEditorAndViewer('gallery').waitForGalleryImagesToLoad();
cy.openPluginToolbar(PLUGIN_COMPONENT.GALLERY).shrinkPlugin(PLUGIN_COMPONENT.GALLERY);
cy.waitForDocumentMutations();
cy.eyesCheckWindow(this.test.title + ' toolbar');
cy.openGalleryAdvancedSettings();
cy.loadOutOfViewImagesInGallery();
cy.waitForGalleryImagesToLoad();
cy.eyesCheckWindow(this.test.title + ' settings');
});
it('render gallery out of view', function() {
cy.loadRicosEditorAndViewer('gallery-out-of-view');
cy.get(`[data-hook=${PLUGIN_COMPONENT.GALLERY}]`).eq(3);
cy.scrollTo('bottom');
cy.waitForDocumentMutations();
cy.eyesCheckWindow(`${this.test.title} - in view`);
});
context('organize media', () => {
it('allow to manipulate the media items', function() {
const firstImage = `[data-hook=${GALLERY_SETTINGS.IMAGE}]:first`;
// const anyImage = `[data-hook=${GALLERY_SETTINGS.IMAGE}]`;
cy.loadRicosEditorAndViewer('gallery')
.openPluginToolbar(PLUGIN_COMPONENT.GALLERY)
.shrinkPlugin(PLUGIN_COMPONENT.GALLERY)
.waitForGalleryImagesToLoad()
.openGalleryAdvancedSettings()
.openGallerySettings()
.waitForGalleryImagesToLoad();
cy.eyesCheckWindow(this.test.parent.title + ' - render settings');
cy.get(firstImage).click();
cy.get(`[data-hook=${GALLERY_SETTINGS.DELETE}]`);
cy.waitForGalleryImagesToLoad();
cy.eyesCheckWindow(this.test.parent.title + ' - select an item');
cy.get(`[data-hook=${GALLERY_SETTINGS.SELECT_ALL}]`).click();
cy.waitForGalleryImagesToLoad();
cy.eyesCheckWindow(this.test.parent.title + ' - select all items');
cy.get(`[data-hook=${GALLERY_SETTINGS.DESELECT}]`).click();
cy.waitForGalleryImagesToLoad();
cy.eyesCheckWindow(this.test.parent.title + ' - deselect items');
// TODO: stabalize reordering tests
// cy.dragAndDrop(firstImage, anyImage, 1);
// cy.get(firstImage);
// cy.waitForGalleryImagesToLoad();
// cy.eyesCheckWindow(this.test.parent.title + ' - reorder images');
cy.get(firstImage).click();
cy.get(`[data-hook=${GALLERY_SETTINGS.DELETE}]`).click();
cy.get(firstImage);
cy.waitForGalleryImagesToLoad();
cy.eyesCheckWindow(this.test.parent.title + ' - delete an item');
cy.get(`[data-hook=${GALLERY_SETTINGS.SELECT_ALL}]`).click();
cy.get(`[data-hook=${GALLERY_SETTINGS.DELETE}]`).click();
cy.waitForGalleryImagesToLoad();
cy.eyesCheckWindow(this.test.parent.title + ' - delete all items');
});
});
context('media settings', () => {
it('allow to update media content', function() {
cy.loadRicosEditorAndViewer('gallery')
.openPluginToolbar(PLUGIN_COMPONENT.GALLERY)
.shrinkPlugin(PLUGIN_COMPONENT.GALLERY)
.waitForGalleryImagesToLoad()
.openGalleryAdvancedSettings()
.openGallerySettings()
.openGalleryImageSettings()
.get(`[data-hook=${GALLERY_IMAGE_SETTINGS.PREVIEW}]:first`);
cy.eyesCheckWindow(this.test.parent.title + ' - render item settings');
cy.get(`[data-hook=${GALLERY_IMAGE_SETTINGS.TITLE}]`).type('Amazing Title');
cy.get(`[data-hook=${GALLERY_IMAGE_SETTINGS.LINK}]`).type('Stunning.com');
cy.get(`[data-hook=${GALLERY_IMAGE_SETTINGS.LINK_NOFOLLOW}]`).click();
cy.waitForGalleryImagesToLoad();
cy.eyesCheckWindow(this.test.parent.title + ' - enter image settings');
cy.get(`[data-hook=${GALLERY_IMAGE_SETTINGS.DONE}]:first`).click();
cy.openGalleryImageSettings();
cy.waitForGalleryImagesToLoad();
cy.eyesCheckWindow(this.test.parent.title + ' - settings saved & title shows on image ');
cy.get(`[data-hook=${GALLERY_IMAGE_SETTINGS.DELETE}]`).click({ force: true });
cy.get(`[data-hook=${GALLERY_IMAGE_SETTINGS.PREVIEW}]:first`);
cy.waitForGalleryImagesToLoad();
cy.eyesCheckWindow(this.test.parent.title + ' - delete a media item');
cy.get(`[data-hook=${GALLERY_IMAGE_SETTINGS.DELETE}]`).click({ force: true });
cy.get(`[data-hook=${GALLERY_SETTINGS.UPLOAD}]`);
cy.waitForGalleryImagesToLoad();
cy.eyesCheckWindow(this.test.parent.title + ' - delete all items');
});
// TODO: title and link image tests
// // eslint-disable-next-line mocha/no-skipped-tests
// it.skip('allow to add a title', function() {
// cy.addGalleryImageTitle().checkTitle();
// cy.eyesCheckWindow(this.test.parent.title + ' - ' + this.test.title);
// });
});
context('settings', () => {
it('should render all tabs', function() {
cy.loadRicosEditorAndViewer('gallery')
.openPluginToolbar(PLUGIN_COMPONENT.GALLERY)
.openGalleryAdvancedSettings();
cy.eyesCheckWindow(this.test.parent.title + ' - render settings tab');
cy.get(`[data-hook=advanced_settings_Tab]:first`).click();
cy.eyesCheckWindow(this.test.parent.title + ' - render layout tab');
cy.get(`[data-hook=manage_media_Tab]:first`).click();
cy.eyesCheckWindow(this.test.parent.title + ' - render manage media tab');
});
it('should disable gallery expand', () => {
cy.loadRicosEditorAndViewer('gallery');
cy.openPluginToolbar(PLUGIN_COMPONENT.GALLERY);
cy.openSettings('ADV_SETTINGS');
cy.eyesCheckWindow();
cy.get(`[data-hook=${GALLERY_SETTINGS.GALLERY_EXPAND_TOGGLE}]`).click();
cy.wait(200);
cy.eyesCheckWindow();
cy.get(`[data-hook=${ACTION_BUTTONS.SAVE}]`).click();
cy.wait(200);
cy.get(`[data-hook=${PLUGIN_COMPONENT.GALLERY}]`)
.eq(1)
.parent()
.click();
cy.eyesCheckWindow();
});
});
});
context('video', () => {
before(function() {
eyesOpen(this);
});
beforeEach('load editor', () => {
cy.switchToDesktop();
cy.loadRicosEditorAndViewer('empty');
});
after(() => cy.eyesClose());
it('render upload modal', function() {
cy.openVideoUploadModal();
cy.eyesCheckWindow(this.test.title);
});
it('add a video from URL', function() {
cy.openVideoUploadModal().addVideoFromURL();
cy.openPluginToolbar(PLUGIN_COMPONENT.VIDEO).shrinkPlugin(PLUGIN_COMPONENT.VIDEO);
cy.focusEditor()
.type('{uparrow}') //try to fix bug where sometimes it doesn't type
.type('{uparrow}')
.type('Will this fix the flakiness?');
cy.waitForVideoToLoad();
cy.eyesCheckWindow(this.test.title);
});
it('add a custom video', function() {
cy.openVideoUploadModal().addCustomVideo();
cy.openPluginToolbar(PLUGIN_COMPONENT.VIDEO).shrinkPlugin(PLUGIN_COMPONENT.VIDEO);
cy.focusEditor()
.type('{uparrow}') //try to fix bug where sometimes it doesn't type
.type('{uparrow}')
.type('Will this fix the flakiness?');
cy.waitForVideoToLoad();
cy.eyesCheckWindow(this.test.title);
});
it('should toggle download option', () => {
cy.loadRicosEditorAndViewer('video');
cy.openPluginToolbar(PLUGIN_COMPONENT.VIDEO);
cy.openSettings();
cy.wait(5000);
cy.eyesCheckWindow();
cy.get(`[data-hook=${VIDEO_SETTINGS.DOWNLOAD_TOGGLE}]`).click();
cy.eyesCheckWindow();
cy.get(`[data-hook=${ACTION_BUTTONS.SAVE}]`).click();
});
});
context('youTube', () => {
before(function() {
eyesOpen(this);
});
const testAppConfig = {
...usePlugins(plugins.video),
...usePluginsConfig({
video: {
exposeButtons: ['video', 'soundCloud', 'youTube'],
},
}),
};
beforeEach('load editor', () => {
cy.switchToDesktop();
cy.loadRicosEditorAndViewer('empty', testAppConfig);
});
after(() => cy.eyesClose());
it(`open youTube modal`, function() {
cy.openEmbedModal(STATIC_TOOLBAR_BUTTONS.YOUTUBE);
cy.eyesCheckWindow(this.test.title);
});
});
context('giphy', () => {
before('load editor', function() {
eyesOpen(this);
});
beforeEach('load editor', () => {
cy.switchToDesktop();
});
after(() => cy.eyesClose());
it('render giphy plugin toolbar', function() {
cy.loadRicosEditorAndViewer('giphy');
cy.openPluginToolbar(PLUGIN_COMPONENT.GIPHY).clickToolbarButton(
PLUGIN_TOOLBAR_BUTTONS.SMALL_CENTER
);
cy.get(`button[data-hook=${PLUGIN_TOOLBAR_BUTTONS.REPLACE}][tabindex=0]`).click();
cy.get(`[data-hook=${GIPHY_PLUGIN.UPLOAD_MODAL}] img`);
cy.eyesCheckWindow(this.test.title);
});
});
context('emoji', () => {
before('load editor', function() {
eyesOpen(this);
});
beforeEach('load editor', () => {
cy.switchToDesktop();
});
after(() => cy.eyesClose());
// it('render some emojies', function() {
// cy.loadRicosEditorAndViewer('empty');
// cy.get(`button[data-hook=${PLUGIN_COMPONENT.EMOJI}]`).click();
// cy.eyesCheckWindow('render emoji modal');
// cy.get(`[data-hook=emoji-5]`).click();
// cy.get(`[data-hook=emoji-group-5]`).click();
// cy.get(`[data-hook=emoji-95]`).click();
// cy.get(`[data-hook=emoji-121]`).click();
// cy.eyesCheckWindow(this.test.title);
// });
});
}); | the_stack |
import 'mocha';
import { expect } from '@integration/testing-tools';
import { Ensure, equals } from '@serenity-js/assertions';
import { actorCalled, engage, LogicError } from '@serenity-js/core';
import { by } from 'protractor';
import { error } from 'selenium-webdriver';
import { Click, Close, Navigate, Switch, Target, Text } from '../../../src';
import { pageFromTemplate } from '../../fixtures';
import { UIActors } from '../../UIActors';
/** @test {Switch} */
describe('Switch', () => {
const
h1 = Target.the('header').located(by.css('h1')),
iframe = Target.the('test iframe').located(by.tagName('iframe')),
newTabLink = Target.the('link').located(by.linkText('open new tab'));
const page =
(header: string) =>
pageFromTemplate(`
<html>
<body>
<h1>${ header }</h1>
</body>
</html>
`);
const pageWithIframe =
(header: string, iframeSource: string) =>
pageFromTemplate(`
<html>
<body>
<h1>${ header }</h1>
<iframe name="example-iframe" src="${ iframeSource.replace(/"/g, '"') }" />
</body>
</html>
`);
const pageWithLinkToNewTab =
(header: string) =>
pageFromTemplate(`
<html>
<body>
<h1>${ header }</h1>
<a href="javascript:void(0)" onclick="popup()">open new tab</a>
<script>
function popup() {
var w = window.open('', 'new-tab');
w.document.write('<h1>New tab</h1>');
w.document.close();
}
</script>
</body>
</html>
`);
beforeEach(() => engage(new UIActors()));
describe('when working with frames', () => {
describe('toFrame()', () => {
/** @test {Switch.toFrame} */
it(`should complain if there's no frame to switch to`, () =>
expect(actorCalled('Franceska').attemptsTo(
Navigate.to(page('main page')),
Switch.toFrame(0),
)).to.be.rejectedWith(error.NoSuchFrameError));
/** @test {Switch.toFrame} */
it('should switch to an iframe identified by Question<ElementFinder>', () =>
actorCalled('Franceska').attemptsTo(
Navigate.to(pageWithIframe('main page', page('an iframe'))),
Ensure.that(Text.of(h1), equals('main page')),
Switch.toFrame(iframe),
Ensure.that(Text.of(h1), equals('an iframe')),
));
/** @test {Switch.toFrame} */
it('should switch to an iframe identified by index', () =>
actorCalled('Franceska').attemptsTo(
Navigate.to(pageWithIframe('main page', page('an iframe'))),
Ensure.that(Text.of(h1), equals('main page')),
Switch.toFrame(0),
Ensure.that(Text.of(h1), equals('an iframe')),
));
/** @test {Switch.toFrame} */
it('should switch to an iframe identified by name', () =>
actorCalled('Franceska').attemptsTo(
Navigate.to(pageWithIframe('main page', page('an iframe'))),
Ensure.that(Text.of(h1), equals('main page')),
Switch.toFrame('example-iframe'),
Ensure.that(Text.of(h1), equals('an iframe')),
));
describe('should provide a sensible description when the iframe', () => {
/** @test {Switch.toFrame} */
/** @test {Switch#toString} */
it('is specified by Question<ElementFinder>', () => {
expect(Switch.toFrame(iframe).toString()).to.equal('#actor switches to frame: the test iframe')
});
/** @test {Switch.toFrame} */
/** @test {Switch#toString} */
it('is specified by index number', () => {
expect(Switch.toFrame(1).toString()).to.equal('#actor switches to frame: 1')
});
/** @test {Switch.toFrame} */
/** @test {Switch#toString} */
it('is specified by name', () => {
expect(Switch.toFrame('example-iframe').toString()).to.equal('#actor switches to frame: example-iframe')
});
});
});
describe('toParentFrame()', () => {
/** @test {Switch.toParentFrame} */
it('should not switch the frame if there are no parent frames', () =>
actorCalled('Franceska').attemptsTo(
Navigate.to(page('main page')),
Ensure.that(Text.of(h1), equals('main page')),
Switch.toParentFrame(),
Ensure.that(Text.of(h1), equals('main page')),
));
/** @test {Switch.toParentFrame} */
it('should switch to the parent hosting an iframe', () =>
actorCalled('Franceska').attemptsTo(
Navigate.to(pageWithIframe('main page', page('an iframe'))),
Ensure.that(Text.of(h1), equals('main page')),
Switch.toFrame(iframe),
Ensure.that(Text.of(h1), equals('an iframe')),
Switch.toParentFrame(),
Ensure.that(Text.of(h1), equals('main page')),
));
/** @test {Switch.toFrame} */
/** @test {Switch.toParentFrame} */
it('should support nested frames', () =>
actorCalled('Franceska').attemptsTo(
Navigate.to(pageWithIframe('Level 0', pageWithIframe('Level 1', page('Level 2')))),
Ensure.that(Text.of(h1), equals('Level 0')),
Switch.toFrame(iframe),
Ensure.that(Text.of(h1), equals('Level 1')),
Switch.toFrame(iframe),
Ensure.that(Text.of(h1), equals('Level 2')),
Switch.toParentFrame(),
Ensure.that(Text.of(h1), equals('Level 1')),
));
/** @test {Switch.toParentFrame} */
/** @test {Switch#toString} */
it('should provide a sensible description of the interaction being performed', () => {
expect(Switch.toParentFrame().toString()).to.equal('#actor switches to parent frame')
});
});
describe('toDefaultContent()', () => {
/** @test {Switch.toDefaultContent} */
it('should not switch the frame if there are no parent frames', () =>
actorCalled('Franceska').attemptsTo(
Navigate.to(page('main page')),
Ensure.that(Text.of(h1), equals('main page')),
Switch.toDefaultContent(),
Ensure.that(Text.of(h1), equals('main page')),
));
/** @test {Switch.toFrame} */
/** @test {Switch.toDefaultContent} */
it('should support nested frames', () =>
actorCalled('Franceska').attemptsTo(
Navigate.to(pageWithIframe('Level 0', pageWithIframe('Level 1', page('Level 2')))),
Ensure.that(Text.of(h1), equals('Level 0')),
Switch.toFrame(iframe),
Ensure.that(Text.of(h1), equals('Level 1')),
Switch.toFrame(iframe),
Ensure.that(Text.of(h1), equals('Level 2')),
Switch.toDefaultContent(),
Ensure.that(Text.of(h1), equals('Level 0')),
));
/** @test {Switch.toDefaultContent} */
/** @test {Switch#toString} */
it('should provide a sensible description of the interaction being performed', () => {
expect(Switch.toDefaultContent().toString()).to.equal('#actor switches to default content')
});
});
describe('toFrame().and()', () => {
/** @test {Switch.toFrame} */
it('should perform any activities in the context of the frame it switched to', () =>
actorCalled('Franceska').attemptsTo(
Navigate.to(pageWithIframe('Level 0', pageWithIframe('Level 1', page('Level 2')))),
Ensure.that(Text.of(h1), equals('Level 0')),
Switch.toFrame(iframe).and(
Switch.toFrame(iframe).and(
Ensure.that(Text.of(h1), equals('Level 2')),
),
Ensure.that(Text.of(h1), equals('Level 1')),
),
Ensure.that(Text.of(h1), equals('Level 0')),
));
/** @test {Switch.toFrame} */
/** @test {Switch#toString} */
it('should provide a sensible description of the interaction being performed', () => {
expect(Switch.toFrame(0).and().toString()).to.equal('#actor switches to frame: 0')
});
});
});
describe('when working with windows', () => {
afterEach(() =>
actorCalled('Ventana').attemptsTo(
Close.anyNewWindows(),
));
describe('toWindow()', () => {
/** @test {Switch.toWindow} */
it('should switch to a window identified by its index', () =>
actorCalled('Ventana').attemptsTo(
Navigate.to(pageWithLinkToNewTab('Main window')),
Ensure.that(Text.of(h1), equals('Main window')),
Click.on(newTabLink),
Switch.toWindow(1),
Ensure.that(Text.of(h1), equals('New tab')),
));
/** @test {Switch.toWindow} */
it('should switch to a window identified by its name', () =>
actorCalled('Ventana').attemptsTo(
Navigate.to(pageWithLinkToNewTab('Main window')),
Ensure.that(Text.of(h1), equals('Main window')),
Click.on(newTabLink),
Switch.toWindow('new-tab'),
Ensure.that(Text.of(h1), equals('New tab')),
));
/** @test {Switch.toWindow} */
it(`should complain if the desired window doesn't exit`, () =>
expect(actorCalled('Ventana').attemptsTo(
Navigate.to(page('Main window')),
Switch.toWindow(10),
)).to.be.rejectedWith(LogicError, `Window 10 doesn't exist`));
describe('should provide a sensible description when the window', () => {
/** @test {Switch.toWindow} */
/** @test {Switch#toString} */
it('is specified by its index', () => {
expect(Switch.toWindow(1).toString()).to.equal('#actor switches to window: 1')
});
/** @test {Switch.toWindow} */
/** @test {Switch#toString} */
it('is specified by name', () => {
expect(Switch.toWindow('example-window').toString()).to.equal('#actor switches to window: example-window')
});
});
});
describe('toWindow().and()', () => {
/** @test {Switch.toWindow} */
it('should perform any activities in the context of the window it switched to', () =>
actorCalled('Ventana').attemptsTo(
Navigate.to(pageWithLinkToNewTab('Main window')),
Ensure.that(Text.of(h1), equals('Main window')),
Click.on(newTabLink),
Switch.toWindow('new-tab').and(
Ensure.that(Text.of(h1), equals('New tab')),
),
Ensure.that(Text.of(h1), equals('Main window')),
));
/** @test {Switch.toWindow} */
/** @test {Switch#toString} */
it('should provide a sensible description of the interaction being performed', () => {
expect(Switch.toWindow('new-tab').and().toString()).to.equal('#actor switches to window: new-tab')
});
});
describe(`toNewWindow()`, () => {
/** @test {Switch.toNewWindow} */
it(`should complain if no new window has been opened`, () =>
expect(actorCalled('Ventana').attemptsTo(
Navigate.to(page('Main window')),
Switch.toNewWindow(),
)).to.be.rejectedWith(LogicError, `No new window has been opened to switch to`));
/** @test {Switch.toNewWindow} */
it('should switch to a newly opened window', () =>
actorCalled('Ventana').attemptsTo(
Navigate.to(pageWithLinkToNewTab('Main window')),
Ensure.that(Text.of(h1), equals('Main window')),
Click.on(newTabLink),
Switch.toNewWindow(),
Ensure.that(Text.of(h1), equals('New tab')),
));
/** @test {Switch.toNewWindow} */
/** @test {Switch#toString} */
it('should provide a sensible description of the interaction being performed', () => {
expect(Switch.toNewWindow().toString()).to.equal('#actor switches to the new browser window')
});
});
describe('toNewWindow().and()', () => {
/** @test {Switch.toNewWindow} */
it('should perform any activities in the context of the new window it switched to', () =>
actorCalled('Ventana').attemptsTo(
Navigate.to(pageWithLinkToNewTab('Main window')),
Ensure.that(Text.of(h1), equals('Main window')),
Click.on(newTabLink),
Switch.toNewWindow().and(
Ensure.that(Text.of(h1), equals('New tab')),
),
Ensure.that(Text.of(h1), equals('Main window')),
));
/** @test {Switch.toNewWindow} */
/** @test {Switch#toString} */
it('should provide a sensible description of the interaction being performed', () => {
expect(Switch.toNewWindow().and().toString()).to.equal('#actor switches to the new window')
});
});
describe(`toOriginalWindow()`, function () {
/** @test {Switch.toOriginalWindow} */
it(`should not complain if it's already in the original window`, () =>
actorCalled('Ventana').attemptsTo(
Navigate.to(page('Main window')),
Switch.toOriginalWindow(),
Ensure.that(Text.of(h1), equals('Main window')),
));
/** @test {Switch.toOriginalWindow} */
it('should switch back from a newly opened window', () =>
actorCalled('Ventana').attemptsTo(
Navigate.to(pageWithLinkToNewTab('Main window')),
Ensure.that(Text.of(h1), equals('Main window')),
Click.on(newTabLink),
Switch.toNewWindow(),
Ensure.that(Text.of(h1), equals('New tab')),
Switch.toOriginalWindow(),
Ensure.that(Text.of(h1), equals('Main window')),
));
/** @test {Switch.toOriginalWindow} */
/** @test {Switch#toString} */
it('should provide a sensible description of the interaction being performed', () => {
expect(Switch.toOriginalWindow().toString()).to.equal('#actor switches back to the original browser window')
});
});
});
}); | the_stack |
import type { BuildPlatformContext, BuildPlatformEvents } from '@jovotech/cli-command-build';
import {
ANSWER_BACKUP,
ANSWER_CANCEL,
deleteFolderRecursive,
DISK,
flags,
getResolvedLocales,
InstallContext,
JovoCliError,
mergeArrayCustomizer,
OK_HAND,
PluginHook,
printHighlight,
printStage,
printSubHeadline,
promptOverwriteReverseBuild,
REVERSE_ARROWS,
STATION,
Task,
wait,
} from '@jovotech/cli-core';
import { FileBuilder, FileObject } from '@jovotech/filebuilder';
import { JovoModelData, JovoModelDataV3, NativeFileInformation } from '@jovotech/model';
import { JovoModelGoogle } from '@jovotech/model-google';
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'fs';
import { copySync, removeSync } from 'fs-extra';
import _get from 'lodash.get';
import _has from 'lodash.has';
import _merge from 'lodash.merge';
import _mergeWith from 'lodash.mergewith';
import _set from 'lodash.set';
import { join as joinPaths } from 'path';
import * as yaml from 'yaml';
import { GoogleAssistantCli } from '..';
import DefaultFiles from '../DefaultFiles.json';
import {
GoogleActionActions,
GoogleContext,
SupportedLocales,
SupportedLocalesType,
} from '../utilities';
export interface BuildPlatformContextGoogle extends BuildPlatformContext, GoogleContext {
flags: BuildPlatformContext['flags'] & { 'project-id'?: string };
googleAssistant: GoogleContext['googleAssistant'] & {
defaultLocale?: string;
};
}
export class BuildHook extends PluginHook<BuildPlatformEvents> {
$plugin!: GoogleAssistantCli;
$context!: BuildPlatformContextGoogle;
install(): void {
this.middlewareCollection = {
'install': [this.addCliOptions.bind(this)],
'before.build:platform': [
this.checkForPlatform.bind(this),
this.updatePluginContext.bind(this),
this.checkForCleanBuild.bind(this),
this.validateLocales.bind(this),
],
'build:platform': [this.validateModels.bind(this), this.build.bind(this)],
'build:platform.reverse': [this.buildReverse.bind(this)],
};
}
/**
* Add platform-specific CLI options, including flags and args.
* @param context - Context providing an access point to command flags and args.
*/
addCliOptions(context: InstallContext): void {
if (context.command !== 'build:platform') {
return;
}
context.flags['project-id'] = flags.string({
description: 'Google Cloud Project ID',
});
}
/**
* Checks if the currently selected platform matches this CLI plugin.
* @param context - Context containing information after flags and args have been parsed by the CLI.
*/
checkForPlatform(): void {
// Check if this plugin should be used or not.
if (!this.$context.platforms.includes(this.$plugin.id)) {
this.uninstall();
}
}
/**
* Updates the current plugin context with platform-specific values.
*/
updatePluginContext(): void {
if (!this.$context.googleAssistant) {
this.$context.googleAssistant = {};
}
this.$context.googleAssistant.projectId =
this.$context.flags['project-id'] || _get(this.$plugin.config, 'projectId');
if (!this.$context.googleAssistant.projectId) {
throw new JovoCliError({
message: 'Could not find project ID.',
module: this.$plugin.name,
hint: 'Please provide a project ID by using the flag "--project-id" or in your project configuration.',
});
}
// Set default locale.
this.setDefaultLocale();
}
/**
* Checks, if --clean has been set and deletes the platform folder accordingly.
*/
checkForCleanBuild(): void {
// If --clean has been set, delete the respective platform folders before building.
if (this.$context.flags.clean) {
deleteFolderRecursive(this.$plugin.platformPath);
}
}
/**
* Checks if any provided locale is not supported, thus invalid.
*/
validateLocales(): void {
const locales: SupportedLocalesType[] = this.$context.locales.reduce(
(locales: string[], locale: string) => {
locales.push(...getResolvedLocales(locale, SupportedLocales, this.$plugin.config.locales));
return locales;
},
[],
) as SupportedLocalesType[];
for (const locale of locales) {
const genericLocale: string = locale.substring(0, 2);
// For Google Conversational Actions, some locales require a generic locale to be set, e.g. en for en-US.
if (
SupportedLocales.includes(genericLocale as SupportedLocalesType) &&
!locales.includes(genericLocale as SupportedLocalesType)
) {
throw new JovoCliError({
message: `Locale ${printHighlight(locale)} requires a generic locale ${printHighlight(
genericLocale,
)}.`,
module: this.$plugin.name,
});
}
if (!SupportedLocales.includes(locale)) {
throw new JovoCliError({
message: `Locale ${printHighlight(
locale,
)} is not supported by Google Conversational Actions.`,
module: this.$plugin.name,
learnMore:
'For more information on multiple language support: https://developers.google.com/assistant/console/languages-locales',
});
}
}
}
/**
* Validates Jovo models with platform-specific validators.
*/
async validateModels(): Promise<void> {
// Validate Jovo model.
const validationTask: Task = new Task(`${OK_HAND} Validating Google Assistant model files`);
for (const locale of this.$context.locales) {
const localeTask = new Task(locale, async () => {
const model: JovoModelData | JovoModelDataV3 = await this.$cli.project!.getModel(locale);
await this.$cli.project!.validateModel(
locale,
model,
JovoModelGoogle.getValidator(model),
this.$plugin.name,
);
await wait(500);
});
validationTask.add(localeTask);
}
await validationTask.run();
}
/**
* Builds Jovo model files from platform-specific files.
*/
async buildReverse(): Promise<void> {
// Since platform can be prompted for, check if this plugin should actually be executed again.
if (!this.$context.platforms.includes(this.$plugin.id)) {
return;
}
this.updatePluginContext();
const reverseBuildTask: Task = new Task(`${REVERSE_ARROWS} Reversing model files`);
if (this.$cli.project!.config.getParameter('models.enabled') !== false) {
// Get locales to reverse build from.
// If --locale is not specified, reverse build from every locale available in the platform folder.
const selectedLocales: string[] = [];
const platformLocales: string[] = this.getPlatformLocales();
if (!this.$context.flags.locale) {
selectedLocales.push(...platformLocales);
} else {
// Otherwise only reverse build from the specified locale if it exists inside the platform folder.
for (const locale of this.$context.flags.locale) {
if (platformLocales.includes(locale)) {
selectedLocales.push(locale);
} else {
throw new JovoCliError({
message: `Could not find platform models for locale: ${printHighlight(locale)}`,
module: this.$plugin.name,
hint: `Available locales include: ${platformLocales.join(', ')}`,
});
}
}
}
// Try to resolve the locale according to the locale map provided in this.$plugin.config.locales.
// If en resolves to en-US, this loop will generate { 'en-US': 'en' }
const buildLocaleMap: { [locale: string]: string } = selectedLocales.reduce(
(localeMap: { [locale: string]: string }, locale: string) => {
localeMap[locale] = locale;
return localeMap;
},
{},
);
for (const modelLocale in this.$plugin.config.locales) {
const resolvedLocales: string[] = getResolvedLocales(
modelLocale,
SupportedLocales,
this.$plugin.config.locales,
);
for (const selectedLocale of selectedLocales) {
if (resolvedLocales.includes(selectedLocale)) {
buildLocaleMap[selectedLocale] = modelLocale;
}
}
}
// If Jovo model files for the current locales exist, ask whether to back them up or not.
if (
this.$cli.project!.hasModelFiles(Object.values(buildLocaleMap)) &&
!this.$context.flags.clean
) {
const answer = await promptOverwriteReverseBuild();
if (answer.overwrite === ANSWER_CANCEL) {
return;
}
if (answer.overwrite === ANSWER_BACKUP) {
// Backup old files.
const backupTask: Task = new Task(`${DISK} Creating backups`);
for (const locale of Object.values(buildLocaleMap)) {
const localeTask: Task = new Task(locale, () => this.$cli.project!.backupModel(locale));
backupTask.add(localeTask);
}
await backupTask.run();
}
}
for (const [platformLocale, modelLocale] of Object.entries(buildLocaleMap)) {
const taskDetails: string = platformLocale === modelLocale ? '' : `(${modelLocale})`;
const localeTask: Task = new Task(`${platformLocale} ${taskDetails}`, async () => {
// Extract platform models, containing platform-specific intents and entities.
const platformFiles: NativeFileInformation[] = this.getPlatformModels(platformLocale);
const jovoModel: JovoModelGoogle = new JovoModelGoogle();
jovoModel.importNative(platformFiles, modelLocale);
const nativeData: JovoModelData | undefined = jovoModel.exportJovoModel();
if (!nativeData) {
throw new JovoCliError({
message: 'Something went wrong while exporting your Jovo model.',
module: this.$plugin.name,
});
}
nativeData.invocation = this.getPlatformInvocationName(platformLocale);
this.$cli.project!.saveModel(nativeData, modelLocale);
await wait(500);
});
reverseBuildTask.add(localeTask);
}
}
await reverseBuildTask.run();
}
/**
* Builds platform-specific models from Jovo language model.
*/
async build(): Promise<void> {
const buildPath = `Path: ./${joinPaths(
this.$cli.project!.getBuildDirectory(),
this.$plugin.platformDirectory,
)}`;
const buildTaskTitle = `${STATION} Building Google Conversational Action files${printStage(
this.$cli.project!.stage,
)}\n${printSubHeadline(buildPath)}`;
// Define main build task
const buildTask: Task = new Task(buildTaskTitle);
// Update or create Google Conversational Action project files, depending on whether it has already been built or not
const projectFilesTask: Task = new Task(`Project files`, this.buildProjectFiles.bind(this));
const buildInteractionModelTask: Task = new Task(
`Interaction model`,
this.buildInteractionModel.bind(this),
{
enabled:
this.$cli.project!.config.getParameter('models.enabled') !== false &&
this.$cli.project!.hasModelFiles(this.$context.locales),
},
);
buildTask.add(projectFilesTask, buildInteractionModelTask);
await buildTask.run();
}
/**
* Creates Google Conversational Action specific project files.
*/
async buildProjectFiles(): Promise<void> {
const files: FileObject = FileBuilder.normalizeFileObject(
_get(this.$plugin.config, 'files', {}),
);
// If platforms folder doesn't exist, take default files and parse them with project.js config into FileBuilder.
const projectFiles: FileObject = this.$cli.project!.hasPlatform(this.$plugin.platformDirectory)
? files
: _merge(DefaultFiles, files);
// Get default locale.
// Merge global project.js properties with platform files.
// Set endpoint.
const endpoint: string = this.getPluginEndpoint();
const webhookPath = 'webhooks/["ActionsOnGoogleFulfillment.yaml"]';
if (endpoint && !_has(projectFiles, webhookPath)) {
const defaultHandler = {
handlers: [
{
name: 'Jovo',
},
],
httpsEndpoint: {
baseUrl: this.getPluginEndpoint(),
},
};
_set(projectFiles, webhookPath, defaultHandler);
}
// Set default settings, such as displayName.
for (const locale of this.$context.locales) {
const resolvedLocales: SupportedLocalesType[] = getResolvedLocales(
locale,
SupportedLocales,
this.$plugin.config.locales,
) as SupportedLocalesType[];
for (const resolvedLocale of resolvedLocales) {
const settingsPathArr: string[] = ['settings/'];
if (resolvedLocale !== this.$context.googleAssistant.defaultLocale!) {
settingsPathArr.push(`${resolvedLocale}/`);
}
settingsPathArr.push('["settings.yaml"]');
const settingsPath: string = settingsPathArr.join('.');
// Set default settings.
if (resolvedLocale === this.$context.googleAssistant.defaultLocale) {
if (!_has(projectFiles, `${settingsPath}.defaultLocale`)) {
_set(
projectFiles,
`${settingsPath}.defaultLocale`,
this.$context.googleAssistant.defaultLocale!,
);
}
if (!_has(projectFiles, `${settingsPath}.projectId`)) {
_set(
projectFiles,
`${settingsPath}.projectId`,
this.$context.googleAssistant.projectId,
);
}
}
// Set minimal required localized settings, such as displayName and pronunciation.
const localizedSettingsPath = `${settingsPath}.localizedSettings`;
const invocationName: string = await this.getInvocationName(locale);
if (!_has(projectFiles, `${localizedSettingsPath}.displayName`)) {
_set(projectFiles, `${localizedSettingsPath}.displayName`, invocationName);
}
if (!_has(projectFiles, `${localizedSettingsPath}.pronunciation`)) {
_set(projectFiles, `${localizedSettingsPath}.pronunciation`, invocationName);
}
}
}
FileBuilder.buildDirectory(projectFiles, this.$plugin.platformPath);
if (existsSync(this.$plugin.config.resourcesDirectory)) {
// Copies across any resources so they can be used in the project settings manifest.
// Docs: https://developers.google.com/assistant/conversational/build/projects?hl=en&tool=sdk#add_resources
const copyResourcesTask: Task = new Task(
`Copying resources from ${this.$plugin.config.resourcesDirectory!}`,
() => {
const src: string = joinPaths(
this.$cli.projectPath,
this.$plugin.config.resourcesDirectory!,
);
const dest: string = joinPaths(this.$plugin.platformPath, 'resources');
// Delete existing resources folder before copying data
removeSync(dest);
copySync(src, dest);
},
{ indentation: 2 },
);
await copyResourcesTask.run();
}
}
/**
* Creates and returns tasks for each locale to build the interaction model for Alexa.
*/
async buildInteractionModel(): Promise<string[]> {
const output: string[] = [];
for (const locale of this.$context.locales) {
const resolvedLocales: string[] = getResolvedLocales(
locale,
SupportedLocales,
this.$plugin.config.locales,
);
const resolvedLocalesOutput: string = resolvedLocales.join(', ');
// If the model locale is resolved to different locales, provide task details, i.e. "en (en-US, en-CA)"".
const taskDetails: string =
resolvedLocalesOutput === locale ? '' : `(${resolvedLocalesOutput})`;
await this.buildLanguageModel(locale, resolvedLocales);
await wait(500);
output.push(`${locale} ${taskDetails}`);
}
return output;
}
/**
* Builds and saves a Google Conversational Action model from a Jovo model.
* @param modelLocale - Locale of the Jovo model.
* @param resolvedLocales - Locales to which to resolve the modelLocale.
*/
async buildLanguageModel(modelLocale: string, resolvedLocales: string[]): Promise<void> {
const model = _merge(
await this.getJovoModel(modelLocale),
this.$cli.project!.config.getParameter(`models.override.${modelLocale}`),
);
for (const locale of resolvedLocales) {
const jovoModel = new JovoModelGoogle(
model as JovoModelData,
locale,
this.$context.googleAssistant.defaultLocale,
);
const modelFiles: NativeFileInformation[] = jovoModel.exportNative()!;
const actions: GoogleActionActions = {
custom: {
'actions.intent.MAIN': {},
},
};
for (const file of modelFiles) {
const fileName = file.path.pop()!;
const modelPath = joinPaths(this.$plugin.platformPath, ...file.path);
// Check if the path for the current model type (e.g. intent, types, ...) exists.
if (!existsSync(modelPath)) {
mkdirSync(modelPath, { recursive: true });
}
// Register actions.
if (file.path.includes('global')) {
actions.custom[fileName.replace('.yaml', '')] = {};
}
writeFileSync(joinPaths(modelPath, fileName), file.content);
}
// Merge existing actions file with configuration in project.js.
_merge(actions, this.getProjectActions());
const actionsPath: string = joinPaths(this.$plugin.platformPath, 'actions');
if (!existsSync(actionsPath)) {
mkdirSync(actionsPath, { recursive: true });
}
writeFileSync(joinPaths(actionsPath, 'actions.yaml'), yaml.stringify(actions));
}
}
/**
* Gets configured actions from config.
*/
getProjectActions(): void {
const actions = _get(this.$plugin.config, 'files.["actions/"]');
return actions;
}
/**
* Sets the default locale for the current Conversational Action.
*/
setDefaultLocale(): void {
const resolvedLocales: SupportedLocalesType[] = this.$context.locales.reduce(
(locales: string[], locale: string) => {
locales.push(...getResolvedLocales(locale, SupportedLocales, this.$plugin.config.locales));
return locales;
},
[],
) as SupportedLocalesType[];
let defaultLocale: string =
_get(this.$plugin.config, 'files.settings/["settings.yaml"].defaultLocale') ||
_get(this.$plugin.config, 'defaultLocale');
// Try to get default locale from platform-specific settings.
const settingsPath: string = joinPaths(this.$plugin.platformPath, 'settings', 'settings.yaml');
if (existsSync(settingsPath)) {
const settingsFile: string = readFileSync(
joinPaths(this.$plugin.platformPath, 'settings', 'settings.yaml'),
'utf-8',
);
const settings = yaml.parse(settingsFile);
defaultLocale = _get(settings, 'defaultLocale');
}
if (!defaultLocale && resolvedLocales) {
// If locales includes an english model, take english as default automatically.
for (const locale of resolvedLocales) {
if (locale === 'en') {
this.$context.googleAssistant.defaultLocale = locale;
}
}
// Otherwise take the first locale in the array as the default one.
this.$context.googleAssistant.defaultLocale = resolvedLocales[0];
return;
}
if (!defaultLocale) {
throw new JovoCliError({
message: 'Could not find a default locale.',
module: this.$plugin.name,
hint: 'Try adding the property "defaultLocale" to your project.js.',
});
}
this.$context.googleAssistant.defaultLocale = defaultLocale;
}
/**
* Try to get locale resolution (en -> en-US) from project configuration.
* @param locale - The locale to get the resolution from.
*/
getProjectLocales(locale: string): string[] {
return _get(this.$plugin.config, `options.locales.${locale}`) as string[];
}
/**
* Get plugin-specific endpoint.
*/
getPluginEndpoint(): string {
const endpoint: string =
_get(this.$plugin.config, 'endpoint') ||
(this.$cli.project!.config.getParameter('endpoint') as string);
return this.$cli.resolveEndpoint(endpoint);
}
/**
* Gets the invocation name for the specified locale.
* @param locale - The locale of the Jovo model to fetch the invocation name from.
*/
async getInvocationName(locale: string): Promise<string> {
const { invocation } = _merge(
await this.getJovoModel(locale),
this.$cli.project!.config.getParameter(`models.override.${locale}`),
);
if (typeof invocation === 'object') {
// ToDo: Test!
const platformInvocation: string = invocation[this.$plugin.id];
if (!platformInvocation) {
throw new JovoCliError({
message: `Can\'t find invocation name for locale ${locale}.`,
module: this.$plugin.name,
});
}
return platformInvocation;
}
return invocation;
}
/**
* Parses and returns platform-specific intents and entities.
* @param locale - Locale for which to return the model data.
*/
getPlatformModels(locale: string): NativeFileInformation[] {
const platformModels: NativeFileInformation[] = [];
const modelPath: string = joinPaths(this.$plugin.platformPath, 'custom');
// Go through a predefined set of folders to extract intent and type information.
const foldersToInclude: string[] = ['intents', 'types', 'scenes', 'global'];
for (const folder of foldersToInclude) {
const path: string[] = [modelPath, folder];
if (locale !== this.$context.googleAssistant.defaultLocale) {
path.push(locale);
}
const folderPath = joinPaths(...path);
if (!existsSync(folderPath)) {
continue;
}
let files: string[] = readdirSync(joinPaths(...path));
if (folder === 'global') {
files = files.filter((file) => file.includes('actions.intent'));
}
const yamlRegex = /.*\.yaml/;
for (const file of files) {
if (yamlRegex.test(file)) {
const fileContent = readFileSync(joinPaths(...path, file), 'utf-8');
platformModels.push({
path: [...path, file],
content: yaml.parse(fileContent),
});
}
}
}
return platformModels;
}
/**
* Parses platform-specific settings and returns the localized invocation name.
* @param locale - Locale for which to parse the invocation name.
*/
getPlatformInvocationName(locale: string): string {
const path: string[] = [this.$plugin.platformPath, 'settings'];
if (locale !== this.$context.googleAssistant.defaultLocale) {
path.push(locale);
}
const settingsPath: string = joinPaths(...path, 'settings.yaml');
const settingsFile: string = readFileSync(settingsPath, 'utf-8');
const settings = yaml.parse(settingsFile);
return settings.localizedSettings.displayName;
}
/**
* Returns all locales for the current platform.
*/
getPlatformLocales(): string[] {
const locales: string[] = [];
const settingsPath: string = joinPaths(this.$plugin.platformPath, 'settings');
const files: string[] = readdirSync(settingsPath);
for (const file of files) {
if (
statSync(joinPaths(settingsPath, file)).isDirectory() &&
/^[a-z]{2}-?([A-Z]{2})?$/.test(file)
) {
locales.push(file);
} else if (file === 'settings.yaml') {
const settings = yaml.parse(readFileSync(joinPaths(settingsPath, file), 'utf-8'));
locales.push(settings.defaultLocale);
}
}
return locales;
}
/**
* Loads a Jovo model specified by a locale and merges it with plugin-specific models.
* @param locale - The locale that specifies which model to load.
*/
async getJovoModel(locale: string): Promise<JovoModelData | JovoModelDataV3> {
const model: JovoModelData | JovoModelDataV3 = await this.$cli.project!.getModel(locale);
// Merge model with configured language model in project.js.
_mergeWith(
model,
this.$cli.project!.config.getParameter(`languageModel.${locale}`) || {},
mergeArrayCustomizer,
);
// Merge model with configured, platform-specific language model in project.js.
_mergeWith(
model,
_get(this.$plugin.config, `languageModel.${locale}`, {}),
mergeArrayCustomizer,
);
return model;
}
} | the_stack |
import { GlobalProps } from 'ojs/ojvcomponent';
import { ComponentChildren } from 'preact';
import { DataProvider } from '../ojdataprovider';
import { dvtBaseComponent, dvtBaseComponentEventMap, dvtBaseComponentSettableProperties } from '../ojdvt-base';
import { JetElement, JetSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..';
export interface ojTagCloud<K, D extends ojTagCloud.Item<K> | any> extends dvtBaseComponent<ojTagCloudSettableProperties<K, D>> {
animationOnDataChange?: 'auto' | 'none';
animationOnDisplay?: 'auto' | 'none';
as?: string;
data: DataProvider<K, D> | null;
hiddenCategories?: string[];
highlightMatch?: 'any' | 'all';
highlightedCategories?: string[];
hoverBehavior?: 'dim' | 'none';
layout?: 'cloud' | 'rectangular';
selection?: K[];
selectionMode?: 'none' | 'single' | 'multiple';
styleDefaults?: {
animationDuration?: number;
hoverBehaviorDelay?: number;
svgStyle?: Partial<CSSStyleDeclaration>;
};
tooltip?: {
renderer: ((context: ojTagCloud.TooltipContext<K>) => ({
insert: Element | string;
} | {
preventDefault: boolean;
}));
};
touchResponse?: 'touchStart' | 'auto';
translations: {
componentName?: string;
labelAndValue?: string;
labelClearSelection?: string;
labelCountWithTotal?: string;
labelDataVisualization?: string;
labelInvalidData?: string;
labelNoData?: string;
stateCollapsed?: string;
stateDrillable?: string;
stateExpanded?: string;
stateHidden?: string;
stateIsolated?: string;
stateMaximized?: string;
stateMinimized?: string;
stateSelected?: string;
stateUnselected?: string;
stateVisible?: string;
};
addEventListener<T extends keyof ojTagCloudEventMap<K, D>>(type: T, listener: (this: HTMLElement, ev: ojTagCloudEventMap<K, D>[T]) => any, options?: (boolean | AddEventListenerOptions)): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void;
getProperty<T extends keyof ojTagCloudSettableProperties<K, D>>(property: T): ojTagCloud<K, D>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojTagCloudSettableProperties<K, D>>(property: T, value: ojTagCloudSettableProperties<K, D>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojTagCloudSettableProperties<K, D>>): void;
setProperties(properties: ojTagCloudSettablePropertiesLenient<K, D>): void;
getContextByNode(node: Element): ojTagCloud.NodeContext | null;
}
export namespace ojTagCloud {
// tslint:disable-next-line interface-over-type-literal
type animationOnDataChangeChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojTagCloud<K, D>["animationOnDataChange"]>;
// tslint:disable-next-line interface-over-type-literal
type animationOnDisplayChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojTagCloud<K, D>["animationOnDisplay"]>;
// tslint:disable-next-line interface-over-type-literal
type asChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojTagCloud<K, D>["as"]>;
// tslint:disable-next-line interface-over-type-literal
type dataChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojTagCloud<K, D>["data"]>;
// tslint:disable-next-line interface-over-type-literal
type hiddenCategoriesChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojTagCloud<K, D>["hiddenCategories"]>;
// tslint:disable-next-line interface-over-type-literal
type highlightMatchChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojTagCloud<K, D>["highlightMatch"]>;
// tslint:disable-next-line interface-over-type-literal
type highlightedCategoriesChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojTagCloud<K, D>["highlightedCategories"]>;
// tslint:disable-next-line interface-over-type-literal
type hoverBehaviorChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojTagCloud<K, D>["hoverBehavior"]>;
// tslint:disable-next-line interface-over-type-literal
type layoutChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojTagCloud<K, D>["layout"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojTagCloud<K, D>["selection"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionModeChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojTagCloud<K, D>["selectionMode"]>;
// tslint:disable-next-line interface-over-type-literal
type styleDefaultsChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojTagCloud<K, D>["styleDefaults"]>;
// tslint:disable-next-line interface-over-type-literal
type tooltipChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojTagCloud<K, D>["tooltip"]>;
// tslint:disable-next-line interface-over-type-literal
type touchResponseChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojTagCloud<K, D>["touchResponse"]>;
//------------------------------------------------------------
// Start: generated events for inherited properties
//------------------------------------------------------------
// tslint:disable-next-line interface-over-type-literal
type trackResizeChanged<K, D extends Item<K> | any> = dvtBaseComponent.trackResizeChanged<ojTagCloudSettableProperties<K, D>>;
// tslint:disable-next-line interface-over-type-literal
type Item<K> = {
categories?: string[];
color?: string;
id?: K;
label: string;
shortDesc?: (string | ((context: ItemShortDescContext<K>) => string));
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
url?: string;
value: number;
};
// tslint:disable-next-line interface-over-type-literal
type ItemContext = {
color: string;
label: string;
selected: boolean;
tooltip: string;
value: number;
};
// tslint:disable-next-line interface-over-type-literal
type ItemShortDescContext<K> = {
id: K;
label: string;
value: number;
};
// tslint:disable-next-line interface-over-type-literal
type ItemTemplateContext<K> = {
componentElement: Element;
data: object;
index: number;
key: K;
};
// tslint:disable-next-line interface-over-type-literal
type NodeContext = {
index: number;
subId: string;
};
// tslint:disable-next-line interface-over-type-literal
type TooltipContext<K> = {
color: string;
componentElement: Element;
id: K;
label: string;
parentElement: Element;
value: number;
};
}
export interface ojTagCloudEventMap<K, D extends ojTagCloud.Item<K> | any> extends dvtBaseComponentEventMap<ojTagCloudSettableProperties<K, D>> {
'animationOnDataChangeChanged': JetElementCustomEvent<ojTagCloud<K, D>["animationOnDataChange"]>;
'animationOnDisplayChanged': JetElementCustomEvent<ojTagCloud<K, D>["animationOnDisplay"]>;
'asChanged': JetElementCustomEvent<ojTagCloud<K, D>["as"]>;
'dataChanged': JetElementCustomEvent<ojTagCloud<K, D>["data"]>;
'hiddenCategoriesChanged': JetElementCustomEvent<ojTagCloud<K, D>["hiddenCategories"]>;
'highlightMatchChanged': JetElementCustomEvent<ojTagCloud<K, D>["highlightMatch"]>;
'highlightedCategoriesChanged': JetElementCustomEvent<ojTagCloud<K, D>["highlightedCategories"]>;
'hoverBehaviorChanged': JetElementCustomEvent<ojTagCloud<K, D>["hoverBehavior"]>;
'layoutChanged': JetElementCustomEvent<ojTagCloud<K, D>["layout"]>;
'selectionChanged': JetElementCustomEvent<ojTagCloud<K, D>["selection"]>;
'selectionModeChanged': JetElementCustomEvent<ojTagCloud<K, D>["selectionMode"]>;
'styleDefaultsChanged': JetElementCustomEvent<ojTagCloud<K, D>["styleDefaults"]>;
'tooltipChanged': JetElementCustomEvent<ojTagCloud<K, D>["tooltip"]>;
'touchResponseChanged': JetElementCustomEvent<ojTagCloud<K, D>["touchResponse"]>;
'trackResizeChanged': JetElementCustomEvent<ojTagCloud<K, D>["trackResize"]>;
}
export interface ojTagCloudSettableProperties<K, D extends ojTagCloud.Item<K> | any> extends dvtBaseComponentSettableProperties {
animationOnDataChange?: 'auto' | 'none';
animationOnDisplay?: 'auto' | 'none';
as?: string;
data: DataProvider<K, D> | null;
hiddenCategories?: string[];
highlightMatch?: 'any' | 'all';
highlightedCategories?: string[];
hoverBehavior?: 'dim' | 'none';
layout?: 'cloud' | 'rectangular';
selection?: K[];
selectionMode?: 'none' | 'single' | 'multiple';
styleDefaults?: {
animationDuration?: number;
hoverBehaviorDelay?: number;
svgStyle?: Partial<CSSStyleDeclaration>;
};
tooltip?: {
renderer: ((context: ojTagCloud.TooltipContext<K>) => ({
insert: Element | string;
} | {
preventDefault: boolean;
}));
};
touchResponse?: 'touchStart' | 'auto';
translations: {
componentName?: string;
labelAndValue?: string;
labelClearSelection?: string;
labelCountWithTotal?: string;
labelDataVisualization?: string;
labelInvalidData?: string;
labelNoData?: string;
stateCollapsed?: string;
stateDrillable?: string;
stateExpanded?: string;
stateHidden?: string;
stateIsolated?: string;
stateMaximized?: string;
stateMinimized?: string;
stateSelected?: string;
stateUnselected?: string;
stateVisible?: string;
};
}
export interface ojTagCloudSettablePropertiesLenient<K, D extends ojTagCloud.Item<K> | any> extends Partial<ojTagCloudSettableProperties<K, D>> {
[key: string]: any;
}
export interface ojTagCloudItem<K = any> extends dvtBaseComponent<ojTagCloudItemSettableProperties<K>> {
categories?: string[];
color?: string;
label?: string;
shortDesc?: (string | ((context: ojTagCloud.ItemShortDescContext<K>) => string));
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
url?: string;
value?: number | null;
addEventListener<T extends keyof ojTagCloudItemEventMap<K>>(type: T, listener: (this: HTMLElement, ev: ojTagCloudItemEventMap<K>[T]) => any, options?: (boolean | AddEventListenerOptions)): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void;
getProperty<T extends keyof ojTagCloudItemSettableProperties<K>>(property: T): ojTagCloudItem<K>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojTagCloudItemSettableProperties<K>>(property: T, value: ojTagCloudItemSettableProperties<K>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojTagCloudItemSettableProperties<K>>): void;
setProperties(properties: ojTagCloudItemSettablePropertiesLenient<K>): void;
}
export namespace ojTagCloudItem {
// tslint:disable-next-line interface-over-type-literal
type categoriesChanged<K = any> = JetElementCustomEvent<ojTagCloudItem<K>["categories"]>;
// tslint:disable-next-line interface-over-type-literal
type colorChanged<K = any> = JetElementCustomEvent<ojTagCloudItem<K>["color"]>;
// tslint:disable-next-line interface-over-type-literal
type labelChanged<K = any> = JetElementCustomEvent<ojTagCloudItem<K>["label"]>;
// tslint:disable-next-line interface-over-type-literal
type shortDescChanged<K = any> = JetElementCustomEvent<ojTagCloudItem<K>["shortDesc"]>;
// tslint:disable-next-line interface-over-type-literal
type svgClassNameChanged<K = any> = JetElementCustomEvent<ojTagCloudItem<K>["svgClassName"]>;
// tslint:disable-next-line interface-over-type-literal
type svgStyleChanged<K = any> = JetElementCustomEvent<ojTagCloudItem<K>["svgStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type urlChanged<K = any> = JetElementCustomEvent<ojTagCloudItem<K>["url"]>;
// tslint:disable-next-line interface-over-type-literal
type valueChanged<K = any> = JetElementCustomEvent<ojTagCloudItem<K>["value"]>;
}
export interface ojTagCloudItemEventMap<K = any> extends dvtBaseComponentEventMap<ojTagCloudItemSettableProperties<K>> {
'categoriesChanged': JetElementCustomEvent<ojTagCloudItem<K>["categories"]>;
'colorChanged': JetElementCustomEvent<ojTagCloudItem<K>["color"]>;
'labelChanged': JetElementCustomEvent<ojTagCloudItem<K>["label"]>;
'shortDescChanged': JetElementCustomEvent<ojTagCloudItem<K>["shortDesc"]>;
'svgClassNameChanged': JetElementCustomEvent<ojTagCloudItem<K>["svgClassName"]>;
'svgStyleChanged': JetElementCustomEvent<ojTagCloudItem<K>["svgStyle"]>;
'urlChanged': JetElementCustomEvent<ojTagCloudItem<K>["url"]>;
'valueChanged': JetElementCustomEvent<ojTagCloudItem<K>["value"]>;
}
export interface ojTagCloudItemSettableProperties<K = any> extends dvtBaseComponentSettableProperties {
categories?: string[];
color?: string;
label?: string;
shortDesc?: (string | ((context: ojTagCloud.ItemShortDescContext<K>) => string));
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
url?: string;
value?: number | null;
}
export interface ojTagCloudItemSettablePropertiesLenient<K = any> extends Partial<ojTagCloudItemSettableProperties<K>> {
[key: string]: any;
}
export type TagCloudElement<K, D extends ojTagCloud.Item<K> | any> = ojTagCloud<K, D>;
export type TagCloudItemElement<K = any> = ojTagCloudItem<K>;
export namespace TagCloudElement {
// tslint:disable-next-line interface-over-type-literal
type animationOnDataChangeChanged<K, D extends ojTagCloud.Item<K> | any> = JetElementCustomEvent<ojTagCloud<K, D>["animationOnDataChange"]>;
// tslint:disable-next-line interface-over-type-literal
type animationOnDisplayChanged<K, D extends ojTagCloud.Item<K> | any> = JetElementCustomEvent<ojTagCloud<K, D>["animationOnDisplay"]>;
// tslint:disable-next-line interface-over-type-literal
type asChanged<K, D extends ojTagCloud.Item<K> | any> = JetElementCustomEvent<ojTagCloud<K, D>["as"]>;
// tslint:disable-next-line interface-over-type-literal
type dataChanged<K, D extends ojTagCloud.Item<K> | any> = JetElementCustomEvent<ojTagCloud<K, D>["data"]>;
// tslint:disable-next-line interface-over-type-literal
type hiddenCategoriesChanged<K, D extends ojTagCloud.Item<K> | any> = JetElementCustomEvent<ojTagCloud<K, D>["hiddenCategories"]>;
// tslint:disable-next-line interface-over-type-literal
type highlightMatchChanged<K, D extends ojTagCloud.Item<K> | any> = JetElementCustomEvent<ojTagCloud<K, D>["highlightMatch"]>;
// tslint:disable-next-line interface-over-type-literal
type highlightedCategoriesChanged<K, D extends ojTagCloud.Item<K> | any> = JetElementCustomEvent<ojTagCloud<K, D>["highlightedCategories"]>;
// tslint:disable-next-line interface-over-type-literal
type hoverBehaviorChanged<K, D extends ojTagCloud.Item<K> | any> = JetElementCustomEvent<ojTagCloud<K, D>["hoverBehavior"]>;
// tslint:disable-next-line interface-over-type-literal
type layoutChanged<K, D extends ojTagCloud.Item<K> | any> = JetElementCustomEvent<ojTagCloud<K, D>["layout"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionChanged<K, D extends ojTagCloud.Item<K> | any> = JetElementCustomEvent<ojTagCloud<K, D>["selection"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionModeChanged<K, D extends ojTagCloud.Item<K> | any> = JetElementCustomEvent<ojTagCloud<K, D>["selectionMode"]>;
// tslint:disable-next-line interface-over-type-literal
type styleDefaultsChanged<K, D extends ojTagCloud.Item<K> | any> = JetElementCustomEvent<ojTagCloud<K, D>["styleDefaults"]>;
// tslint:disable-next-line interface-over-type-literal
type tooltipChanged<K, D extends ojTagCloud.Item<K> | any> = JetElementCustomEvent<ojTagCloud<K, D>["tooltip"]>;
// tslint:disable-next-line interface-over-type-literal
type touchResponseChanged<K, D extends ojTagCloud.Item<K> | any> = JetElementCustomEvent<ojTagCloud<K, D>["touchResponse"]>;
//------------------------------------------------------------
// Start: generated events for inherited properties
//------------------------------------------------------------
// tslint:disable-next-line interface-over-type-literal
type trackResizeChanged<K, D extends ojTagCloud.Item<K> | any> = dvtBaseComponent.trackResizeChanged<ojTagCloudSettableProperties<K, D>>;
// tslint:disable-next-line interface-over-type-literal
type Item<K> = {
categories?: string[];
color?: string;
id?: K;
label: string;
shortDesc?: (string | ((context: ojTagCloud.ItemShortDescContext<K>) => string));
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
url?: string;
value: number;
};
// tslint:disable-next-line interface-over-type-literal
type ItemShortDescContext<K> = {
id: K;
label: string;
value: number;
};
// tslint:disable-next-line interface-over-type-literal
type NodeContext = {
index: number;
subId: string;
};
}
export namespace TagCloudItemElement {
// tslint:disable-next-line interface-over-type-literal
type categoriesChanged<K = any> = JetElementCustomEvent<ojTagCloudItem<K>["categories"]>;
// tslint:disable-next-line interface-over-type-literal
type colorChanged<K = any> = JetElementCustomEvent<ojTagCloudItem<K>["color"]>;
// tslint:disable-next-line interface-over-type-literal
type labelChanged<K = any> = JetElementCustomEvent<ojTagCloudItem<K>["label"]>;
// tslint:disable-next-line interface-over-type-literal
type shortDescChanged<K = any> = JetElementCustomEvent<ojTagCloudItem<K>["shortDesc"]>;
// tslint:disable-next-line interface-over-type-literal
type svgClassNameChanged<K = any> = JetElementCustomEvent<ojTagCloudItem<K>["svgClassName"]>;
// tslint:disable-next-line interface-over-type-literal
type svgStyleChanged<K = any> = JetElementCustomEvent<ojTagCloudItem<K>["svgStyle"]>;
// tslint:disable-next-line interface-over-type-literal
type urlChanged<K = any> = JetElementCustomEvent<ojTagCloudItem<K>["url"]>;
// tslint:disable-next-line interface-over-type-literal
type valueChanged<K = any> = JetElementCustomEvent<ojTagCloudItem<K>["value"]>;
}
export interface TagCloudIntrinsicProps extends Partial<Readonly<ojTagCloudSettableProperties<any, any>>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> {
onanimationOnDataChangeChanged?: (value: ojTagCloudEventMap<any, any>['animationOnDataChangeChanged']) => void;
onanimationOnDisplayChanged?: (value: ojTagCloudEventMap<any, any>['animationOnDisplayChanged']) => void;
onasChanged?: (value: ojTagCloudEventMap<any, any>['asChanged']) => void;
ondataChanged?: (value: ojTagCloudEventMap<any, any>['dataChanged']) => void;
onhiddenCategoriesChanged?: (value: ojTagCloudEventMap<any, any>['hiddenCategoriesChanged']) => void;
onhighlightMatchChanged?: (value: ojTagCloudEventMap<any, any>['highlightMatchChanged']) => void;
onhighlightedCategoriesChanged?: (value: ojTagCloudEventMap<any, any>['highlightedCategoriesChanged']) => void;
onhoverBehaviorChanged?: (value: ojTagCloudEventMap<any, any>['hoverBehaviorChanged']) => void;
onlayoutChanged?: (value: ojTagCloudEventMap<any, any>['layoutChanged']) => void;
onselectionChanged?: (value: ojTagCloudEventMap<any, any>['selectionChanged']) => void;
onselectionModeChanged?: (value: ojTagCloudEventMap<any, any>['selectionModeChanged']) => void;
onstyleDefaultsChanged?: (value: ojTagCloudEventMap<any, any>['styleDefaultsChanged']) => void;
ontooltipChanged?: (value: ojTagCloudEventMap<any, any>['tooltipChanged']) => void;
ontouchResponseChanged?: (value: ojTagCloudEventMap<any, any>['touchResponseChanged']) => void;
ontrackResizeChanged?: (value: ojTagCloudEventMap<any, any>['trackResizeChanged']) => void;
children?: ComponentChildren;
}
export interface TagCloudItemIntrinsicProps extends Partial<Readonly<ojTagCloudItemSettableProperties<any>>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> {
oncategoriesChanged?: (value: ojTagCloudItemEventMap<any>['categoriesChanged']) => void;
oncolorChanged?: (value: ojTagCloudItemEventMap<any>['colorChanged']) => void;
onlabelChanged?: (value: ojTagCloudItemEventMap<any>['labelChanged']) => void;
onshortDescChanged?: (value: ojTagCloudItemEventMap<any>['shortDescChanged']) => void;
onsvgClassNameChanged?: (value: ojTagCloudItemEventMap<any>['svgClassNameChanged']) => void;
onsvgStyleChanged?: (value: ojTagCloudItemEventMap<any>['svgStyleChanged']) => void;
onurlChanged?: (value: ojTagCloudItemEventMap<any>['urlChanged']) => void;
onvalueChanged?: (value: ojTagCloudItemEventMap<any>['valueChanged']) => void;
children?: ComponentChildren;
}
declare global {
namespace preact.JSX {
interface IntrinsicElements {
"oj-tag-cloud": TagCloudIntrinsicProps;
"oj-tag-cloud-item": TagCloudItemIntrinsicProps;
}
}
} | the_stack |
import { getRealVariables, parseAndAnalyze } from '../util';
describe('References:', () => {
describe('When there is a `let` declaration on global,', () => {
it('the reference on global should be resolved.', () => {
const { scopeManager } = parseAndAnalyze('let a = 0;');
expect(scopeManager.scopes).toHaveLength(1);
const scope = scopeManager.scopes[0];
const variables = getRealVariables(scope.variables);
expect(variables).toHaveLength(1);
expect(scope.references).toHaveLength(1);
const reference = scope.references[0];
expect(reference.from).toBe(scope);
expect(reference.identifier.name).toBe('a');
expect(reference.resolved).toBe(variables[0]);
expect(reference.writeExpr).toBeDefined();
expect(reference.isWrite()).toBeTruthy();
expect(reference.isRead()).toBeFalsy();
});
it('the reference in functions should be resolved.', () => {
const { scopeManager } = parseAndAnalyze(`
let a = 0;
function foo() {
let b = a;
}
`);
expect(scopeManager.scopes).toHaveLength(2); // [global, foo]
const scope = scopeManager.scopes[1];
const variables = getRealVariables(scope.variables);
expect(variables).toHaveLength(2); // [arguments, b]
expect(scope.references).toHaveLength(2); // [b, a]
const reference = scope.references[1];
expect(reference.from).toBe(scope);
expect(reference.identifier.name).toBe('a');
expect(reference.resolved).toBe(
getRealVariables(scopeManager.scopes[0].variables)[0],
);
expect(reference.writeExpr).toBeUndefined();
expect(reference.isWrite()).toBeFalsy();
expect(reference.isRead()).toBeTruthy();
});
it('the reference in default parameters should be resolved.', () => {
const { scopeManager } = parseAndAnalyze(`
let a = 0;
function foo(b = a) {
}
`);
expect(scopeManager.scopes).toHaveLength(2); // [global, foo]
const scope = scopeManager.scopes[1];
const variables = getRealVariables(scope.variables);
expect(variables).toHaveLength(2); // [arguments, b]
expect(scope.references).toHaveLength(2); // [b, a]
const reference = scope.references[1];
expect(reference.from).toBe(scope);
expect(reference.identifier.name).toBe('a');
expect(reference.resolved).toBe(
getRealVariables(scopeManager.scopes[0].variables)[0],
);
expect(reference.writeExpr).toBeUndefined();
expect(reference.isWrite()).toBeFalsy();
expect(reference.isRead()).toBeTruthy();
});
});
describe('When there is a `const` declaration on global,', () => {
it('the reference on global should be resolved.', () => {
const { scopeManager } = parseAndAnalyze('const a = 0;');
expect(scopeManager.scopes).toHaveLength(1);
const scope = scopeManager.scopes[0];
const variables = getRealVariables(scope.variables);
expect(variables).toHaveLength(1);
expect(scope.references).toHaveLength(1);
const reference = scope.references[0];
expect(reference.from).toBe(scope);
expect(reference.identifier.name).toBe('a');
expect(reference.resolved).toBe(variables[0]);
expect(reference.writeExpr).toBeDefined();
expect(reference.isWrite()).toBeTruthy();
expect(reference.isRead()).toBeFalsy();
});
it('the reference in functions should be resolved.', () => {
const { scopeManager } = parseAndAnalyze(`
const a = 0;
function foo() {
const b = a;
}
`);
expect(scopeManager.scopes).toHaveLength(2); // [global, foo]
const scope = scopeManager.scopes[1];
const variables = getRealVariables(scope.variables);
expect(variables).toHaveLength(2); // [arguments, b]
expect(scope.references).toHaveLength(2); // [b, a]
const reference = scope.references[1];
expect(reference.from).toBe(scope);
expect(reference.identifier.name).toBe('a');
expect(reference.resolved).toBe(
getRealVariables(scopeManager.scopes[0].variables)[0],
);
expect(reference.writeExpr).toBeUndefined();
expect(reference.isWrite()).toBeFalsy();
expect(reference.isRead()).toBeTruthy();
});
});
describe('When there is a `var` declaration on global,', () => {
it('the reference on global should NOT be resolved.', () => {
const { scopeManager } = parseAndAnalyze('var a = 0;');
expect(scopeManager.scopes).toHaveLength(1);
const scope = scopeManager.scopes[0];
const variables = getRealVariables(scope.variables);
expect(variables).toHaveLength(1);
expect(scope.references).toHaveLength(1);
const reference = scope.references[0];
expect(reference.from).toBe(scope);
expect(reference.identifier.name).toBe('a');
expect(reference.resolved).toBeNull();
expect(reference.writeExpr).toBeDefined();
expect(reference.isWrite()).toBeTruthy();
expect(reference.isRead()).toBeFalsy();
});
it('the reference in functions should NOT be resolved.', () => {
const { scopeManager } = parseAndAnalyze(`
var a = 0;
function foo() {
var b = a;
}
`);
expect(scopeManager.scopes).toHaveLength(2); // [global, foo]
const scope = scopeManager.scopes[1];
const variables = getRealVariables(scope.variables);
expect(variables).toHaveLength(2); // [arguments, b]
expect(scope.references).toHaveLength(2); // [b, a]
const reference = scope.references[1];
expect(reference.from).toBe(scope);
expect(reference.identifier.name).toBe('a');
expect(reference.resolved).toBeNull();
expect(reference.writeExpr).toBeUndefined();
expect(reference.isWrite()).toBeFalsy();
expect(reference.isRead()).toBeTruthy();
});
});
describe('When there is a `class` declaration on global,', () => {
it('the reference on global should be resolved.', () => {
const { scopeManager } = parseAndAnalyze(`
class A {}
let b = new A();
`);
expect(scopeManager.scopes).toHaveLength(2); // [global, A]
const scope = scopeManager.scopes[0];
const variables = getRealVariables(scope.variables);
expect(variables).toHaveLength(2); // [A, b]
expect(scope.references).toHaveLength(2); // [b, A]
const reference = scope.references[1];
expect(reference.from).toBe(scope);
expect(reference.identifier.name).toBe('A');
expect(reference.resolved).toBe(variables[0]);
expect(reference.writeExpr).toBeUndefined();
expect(reference.isWrite()).toBeFalsy();
expect(reference.isRead()).toBeTruthy();
});
it('the reference in functions should be resolved.', () => {
const { scopeManager } = parseAndAnalyze(`
class A {}
function foo() {
let b = new A();
}
`);
expect(scopeManager.scopes).toHaveLength(3); // [global, A, foo]
const scope = scopeManager.scopes[2];
const variables = getRealVariables(scope.variables);
expect(variables).toHaveLength(2); // [arguments, b]
expect(scope.references).toHaveLength(2); // [b, A]
const reference = scope.references[1];
expect(reference.from).toBe(scope);
expect(reference.identifier.name).toBe('A');
expect(reference.resolved).toBe(
getRealVariables(scopeManager.scopes[0].variables)[0],
);
expect(reference.writeExpr).toBeUndefined();
expect(reference.isWrite()).toBeFalsy();
expect(reference.isRead()).toBeTruthy();
});
});
describe('When there is a `let` declaration in functions,', () => {
it('the reference on the function should be resolved.', () => {
const { scopeManager } = parseAndAnalyze(`
function foo() {
let a = 0;
}
`);
expect(scopeManager.scopes).toHaveLength(2); // [global, foo]
const scope = scopeManager.scopes[1];
const variables = getRealVariables(scope.variables);
expect(variables).toHaveLength(2); // [arguments, a]
expect(scope.references).toHaveLength(1);
const reference = scope.references[0];
expect(reference.from).toBe(scope);
expect(reference.identifier.name).toBe('a');
expect(reference.resolved).toBe(variables[1]);
expect(reference.writeExpr).toBeDefined();
expect(reference.isWrite()).toBeTruthy();
expect(reference.isRead()).toBeFalsy();
});
it('the reference in nested functions should be resolved.', () => {
const { scopeManager } = parseAndAnalyze(`
function foo() {
let a = 0;
function bar() {
let b = a;
}
}
`);
expect(scopeManager.scopes).toHaveLength(3); // [global, foo, bar]
const scope = scopeManager.scopes[2];
const variables = getRealVariables(scope.variables);
expect(variables).toHaveLength(2); // [arguments, b]
expect(scope.references).toHaveLength(2); // [b, a]
const reference = scope.references[1];
expect(reference.from).toBe(scope);
expect(reference.identifier.name).toBe('a');
expect(reference.resolved).toBe(
getRealVariables(scopeManager.scopes[1].variables)[1],
);
expect(reference.writeExpr).toBeUndefined();
expect(reference.isWrite()).toBeFalsy();
expect(reference.isRead()).toBeTruthy();
});
});
describe('When there is a `var` declaration in functions,', () => {
it('the reference on the function should be resolved.', () => {
const { scopeManager } = parseAndAnalyze(`
function foo() {
var a = 0;
}
`);
expect(scopeManager.scopes).toHaveLength(2); // [global, foo]
const scope = scopeManager.scopes[1];
const variables = getRealVariables(scope.variables);
expect(variables).toHaveLength(2); // [arguments, a]
expect(scope.references).toHaveLength(1);
const reference = scope.references[0];
expect(reference.from).toBe(scope);
expect(reference.identifier.name).toBe('a');
expect(reference.resolved).toBe(variables[1]);
expect(reference.writeExpr).toBeDefined();
expect(reference.isWrite()).toBeTruthy();
expect(reference.isRead()).toBeFalsy();
});
it('the reference in nested functions should be resolved.', () => {
const { scopeManager } = parseAndAnalyze(`
function foo() {
var a = 0;
function bar() {
var b = a;
}
}
`);
expect(scopeManager.scopes).toHaveLength(3); // [global, foo, bar]
const scope = scopeManager.scopes[2];
const variables = getRealVariables(scope.variables);
expect(variables).toHaveLength(2); // [arguments, b]
expect(scope.references).toHaveLength(2); // [b, a]
const reference = scope.references[1];
expect(reference.from).toBe(scope);
expect(reference.identifier.name).toBe('a');
expect(reference.resolved).toBe(
getRealVariables(scopeManager.scopes[1].variables)[1],
);
expect(reference.writeExpr).toBeUndefined();
expect(reference.isWrite()).toBeFalsy();
expect(reference.isRead()).toBeTruthy();
});
});
describe('When there is a `let` declaration with destructuring assignment', () => {
it('"let [a] = [1];", the reference should be resolved.', () => {
const { scopeManager } = parseAndAnalyze('let [a] = [1];');
expect(scopeManager.scopes).toHaveLength(1);
const scope = scopeManager.scopes[0];
const variables = getRealVariables(scope.variables);
expect(variables).toHaveLength(1);
expect(scope.references).toHaveLength(1);
const reference = scope.references[0];
expect(reference.from).toBe(scope);
expect(reference.identifier.name).toBe('a');
expect(reference.resolved).toBe(variables[0]);
expect(reference.writeExpr).toBeDefined();
expect(reference.isWrite()).toBeTruthy();
expect(reference.isRead()).toBeFalsy();
});
it('"let {a} = {a: 1};", the reference should be resolved.', () => {
const { scopeManager } = parseAndAnalyze('let {a} = {a: 1};');
expect(scopeManager.scopes).toHaveLength(1);
const scope = scopeManager.scopes[0];
const variables = getRealVariables(scope.variables);
expect(variables).toHaveLength(1);
expect(scope.references).toHaveLength(1);
const reference = scope.references[0];
expect(reference.from).toBe(scope);
expect(reference.identifier.name).toBe('a');
expect(reference.resolved).toBe(variables[0]);
expect(reference.writeExpr).toBeDefined();
expect(reference.isWrite()).toBeTruthy();
expect(reference.isRead()).toBeFalsy();
});
it('"let {a: {a}} = {a: {a: 1}};", the reference should be resolved.', () => {
const { scopeManager } = parseAndAnalyze('let {a: {a}} = {a: {a: 1}};');
expect(scopeManager.scopes).toHaveLength(1);
const scope = scopeManager.scopes[0];
const variables = getRealVariables(scope.variables);
expect(variables).toHaveLength(1);
expect(scope.references).toHaveLength(1);
const reference = scope.references[0];
expect(reference.from).toBe(scope);
expect(reference.identifier.name).toBe('a');
expect(reference.resolved).toBe(variables[0]);
expect(reference.writeExpr).toBeDefined();
expect(reference.isWrite()).toBeTruthy();
expect(reference.isRead()).toBeFalsy();
});
});
describe('Reference.init should be a boolean value of whether it is one to initialize or not.', () => {
const trueCodes = [
'var a = 0;',
'let a = 0;',
'const a = 0;',
'var [a] = [];',
'let [a] = [];',
'const [a] = [];',
'var [a = 1] = [];',
'let [a = 1] = [];',
'const [a = 1] = [];',
'var {a} = {};',
'let {a} = {};',
'const {a} = {};',
'var {b: a} = {};',
'let {b: a} = {};',
'const {b: a} = {};',
'var {b: a = 0} = {};',
'let {b: a = 0} = {};',
'const {b: a = 0} = {};',
'for (var a in []);',
'for (let a in []);',
'for (var [a] in []);',
'for (let [a] in []);',
'for (var [a = 0] in []);',
'for (let [a = 0] in []);',
'for (var {a} in []);',
'for (let {a} in []);',
'for (var {a = 0} in []);',
'for (let {a = 0} in []);',
'new function(a = 0) {}',
'new function([a = 0] = []) {}',
'new function({b: a = 0} = {}) {}',
];
trueCodes.forEach(code =>
it(`"${code}", all references should be true.`, () => {
const { scopeManager } = parseAndAnalyze(code);
expect(scopeManager.scopes.length).toBeGreaterThanOrEqual(1);
const scope = scopeManager.scopes[scopeManager.scopes.length - 1];
const variables = getRealVariables(scope.variables);
expect(variables.length).toBeGreaterThanOrEqual(1);
expect(scope.references.length).toBeGreaterThanOrEqual(1);
scope.references.forEach(reference => {
expect(reference.identifier.name).toBe('a');
expect(reference.isWrite()).toBeTruthy();
expect(reference.init).toBeTruthy();
});
}),
);
let falseCodes = [
'let a; a = 0;',
'let a; [a] = [];',
'let a; [a = 1] = [];',
'let a; ({a} = {});',
'let a; ({b: a} = {});',
'let a; ({b: a = 0} = {});',
'let a; for (a in []);',
'let a; for ([a] in []);',
'let a; for ([a = 0] in []);',
'let a; for ({a} in []);',
'let a; for ({a = 0} in []);',
];
falseCodes.forEach(code =>
it(`"${code}", all references should be false.`, () => {
const { scopeManager } = parseAndAnalyze(code);
expect(scopeManager.scopes.length).toBeGreaterThanOrEqual(1);
const scope = scopeManager.scopes[scopeManager.scopes.length - 1];
const variables = getRealVariables(scope.variables);
expect(variables).toHaveLength(1);
expect(scope.references.length).toBeGreaterThanOrEqual(1);
scope.references.forEach(reference => {
expect(reference.identifier.name).toBe('a');
expect(reference.isWrite()).toBeTruthy();
expect(reference.init).toBeFalsy();
});
}),
);
falseCodes = [
'let a; let b = a;',
'let a; let [b] = a;',
'let a; let [b = a] = [];',
'let a; for (var b in a);',
'let a; for (var [b = a] in []);',
'let a; for (let b in a);',
'let a; for (let [b = a] in []);',
'let a,b; b = a;',
'let a,b; [b] = a;',
'let a,b; [b = a] = [];',
'let a,b; for (b in a);',
'let a,b; for ([b = a] in []);',
'let a; a.foo = 0;',
'let a,b; b = a.foo;',
];
falseCodes.forEach(code =>
it(`"${code}", readonly references of "a" should be undefined.`, () => {
const { scopeManager } = parseAndAnalyze(code);
expect(scopeManager.scopes.length).toBeGreaterThanOrEqual(1);
const scope = scopeManager.scopes[0];
const variables = getRealVariables(scope.variables);
expect(variables.length).toBeGreaterThanOrEqual(1);
expect(variables[0].name).toBe('a');
const references = variables[0].references;
expect(references.length).toBeGreaterThanOrEqual(1);
references.forEach(reference => {
expect(reference.isRead()).toBeTruthy();
expect(reference.init).toBeUndefined();
});
}),
);
});
describe('When emitDecoratorMetadata is true', () => {
it('check type referenced by decorator metadata', () => {
const { scopeManager } = parseAndAnalyze(
`
@deco
class A {
property: Type1;
@deco
propertyWithDeco: a.Foo;
set foo(@deco a: SetterType) {}
constructor(foo: b.Foo) {}
foo1(@deco a: Type2, b: Type0) {}
@deco
foo2(a: Type3) {}
@deco
foo3(): Type4 {}
set ['a'](a: Type5) {}
set [0](a: Type6) {}
@deco
get a() {}
@deco
get [0]() {}
}
const keyName = 'foo';
class B {
constructor(@deco foo: c.Foo) {}
set [keyName](a: Type) {}
@deco
get [keyName]() {}
}
declare class C {
@deco
foo(): TypeC;
}
`,
{
emitDecoratorMetadata: true,
},
);
const classAScope = scopeManager.globalScope!.childScopes[0];
const propertyTypeRef = classAScope.references[2];
expect(propertyTypeRef.identifier.name).toBe('a');
expect(propertyTypeRef.isTypeReference).toBe(true);
expect(propertyTypeRef.isValueReference).toBe(true);
const setterParamTypeRef = classAScope.childScopes[0].references[0];
expect(setterParamTypeRef.identifier.name).toBe('SetterType');
expect(setterParamTypeRef.isTypeReference).toBe(true);
expect(setterParamTypeRef.isValueReference).toBe(false);
const constructorParamTypeRef = classAScope.childScopes[1].references[0];
expect(constructorParamTypeRef.identifier.name).toBe('b');
expect(constructorParamTypeRef.isTypeReference).toBe(true);
expect(constructorParamTypeRef.isValueReference).toBe(true);
const methodParamTypeRef = classAScope.childScopes[2].references[0];
expect(methodParamTypeRef.identifier.name).toBe('Type2');
expect(methodParamTypeRef.isTypeReference).toBe(true);
expect(methodParamTypeRef.isValueReference).toBe(true);
const methodParamTypeRef0 = classAScope.childScopes[2].references[2];
expect(methodParamTypeRef0.identifier.name).toBe('Type0');
expect(methodParamTypeRef0.isTypeReference).toBe(true);
expect(methodParamTypeRef0.isValueReference).toBe(true);
const methodParamTypeRef1 = classAScope.childScopes[3].references[0];
expect(methodParamTypeRef1.identifier.name).toBe('Type3');
expect(methodParamTypeRef1.isTypeReference).toBe(true);
expect(methodParamTypeRef1.isValueReference).toBe(true);
const methodReturnTypeRef = classAScope.childScopes[4].references[0];
expect(methodReturnTypeRef.identifier.name).toBe('Type4');
expect(methodReturnTypeRef.isTypeReference).toBe(true);
expect(methodReturnTypeRef.isValueReference).toBe(true);
const setterParamTypeRef1 = classAScope.childScopes[5].references[0];
expect(setterParamTypeRef1.identifier.name).toBe('Type5');
expect(setterParamTypeRef1.isTypeReference).toBe(true);
expect(setterParamTypeRef1.isValueReference).toBe(true);
const setterParamTypeRef2 = classAScope.childScopes[6].references[0];
expect(setterParamTypeRef2.identifier.name).toBe('Type6');
expect(setterParamTypeRef2.isTypeReference).toBe(true);
expect(setterParamTypeRef2.isValueReference).toBe(true);
const classBScope = scopeManager.globalScope!.childScopes[1];
const constructorParamTypeRef1 = classBScope.childScopes[0].references[0];
expect(constructorParamTypeRef1.identifier.name).toBe('c');
expect(constructorParamTypeRef1.isTypeReference).toBe(true);
expect(constructorParamTypeRef1.isValueReference).toBe(true);
const setterParamTypeRef3 = classBScope.childScopes[1].references[0];
// eslint-disable-next-line @typescript-eslint/internal/prefer-ast-types-enum
expect(setterParamTypeRef3.identifier.name).toBe('Type');
expect(setterParamTypeRef3.isTypeReference).toBe(true);
expect(setterParamTypeRef3.isValueReference).toBe(false);
const classCScope = scopeManager.globalScope!.childScopes[2];
const methodReturnTypeRef1 = classCScope.childScopes[0].references[0];
expect(methodReturnTypeRef1.identifier.name).toBe('TypeC');
expect(methodReturnTypeRef1.isTypeReference).toBe(true);
expect(methodReturnTypeRef1.isValueReference).toBe(false);
});
});
}); | the_stack |
import { html, render } from 'lit-html';
import EventManager from '../utils/event-manager';
import { INPUT_SIZE } from '../../src/components/input/input';
import BXSelect, { SELECT_COLOR_SCHEME } from '../../src/components/select/select';
import BXSelectItem from '../../src/components/select/select-item';
import BXSelectItemGroup from '../../src/components/select/select-item-group';
import { Default } from '../../src/components/select/select-story';
/**
* @param formData A `FormData` instance.
* @returns The given `formData` converted to a classic key-value pair.
*/
const getValues = (formData: FormData) => {
const values = {};
// eslint-disable-next-line no-restricted-syntax
for (const [key, value] of formData.entries()) {
values[key] = value;
}
return values;
};
const template = (props?) =>
Default({
'bx-select': props,
});
describe('bx-select', function() {
const events = new EventManager();
describe('Misc attributes', function() {
it('should render with minimum attributes', async function() {
render(template(), document.body);
await Promise.resolve();
expect(document.body.querySelector('bx-select')).toMatchSnapshot({ mode: 'shadow' });
});
it('should render with various attributes', async function() {
render(
template({
autofocus: true,
colorScheme: SELECT_COLOR_SCHEME.LIGHT,
disabled: true,
helperText: 'helper-text-foo',
labelText: 'label-text-foo',
name: 'name-foo',
placeholder: 'placeholder-foo',
size: INPUT_SIZE.EXTRA_LARGE,
value: 'staging',
}),
document.body
);
await Promise.resolve();
expect(document.body.querySelector('bx-select')).toMatchSnapshot({ mode: 'shadow' });
});
it('should render invalid state', async function() {
render(
template({
helperText: 'helper-text-foo', // `validityMessage` should take precedence
invalid: true,
validityMessage: 'validity-message-foo',
}),
document.body
);
await Promise.resolve();
expect(document.body.querySelector('bx-select')).toMatchSnapshot({ mode: 'shadow' });
});
});
describe('Changing child `<option>`s', function() {
it('should support adding an option', async function() {
render(template(), document.body);
await Promise.resolve();
const elem = document.body.querySelector('bx-select');
const item = document.createElement('bx-select-item') as BXSelectItem;
item.disabled = true;
item.label = 'label-foo';
item.selected = true;
item.value = 'value-foo';
elem!.appendChild(item);
await Promise.resolve(); // Let `MutationObserver` run
await Promise.resolve(); // Update cycle of rendering new child `<option>`s
const option = elem!.shadowRoot!.querySelector('option[value="value-foo"]') as HTMLOptionElement;
expect(option.disabled).toBe(true);
expect(option.label).toBe('label-foo');
expect(option.selected).toBe(true);
});
it('should support changing a property of an option', async function() {
render(template(), document.body);
await Promise.resolve();
const item = document.body.querySelector('bx-select-item[value="staging"]');
(item as BXSelectItem).disabled = true;
await Promise.resolve(); // Let `MutationObserver` run
await Promise.resolve(); // Update cycle of rendering new child `<option>`s
const elem = document.body.querySelector('bx-select');
const option = elem!.shadowRoot!.querySelector('option[value="staging"]') as HTMLOptionElement;
expect(option.disabled).toBe(true);
});
it('should support removing an option', async function() {
render(template(), document.body);
await Promise.resolve();
const item = document.body.querySelector('bx-select-item[value="staging"]');
item!.parentNode!.removeChild(item!);
await Promise.resolve(); // Let `MutationObserver` run
await Promise.resolve(); // Update cycle of rendering new child `<option>`s
const elem = document.body.querySelector('bx-select');
expect(elem!.shadowRoot!.querySelector('option[value="staging"]')).toBeNull();
});
it('should support adding an option group', async function() {
render(template(), document.body);
await Promise.resolve();
const elem = document.body.querySelector('bx-select');
const item = document.createElement('bx-select-item-group') as BXSelectItem;
item.disabled = true;
item.label = 'label-foo';
elem!.appendChild(item);
await Promise.resolve(); // Let `MutationObserver` run
await Promise.resolve(); // Update cycle of rendering new child `<optgroup>`s
const option = elem!.shadowRoot!.querySelector('optgroup[label="label-foo"]') as HTMLOptGroupElement;
expect(option.disabled).toBe(true);
expect(option.label).toBe('label-foo');
});
it('should support changing a property of an option group', async function() {
render(template(), document.body);
await Promise.resolve();
const itemGroup = document.body.querySelector('bx-select-item-group[label="Category 2"]');
(itemGroup as BXSelectItemGroup).disabled = true;
await Promise.resolve(); // Let `MutationObserver` run
await Promise.resolve(); // Update cycle of rendering new child `<optgroup>`s
const elem = document.body.querySelector('bx-select');
const option = elem!.shadowRoot!.querySelector('optgroup[label="Category 2"]') as HTMLOptGroupElement;
expect(option.disabled).toBe(true);
});
it('should support removing an option group', async function() {
render(template(), document.body);
await Promise.resolve();
const itemGroup = document.body.querySelector('bx-select-item-group[label="Category 2"]');
itemGroup!.parentNode!.removeChild(itemGroup!);
await Promise.resolve(); // Let `MutationObserver` run
await Promise.resolve(); // Update cycle of rendering new child `<optgroup>`s
const elem = document.body.querySelector('bx-select');
expect(elem!.shadowRoot!.querySelector('optgroup[label="Category 2"]')).toBeNull();
});
});
describe('Properties', function() {
it('should support querying the `<option>`', async function() {
render(
template({
children: html`
<bx-select-item value="all">Option 1</bx-select-item>
<bx-select-item value="cloudFoundry">Option 2</bx-select-item>
`,
}),
document.body
);
await Promise.resolve();
const { options } = document.body.querySelector('bx-select') as BXSelect;
expect(Array.prototype.map.call(options, option => option.value)).toEqual(['all', 'cloudFoundry']);
});
it('should support querying the length of `<option>`', async function() {
render(
template({
children: html`
<bx-select-item value="all">Option 1</bx-select-item>
<bx-select-item value="cloudFoundry">Option 2</bx-select-item>
`,
}),
document.body
);
await Promise.resolve();
expect((document.body.querySelector('bx-select') as BXSelect).length).toBe(2);
});
it('should support querying the type', async function() {
render(template(), document.body);
await Promise.resolve();
expect((document.body.querySelector('bx-select') as BXSelect).type).toBe('select-one');
});
it('should unsupport multiple selection', async function() {
render(template(), document.body);
await Promise.resolve();
const elem = document.body.querySelector('bx-select');
const { _attributeToProperty: origAttributeToProperty } = elem as any;
let caught;
await new Promise(resolve => {
spyOn(BXSelect.prototype as any, '_attributeToProperty').and.callFake(function() {
try {
// TODO: See if we can get around TS2683
// @ts-ignore
origAttributeToProperty.apply(this, arguments);
} catch (error) {
caught = error;
}
resolve();
});
elem!.setAttribute('multiple', '');
});
expect(caught).toBeDefined();
expect((elem as BXSelect).multiple).toBe(false);
});
it('should support querying the selected index', async function() {
render(template({ value: 'staging' }), document.body);
await Promise.resolve();
expect((document.body.querySelector('bx-select') as BXSelect).selectedIndex).toBe(2);
});
it('should support setting the selected index', async function() {
render(template(), document.body);
await Promise.resolve();
const select = document.body.querySelector('bx-select') as BXSelect;
select.selectedIndex = 2;
expect(select.value).toBe('staging');
});
});
describe('Event-based form participation', function() {
it('Should respond to `formdata` event', async function() {
render(
html`
<form>
${template({
name: 'name-foo',
value: 'staging',
})}
</form>
`,
document.body
);
await Promise.resolve();
const formData = new FormData();
const event = new CustomEvent('formdata', { bubbles: true, cancelable: false, composed: false });
(event as any).formData = formData; // TODO: Wait for `FormDataEvent` being available in `lib.dom.d.ts`
const form = document.querySelector('form');
form!.dispatchEvent(event);
expect(getValues(formData)).toEqual({ 'name-foo': 'staging' });
});
it('Should not respond to `formdata` event if disabled', async function() {
render(
html`
<form>
${template({
disabled: true,
name: 'name-foo',
value: 'staging',
})}
</form>
`,
document.body
);
await Promise.resolve();
const formData = new FormData();
const event = new CustomEvent('formdata', { bubbles: true, cancelable: false, composed: false });
(event as any).formData = formData; // TODO: Wait for `FormDataEvent` being available in `lib.dom.d.ts`
const form = document.querySelector('form');
form!.dispatchEvent(event);
expect(getValues(formData)).toEqual({});
});
});
describe('Form validation', function() {
let elem: Element;
beforeEach(async function() {
render(template(), document.body);
await Promise.resolve();
elem = document.body.querySelector('bx-select')!;
});
it('should support checking if required value exists', async function() {
const select = elem as BXSelect;
select.required = true;
const spyInvalid = jasmine.createSpy('invalid');
events.on(select, 'invalid', spyInvalid);
expect(select.checkValidity()).toBe(false);
expect(spyInvalid).toHaveBeenCalled();
expect(select.invalid).toBe(true);
expect(select.validityMessage).toBe('Please fill out this field.');
select.value = 'staging';
expect(select.checkValidity()).toBe(true);
expect(select.invalid).toBe(false);
expect(select.validityMessage).toBe('');
});
it('should support canceling required check', async function() {
const select = elem as BXSelect;
select.required = true;
events.on(select, 'invalid', event => {
event.preventDefault();
});
expect(select.checkValidity()).toBe(false);
expect(select.invalid).toBe(false);
expect(select.validityMessage).toBe('');
});
it('should treat empty custom validity message as not invalid', async function() {
const select = elem as BXSelect;
select.setCustomValidity('');
expect(select.invalid).toBe(false);
expect(select.validityMessage).toBe('');
});
it('should treat non-empty custom validity message as invalid', async function() {
const select = elem as BXSelect;
select.setCustomValidity('validity-message-foo');
expect(select.invalid).toBe(true);
expect(select.validityMessage).toBe('validity-message-foo');
});
});
afterEach(async function() {
events.reset();
await render(undefined!, document.body);
});
}); | the_stack |
import * as S from '@apollo-elements/test/schema';
import * as C from '@apollo/client/core';
import { aTimeout, fixture, expect, nextFrame } from '@open-wc/testing';
import { html } from 'lit/static-html.js';
import { setupClient, teardownClient } from '@apollo-elements/test';
import './apollo-subscription';
import { ApolloSubscriptionElement } from './apollo-subscription';
describe('[components] <apollo-subscription>', function describeApolloSubscription() {
beforeEach(setupClient);
afterEach(teardownClient);
describe('simply instantiating', function() {
let element: ApolloSubscriptionElement;
beforeEach(async function() {
element = await fixture(html`<apollo-subscription></apollo-subscription>`);
});
it('has a shadow root', function() {
expect(element.shadowRoot).to.be.ok;
});
it('doesn\'t render anything', function() {
expect(element).shadowDom.to.equal('');
});
describe('setting fetch-policy attr', function() {
it('cache-first', async function() {
element.setAttribute('fetch-policy', 'cache-first');
await element.updateComplete;
expect(element.fetchPolicy === 'cache-first').to.be.true;
expect(element.fetchPolicy).to.equal(element.controller.options.fetchPolicy);
});
it('cache-only', async function() {
element.setAttribute('fetch-policy', 'cache-only');
await element.updateComplete;
expect(element.fetchPolicy === 'cache-only').to.be.true;
expect(element.fetchPolicy).to.equal(element.controller.options.fetchPolicy);
});
it('network-only', async function() {
element.setAttribute('fetch-policy', 'network-only');
await element.updateComplete;
expect(element.fetchPolicy === 'network-only').to.be.true;
expect(element.fetchPolicy).to.equal(element.controller.options.fetchPolicy);
});
it('no-cache', async function() {
element.setAttribute('fetch-policy', 'no-cache');
await element.updateComplete;
expect(element.fetchPolicy === 'no-cache').to.be.true;
expect(element.fetchPolicy).to.equal(element.controller.options.fetchPolicy);
});
it('standby', async function() {
element.setAttribute('fetch-policy', 'standby');
await element.updateComplete;
expect(element.fetchPolicy === 'standby').to.be.true;
expect(element.fetchPolicy).to.equal(element.controller.options.fetchPolicy);
});
it('forwards an illegal value', async function() {
element.setAttribute('fetch-policy', 'cache-and-network');
await element.updateComplete;
// @ts-expect-error: test for bad value
expect(element.fetchPolicy === 'cache-and-network').to.be.true;
expect(element.fetchPolicy).to.equal(element.controller.options.fetchPolicy);
});
});
describe('setting error-policy attr', function() {
it('all', async function() {
element.setAttribute('error-policy', 'all');
await element.updateComplete;
expect(element.errorPolicy === 'all').to.be.true;
expect(element.errorPolicy).to.equal(element.controller.options.errorPolicy);
});
it('none', async function() {
element.setAttribute('error-policy', 'none');
await element.updateComplete;
expect(element.errorPolicy === 'none').to.be.true;
expect(element.errorPolicy).to.equal(element.controller.options.errorPolicy);
});
it('ignore', async function() {
element.setAttribute('error-policy', 'ignore');
await element.updateComplete;
expect(element.errorPolicy === 'ignore').to.be.true;
expect(element.errorPolicy).to.equal(element.controller.options.errorPolicy);
});
it('forwards an illegal value', async function() {
element.setAttribute('error-policy', 'shmoo');
await element.updateComplete;
// @ts-expect-error: test for bad value
expect(element.errorPolicy === 'shmoo').to.be.true;
expect(element.errorPolicy).to.equal(element.controller.options.errorPolicy);
});
});
describe('setting context', function() {
it('as empty object', async function() {
element.context = {};
await element.updateComplete;
expect(element.controller.options.context).to.be.ok.and.to.be.empty;
});
it('as non-empty object', async function() {
element.context = { a: 'b' };
await element.updateComplete;
expect(element.controller.options.context).to.deep.equal({ a: 'b' });
});
it('as illegal non-object', async function() {
// @ts-expect-error: test bad value
element.context = 1;
await element.updateComplete;
expect(element.controller.options.context).to.equal(1);
});
});
describe('setting client', function() {
it('as global client', async function() {
element.client = window.__APOLLO_CLIENT__!;
await element.updateComplete;
expect(element.controller.client).to.equal(window.__APOLLO_CLIENT__);
});
it('as new client', async function() {
const client = new C.ApolloClient({ cache: new C.InMemoryCache() });
element.client = client;
await element.updateComplete;
expect(element.controller.client).to.equal(client);
});
it('as illegal value', async function() {
// @ts-expect-error: test bad value
element.client = 1;
await element.updateComplete;
expect(element.controller.client).to.equal(1);
});
});
describe('setting loading', function() {
it('as true', async function() {
element.loading = true;
await element.updateComplete;
expect(element.controller.loading).to.equal(true);
});
it('as false', async function() {
element.loading = false;
await element.updateComplete;
expect(element.controller.loading).to.equal(false);
});
it('as illegal value', async function() {
// @ts-expect-error: test bad value
element.loading = 1;
await element.updateComplete;
expect(element.controller.loading).to.equal(1);
});
});
describe('setting subscription', function() {
it('as DocumentNode', async function() {
const subscription = C.gql`{ nullable }`;
element.subscription = subscription;
await element.updateComplete;
expect(element.controller.subscription)
.to.equal(subscription)
.and.to.equal(element.controller.document);
});
it('as TypedDocumentNode', async function() {
const subscription = C.gql`{ nullable }` as C.TypedDocumentNode<{ a: 'b'}, {a: 'b'}>;
element.subscription = subscription;
await element.updateComplete;
expect(element.controller.subscription).to.equal(subscription);
const l = element as unknown as ApolloSubscriptionElement<typeof subscription>;
l.data = { a: 'b' };
// @ts-expect-error: can't assign bad data type
l.data = { b: 'c' };
// @ts-expect-error: can't assign bad variables type
l.variables = { b: 'c' };
});
it('as illegal value', async function() {
expect(() => {
// @ts-expect-error: can't assign bad variables type
element.subscription = 1;
}).to.throw(/Subscription must be a parsed GraphQL document./);
await element.updateComplete;
expect(element.subscription)
.to.be.null.and
.to.equal(element.document).and
.to.equal(element.controller.subscription).and
.to.equal(element.controller.document);
});
});
describe('setting error', function() {
it('as ApolloError', async function() {
let error: C.ApolloError;
try { throw new C.ApolloError({}); } catch (e) { error = e; }
element.error = error;
await element.updateComplete;
expect(element.controller.error).to.equal(error);
});
it('as Error', async function() {
let error: Error;
try {
throw new Error();
} catch (err) {
error = err;
element.error = error;
}
await element.updateComplete;
expect(element.controller.error).to.equal(error);
});
it('as null', async function() {
const error = null;
element.error = error;
await element.updateComplete;
expect(element.controller.error).to.equal(error);
});
it('as illegal value', async function() {
const error = 0;
// @ts-expect-error: test bad value
element.error = error;
await element.updateComplete;
expect(element.controller.error).to.equal(error);
});
});
});
describe('with "no-auto-subscribe" attribute', function() {
let element: ApolloSubscriptionElement;
beforeEach(async function() {
element = await fixture(html`
<apollo-subscription no-auto-subscribe>
<template>{{ data.noParam.noParam }}</template>
</apollo-subscription>
`);
});
beforeEach(nextFrame);
it('sets noAutoSubscribe', function() {
expect(element.noAutoSubscribe, 'element').to.be.true;
expect(element.controller.options.noAutoSubscribe, 'options').to.be.true;
});
describe('setting subscription', function() {
beforeEach(() => element.subscription = S.NoParamSubscription);
beforeEach(() => aTimeout(50));
it('doesn\'t render anything', function() {
expect(element).shadowDom.to.equal('');
});
describe('then calling subscribe()', function() {
beforeEach(() => element.subscribe());
beforeEach(() => aTimeout(50));
it('renders data', function() {
expect(element).shadowDom.to.equal('noParam');
});
});
});
});
describe('with template attribute set but empty', function() {
let element: ApolloSubscriptionElement;
beforeEach(async function() {
element = await fixture(html`<apollo-subscription template=""></apollo-subscription>`);
});
it('has null template', function() {
expect(element.template).to.be.null;
});
});
describe('with template attribute set but no template', function() {
let element: ApolloSubscriptionElement;
beforeEach(async function() {
element = await fixture(html`<apollo-subscription template="heh"></apollo-subscription>`);
});
it('has null template', function() {
expect(element.template).to.be.null;
});
});
describe('with `no-shadow` attribute set as a string', function() {
let element: ApolloSubscriptionElement;
beforeEach(async function() {
element = await fixture(html`<apollo-subscription no-shadow="special"></apollo-subscription>`);
});
it('creates a special div', function() {
expect(element.querySelector('.special')).to.be.ok;
});
});
describe('with template and subscription DOM and `no-shadow` attribute set', function() {
let element: ApolloSubscriptionElement<typeof S.NoParamSubscription>;
beforeEach(async function() {
element = await fixture(html`
<apollo-subscription no-shadow>
<script type="application/graphql">
subscription NoParamSubscription {
noParam {
noParam
}
}
</script>
<template>
<h1>Template</h1>
<span id="data">{{ data.noParam.noParam }}</span>
<span id="error">{{ error.message }}</span>
</template>
</apollo-subscription>
`);
});
beforeEach(() => aTimeout(50));
it('renders', function() {
expect(element.$$('h1').length, 'h1').to.equal(1);
expect(element.$$('span').length, 'span').to.equal(2);
expect(element.$('#data'), '#data').to.be.ok;
expect(element.$('#data')?.textContent, '#data').to.equal('noParam');
});
it('creates a subscription-result div', function() {
expect(element.querySelector('.output')).to.be.ok;
});
it('renders to the light DOM', function() {
expect(element.$('#data')).to.equal(element.querySelector('#data'));
});
it('does not blow away template', function() {
expect(element.template).to.be.an.instanceof(HTMLTemplateElement);
});
it('does not blow away subscription', function() {
expect(element.querySelector('script[type="application/graphql"]')).to.be.ok;
});
});
describe('with `no-shadow` and `template` attributes set', function() {
let element: ApolloSubscriptionElement<typeof S.NoParamSubscription>;
beforeEach(async function() {
element = await fixture(html`
<apollo-subscription no-shadow template="tpl" .subscription="${S.NoParamSubscription}"></apollo-subscription>
<template id="tpl">
<h1>Template</h1>
<span id="data">{{ data.noParam.noParam }}</span>
<span id="error">{{ error.message }}</span>
</template>
`);
});
beforeEach(() => aTimeout(50));
it('renders', function() {
expect(element.$$('h1').length, 'h1').to.equal(1);
expect(element.$$('span').length, 'span').to.equal(2);
expect(element.$('#data'), '#data').to.be.ok;
expect(element.$('#data')?.textContent, '#data').to.equal('noParam');
});
it('renders to the light DOM', function() {
expect(element.$('#data')).to.equal(element.querySelector('#data'));
});
it('does not blow away template', function() {
expect(element.template).to.be.an.instanceof(HTMLTemplateElement);
});
});
describe('with template in DOM and a subscription property', function() {
let element: ApolloSubscriptionElement<typeof S.NoParamSubscription>;
beforeEach(async function() {
element = await fixture(html`
<apollo-subscription .subscription="${S.NoParamSubscription}">
<template>
<h1>Template</h1>
<span id="data">{{ data.noParam.noParam }}</span>
<span id="error">{{ error.message }}</span>
</template>
</apollo-subscription>
`);
});
beforeEach(() => aTimeout(50));
it('renders', function() {
expect(element.$$('h1').length).to.equal(1);
expect(element.$$('span').length).to.equal(2);
expect(element.$('#data')).to.be.ok;
expect(element.$('#data')?.textContent).to.equal('noParam');
});
});
describe('with template, subscription, and variables in DOM', function() {
let element: ApolloSubscriptionElement<typeof S.NullableParamSubscription>;
beforeEach(async function() {
element = await fixture(html`
<apollo-subscription>
<script type="application/graphql">
subscription NullableParamSubscription($nullable: String) {
nullableParam(nullable: $nullable) {
nullable
}
}
</script>
<script type="application/json">
{
"nullable": "DOM"
}
</script>
<template>
<h1>Template</h1>
<span id="data">{{ data.nullableParam.nullable }}</span>
<span id="error">{{ error.message }}</span>
</template>
</apollo-subscription>
`);
});
beforeEach(() => aTimeout(50));
it('renders', function() {
expect(element.$$('h1').length).to.equal(1);
expect(element.$$('span').length).to.equal(2);
expect(element.$('#data')).to.be.ok;
expect(element.$('#data')?.textContent).to.equal('DOM');
});
describe('setting variables property', function() {
beforeEach(function() {
element.variables = { nullable: 'set by js' };
});
beforeEach(() => aTimeout(50));
it('rerenders', function() {
expect(element.$('#data')).to.be.ok;
expect(element.$('#data')?.textContent).to.equal('set by js');
});
});
});
describe('when subscription errors', function() {
let element: ApolloSubscriptionElement<typeof S.NullableParamSubscription>;
beforeEach(async function() {
element = await fixture(html`
<apollo-subscription
.subscription="${S.NullableParamSubscription}"
.variables="${{ nullable: 'error' }}">
<template>
<h1>Template</h1>
<span id="data">{{ data.nullableParam.nullable }}</span>
<span id="error">{{ error.message }}</span>
</template>
</apollo-subscription>
`);
});
beforeEach(nextFrame);
beforeEach(() => element.updateComplete);
it('renders', function() {
expect(element.$('#error')).to.be.ok;
expect(element.$('#error')?.textContent).to.equal('error');
});
});
describe('with a list rendering template', function() {
let element: ApolloSubscriptionElement;
beforeEach(async function() {
element = await fixture(html`
<apollo-subscription>
<template>
<p>{{ data.me.name }}</p>
<ul>
<template type="repeat" repeat="{{ data.friends || [] }}">
<li data-id="{{ item.id }}"
data-index="{{ index }}">{{ item.name }}</li>
</template>
</ul>
</template>
</apollo-subscription>
`);
});
describe('cancelling', function() {
beforeEach(() => element.cancel());
describe('then setting data', function() {
beforeEach(function() {
element.data = {
me: { name: 'ME' },
friends: [
{ id: 'friend-a', name: 'A' },
{ id: 'friend-b', name: 'B' },
{ id: 'friend-c', name: 'C' },
],
};
});
beforeEach(nextFrame);
it('renders the list', function() {
expect(element).shadowDom.to.equal(`
<p>ME</p>
<ul>
<li data-id="friend-a" data-index="0">A</li>
<li data-id="friend-b" data-index="1">B</li>
<li data-id="friend-c" data-index="2">C</li>
</ul>
`);
});
});
});
});
}); | the_stack |
import {LOCALES} from '../locales';
export default {
property: {
weight: 'pes',
label: 'etiqueta',
fillColor: 'color fons',
color: 'color',
coverage: 'cobertura',
strokeColor: 'color de traç',
radius: 'radi',
outline: 'outline',
stroke: 'traç',
density: 'densitat',
height: 'alçada',
sum: 'suma',
pointCount: 'Recompte de Punts'
},
placeholder: {
search: 'Cerca',
selectField: 'Selecciona un camp',
yAxis: 'Eix Y',
selectType: 'Selecciona un Tipus',
selectValue: 'Selecciona un Valor',
enterValue: 'Entra un valor',
empty: 'buit'
},
misc: {
by: '',
valuesIn: 'Valors a',
valueEquals: 'Valor igual a',
dataSource: 'Font de dades',
brushRadius: 'Radi del pinzell (km)',
empty: ' '
},
mapLayers: {
title: 'Capes del mapa',
label: 'Etiqueta',
road: 'Carretera',
border: 'Frontera',
building: 'Edifici',
water: 'Aigua',
land: 'Terra',
'3dBuilding': 'Edifici 3D'
},
panel: {
text: {
label: 'etiqueta',
labelWithId: 'Etiqueta {labelId}',
fontSize: 'Mida de la font',
fontColor: 'Color de la font',
textAnchor: 'Àncora del text',
alignment: 'Alineació',
addMoreLabel: 'Afegeix més etiquetes'
}
},
sidebar: {
panels: {
layer: 'Capes',
filter: 'Filtres',
interaction: 'Interaccions',
basemap: 'Mapa base'
}
},
layer: {
required: 'Requerit*',
radius: 'Radi',
color: 'Color',
fillColor: 'Color fons',
outline: 'Contorn',
weight: 'Gruix',
propertyBasedOn: '{property} basada en',
coverage: 'Cobertura',
stroke: 'Traç',
strokeWidth: 'Amplada de traç',
strokeColor: 'Color de traç',
basic: 'Basic',
trailLength: 'Longitud de pista',
trailLengthDescription: 'Nombre de segons fins que desapareix el camí',
newLayer: 'nova capa',
elevationByDescription: "Si desactivat, l'alçada es basa en el recompte de punts",
colorByDescription: 'Si desactivat, el color es basa en el recompte de punts',
aggregateBy: '{field} agregat per',
'3DModel': 'Model 3D',
'3DModelOptions': 'Opcions del model 3D',
type: {
point: 'punt',
arc: 'arc',
line: 'línia',
grid: 'malla',
hexbin: 'hexbin',
polygon: 'polígon',
geojson: 'geojson',
cluster: 'cluster',
icon: 'icona',
heatmap: 'heatmap',
hexagon: 'hexàgon',
hexagonid: 'H3',
trip: 'viatge',
s2: 'S2',
'3d': '3D'
}
},
layerVisConfigs: {
angle: 'Angle',
strokeWidth: 'Amplada traç',
strokeWidthRange: 'Rang amplada de traç',
radius: 'Radi',
fixedRadius: 'Radi fixe a mesurar',
fixedRadiusDescription: 'Ajusta el radi al radi absolut en metres, p.ex 5 a 5 metres',
radiusRange: 'Rang de radi',
clusterRadius: 'Radi Cluster en Pixels',
radiusRangePixels: 'Rang del radi en pixels',
opacity: 'Opacitat',
coverage: 'Cobertura',
outline: 'Outline',
colorRange: 'Rang de color',
stroke: 'Traç',
strokeColor: 'Color de traç',
strokeColorRange: 'Rang de color de traç',
targetColor: 'Color destí',
colorAggregation: 'Agregació de color',
heightAggregation: 'Agregació alçada',
resolutionRange: 'Rang de resolució',
sizeScale: 'Mida escala',
worldUnitSize: 'Mida de la unitat mundial',
elevationScale: 'Escala elevació',
enableElevationZoomFactor: 'Utilitzeu el factor de zoom d’elevació',
enableElevationZoomFactorDescription:
"'Ajusteu l'alçada / elevació en funció del factor de zoom actual",
enableHeightZoomFactor: 'Utilitzeu el factor de zoom d’alçada',
heightScale: 'Escala alçada',
coverageRange: 'Rang ed cobertura',
highPrecisionRendering: 'Representació alta precisió',
highPrecisionRenderingDescription: 'La precisió alta tindrà rendiment més baix',
height: 'Alçada',
heightDescription: 'Fes clic al botó a dalt a la dreta del mapa per canviar a vista 3D',
fill: 'Omple',
enablePolygonHeight: 'Activa alçada del polígon',
showWireframe: 'Mostra Wireframe',
weightIntensity: 'Intensitat de pes',
zoomScale: 'Escala de zoom',
heightRange: 'Rang alçada',
heightMultiplier: "Multiplicador d'alçada"
},
layerManager: {
addData: 'Afegeix Dades',
addLayer: 'Afegeix Capes',
layerBlending: 'Combinar capes'
},
mapManager: {
mapStyle: 'Estil de mapa',
addMapStyle: 'Afegeix estils de mapa',
'3dBuildingColor': 'Color edifici 3D'
},
layerConfiguration: {
defaultDescription: 'Calcula {property} segons el camp seleccionat',
howTo: 'How to'
},
filterManager: {
addFilter: 'Afegeix Filtre'
},
datasetTitle: {
showDataTable: 'Mostra taula de dades',
removeDataset: 'Elimina conjunt de dades'
},
datasetInfo: {
rowCount: '{rowCount} files'
},
tooltip: {
hideLayer: 'oculta la capa',
showLayer: 'mostra la capa',
hideFeature: "Amaga l'objecte",
showFeature: "Mostra l'objecte",
hide: 'amaga',
show: 'mostra',
removeLayer: 'Elimina capa',
layerSettings: 'Configuració de capa',
closePanel: 'Tanca panel actual',
switchToDualView: 'Canvia a la vista de mapa dual',
showLegend: 'mostra llegenda',
disable3DMap: 'Desactiva mapa 3D',
DrawOnMap: 'Dibuixa al mapa',
selectLocale: 'Selecciona configuració regional',
hideLayerPanel: 'Oculta el tauler de capes',
showLayerPanel: 'Mostra el tauler de capes',
moveToTop: 'Desplaça a dalt de tot de les capes de dades',
selectBaseMapStyle: 'Selecciona estil de mapa base',
delete: 'Esborra',
timePlayback: 'Reproducció de temps',
cloudStorage: 'Emmagatzematge al núvol',
'3DMap': 'Mapa 3D',
animationByWindow: 'Finestra Temporal Mòbil',
animationByIncremental: 'Finestra Temporal Incremental',
speed: 'velocitat',
play: 'iniciar',
pause: 'pausar',
reset: 'reiniciar'
},
toolbar: {
exportImage: 'Exporta imatge',
exportData: 'Exporta dades',
exportMap: 'Exporta mapa',
shareMapURL: 'Comparteix URL del mapa',
saveMap: 'Desa mapa',
select: 'selecciona',
polygon: 'polígon',
rectangle: 'rectangle',
hide: 'amaga',
show: 'mostra',
...LOCALES
},
modal: {
title: {
deleteDataset: 'Esborra conjunt de dades',
addDataToMap: 'Afegeix dades al mapa',
exportImage: 'Exporta imatge',
exportData: 'Exporta dades',
exportMap: 'Exporta mapa',
addCustomMapboxStyle: 'Afegeix estil Mapbox propi',
saveMap: 'Desa mapa',
shareURL: 'Comparteix URL'
},
button: {
delete: 'Esborra',
download: 'Descarrega',
export: 'Exporta',
addStyle: 'Afegeix estil',
save: 'Desa',
defaultCancel: 'Cancel·la',
defaultConfirm: 'Confirma'
},
exportImage: {
ratioTitle: 'Ràtio',
ratioDescription: 'Escull ràtio per diversos usos.',
ratioOriginalScreen: 'Pantalla original',
ratioCustom: 'Personalitzat',
ratio4_3: '4:3',
ratio16_9: '16:9',
resolutionTitle: 'Resolució',
resolutionDescription: 'Alta resolució és millor per a les impressions.',
mapLegendTitle: 'Llegenda del mapa',
mapLegendAdd: 'Afegir llegenda al mapa'
},
exportData: {
datasetTitle: 'Conjunt de dades',
datasetSubtitle: 'Escull els conjunts de dades que vols exportar',
allDatasets: 'Tots',
dataTypeTitle: 'Tipus de dades',
dataTypeSubtitle: 'Escull els tipus de dades que vols exportar',
filterDataTitle: 'Filtra dades',
filterDataSubtitle: 'Pots escollir exportar les dades originals o les filtrades',
filteredData: 'Dades filtrades',
unfilteredData: 'Dades sense filtrar',
fileCount: '{fileCount} Arxius',
rowCount: '{rowCount} Files'
},
deleteData: {
warning: "estàs a punt d'esborrar aquest conjunt de dades. Afectarà {length} capes"
},
addStyle: {
publishTitle: "2. Publica el teu estil a Mapbox o proporciona el token d'accés",
publishSubtitle1: 'Pots crear el teu propi estil de mapa a',
publishSubtitle2: 'i',
publishSubtitle3: 'publicar',
publishSubtitle4: 'ho.',
publishSubtitle5: 'Per utilitzar un estil privat, enganxa el teu',
publishSubtitle6: "token d'accés",
publishSubtitle7:
'aquí. *kepler.gl és una aplicació client, les dades romanen al teu navegador..',
exampleToken: 'p.ex. pk.abcdefg.xxxxxx',
pasteTitle: "1. Enganxa la URL de l'estil",
pasteSubtitle1: 'Què és un',
pasteSubtitle2: "URL de l'estil",
namingTitle: '3. Posa nom al teu estil'
},
shareMap: {
shareUriTitle: 'Comparteix URL del mapa',
shareUriSubtitle: 'Genera una URL del mapa per compartir amb altri',
cloudTitle: 'Emmagatzematge al núvol',
cloudSubtitle: 'Accedeix i carrega dades de mapa al teu emmagatzematge al núvol personal',
shareDisclaimer:
'kepler.gl desarà les dades del mapa al teu emmagatzematge al núvol personal, només qui tingui la URL podrà accedir al mapa i a les dades . ' +
"Pots editar/esborrar l'arxiu de dades en el teu compte al núvol en qualsevol moment.",
gotoPage: 'Ves a la pàgina de {currentProvider} de Kepler.gl'
},
statusPanel: {
mapUploading: 'Carregar un mapa',
error: 'Error'
},
saveMap: {
title: 'Emmagatzematge al núvol',
subtitle: 'Accedeix per desar el mapa al teu emmagatzematge al núvol'
},
exportMap: {
formatTitle: 'Format de mapa',
formatSubtitle: 'Escull el format amb què vols exportar el teu mapa',
html: {
selection: 'Exporta el teu mapa com un arxiu HTML interactiu.',
tokenTitle: "Token d'accés de Mapbox",
tokenSubtitle: "Utilitza el teu token d'accés de Mapbox a l'arxiu HTML (opcional)",
tokenPlaceholder: "Enganxa el teu token d'accés a Mapbox",
tokenMisuseWarning:
'* Si no proporciones el teu propi token, el mapa podria fallar en qualsevol moment quan reemplacem el nostre token per evitar abusos. ',
tokenDisclaimer:
'Pots canviar el toke de Mapbox més endavant fent servir aquestes instruccions: ',
tokenUpdate: 'Com actualitzar un token preexistent.',
modeTitle: 'Mode mapa',
modeSubtitle1: 'Selecciona mode app. Més ',
modeSubtitle2: 'informació',
modeDescription: 'Permet als usuaris {mode} el mapa',
read: 'llegir',
edit: 'editar'
},
json: {
configTitle: 'Configuració del mapa',
configDisclaimer:
"La configuració del mapa s'inclourà a l'arxiu Json. Si utilitzes kepler.gl a la teva pròpia app pots copiar aquesta configuració i passar-la a ",
selection:
'Exporta les dades del mapa i la configuració en un sol arxiu Json. Més endavant pots obrir aquest mateix mapa carregant aquest mateix arxiu a kepler.gl.',
disclaimer:
"* La configuració del mapa es combina amb els conjunts de dades carregats. ‘dataId’ s'utilitza per lligar capes, filtres i suggeriments a un conjunt de dades específic. " +
"Quan passis aquesta configuració a addDataToMap, assegura que l'identificador del conjunt de dades coincideixi amb els ‘dataId’ d'aquesta configuració."
}
},
loadingDialog: {
loading: 'Carregant...'
},
loadData: {
upload: 'Carregar arxius',
storage: "Carregar des d'emmagatzematge"
},
tripInfo: {
title: 'Com habilitar l’animació de viatge',
description1:
'Per animar la ruta, les dades geoJSON han de contenir `LineString` en la seva geometria i les coordenades de LineString han de tenir 4 elements en els formats de ',
code: ' [longitude, latitude, altitude, timestamp] ',
description2:
'i el darrer element ha de ser la marca de temps. Els formats vàlids per a la marca de temps inclouen Unix en segons com `1564184363` o en milisegons com `1564184363000`.',
example: 'Exemple:'
},
iconInfo: {
title: 'Com dibuixar icones',
description1:
"En el teu CSV crea una columna i posa-hi el nom de la icona que vols dibuixar. Pots deixar la cel·la buida quan no vulguis que es mostri per a certs punts. Quan la columna s'anomena",
code: 'icon',
description2: " kepler.gl automàticament crearà una capa d'icona.",
example: 'Exemple:',
icons: 'Icones'
},
storageMapViewer: {
lastModified: 'Darrera modificació fa {lastUpdated}',
back: 'Enrere'
},
overwriteMap: {
title: 'Desant mapa...',
alreadyExists: 'ja existeix a {mapSaved}. El vols sobreescriure?'
},
loadStorageMap: {
back: 'Enrere',
goToPage: 'Ves a la pàgina {displayName} de Kepler.gl',
storageMaps: 'Emmagatzematge / Mapes',
noSavedMaps: 'Cap mapa desat encara'
}
},
header: {
visibleLayers: 'Capes visibles',
layerLegend: 'Llegenda de capes'
},
interactions: {
tooltip: 'Suggeriment',
brush: 'Pinzell',
coordinate: 'Coordenades',
geocoder: 'Geocodificador'
},
layerBlending: {
title: 'Combinació de capes',
additive: 'additiva',
normal: 'normal',
subtractive: 'substractiva'
},
columns: {
title: 'Columnes',
lat: 'lat',
lng: 'lon',
altitude: 'alçada',
icon: 'icona',
geojson: 'geojson',
arc: {
lat0: 'lat origen',
lng0: 'lng origen ',
lat1: 'lat destinació',
lng1: 'lng destinació'
},
line: {
alt0: 'alçada origen',
alt1: 'alçada destinació'
},
grid: {
worldUnitSize: 'Mida de malla (km)'
},
hexagon: {
worldUnitSize: "Radi d'hexàgon (km)"
},
hex_id: 'id hex'
},
color: {
customPalette: 'Paleta personalitzada',
steps: 'intervals',
type: 'tipus',
reversed: 'invertida'
},
scale: {
colorScale: 'Escala de color',
sizeScale: 'Escala de mides',
strokeScale: 'Escala de traç',
scale: 'Escala'
},
fileUploader: {
message: "Arrossega i deixa anar l'arxiu aquí",
chromeMessage:
'*usuari de Chrome: la mida màxima són 250mb, si has de carrgar un arxiu més gran fes servir Safari',
disclaimer:
'*kepler.gl és una aplicació a la banda client que no es recolza en cap servidor. Les dades només existeixen a la teva màquina/navegador. ' +
"No s'envien dades ni mapes a cap servidor.",
configUploadMessage:
'Carrega {fileFormatNames} o un mapa desat en **Json**. Més informació sobre [**supported file formats**]',
browseFiles: 'navega pels teus arxius',
uploading: 'Carregant',
fileNotSupported: "L'arxiu {errorFiles} no és compatible.",
or: 'o'
},
geocoder: {
title: 'Introdueix una adreça'
},
fieldSelector: {
clearAll: 'Treure tots',
formatting: 'Format'
},
compare: {
modeLabel: 'Mode Comparació',
typeLabel: 'Tipus de Comparació',
types: {
absolute: 'Absoluta',
relative: 'Relativa'
}
},
mapPopover: {
primary: 'Principal'
},
density: 'densitat',
'Bug Report': "Informe d'errors",
'User Guide': "Guia d'usuari",
Save: 'Desa',
Share: 'Comparteix'
}; | the_stack |
import React from 'react'
import { expect, mount, stub, wait } from '@instructure/ui-test-utils'
import { TreeBrowser } from '../index'
import { TreeNode } from '../TreeNode'
import { TreeBrowserLocator } from '../TreeBrowserLocator'
const COLLECTIONS_DATA = {
2: { id: 2, name: 'Root Directory', collections: [3, 4], items: [1] },
3: { id: 3, name: 'Sub Root 1', collections: [5] },
4: { id: 4, name: 'Sub Root 2' },
5: { id: 5, name: 'Nested Sub Collection' }
}
const COLLECTIONS_DATA_WITH_ZERO = {
0: { id: 0, name: 'Root Directory', collections: [3, 4], items: [1] },
3: { id: 3, name: 'Sub Root 1', collections: [5] },
4: { id: 4, name: 'Sub Root 2' },
5: { id: 5, name: 'Nested Sub Collection' }
}
const COLLECTIONS_DATA_WITH_STRING_IDS = {
'2': { id: '2', name: 'Root Directory', collections: ['3', '4'], items: [1] },
'3': { id: '3', name: 'Sub Root 1', collections: ['5'] },
'4': { id: '4', name: 'Sub Root 2' },
'5': { id: '5', name: 'Nested Sub Collection' }
}
const ITEMS_DATA = {
1: { id: 1, name: 'Item 1' }
}
describe('<TreeBrowser />', async () => {
it('should render a tree', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
/>
)
const tree = await TreeBrowserLocator.find()
expect(tree).to.exist()
})
it('should render subcollections', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
/>
)
const tree = await TreeBrowserLocator.find()
const items = await tree.findAllItems()
expect(items.length).to.equal(1)
await items[0].click()
const itemsAfterClick = await tree.findAllItems()
expect(itemsAfterClick.length).to.equal(4)
})
it('should render all collections at top level if showRootCollection is true and rootId is undefined', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={undefined}
/>
)
const tree = await TreeBrowserLocator.find()
const items = await tree.findAllItems()
expect(items.length).to.equal(4)
})
describe('expanded', async () => {
it('should not expand collections or items without defaultExpanded prop', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
/>
)
const tree = await TreeBrowserLocator.find()
const items = await tree.findAllItems()
await wait(() => {
expect(items.length).to.equal(1)
expect(items[0]).to.have.text('Root Directory')
})
})
it('should accept an array of default expanded collections', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
defaultExpanded={[2, 3]}
/>
)
const tree = await TreeBrowserLocator.find()
const items = await tree.findAllItems()
expect(items.length).to.equal(5)
expect(await tree.findItem(':label(Sub Root 2)')).to.exist()
expect(await tree.findItem(':label(Nested Sub Collection)')).to.exist()
})
it('should persist the state of expanded children when parent collapsed', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
/>
)
const tree = await TreeBrowserLocator.find()
const items = await tree.findAllItems()
const rootCollection = items[0]
await rootCollection.click()
expect((await tree.findAllItems()).length).to.equal(4)
const subCollection = await tree.findItem(':label(Sub Root 1)')
await subCollection.click()
expect((await tree.findAllItems()).length).to.equal(5)
await rootCollection.click()
expect((await tree.findAllItems()).length).to.equal(1)
await rootCollection.click()
expect((await tree.findAllItems()).length).to.equal(5)
})
it('should not update expanded on click when set as explicit prop', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
expanded={[2]}
/>
)
const tree = await TreeBrowserLocator.find()
const items = await tree.findAllItems()
expect(items.length).to.equal(4)
await items[0].click()
expect((await tree.findAllItems()).length).to.equal(4)
await (await tree.findItem(':label(Sub Root 1)')).click()
expect((await tree.findAllItems()).length).to.equal(4)
expect(
await tree.findItem(':label(Nested Sub Collection)', {
expectEmpty: true
})
).to.not.exist()
})
})
describe('selected', async () => {
it('should not show the selection if selectionType is none', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
/>
)
const tree = await TreeBrowserLocator.find()
const item = await tree.findItem()
item.click()
await wait(() => {
expect(item).to.not.have.attribute('aria-selected')
})
})
it('should show the selection indicator on last clicked collection or item', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
selectionType="single"
/>
)
const tree = await TreeBrowserLocator.find()
const item = await tree.findItem(':label(Root Directory)')
await item.click()
await wait(() => {
expect(item).to.have.attribute('aria-selected')
})
const nestedItem = await tree.findItem(':label(Item 1)')
await nestedItem.click()
await wait(() => {
expect(nestedItem).to.have.attribute('aria-selected')
})
})
})
describe('collections', async () => {
it('should render collections with string-keyed ids', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA_WITH_STRING_IDS}
items={ITEMS_DATA}
rootId={'2'}
showRootCollection={true}
/>
)
const tree = await TreeBrowserLocator.find()
const item = await tree.findItem(':label(Root Directory)')
expect(item).to.exist()
})
it('should not show the first keyed collection if showRootCollection is false', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
showRootCollection={false}
/>
)
const tree = await TreeBrowserLocator.find()
const items = await tree.findAllItems()
expect(items.length).to.equal(3)
})
it('should render first keyed collection if showRootCollection is true and rootId specified', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
/>
)
const tree = await TreeBrowserLocator.find()
const item = await tree.findItem(':label(Root Directory)')
expect(item).to.exist()
})
it('should not show the first keyed collection if showRootCollection is false and rootId is 0', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA_WITH_ZERO}
items={ITEMS_DATA}
rootId={0}
showRootCollection={false}
/>
)
const tree = await TreeBrowserLocator.find()
const items = await tree.findAllItems()
expect(items.length).to.equal(3)
})
it('should render a folder icon by default', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
/>
)
const tree = await TreeBrowserLocator.find()
const iconFolder = await tree.findAll('[name="IconFolder"]')
expect(iconFolder.length).to.equal(1)
})
it('should render a custom icon', async () => {
const IconCustom = (
<svg height="100" width="100">
<title>Custom icon</title>
<circle cx="50" cy="50" r="40" />
</svg>
)
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
collectionIcon={() => IconCustom}
/>
)
const tree = await TreeBrowserLocator.find()
const item = await tree.findItem(':label(Root Directory)')
const icons = await item.findAll('svg:title(Custom icon)')
expect(icons.length).to.equal(1)
})
it('should render without icon if set to null', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
collectionIcon={null}
/>
)
const tree = await TreeBrowserLocator.find()
expect(await tree.find('svg', { expectEmpty: true })).to.not.exist()
})
it('should call onCollectionToggle when expanding and collapsing with mouse', async () => {
const onCollectionToggle = stub()
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
onCollectionToggle={onCollectionToggle}
/>
)
const tree = await TreeBrowserLocator.find()
const item = await tree.findItem()
await item.click()
await wait(() => {
expect(onCollectionToggle).to.have.been.called()
})
})
it('should call onCollectionToggle on arrow key expansion or collapse', async () => {
const onCollectionToggle = stub()
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
onCollectionToggle={onCollectionToggle}
/>
)
const tree = await TreeBrowserLocator.find()
const item = await tree.find(':label(Root Directory)')
await item.focus()
await wait(() => {
// @ts-expect-error This is intentionally overridden in assertions.ts
expect(item).to.contain.focus()
})
await item.keyDown('right')
await item.keyDown('left')
await item.keyDown('left')
await wait(() => {
expect(onCollectionToggle).to.have.been.calledTwice()
})
})
it('should call onCollectionClick on button activation (space/enter or click)', async () => {
const onCollectionClick = stub()
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
onCollectionClick={onCollectionClick}
/>
)
const tree = await TreeBrowserLocator.find()
const item = await tree.findItem(':label(Root Directory)')
await item.click()
await item.keyDown('space')
await item.keyDown('enter')
await wait(() => {
expect(onCollectionClick).to.have.been.calledThrice()
})
})
it('should render before, after nodes of the provided collection', async () => {
await mount(
<TreeBrowser
collections={{
2: {
id: 2,
name: 'Root Directory',
collections: [],
items: [],
renderBeforeItems: (
<TreeNode>
<input id="input-before" />
</TreeNode>
),
renderAfterItems: (
<TreeNode>
<input id="input-after" />
</TreeNode>
)
}
}}
items={{}}
expanded={[2]}
rootId={2}
/>
)
const tree = await TreeBrowserLocator.find()
const contentBefore = await tree.find('#input-before')
expect(contentBefore).to.exist()
const contentAfter = await tree.find('#input-after')
expect(contentAfter).to.exist()
})
})
describe('items', async () => {
it('should render a document icon by default', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
defaultExpanded={[2]}
/>
)
const tree = await TreeBrowserLocator.find()
const iconDoc = await tree.findAll('[name="IconDocument"]')
expect(iconDoc.length).to.equal(1)
})
it('should render a custom icon', async () => {
const IconCustom = (
<svg height="100" width="100">
<title>Custom icon</title>
<circle cx="50" cy="50" r="40" />
</svg>
)
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
defaultExpanded={[2]}
itemIcon={() => IconCustom}
/>
)
const tree = await TreeBrowserLocator.find()
const item = await tree.findItem(':label(Item 1)')
const icons = await item.findAll('svg:title(Custom icon)')
expect(icons.length).to.equal(1)
})
it('should render without icon if set to null', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
/>
)
const tree = await TreeBrowserLocator.find()
const icon = await tree.find('[name="IconDocument"]', {
expectEmpty: true
})
expect(icon).to.not.exist()
})
})
describe('for a11y', async () => {
it('should meet a11y standards', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
/>
)
const tree = await TreeBrowserLocator.find()
expect(await tree.accessible()).to.be.true()
})
it('should accept a treeLabel prop', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
treeLabel="Test treeLabel"
/>
)
const tree = await TreeBrowserLocator.find(':label(Test treeLabel)')
expect(tree).to.exist()
})
it('should toggle aria-expanded', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
/>
)
const tree = await TreeBrowserLocator.find()
const item = await tree.findItem()
await wait(() => {
expect(item).to.have.attribute('aria-expanded', 'false')
})
await item.click()
await wait(() => {
expect(item).to.have.attribute('aria-expanded', 'true')
})
})
it('should use aria-selected when selectionType is not none', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
selectionType="single"
/>
)
const tree = await TreeBrowserLocator.find()
const item = await tree.findItem()
expect(item).to.not.have.attribute('aria-selected')
await item.click()
await wait(() => {
expect(item).to.have.attribute('aria-selected', 'true')
})
const nestedItem = await tree.findItem(':label(Sub Root 1)')
await wait(() => {
expect(nestedItem).to.have.attribute('aria-selected', 'false')
})
})
it('should move focus with the up/down arrow keys', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
defaultExpanded={[2]}
/>
)
const tree = await TreeBrowserLocator.find(':focusable')
const items = await tree.findAllItems()
await tree.focus()
await wait(() => {
expect(tree.focused()).to.be.true()
})
await tree.keyDown('down')
await wait(() => {
expect(items[0].focused()).to.be.true()
})
await tree.keyDown('down')
await wait(() => {
expect(items[0].focused()).to.be.false()
expect(items[1].focused()).to.be.true()
})
await tree.keyDown('up')
await wait(() => {
expect(items[0].focused()).to.be.true()
})
})
it('should move focus via keyboard shortcuts', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
defaultExpanded={[2]}
/>
)
const tree = await TreeBrowserLocator.find()
const items = await tree.findAllItems()
await tree.focus()
await wait(() => {
expect(tree.focused()).to.be.true()
})
await tree.keyDown('j')
await wait(() => {
expect(items[0].focused()).to.be.true()
})
await tree.keyDown('j')
await wait(() => {
expect(items[0].focused()).to.be.false()
expect(items[1].focused()).to.be.true()
})
await tree.keyDown('k')
await wait(() => {
expect(items[0].focused()).to.be.true()
})
})
it('should open collapsed collection with right arrow', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
/>
)
const tree = await TreeBrowserLocator.find()
const items = await tree.findAllItems()
expect(items.length).to.equal(1)
await items[0].focus()
await wait(() => {
expect(items[0].focused()).to.be.true()
})
await items[0].keyDown('right')
expect((await tree.findAllItems()).length).to.equal(4)
})
it('should move focus down when right arrow is pressed on expanded collection', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
defaultExpanded={[2]}
/>
)
const tree = await TreeBrowserLocator.find()
const items = await tree.findAllItems()
expect(items.length).to.equal(4)
await items[0].focus()
await wait(() => {
expect(items[0].focused()).to.be.true()
})
await items[0].keyDown('right')
await wait(() => {
expect(items[1].focused()).to.be.true()
})
expect((await tree.findAllItems()).length).to.equal(4)
})
it('should collapse expanded collection when left arrow is pressed', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
defaultExpanded={[2]}
/>
)
const tree = await TreeBrowserLocator.find()
const items = await tree.findAllItems()
expect(items.length).to.equal(4)
await items[0].focus()
await items[0].keyDown('left')
await wait(() => {
expect(items[0].focused()).to.be.true()
})
expect((await tree.findAllItems()).length).to.equal(1)
})
it('should move focus up when left arrow is pressed on collapsed collection', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
defaultExpanded={[2]}
/>
)
const tree = await TreeBrowserLocator.find()
const items = await tree.findAllItems()
expect(items.length).to.equal(4)
const firstItem = items[0]
const secondItem = items[1]
await secondItem.focus()
await secondItem.keyDown('left')
await wait(() => {
expect(firstItem.focused()).to.be.true()
})
expect((await tree.findAllItems()).length).to.equal(4)
})
it('should select the node on enter or space if selectionType is not "none"', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
defaultExpanded={[2]}
selectionType="single"
/>
)
const tree = await TreeBrowserLocator.find()
const items = await tree.findAllItems()
const firstItem = items[0]
const secondItem = items[1]
await firstItem.focus()
await firstItem.keyDown('enter')
await wait(() => {
expect(firstItem).to.have.attribute('aria-selected', 'true')
})
await secondItem.focus()
await secondItem.keyDown('space')
await wait(() => {
expect(secondItem).to.have.attribute('aria-selected', 'true')
})
})
it('should not expand the node on enter or space if selectionType is not "none"', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
selectionType="single"
/>
)
const tree = await TreeBrowserLocator.find()
const items = await tree.findAllItems()
expect(items.length).to.equal(1)
const firstItem = items[0]
await firstItem.focus()
await firstItem.keyDown('enter')
expect((await tree.findAllItems()).length).to.equal(1)
})
it('should move to the top node without expanding/collapsing anything when home is pressed', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
defaultExpanded={[2]}
/>
)
const tree = await TreeBrowserLocator.find()
const items = await tree.findAllItems()
expect(items.length).to.equal(4)
const firstItem = items[0]
const lastItem = items[3]
await lastItem.focus()
await firstItem.keyDown('home')
expect(firstItem.focused()).to.be.true()
expect((await tree.findAllItems()).length).to.equal(4)
})
it('should move to the bottom node without expanding/collapsing anything when end is pressed', async () => {
await mount(
<TreeBrowser
collections={COLLECTIONS_DATA}
items={ITEMS_DATA}
rootId={2}
defaultExpanded={[2]}
/>
)
const tree = await TreeBrowserLocator.find()
const items = await tree.findAllItems()
const firstItem = items[0]
const lastItem = items[3]
await firstItem.focus()
await firstItem.keyDown('end')
expect(lastItem.focused()).to.be.true()
expect((await tree.findAllItems()).length).to.equal(4)
})
})
describe('sorting', async () => {
it("should present collections and items in alphabetical order, in spite of the order of 'collections' and 'items' arrays", async () => {
await mount(
<TreeBrowser
collections={{
1: {
id: 1,
name: 'Assignments',
collections: [5, 3, 2, 4],
items: [3, 5, 2, 1, 4]
},
2: {
id: 2,
name: 'English Assignments',
collections: [],
items: []
},
3: { id: 3, name: 'Math Assignments', collections: [], items: [] },
4: {
id: 4,
name: 'Reading Assignments',
collections: [],
items: []
},
5: { id: 5, name: 'Advanced Math Assignments', items: [] }
}}
items={{
1: { id: 1, name: 'Addition Worksheet' },
2: { id: 2, name: 'Subtraction Worksheet' },
3: { id: 3, name: 'General Questions' },
4: { id: 4, name: 'Vogon Poetry' },
5: { id: 5, name: 'Bistromath' }
}}
rootId={1}
defaultExpanded={[1]}
sortOrder={(a, b) => {
return a.name.localeCompare(b.name)
}}
/>
)
const tree = await TreeBrowserLocator.find()
const items = await tree.findAllItems()
const arr = items.map((item) => item.getDOMNode().textContent)
expect(arr.slice(1, 5)).deep.equal([
'Advanced Math Assignments',
'English Assignments',
'Math Assignments',
'Reading Assignments'
])
expect(arr.slice(5)).deep.equal([
'Addition Worksheet',
'Bistromath',
'General Questions',
'Subtraction Worksheet',
'Vogon Poetry'
])
})
})
}) | the_stack |
import * as _ from 'lodash';
import { SinonStub, stub } from 'sinon';
import { expect } from 'chai';
import { StatusCodeError, UpdatesLockedError } from '../src/lib/errors';
import prepare = require('./lib/prepare');
import * as dockerUtils from '../src/lib/docker-utils';
import * as config from '../src/config';
import * as images from '../src/compose/images';
import { ConfigTxt } from '../src/config/backends/config-txt';
import * as deviceState from '../src/device-state';
import * as deviceConfig from '../src/device-config';
import { loadTargetFromFile } from '../src/device-state/preload';
import Service from '../src/compose/service';
import { intialiseContractRequirements } from '../src/lib/contracts';
import * as updateLock from '../src/lib/update-lock';
const mockedInitialConfig = {
RESIN_SUPERVISOR_CONNECTIVITY_CHECK: 'true',
RESIN_SUPERVISOR_DELTA: 'false',
RESIN_SUPERVISOR_DELTA_APPLY_TIMEOUT: '0',
RESIN_SUPERVISOR_DELTA_REQUEST_TIMEOUT: '30000',
RESIN_SUPERVISOR_DELTA_RETRY_COUNT: '30',
RESIN_SUPERVISOR_DELTA_RETRY_INTERVAL: '10000',
RESIN_SUPERVISOR_DELTA_VERSION: '2',
RESIN_SUPERVISOR_INSTANT_UPDATE_TRIGGER: 'true',
RESIN_SUPERVISOR_LOCAL_MODE: 'false',
RESIN_SUPERVISOR_LOG_CONTROL: 'true',
RESIN_SUPERVISOR_OVERRIDE_LOCK: 'false',
RESIN_SUPERVISOR_POLL_INTERVAL: '60000',
RESIN_SUPERVISOR_VPN_CONTROL: 'true',
};
const testTarget2 = {
local: {
name: 'aDeviceWithDifferentName',
config: {
RESIN_HOST_CONFIG_gpu_mem: '512',
},
apps: {
'1234': {
name: 'superapp',
commit: 'afafafa',
releaseId: 2,
services: {
'23': {
serviceName: 'aservice',
imageId: 12345,
image: 'registry2.resin.io/superapp/edfabc',
environment: {
FOO: 'bar',
},
labels: {},
},
'24': {
serviceName: 'anotherService',
imageId: 12346,
image: 'registry2.resin.io/superapp/afaff',
environment: {
FOO: 'bro',
},
labels: {},
},
},
volumes: {},
networks: {},
},
},
},
dependent: { apps: {}, devices: {} },
};
const testTargetWithDefaults2 = {
local: {
name: 'aDeviceWithDifferentName',
config: {
HOST_CONFIG_gpu_mem: '512',
HOST_FIREWALL_MODE: 'off',
HOST_DISCOVERABILITY: 'true',
SUPERVISOR_CONNECTIVITY_CHECK: 'true',
SUPERVISOR_DELTA: 'false',
SUPERVISOR_DELTA_APPLY_TIMEOUT: '0',
SUPERVISOR_DELTA_REQUEST_TIMEOUT: '30000',
SUPERVISOR_DELTA_RETRY_COUNT: '30',
SUPERVISOR_DELTA_RETRY_INTERVAL: '10000',
SUPERVISOR_DELTA_VERSION: '2',
SUPERVISOR_INSTANT_UPDATE_TRIGGER: 'true',
SUPERVISOR_LOCAL_MODE: 'false',
SUPERVISOR_LOG_CONTROL: 'true',
SUPERVISOR_OVERRIDE_LOCK: 'false',
SUPERVISOR_POLL_INTERVAL: '60000',
SUPERVISOR_VPN_CONTROL: 'true',
SUPERVISOR_PERSISTENT_LOGGING: 'false',
},
apps: {
'1234': {
appId: 1234,
name: 'superapp',
commit: 'afafafa',
releaseId: 2,
services: [
_.merge(
{ appId: 1234, serviceId: 23, releaseId: 2 },
_.clone(testTarget2.local.apps['1234'].services['23']),
),
_.merge(
{ appId: 1234, serviceId: 24, releaseId: 2 },
_.clone(testTarget2.local.apps['1234'].services['24']),
),
],
volumes: {},
networks: {},
},
},
},
};
const testTargetInvalid = {
local: {
name: 'aDeviceWithDifferentName',
config: {
RESIN_HOST_CONFIG_gpu_mem: '512',
},
apps: {
1234: {
appId: '1234',
name: 'superapp',
commit: 'afafafa',
releaseId: '2',
config: {},
services: {
23: {
serviceId: '23',
serviceName: 'aservice',
imageId: '12345',
image: 'registry2.resin.io/superapp/edfabc',
config: {},
environment: {
' FOO': 'bar',
},
labels: {},
},
24: {
serviceId: '24',
serviceName: 'anotherService',
imageId: '12346',
image: 'registry2.resin.io/superapp/afaff',
config: {},
environment: {
FOO: 'bro',
},
labels: {},
},
},
},
},
},
dependent: { apps: {}, devices: {} },
};
describe('deviceState', () => {
let source: string;
const originalImagesSave = images.save;
const originalImagesInspect = images.inspectByName;
const originalGetCurrent = deviceConfig.getCurrent;
before(async () => {
await prepare();
await config.initialized;
await deviceState.initialized;
source = await config.get('apiEndpoint');
stub(Service as any, 'extendEnvVars').callsFake((env) => {
env['ADDITIONAL_ENV_VAR'] = 'foo';
return env;
});
intialiseContractRequirements({
supervisorVersion: '11.0.0',
deviceType: 'intel-nuc',
});
stub(dockerUtils, 'getNetworkGateway').returns(
Promise.resolve('172.17.0.1'),
);
// @ts-expect-error Assigning to a RO property
images.cleanImageData = () => {
console.log('Cleanup database called');
};
// @ts-expect-error Assigning to a RO property
images.save = () => Promise.resolve();
// @ts-expect-error Assigning to a RO property
images.inspectByName = () => {
const err: StatusCodeError = new Error();
err.statusCode = 404;
return Promise.reject(err);
};
// @ts-expect-error Assigning to a RO property
deviceConfig.configBackend = new ConfigTxt();
// @ts-expect-error Assigning to a RO property
deviceConfig.getCurrent = async () => mockedInitialConfig;
});
after(() => {
(Service as any).extendEnvVars.restore();
(dockerUtils.getNetworkGateway as sinon.SinonStub).restore();
// @ts-expect-error Assigning to a RO property
images.save = originalImagesSave;
// @ts-expect-error Assigning to a RO property
images.inspectByName = originalImagesInspect;
// @ts-expect-error Assigning to a RO property
deviceConfig.getCurrent = originalGetCurrent;
});
beforeEach(async () => {
await prepare();
});
it('loads a target state from an apps.json file and saves it as target state, then returns it', async () => {
await loadTargetFromFile(process.env.ROOT_MOUNTPOINT + '/apps.json');
const targetState = await deviceState.getTarget();
expect(targetState)
.to.have.property('local')
.that.has.property('apps')
.that.has.property('1234')
.that.is.an('object');
const app = targetState.local.apps[1234];
expect(app).to.have.property('appName').that.equals('superapp');
expect(app).to.have.property('services').that.is.an('array').with.length(1);
expect(app.services[0])
.to.have.property('config')
.that.has.property('image')
.that.equals('registry2.resin.io/superapp/abcdef:latest');
expect(app.services[0].config)
.to.have.property('labels')
.that.has.property('io.balena.something')
.that.equals('bar');
expect(app).to.have.property('appName').that.equals('superapp');
expect(app).to.have.property('services').that.is.an('array').with.length(1);
expect(app.services[0])
.to.have.property('config')
.that.has.property('image')
.that.equals('registry2.resin.io/superapp/abcdef:latest');
expect(app.services[0].config)
.to.have.property('labels')
.that.has.property('io.balena.something')
.that.equals('bar');
expect(app).to.have.property('appName').that.equals('superapp');
expect(app).to.have.property('services').that.is.an('array').with.length(1);
expect(app.services[0])
.to.have.property('config')
.that.has.property('image')
.that.equals('registry2.resin.io/superapp/abcdef:latest');
expect(app.services[0].config)
.to.have.property('labels')
.that.has.property('io.balena.something')
.that.equals('bar');
expect(app).to.have.property('appName').that.equals('superapp');
expect(app).to.have.property('services').that.is.an('array').with.length(1);
expect(app.services[0])
.to.have.property('config')
.that.has.property('image')
.that.equals('registry2.resin.io/superapp/abcdef:latest');
expect(app.services[0].config)
.to.have.property('labels')
.that.has.property('io.balena.something')
.that.equals('bar');
expect(app).to.have.property('appName').that.equals('superapp');
expect(app).to.have.property('services').that.is.an('array').with.length(1);
expect(app.services[0])
.to.have.property('config')
.that.has.property('image')
.that.equals('registry2.resin.io/superapp/abcdef:latest');
expect(app.services[0].config)
.to.have.property('labels')
.that.has.property('io.balena.something')
.that.equals('bar');
});
it('stores info for pinning a device after loading an apps.json with a pinDevice field', async () => {
await loadTargetFromFile(process.env.ROOT_MOUNTPOINT + '/apps-pin.json');
const pinned = await config.get('pinDevice');
expect(pinned).to.have.property('app').that.equals(1234);
expect(pinned).to.have.property('commit').that.equals('abcdef');
});
it('emits a change event when a new state is reported', (done) => {
deviceState.once('change', done);
deviceState.reportCurrentState({ someStateDiff: 'someValue' } as any);
});
it.skip('writes the target state to the db with some extra defaults', async () => {
const testTarget = _.cloneDeep(testTargetWithDefaults2);
const services: Service[] = [];
for (const service of testTarget.local.apps['1234'].services) {
const imageName = await images.normalise(service.image);
service.image = imageName;
(service as any).imageName = imageName;
services.push(
await Service.fromComposeObject(service, {
appName: 'supertest',
} as any),
);
}
(testTarget as any).local.apps['1234'].services = _.keyBy(
services,
'serviceId',
);
(testTarget as any).local.apps['1234'].source = source;
await deviceState.setTarget(testTarget2);
const target = await deviceState.getTarget();
expect(JSON.parse(JSON.stringify(target))).to.deep.equal(
JSON.parse(JSON.stringify(testTarget)),
);
});
it('does not allow setting an invalid target state', () => {
expect(deviceState.setTarget(testTargetInvalid as any)).to.be.rejected;
});
it('allows triggering applying the target state', (done) => {
const applyTargetStub = stub(deviceState, 'applyTarget').returns(
Promise.resolve(),
);
deviceState.triggerApplyTarget({ force: true });
expect(applyTargetStub).to.not.be.called;
setTimeout(() => {
expect(applyTargetStub).to.be.calledWith({
force: true,
initial: false,
});
applyTargetStub.restore();
done();
}, 1000);
});
// TODO: There is no easy way to test this behaviour with the current
// interface of device-state. We should really think about the device-state
// interface to allow this flexibility (and to avoid having to change module
// internal variables)
it.skip('cancels current promise applying the target state');
it.skip('applies the target state for device config');
it.skip('applies the target state for applications');
it('prevents reboot or shutdown when HUP rollback breadcrumbs are present', async () => {
const testErrMsg = 'Waiting for Host OS updates to finish';
stub(updateLock, 'abortIfHUPInProgress').throws(
new UpdatesLockedError(testErrMsg),
);
await expect(deviceState.reboot())
.to.eventually.be.rejectedWith(testErrMsg)
.and.be.an.instanceOf(UpdatesLockedError);
await expect(deviceState.shutdown())
.to.eventually.be.rejectedWith(testErrMsg)
.and.be.an.instanceOf(UpdatesLockedError);
(updateLock.abortIfHUPInProgress as SinonStub).restore();
});
}); | the_stack |
import { RepresentationRegistry, ColormakerRegistry } from '../globals'
import { defaults } from '../utils'
import LabelFactory, { LabelType } from '../utils/label-factory'
import RadiusFactory from '../utils/radius-factory'
import StructureRepresentation, { StructureRepresentationData } from './structure-representation'
import TextBuffer, { TextBufferData } from '../buffer/text-buffer'
import { RepresentationParameters } from './representation';
import { Structure } from '../ngl';
import Viewer from '../viewer/viewer';
import StructureView from '../structure/structure-view';
export interface TextDataField {
position?: boolean
color?: boolean
radius?: boolean
text?: boolean
}
/**
* Label representation parameter object. Extends {@link RepresentationParameters} and
* {@link StructureRepresentationParameters}.
*
* @typedef {Object} LabelRepresentationParameters - label representation parameters
*
* @property {Integer} clipNear - position of camera near/front clipping plane
* in percent of scene bounding box
* @property {Float} opacity - translucency: 1 is fully opaque, 0 is fully transparent
* @property {String} labelType - type of the label, one of:
* "atomname", "atomindex", "occupancy", "bfactor",
* "serial", "element", "atom", "resname", "resno",
* "res", "text", "qualified". When set to "text", the
* `labelText` list is used.
* @property {String[]} labelText - list of label strings, must set `labelType` to "text"
* to take effect
* @property {String[]} labelFormat - sprintf-js format string, any attribute of
* {@link AtomProxy} can be used
* @property {String} labelGrouping - grouping of the label, one of:
* "atom", "residue".
* @property {String} fontFamily - font family, one of: "sans-serif", "monospace", "serif"
* @property {String} fontStyle - font style, "normal" or "italic"
* @property {String} fontWeight - font weight, "normal" or "bold"
* @property {Float} xOffset - offset in x-direction
* @property {Float} yOffset - offset in y-direction
* @property {Float} zOffset - offset in z-direction (i.e. in camera direction)
* @property {String} attachment - attachment of the label, one of:
* "bottom-left", "bottom-center", "bottom-right",
* "middle-left", "middle-center", "middle-right",
* "top-left", "top-center", "top-right"
* @property {Boolean} showBorder - show border/outline
* @property {Color} borderColor - color of the border/outline
* @property {Float} borderWidth - width of the border/outline
* @property {Boolean} showBackground - show background rectangle
* @property {Color} backgroundColor - color of the background
* @property {Float} backgroundMargin - width of the background
* @property {Float} backgroundOpacity - opacity of the background
* @property {Boolean} fixedSize - show text with a fixed pixel size
*/
export interface LabelRepresentationParameters extends RepresentationParameters {
labelType: LabelType
labelText: string
labelFormat: string
labelGrouping: 'atom'|'residue'
fontFamily: 'sans-serif'|'monospace'|'serif'
fontStyle: 'normal'|'italic'
fontWeight: 'normal'|'bold'
xOffset: number
yOffset: number
zOffset: number
attachment: 'bottom-left'|'bottom-center'|'bottom-right'|'middle-left'|'middle-center'|'middle-right'|'top-left'|'top-center'|'top-right'
showBorder: boolean
borderColor: number
borderWidth: number
showBackground: boolean
backgroundColor: number
backgroundMargin: number
backgroundOpacity: number
fixedSize: boolean
}
/**
* Label representation
*/
class LabelRepresentation extends StructureRepresentation {
protected labelType: LabelType
protected labelText: string
protected labelFormat: string
protected labelGrouping: 'atom'|'residue'
protected fontFamily: 'sans-serif'|'monospace'|'serif'
protected fontStyle: 'normal'|'italic'
protected fontWeight: 'normal'|'bold'
protected xOffset: number
protected yOffset: number
protected zOffset: number
protected attachment: 'bottom-left'|'bottom-center'|'bottom-right'|'middle-left'|'middle-center'|'middle-right'|'top-left'|'top-center'|'top-right'
protected showBorder: boolean
protected borderColor: number
protected borderWidth: number
protected showBackground: boolean
protected backgroundColor: number
protected backgroundMargin: number
protected backgroundOpacity: number
protected fixedSize: boolean
/**
* Create Label representation object
* @param {Structure} structure - the structure to be represented
* @param {Viewer} viewer - a viewer object
* @param {LabelRepresentationParameters} params - label representation parameters
*/
constructor (structure: Structure, viewer: Viewer, params: Partial<LabelRepresentationParameters>) {
super(structure, viewer, params)
this.type = 'label'
this.parameters = Object.assign({
labelType: {
type: 'select', options: LabelFactory.types, rebuild: true
},
labelText: {
type: 'hidden', rebuild: true
},
labelFormat: {
type: 'text', rebuild: true
},
labelGrouping: {
type: 'select',
options: {
'atom': 'atom',
'residue': 'residue'
},
rebuild: true
},
fontFamily: {
type: 'select',
options: {
'sans-serif': 'sans-serif',
'monospace': 'monospace',
'serif': 'serif'
},
buffer: true
},
fontStyle: {
type: 'select',
options: {
'normal': 'normal',
'italic': 'italic'
},
buffer: true
},
fontWeight: {
type: 'select',
options: {
'normal': 'normal',
'bold': 'bold'
},
buffer: true
},
xOffset: {
type: 'number', precision: 1, max: 20, min: -20, buffer: true
},
yOffset: {
type: 'number', precision: 1, max: 20, min: -20, buffer: true
},
zOffset: {
type: 'number', precision: 1, max: 20, min: -20, buffer: true
},
attachment: {
type: 'select',
options: {
'bottom-left': 'bottom-left',
'bottom-center': 'bottom-center',
'bottom-right': 'bottom-right',
'middle-left': 'middle-left',
'middle-center': 'middle-center',
'middle-right': 'middle-right',
'top-left': 'top-left',
'top-center': 'top-center',
'top-right': 'top-right'
},
rebuild: true
},
showBorder: {
type: 'boolean', buffer: true
},
borderColor: {
type: 'color', buffer: true
},
borderWidth: {
type: 'number', precision: 2, max: 0.3, min: 0, buffer: true
},
showBackground: {
type: 'boolean', rebuild: true
},
backgroundColor: {
type: 'color', buffer: true
},
backgroundMargin: {
type: 'number', precision: 2, max: 2, min: 0, rebuild: true
},
backgroundOpacity: {
type: 'range', step: 0.01, max: 1, min: 0, buffer: true
},
fixedSize: {
type: 'boolean', buffer: true
}
}, this.parameters, {
side: null,
flatShaded: null,
wireframe: null,
linewidth: null,
roughness: null,
metalness: null,
diffuse: null
})
this.init(params)
}
init (params: Partial<LabelRepresentationParameters>) {
const p = params || {}
this.labelType = defaults(p.labelType, 'res')
this.labelText = defaults(p.labelText, {})
this.labelFormat = defaults(p.labelFormat, '')
this.labelGrouping = defaults(p.labelGrouping, 'atom')
this.fontFamily = defaults(p.fontFamily, 'sans-serif')
this.fontStyle = defaults(p.fontStyle, 'normal')
this.fontWeight = defaults(p.fontWeight, 'bold')
this.xOffset = defaults(p.xOffset, 0.0)
this.yOffset = defaults(p.yOffset, 0.0)
this.zOffset = defaults(p.zOffset, 0.5)
this.attachment = defaults(p.attachment, 'bottom-left')
this.showBorder = defaults(p.showBorder, false)
this.borderColor = defaults(p.borderColor, 'lightgrey')
this.borderWidth = defaults(p.borderWidth, 0.15)
this.showBackground = defaults(p.showBackground, false)
this.backgroundColor = defaults(p.backgroundColor, 'lightgrey')
this.backgroundMargin = defaults(p.backgroundMargin, 0.5)
this.backgroundOpacity = defaults(p.backgroundOpacity, 1.0)
this.fixedSize = defaults(p.fixedSize, false)
super.init(p)
}
getTextData (sview: StructureView, what?: TextDataField) {
const p = this.getAtomParams(what)
const labelFactory = new LabelFactory(this.labelType, this.labelText, this.labelFormat)
let position: Float32Array, size: Float32Array, color: Float32Array, text: string[],
positionN: number[], sizeN: number[], colorN: number[]
if (this.labelGrouping === 'atom') {
const atomData = sview.getAtomData(p)
position = atomData.position as Float32Array
size = atomData.radius as Float32Array
color = atomData.color as Float32Array
if (!what || what.text) {
text = []
sview.eachAtom(ap => text.push(labelFactory.atomLabel(ap)))
}
} else if (this.labelGrouping === 'residue') {
if (!what || what.position) positionN = []
if (!what || what.color) colorN = []
if (!what || what.radius) sizeN = []
if (!what || what.text) text = []
if (p.colorParams) p.colorParams.structure = sview.getStructure()
const colormaker = ColormakerRegistry.getScheme(p.colorParams)
const radiusFactory = new RadiusFactory(p.radiusParams)
const ap1 = sview.getAtomProxy()
let i = 0
sview.eachResidue(rp => {
const i3 = i * 3
if (rp.isProtein() || rp.isNucleic()) {
ap1.index = rp.traceAtomIndex
if (!what || what.position) {
ap1.positionToArray(positionN, i3)
}
} else {
ap1.index = rp.atomOffset
if (!what || what.position) {
rp.positionToArray(positionN, i3)
}
}
if (!what || what.color) {
colormaker.atomColorToArray(ap1, colorN, i3)
}
if (!what || what.radius) {
sizeN[ i ] = radiusFactory.atomRadius(ap1)
}
if (!what || what.text) {
text.push(labelFactory.atomLabel(ap1))
}
++i
})
if (!what || what.position) position = new Float32Array(positionN!)
if (!what || what.color) color = new Float32Array(colorN!)
if (!what || what.radius) size = new Float32Array(sizeN!)
}
return { position: position!, size: size!, color: color!, text: text! }
}
createData (sview: StructureView) {
const what: TextDataField = { position: true, color: true, radius: true, text: true }
const textBuffer = new TextBuffer(
this.getTextData(sview, what) as TextBufferData,
this.getBufferParams({
fontFamily: this.fontFamily,
fontStyle: this.fontStyle,
fontWeight: this.fontWeight,
xOffset: this.xOffset,
yOffset: this.yOffset,
zOffset: this.zOffset,
attachment: this.attachment,
showBorder: this.showBorder,
borderColor: this.borderColor,
borderWidth: this.borderWidth,
showBackground: this.showBackground,
backgroundColor: this.backgroundColor,
backgroundMargin: this.backgroundMargin,
backgroundOpacity: this.backgroundOpacity,
fixedSize: this.fixedSize
})
)
return { bufferList: [ textBuffer ] }
}
updateData (what: TextDataField, data: StructureRepresentationData) {
data.bufferList[ 0 ].setAttributes(this.getTextData(data.sview as StructureView, what))
}
getAtomRadius () {
return 0
}
}
RepresentationRegistry.add('label', LabelRepresentation)
export default LabelRepresentation | the_stack |
declare module '@ailhc/excel2all' {
/**当前系统行尾 platform === "win32" ? "\n" : "\r\n";*/
export const osEol: string;
}
declare module '@ailhc/excel2all' {
export class Logger {
private static _enableOutPutLogFile;
private static _logLevel;
private static _logStr;
/**
* 如果有输出过错误信息则为true
*/
static hasError: boolean;
static init(convertConfig: ITableConvertConfig): void;
/**
* 输出日志,日志等级只是限制了控制台输出,但不限制日志记录
* @param message
* @param level
*/
static log(message: string, level?: LogLevel): void;
/**
* 系统日志输出
* @param args
*/
static systemLog(message: string): void;
/**
* 返回日志数据并清空
*/
static get logStr(): string;
}
}
declare module '@ailhc/excel2all' {
global {
interface IOutPutFileInfo {
filePath: string;
/**写入编码,字符串默认utf8 */
encoding?: BufferEncoding;
/**是否删除 */
isDelete?: boolean;
data?: any;
}
}
/**
* 遍历文件
* @param dirPath 文件夹路径
* @param eachCallback 遍历回调 (filePath: string) => void
*/
export function forEachFile(fileOrDirPath: string, eachCallback?: (filePath: string) => void): void;
/**
* 批量写入和删除文件
* @param outputFileInfos 需要写入的文件信息数组
* @param onProgress 进度变化回调
* @param complete 完成回调
*/
export function writeOrDeleteOutPutFiles(outputFileInfos: IOutPutFileInfo[], onProgress?: (filePath: string, total: number, now: number, isOk: boolean) => void, complete?: (total: number) => void): void;
/**
* 获取变化过的文件数组
* @param dir 目标目录
* @param cacheFilePath 缓存文件绝对路径
* @param eachCallback 遍历回调
* @returns 返回缓存文件路径
*/
export function forEachChangedFile(dir: string, cacheFilePath?: string, eachCallback?: (filePath: string, isDelete?: boolean) => void): void;
/**
* 写入缓存数据
* @param cacheFilePath
* @param cacheData
*/
export function writeCacheData(cacheFilePath: string, cacheData: any): void;
/**
* 读取缓存数据
* @param cacheFilePath
*/
export function getCacheData(cacheFilePath: string): any;
/**
* 获取文件md5 (同步)
* @param filePath
*/
export function getFileMd5Sync(filePath: string, encoding?: BufferEncoding): string;
/**
* 获取文件md5 (异步)
* @param filePath
*/
export function getFileMd5Async(filePath: string, cb: (md5Str: string) => void, encoding?: BufferEncoding): void;
/**
* 获取文件md5
* @param file 文件对象
* @returns
*/
export function getFileMd5(file: any): string;
/**
* 获取文件 md5
* @param filePath
*/
export function getFileMd5ByPath(filePath: string): Promise<string>;
}
declare module '@ailhc/excel2all' {
export const defaultValueTransFuncMap: {
[key: string]: ValueTransFunc;
};
}
declare module '@ailhc/excel2all' {
import * as xlsx from 'xlsx';
/**
* 是否为空表格格子
* @param cell
*/
export function isEmptyCell(cell: xlsx.CellObject): boolean;
/**
* 字母Z的编码
*/
export const ZCharCode = 90;
/**
* 字母A的编码
*
*/
export const ACharCode = 65;
/**
* 根据当前列的charCodes获取下一列Key
* @param charCodes
*/
export function getNextColKey(charCodes: number[]): string;
/**
* 列的字符编码数组转字符串
* @param charCodes
*/
export function charCodesToString(charCodes: number[]): string;
/**
* 字符串转编码数组
* @param colKey
*/
export function stringToCharCodes(colKey: string): any[];
/**
* 获取列标签的大小 用于比较是否最大列 比如 最大列key: BD,当前列key: AF AF < BD
* @param colKey
* @returns
*/
export function getCharCodeSum(colKey: string): number;
/**
* 遍历横向表格
* @param sheet xlsx表格对象
* @param startRow 开始行 从1开始
* @param startCol 列字符 比如A B
* @param callback 遍历回调 (sheet: xlsx.Sheet, colKey: string, rowIndex: number) => void
* @param isSheetRowEnd 是否行结束判断方法
* @param isSheetColEnd 是否列结束判断方法
* @param isSkipSheetRow 是否跳过行
* @param isSkipSheetCol 是否跳过列
*/
export function forEachHorizontalSheet(sheet: xlsx.Sheet, startRow: number, startCol: string, callback: (sheet: xlsx.Sheet, colKey: string, rowIndex: number) => void, isSheetRowEnd?: (sheet: xlsx.Sheet, rowIndex: number) => boolean, isSheetColEnd?: (sheet: xlsx.Sheet, colkey: string) => boolean, isSkipSheetRow?: (sheet: xlsx.Sheet, rowIndex: number) => boolean, isSkipSheetCol?: (sheet: xlsx.Sheet, colKey: string) => boolean): void;
/**
* 遍历纵向表格
* @param sheet xlsx表格对象
* @param startRow 开始行 从1开始
* @param startCol 列字符 比如A B
* @param callback 遍历回调 (sheet: xlsx.Sheet, colKey: string, rowIndex: number) => void
* @param isSheetRowEnd 是否行结束判断方法
* @param isSheetColEnd 是否列结束判断方法
* @param isSkipSheetRow 是否跳过行
* @param isSkipSheetCol 是否跳过列
*/
export function forEachVerticalSheet(sheet: xlsx.Sheet, startRow: number, startCol: string, callback: (sheet: xlsx.Sheet, colKey: string, rowIndex: number) => void, isSheetRowEnd?: (sheet: xlsx.Sheet, rowIndex: number) => boolean, isSheetColEnd?: (sheet: xlsx.Sheet, colkey: string) => boolean, isSkipSheetRow?: (sheet: xlsx.Sheet, rowIndex: number) => boolean, isSkipSheetCol?: (sheet: xlsx.Sheet, colKey: string) => boolean): void;
/**
* 读取配置表文件 同步的
* @param fileInfo
*/
export function readTableFile(fileInfo: IFileInfo): xlsx.WorkBook;
/**
* 读取配置表文件 同步的
* 如果fileData typeof === string xlsx.read 的 type是string,否则是buffer
* @param fileInfo
*/
export function readTableData(fileInfo: IFileInfo): xlsx.WorkBook;
/**
* 获取配置文件类型
* @param fileInfo
* @returns
*/
export function getTableFileType(fileInfo: IFileInfo): "string" | "file";
/**
* 根据文件名后缀判断是否为csv文件
* @param fileExtName
*/
export function isCSV(fileExtName: string): boolean;
}
declare module '@ailhc/excel2all' {
import * as xlsx from 'xlsx'; global {
interface ITableParserConfig {
/**自定义值转换方法字典 */
customValueTransFuncMap?: ValueTransFuncMap;
}
interface ITableConvertConfig {
/**解析配置 */
parserConfig?: ITableParserConfig;
}
interface ITableField {
/**配置表中注释值 */
text: string;
/**配置表中类型值 */
originType: string;
/**配置表中字段名值 */
originFieldName: string;
/**解析后的类型值 */
type?: string;
/**解析后的字段名值 */
fieldName?: string;
/**对象的子字段名 */
subFieldName?: string;
/**多列对象 */
isMutiColObj?: boolean;
}
interface ITableFirstCellValue {
tableNameInSheet: string;
tableType: TableType;
}
interface ITableDefine {
/**配置表名 */
tableName: string;
/**配置表类型 默认两种: vertical 和 horizontal*/
tableType: string;
/**遍历开始行 */
startRow: number;
/**遍历开始列 */
startCol: string;
/**垂直表字段定义 */
verticalFieldDefine: IVerticalFieldDefine;
/**横向表字段定义 */
horizontalFieldDefine: IHorizontalFieldDefine;
}
interface IVerticalFieldDefine {
/**类型行 */
typeCol: string;
/**字段名行 */
fieldCol: string;
/**注释行 */
textCol: string;
}
interface IHorizontalFieldDefine {
/**类型行 */
typeRow: number;
/**字段名行 */
fieldRow: number;
/**注释行 */
textRow: number;
}
/**
* 字段字典
* key是列originFieldName
* value是字段对象
*/
type TableFieldMap = {
[key: string]: ITableField;
};
/**
* 表格的一行或者一列
* key为字段名值,value为表格的一格
*/
type TableRowOrCol = {
[key: string]: ITableCell;
};
/**
* 表格的一格
*/
interface ITableCell {
/**字段对象 */
field: ITableField;
/**值 */
value: any;
}
/**
* 表格行或列的字典
* key为行索引,value为表格的一行
*/
type TableRowOrColMap = {
[key: string]: TableRowOrCol;
};
/**
* 表格行或列值数组
* key主键,value是值数组
*/
type RowOrColValuesMap = {
[key: string]: any[];
};
interface ITableValues {
/**字段名数组 */
fields: string[];
/**表格值数组 */
rowOrColValuesMap: RowOrColValuesMap;
}
/**
* 解析结果
*/
interface ITableParseResult {
/**配置表定义 */
tableDefine?: ITableDefine;
/**当前分表名 */
curSheetName?: string;
/**字段字典 */
fieldMap?: TableFieldMap;
/**单个表格对象 */
/**key是主键值,value是一行对象 */
tableObj?: {
[key: string]: any;
};
/**当前行或列对象 */
curRowOrColObj?: any;
/**主键值 */
mainKeyFieldName?: string;
}
/**值转换结果 */
interface ITransValueResult {
error?: any;
value?: any;
}
/**值转换方法 */
type ValueTransFunc = (fieldItem: ITableField, cellValue: any) => ITransValueResult;
/**
* 值转换方法字典
* key是类型key
* value是方法
*/
type ValueTransFuncMap = {
[key: string]: ValueTransFunc;
};
}
/**
* 配置表类型
* 按照字段扩展方向定
*/
export enum TableType {
/**字段垂直扩展 */
vertical = "vertical",
/**字段横向扩展 */
horizontal = "horizontal"
}
export class DefaultTableParser implements ITableParser {
getTableDefine(fileInfo: IFileInfo, workBook: xlsx.WorkBook): ITableDefine;
private _getFirstCellValue;
/**
* 判断表格是否能解析
* @param sheet
*/
checkSheetCanParse(tableDefine: ITableDefine, sheet: xlsx.Sheet, sheetName: string): boolean;
/**
* 表行结束判断
* @param tableDefine
* @param sheet
* @param row
*/
isSheetRowEnd(tableDefine: ITableDefine, sheet: xlsx.Sheet, row: number): boolean;
/**
* 表列结束判断
* @param tableDefine
* @param sheet
* @param colKey
*/
isSheetColEnd(tableDefine: ITableDefine, sheet: xlsx.Sheet, colKey: string): boolean;
/**
* 检查行是否需要解析
* @param tableDefine
* @param sheet
* @param rowIndex
*/
checkRowNeedParse(tableDefine: ITableDefine, sheet: xlsx.Sheet, rowIndex: number): boolean;
/**
* 解析横向表格的单个格子
* @param tableParseResult
* @param sheet
* @param colKey
* @param rowIndex
* @param isNewRowOrCol 是否为新的一行或者一列
*/
parseHorizontalCell(valueTransFuncMap: ValueTransFuncMap, tableParseResult: ITableParseResult, sheet: xlsx.Sheet, colKey: string, rowIndex: number, isNewRowOrCol: boolean): void;
/**
* 解析纵向表格的单个格子
* @param valueTransFuncMap
* @param tableParseResult
* @param sheet
* @param colKey
* @param rowIndex
* @param isNewRowOrCol 是否为新的一行或者一列
*/
parseVerticalCell(valueTransFuncMap: ValueTransFuncMap, tableParseResult: ITableParseResult, sheet: xlsx.Sheet, colKey: string, rowIndex: number, isNewRowOrCol: boolean): void;
/**
* 解析出横向表的字段对象
* @param tableParseResult
* @param sheet
* @param colKey
* @param rowIndex
*/
getHorizontalTableField(tableParseResult: ITableParseResult, sheet: xlsx.Sheet, colKey: string, rowIndex: number): ITableField;
/**
* 解析出纵向表的字段类型对象
* @param tableParseResult
* @param sheet
* @param colKey
* @param rowIndex
* @returns
*/
getVerticalTableField(tableParseResult: ITableParseResult, sheet: xlsx.Sheet, colKey: string, rowIndex: number): ITableField;
/**
* 检查列是否需要解析
* @param tableDefine
* @param sheet
* @param colKey
*/
checkColNeedParse(tableDefine: ITableDefine, sheet: xlsx.Sheet, colKey: string): boolean;
/**
* 转换表格的值
* @param parseResult
* @param fieldItem
* @param cellValue
*/
transValue(valueTransFuncMap: ValueTransFuncMap, parseResult: ITableParseResult, fieldItem: ITableField, cellValue: any): ITransValueResult;
/**
* 解析配置表文件
* @param convertConfig 解析配置
* @param fileInfo 文件信息
* @param parseResult 解析结果
*/
parseTableFile(convertConfig: ITableConvertConfig, fileInfo: IFileInfo, parseResult: ITableParseResult): ITableParseResult;
}
}
declare module '@ailhc/excel2all' {
global {
interface ITableConvertConfig {
/**输出配置 */
outputConfig?: IOutputConfig;
}
/**
* 输出配置
*/
interface IOutputConfig {
/**自定义 配置字段类型和ts声明类型字符串映射字典 */
customTypeStrMap?: {
[key: string]: string;
};
/**单个配置表json输出目录路径 */
clientSingleTableJsonDir?: string;
/**合并配置表json文件路径(包含文件名,比如 ./out/bundle.json) */
clientBundleJsonOutPath?: string;
/**是否格式化合并后的json,默认不 */
isFormatBundleJson?: boolean;
/**声明文件输出目录(每个配置表一个声明),默认不输出 */
clientDtsOutDir?: string;
/**是否合并所有声明为一个文件,默认true */
isBundleDts?: boolean;
/**合并后的声明文件名,如果没有则默认为tableMap */
bundleDtsFileName?: string;
/**是否将json格式压缩,默认否,减少json字段名字符,效果较小 */
isCompress?: boolean;
/**是否Zip压缩,使用zlib */
isZip?: boolean;
}
}
export class DefaultParseResultTransformer {
/**
* 转换
* @param context
* @returns
*/
transform(context: IConvertContext, cb: VoidFunction): void;
private _addSingleTableDtsOutputFile;
/**
* 解析出单个配置表类型数据
* @param parseResult
*/
private _getSingleTableDts;
/**
* 添加单独导出配置表json文件
* @param config
* @param parseResult
* @param outputFileMap
*/
private _addSingleTableJsonOutputFile;
private _getOneTableTypeStr;
}
}
declare module '@ailhc/excel2all' {
export class DefaultConvertHook implements IConvertHook {
protected _tableParser: any;
protected _tableResultTransformer: any;
constructor();
onStart?(context: IConvertContext, cb: VoidFunction): void;
onParseBefore?(context: IConvertContext, cb: VoidFunction): void;
onParse(context: IConvertContext, cb: VoidFunction): void;
onParseAfter?(context: IConvertContext, cb: VoidFunction): void;
onConvertEnd(context: IConvertContext): void;
}
}
declare module '@ailhc/excel2all' {
/**
* 转换
* @param converConfig 解析配置
*/
export function convert(converConfig: ITableConvertConfig): Promise<void>;
/**
* 测试文件匹配
* @param convertConfig
*/
export function testFileMatch(convertConfig: ITableConvertConfig): void;
}
declare module '@ailhc/excel2all' {
global {
/**
* 多线程传递数据
*/
interface IWorkerShareData {
/**线程id */
threadId: number;
/**解析配置 */
convertConfig: ITableConvertConfig;
/**需要解析的文件数组 */
fileInfos: IFileInfo[];
/**解析结果 */
parseResultMap: TableParseResultMap;
}
/**
* 多线程执行结果
*/
interface IWorkDoResult {
/**线程id */
threadId: number;
/**解析结果 */
parseResultMap: TableParseResultMap;
/**日志 */
logStr: string;
}
/**
* 文件信息对象
*/
interface IFileInfo {
/**
* 文件绝对路径
*/
filePath: string;
/**
* 文件名,不带后缀的
*/
fileName: string;
/**
* 文件后缀 如 .csv .xlsx
*/
fileExtName: string;
/**
* 文件数据
*/
fileData?: any;
/**
* 是否需要删除
*/
isDelete?: boolean;
}
/**
* 配置解析结果
*/
interface ITableParseResult {
/**解析出错,缓存无效 */
hasError?: boolean;
/**文件路径 */
filePath: string;
/**文件哈希值 */
md5hash?: string;
}
interface ITableConvertCacheData {
/**库版本,版本不一样缓存自动失效 */
version: string;
/**解析结果缓存 */
parseResultMap: TableParseResultMap;
}
/**
* 所有配置表解析结果字典
* key为表的文件路径,value为解析结果
*/
type TableParseResultMap = {
[key: string]: ITableParseResult;
};
/**
* 转换配置
*/
interface ITableConvertConfig {
/**
* 项目根目录,是其他相对路径的根据
* 如果没有,则读取命令行执行的目录路径
*/
projRoot?: string;
/**
* 配置表文件夹
*/
tableFileDir: string;
/**
* 是否启用缓存
*/
useCache?: boolean;
/**
* 缓存文件的文件夹路径,可以是相对路径,相对于projRoot
* 默认是项目根目录下的.excel2all文件夹
*/
cacheFileDirPath?: string;
/**
* 文件名匹配规则 ,默认匹配规则 [".\\**\\*.xlsx", ".\\**\\*.csv", "!**\\~$*.*", "!**\\~.*.*", "!.git\\**\\*", "!.svn\\**\\*"]
* 匹配所有后缀为.xlsx和.csv的文件,如果符合~$*.* 或~.*.* 则排除(那个是excel文件的临时文件)
* 匹配规则第一个必须带 ./ 否则匹配会出问题
* 具体匹配规则参考:https://github.com/mrmlnc/fast-glob#pattern-syntax
*/
pattern?: string[];
/**日志等级 ,只是限制了控制台输出,但不限制日志记录*/
logLevel?: LogLevel;
/**
* 日志文件夹路径,默认输出到.excell2all/excell2all.log
* 可以是绝对或相对路径,相对路径相对于projRoot
* 填false则不生成log文件
*/
outputLogDirPath?: string | boolean;
/**自定义转换周期处理函数 */
customConvertHook?: IConvertHook;
}
type LogLevel = "no" | "info" | "warn" | "error";
/**
* 输出文件字典
* key为路径
* value为文件信息
*/
type OutPutFileMap = {
[key: string]: IOutPutFileInfo;
};
/**
* 转换上下文
*/
interface IConvertContext {
/**配置 */
convertConfig: ITableConvertConfig;
/**
* 变动的文件信息数组
*/
changedFileInfos?: IFileInfo[];
/**
* 删除了的文件信息数组
*/
deleteFileInfos?: IFileInfo[];
/**
* 解析结果字典
*/
parseResultMap?: TableParseResultMap;
/**解析缓存 */
cacheData?: ITableConvertCacheData;
/**
* 转换结果字典
*/
outPutFileMap?: OutPutFileMap;
/**
* 是否出错
*/
hasError?: boolean;
/**
* 缓存文件路径
*/
parseResultMapCacheFilePath?: string;
utils: {
/**
* 好用的第三方文件工具库
*/
fs: typeof import("fs-extra");
/**
* excel表解析库
* */
xlsx: typeof import("xlsx");
};
}
interface IConvertHook {
/**
* 开始转换
* 处理好配置
* @param context 上下文
* @param cb 生命周期结束回调,必须调用
*/
onStart?(context: IConvertContext, cb: VoidFunction): void;
/**
* 遍历文件之后,解析之前
* @param context 上下文
* @param cb 生命周期结束回调,必须调用
*/
onParseBefore?(context: IConvertContext, cb: VoidFunction): void;
/**
* 配置表解析
* @param context
* @param cb
*/
onParse?(context: IConvertContext, cb: VoidFunction): void;
/**
* 解析结束
* 可以转换解析结果为多个任意文件
* @param context 上下文
* @param cb 生命周期结束回调,必须调用
*/
onParseAfter?(context: IConvertContext, cb: VoidFunction): void;
/**
* 写入文件结束
* @param context 上下文
*/
onConvertEnd?(context: IConvertContext): void;
}
/**
* 输出转换器
*/
interface ITableParseResultTransformer {
/**
* 转换
* 将结果文件输出路径为key,
* 输出文件对象(文本就是字符串,或者二进制)为值,
* 写入IConvertContext.outPutFileMap
* @param context
* @param cb 回调,必须调用
*/
transform(context: IConvertContext, cb: VoidFunction): void;
}
interface ITableParser {
/**
* 解析配置表文件
* @param fileInfo 文件信息
* @param parseResult 解析结果
*/
parseTableFile(parseConfig: ITableConvertConfig, fileInfo: IFileInfo, parseResult: ITableParseResult): ITableParseResult;
}
}
export interface Interfaces {
}
}
declare module '@ailhc/excel2all' {
export * from '@ailhc/excel2all';
export * from '@ailhc/excel2all';
export * from '@ailhc/excel2all';
export * from '@ailhc/excel2all';
export * from '@ailhc/excel2all';
export * from '@ailhc/excel2all';
export * from '@ailhc/excel2all';
export * from '@ailhc/excel2all';
export * from '@ailhc/excel2all';
} | the_stack |
import * as Common from '../../core/common/common.js';
import * as Host from '../../core/host/host.js';
import * as i18n from '../../core/i18n/i18n.js';
import * as Root from '../../core/root/root.js';
import * as SDK from '../../core/sdk/sdk.js';
import * as Protocol from '../../generated/protocol.js';
import * as UI from '../../ui/legacy/legacy.js';
import type {EmulatedDevice, Mode} from './EmulatedDevices.js';
import {Horizontal, HorizontalSpanned, Vertical, VerticalSpanned} from './EmulatedDevices.js';
const UIStrings = {
/**
* @description Error message shown in the Devices settings pane when the user enters an invalid
* width for a custom device.
*/
widthMustBeANumber: 'Width must be a number.',
/**
* @description Error message shown in the Devices settings pane when the user has entered a width
* for a custom device that is too large.
* @example {9999} PH1
*/
widthMustBeLessThanOrEqualToS: 'Width must be less than or equal to {PH1}.',
/**
* @description Error message shown in the Devices settings pane when the user has entered a width
* for a custom device that is too small.
* @example {50} PH1
*/
widthMustBeGreaterThanOrEqualToS: 'Width must be greater than or equal to {PH1}.',
/**
* @description Error message shown in the Devices settings pane when the user enters an invalid
* height for a custom device.
*/
heightMustBeANumber: 'Height must be a number.',
/**
* @description Error message shown in the Devices settings pane when the user has entered a height
* for a custom device that is too large.
* @example {9999} PH1
*/
heightMustBeLessThanOrEqualToS: 'Height must be less than or equal to {PH1}.',
/**
* @description Error message shown in the Devices settings pane when the user has entered a height
* for a custom device that is too small.
* @example {50} PH1
*/
heightMustBeGreaterThanOrEqualTo: 'Height must be greater than or equal to {PH1}.',
/**
* @description Error message shown in the Devices settings pane when the user enters an invalid
* device pixel ratio for a custom device.
*/
devicePixelRatioMustBeANumberOr: 'Device pixel ratio must be a number or blank.',
/**
* @description Error message shown in the Devices settings pane when the user enters a device
* pixel ratio for a custom device that is too large.
* @example {10} PH1
*/
devicePixelRatioMustBeLessThanOr: 'Device pixel ratio must be less than or equal to {PH1}.',
/**
* @description Error message shown in the Devices settings pane when the user enters a device
* pixel ratio for a custom device that is too small.
* @example {0} PH1
*/
devicePixelRatioMustBeGreater: 'Device pixel ratio must be greater than or equal to {PH1}.',
};
const str_ = i18n.i18n.registerUIStrings('models/emulation/DeviceModeModel.ts', UIStrings);
const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);
let deviceModeModelInstance: DeviceModeModel;
export class DeviceModeModel extends Common.ObjectWrapper.ObjectWrapper<EventTypes> implements
SDK.TargetManager.SDKModelObserver<SDK.EmulationModel.EmulationModel> {
#screenRectInternal: Rect;
#visiblePageRectInternal: Rect;
#availableSize: UI.Geometry.Size;
#preferredSize: UI.Geometry.Size;
#initialized: boolean;
#appliedDeviceSizeInternal: UI.Geometry.Size;
#appliedDeviceScaleFactorInternal: number;
#appliedUserAgentTypeInternal: UA;
readonly #experimentDualScreenSupport: boolean;
readonly #webPlatformExperimentalFeaturesEnabledInternal: boolean;
readonly #scaleSettingInternal: Common.Settings.Setting<number>;
#scaleInternal: number;
#widthSetting: Common.Settings.Setting<number>;
#heightSetting: Common.Settings.Setting<number>;
#uaSettingInternal: Common.Settings.Setting<UA>;
readonly #deviceScaleFactorSettingInternal: Common.Settings.Setting<number>;
readonly #deviceOutlineSettingInternal: Common.Settings.Setting<boolean>;
readonly #toolbarControlsEnabledSettingInternal: Common.Settings.Setting<boolean>;
#typeInternal: Type;
#deviceInternal: EmulatedDevice|null;
#modeInternal: Mode|null;
#fitScaleInternal: number;
#touchEnabled: boolean;
#touchMobile: boolean;
#emulationModel: SDK.EmulationModel.EmulationModel|null;
#onModelAvailable: (() => void)|null;
#emulatedPageSize?: UI.Geometry.Size;
#outlineRectInternal?: Rect;
private constructor() {
super();
this.#screenRectInternal = new Rect(0, 0, 1, 1);
this.#visiblePageRectInternal = new Rect(0, 0, 1, 1);
this.#availableSize = new UI.Geometry.Size(1, 1);
this.#preferredSize = new UI.Geometry.Size(1, 1);
this.#initialized = false;
this.#appliedDeviceSizeInternal = new UI.Geometry.Size(1, 1);
this.#appliedDeviceScaleFactorInternal = window.devicePixelRatio;
this.#appliedUserAgentTypeInternal = UA.Desktop;
this.#experimentDualScreenSupport = Root.Runtime.experiments.isEnabled('dualScreenSupport');
this.#webPlatformExperimentalFeaturesEnabledInternal = 'segments' in window.visualViewport;
this.#scaleSettingInternal = Common.Settings.Settings.instance().createSetting('emulation.deviceScale', 1);
// We've used to allow zero before.
if (!this.#scaleSettingInternal.get()) {
this.#scaleSettingInternal.set(1);
}
this.#scaleSettingInternal.addChangeListener(this.scaleSettingChanged, this);
this.#scaleInternal = 1;
this.#widthSetting = Common.Settings.Settings.instance().createSetting('emulation.deviceWidth', 400);
if (this.#widthSetting.get() < MinDeviceSize) {
this.#widthSetting.set(MinDeviceSize);
}
if (this.#widthSetting.get() > MaxDeviceSize) {
this.#widthSetting.set(MaxDeviceSize);
}
this.#widthSetting.addChangeListener(this.widthSettingChanged, this);
this.#heightSetting = Common.Settings.Settings.instance().createSetting('emulation.deviceHeight', 0);
if (this.#heightSetting.get() && this.#heightSetting.get() < MinDeviceSize) {
this.#heightSetting.set(MinDeviceSize);
}
if (this.#heightSetting.get() > MaxDeviceSize) {
this.#heightSetting.set(MaxDeviceSize);
}
this.#heightSetting.addChangeListener(this.heightSettingChanged, this);
this.#uaSettingInternal = Common.Settings.Settings.instance().createSetting('emulation.deviceUA', UA.Mobile);
this.#uaSettingInternal.addChangeListener(this.uaSettingChanged, this);
this.#deviceScaleFactorSettingInternal =
Common.Settings.Settings.instance().createSetting('emulation.deviceScaleFactor', 0);
this.#deviceScaleFactorSettingInternal.addChangeListener(this.deviceScaleFactorSettingChanged, this);
this.#deviceOutlineSettingInternal =
Common.Settings.Settings.instance().moduleSetting('emulation.showDeviceOutline');
this.#deviceOutlineSettingInternal.addChangeListener(this.deviceOutlineSettingChanged, this);
this.#toolbarControlsEnabledSettingInternal = Common.Settings.Settings.instance().createSetting(
'emulation.toolbarControlsEnabled', true, Common.Settings.SettingStorageType.Session);
this.#typeInternal = Type.None;
this.#deviceInternal = null;
this.#modeInternal = null;
this.#fitScaleInternal = 1;
this.#touchEnabled = false;
this.#touchMobile = false;
this.#emulationModel = null;
this.#onModelAvailable = null;
SDK.TargetManager.TargetManager.instance().observeModels(SDK.EmulationModel.EmulationModel, this);
}
static instance(opts: {
forceNew: null,
} = {forceNew: null}): DeviceModeModel {
if (!deviceModeModelInstance || opts.forceNew) {
deviceModeModelInstance = new DeviceModeModel();
}
return deviceModeModelInstance;
}
static widthValidator(value: string): {
valid: boolean,
errorMessage: (string|undefined),
} {
let valid = false;
let errorMessage;
if (!/^[\d]+$/.test(value)) {
errorMessage = i18nString(UIStrings.widthMustBeANumber);
} else if (Number(value) > MaxDeviceSize) {
errorMessage = i18nString(UIStrings.widthMustBeLessThanOrEqualToS, {PH1: MaxDeviceSize});
} else if (Number(value) < MinDeviceSize) {
errorMessage = i18nString(UIStrings.widthMustBeGreaterThanOrEqualToS, {PH1: MinDeviceSize});
} else {
valid = true;
}
return {valid, errorMessage};
}
static heightValidator(value: string): {
valid: boolean,
errorMessage: (string|undefined),
} {
let valid = false;
let errorMessage;
if (!/^[\d]+$/.test(value)) {
errorMessage = i18nString(UIStrings.heightMustBeANumber);
} else if (Number(value) > MaxDeviceSize) {
errorMessage = i18nString(UIStrings.heightMustBeLessThanOrEqualToS, {PH1: MaxDeviceSize});
} else if (Number(value) < MinDeviceSize) {
errorMessage = i18nString(UIStrings.heightMustBeGreaterThanOrEqualTo, {PH1: MinDeviceSize});
} else {
valid = true;
}
return {valid, errorMessage};
}
static scaleValidator(value: string): {
valid: boolean,
errorMessage: (string|undefined),
} {
let valid = false;
let errorMessage;
const parsedValue = Number(value.trim());
if (!value) {
valid = true;
} else if (Number.isNaN(parsedValue)) {
errorMessage = i18nString(UIStrings.devicePixelRatioMustBeANumberOr);
} else if (Number(value) > MaxDeviceScaleFactor) {
errorMessage = i18nString(UIStrings.devicePixelRatioMustBeLessThanOr, {PH1: MaxDeviceScaleFactor});
} else if (Number(value) < MinDeviceScaleFactor) {
errorMessage = i18nString(UIStrings.devicePixelRatioMustBeGreater, {PH1: MinDeviceScaleFactor});
} else {
valid = true;
}
return {valid, errorMessage};
}
get scaleSettingInternal(): Common.Settings.Setting<number> {
return this.#scaleSettingInternal;
}
setAvailableSize(availableSize: UI.Geometry.Size, preferredSize: UI.Geometry.Size): void {
this.#availableSize = availableSize;
this.#preferredSize = preferredSize;
this.#initialized = true;
this.calculateAndEmulate(false);
}
emulate(type: Type, device: EmulatedDevice|null, mode: Mode|null, scale?: number): void {
const resetPageScaleFactor =
this.#typeInternal !== type || this.#deviceInternal !== device || this.#modeInternal !== mode;
this.#typeInternal = type;
if (type === Type.Device && device && mode) {
console.assert(Boolean(device) && Boolean(mode), 'Must pass device and mode for device emulation');
this.#modeInternal = mode;
this.#deviceInternal = device;
if (this.#initialized) {
const orientation = device.orientationByName(mode.orientation);
this.#scaleSettingInternal.set(
scale ||
this.calculateFitScale(orientation.width, orientation.height, this.currentOutline(), this.currentInsets()));
}
} else {
this.#deviceInternal = null;
this.#modeInternal = null;
}
if (type !== Type.None) {
Host.userMetrics.actionTaken(Host.UserMetrics.Action.DeviceModeEnabled);
}
this.calculateAndEmulate(resetPageScaleFactor);
}
setWidth(width: number): void {
const max = Math.min(MaxDeviceSize, this.preferredScaledWidth());
width = Math.max(Math.min(width, max), 1);
this.#widthSetting.set(width);
}
setWidthAndScaleToFit(width: number): void {
width = Math.max(Math.min(width, MaxDeviceSize), 1);
this.#scaleSettingInternal.set(this.calculateFitScale(width, this.#heightSetting.get()));
this.#widthSetting.set(width);
}
setHeight(height: number): void {
const max = Math.min(MaxDeviceSize, this.preferredScaledHeight());
height = Math.max(Math.min(height, max), 0);
if (height === this.preferredScaledHeight()) {
height = 0;
}
this.#heightSetting.set(height);
}
setHeightAndScaleToFit(height: number): void {
height = Math.max(Math.min(height, MaxDeviceSize), 0);
this.#scaleSettingInternal.set(this.calculateFitScale(this.#widthSetting.get(), height));
this.#heightSetting.set(height);
}
setScale(scale: number): void {
this.#scaleSettingInternal.set(scale);
}
device(): EmulatedDevice|null {
return this.#deviceInternal;
}
mode(): Mode|null {
return this.#modeInternal;
}
type(): Type {
return this.#typeInternal;
}
screenImage(): string {
return (this.#deviceInternal && this.#modeInternal) ? this.#deviceInternal.modeImage(this.#modeInternal) : '';
}
outlineImage(): string {
return (this.#deviceInternal && this.#modeInternal && this.#deviceOutlineSettingInternal.get()) ?
this.#deviceInternal.outlineImage(this.#modeInternal) :
'';
}
outlineRect(): Rect|null {
return this.#outlineRectInternal || null;
}
screenRect(): Rect {
return this.#screenRectInternal;
}
visiblePageRect(): Rect {
return this.#visiblePageRectInternal;
}
scale(): number {
return this.#scaleInternal;
}
fitScale(): number {
return this.#fitScaleInternal;
}
appliedDeviceSize(): UI.Geometry.Size {
return this.#appliedDeviceSizeInternal;
}
appliedDeviceScaleFactor(): number {
return this.#appliedDeviceScaleFactorInternal;
}
appliedUserAgentType(): UA {
return this.#appliedUserAgentTypeInternal;
}
isFullHeight(): boolean {
return !this.#heightSetting.get();
}
private isMobile(): boolean {
switch (this.#typeInternal) {
case Type.Device:
return this.#deviceInternal ? this.#deviceInternal.mobile() : false;
case Type.None:
return false;
case Type.Responsive:
return this.#uaSettingInternal.get() === UA.Mobile || this.#uaSettingInternal.get() === UA.MobileNoTouch;
}
return false;
}
enabledSetting(): Common.Settings.Setting<boolean> {
return Common.Settings.Settings.instance().createSetting('emulation.showDeviceMode', false);
}
scaleSetting(): Common.Settings.Setting<number> {
return this.#scaleSettingInternal;
}
uaSetting(): Common.Settings.Setting<UA> {
return this.#uaSettingInternal;
}
deviceScaleFactorSetting(): Common.Settings.Setting<number> {
return this.#deviceScaleFactorSettingInternal;
}
deviceOutlineSetting(): Common.Settings.Setting<boolean> {
return this.#deviceOutlineSettingInternal;
}
toolbarControlsEnabledSetting(): Common.Settings.Setting<boolean> {
return this.#toolbarControlsEnabledSettingInternal;
}
reset(): void {
this.#deviceScaleFactorSettingInternal.set(0);
this.#scaleSettingInternal.set(1);
this.setWidth(400);
this.setHeight(0);
this.#uaSettingInternal.set(UA.Mobile);
}
modelAdded(emulationModel: SDK.EmulationModel.EmulationModel): void {
if (!this.#emulationModel && emulationModel.supportsDeviceEmulation()) {
this.#emulationModel = emulationModel;
if (this.#onModelAvailable) {
const callback = this.#onModelAvailable;
this.#onModelAvailable = null;
callback();
}
const resourceTreeModel = emulationModel.target().model(SDK.ResourceTreeModel.ResourceTreeModel);
if (resourceTreeModel) {
resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.FrameResized, this.onFrameChange, this);
resourceTreeModel.addEventListener(SDK.ResourceTreeModel.Events.FrameNavigated, this.onFrameChange, this);
}
} else {
emulationModel.emulateTouch(this.#touchEnabled, this.#touchMobile);
}
}
modelRemoved(emulationModel: SDK.EmulationModel.EmulationModel): void {
if (this.#emulationModel === emulationModel) {
this.#emulationModel = null;
}
}
inspectedURL(): string|null {
return this.#emulationModel ? this.#emulationModel.target().inspectedURL() : null;
}
private onFrameChange(): void {
const overlayModel = this.#emulationModel ? this.#emulationModel.overlayModel() : null;
if (!overlayModel) {
return;
}
this.showHingeIfApplicable(overlayModel);
}
private scaleSettingChanged(): void {
this.calculateAndEmulate(false);
}
private widthSettingChanged(): void {
this.calculateAndEmulate(false);
}
private heightSettingChanged(): void {
this.calculateAndEmulate(false);
}
private uaSettingChanged(): void {
this.calculateAndEmulate(true);
}
private deviceScaleFactorSettingChanged(): void {
this.calculateAndEmulate(false);
}
private deviceOutlineSettingChanged(): void {
this.calculateAndEmulate(false);
}
private preferredScaledWidth(): number {
return Math.floor(this.#preferredSize.width / (this.#scaleSettingInternal.get() || 1));
}
private preferredScaledHeight(): number {
return Math.floor(this.#preferredSize.height / (this.#scaleSettingInternal.get() || 1));
}
private currentOutline(): Insets {
let outline: Insets = new Insets(0, 0, 0, 0);
if (this.#typeInternal !== Type.Device || !this.#deviceInternal || !this.#modeInternal) {
return outline;
}
const orientation = this.#deviceInternal.orientationByName(this.#modeInternal.orientation);
if (this.#deviceOutlineSettingInternal.get()) {
outline = orientation.outlineInsets || outline;
}
return outline;
}
private currentInsets(): Insets {
if (this.#typeInternal !== Type.Device || !this.#modeInternal) {
return new Insets(0, 0, 0, 0);
}
return this.#modeInternal.insets;
}
private getScreenOrientationType(): Protocol.Emulation.ScreenOrientationType {
if (!this.#modeInternal) {
throw new Error('Mode required to get orientation type.');
}
switch (this.#modeInternal.orientation) {
case VerticalSpanned:
case Vertical:
return Protocol.Emulation.ScreenOrientationType.PortraitPrimary;
case HorizontalSpanned:
case Horizontal:
default:
return Protocol.Emulation.ScreenOrientationType.LandscapePrimary;
}
}
private calculateAndEmulate(resetPageScaleFactor: boolean): void {
if (!this.#emulationModel) {
this.#onModelAvailable = this.calculateAndEmulate.bind(this, resetPageScaleFactor);
}
const mobile = this.isMobile();
const overlayModel = this.#emulationModel ? this.#emulationModel.overlayModel() : null;
if (overlayModel) {
this.showHingeIfApplicable(overlayModel);
}
if (this.#typeInternal === Type.Device && this.#deviceInternal && this.#modeInternal) {
const orientation = this.#deviceInternal.orientationByName(this.#modeInternal.orientation);
const outline = this.currentOutline();
const insets = this.currentInsets();
this.#fitScaleInternal = this.calculateFitScale(orientation.width, orientation.height, outline, insets);
if (mobile) {
this.#appliedUserAgentTypeInternal = this.#deviceInternal.touch() ? UA.Mobile : UA.MobileNoTouch;
} else {
this.#appliedUserAgentTypeInternal = this.#deviceInternal.touch() ? UA.DesktopTouch : UA.Desktop;
}
this.applyDeviceMetrics(
new UI.Geometry.Size(orientation.width, orientation.height), insets, outline,
this.#scaleSettingInternal.get(), this.#deviceInternal.deviceScaleFactor, mobile,
this.getScreenOrientationType(), resetPageScaleFactor, this.#webPlatformExperimentalFeaturesEnabledInternal);
this.applyUserAgent(this.#deviceInternal.userAgent, this.#deviceInternal.userAgentMetadata);
this.applyTouch(this.#deviceInternal.touch(), mobile);
} else if (this.#typeInternal === Type.None) {
this.#fitScaleInternal = this.calculateFitScale(this.#availableSize.width, this.#availableSize.height);
this.#appliedUserAgentTypeInternal = UA.Desktop;
this.applyDeviceMetrics(
this.#availableSize, new Insets(0, 0, 0, 0), new Insets(0, 0, 0, 0), 1, 0, mobile, null,
resetPageScaleFactor);
this.applyUserAgent('', null);
this.applyTouch(false, false);
} else if (this.#typeInternal === Type.Responsive) {
let screenWidth = this.#widthSetting.get();
if (!screenWidth || screenWidth > this.preferredScaledWidth()) {
screenWidth = this.preferredScaledWidth();
}
let screenHeight = this.#heightSetting.get();
if (!screenHeight || screenHeight > this.preferredScaledHeight()) {
screenHeight = this.preferredScaledHeight();
}
const defaultDeviceScaleFactor = mobile ? defaultMobileScaleFactor : 0;
this.#fitScaleInternal = this.calculateFitScale(this.#widthSetting.get(), this.#heightSetting.get());
this.#appliedUserAgentTypeInternal = this.#uaSettingInternal.get();
this.applyDeviceMetrics(
new UI.Geometry.Size(screenWidth, screenHeight), new Insets(0, 0, 0, 0), new Insets(0, 0, 0, 0),
this.#scaleSettingInternal.get(), this.#deviceScaleFactorSettingInternal.get() || defaultDeviceScaleFactor,
mobile,
screenHeight >= screenWidth ? Protocol.Emulation.ScreenOrientationType.PortraitPrimary :
Protocol.Emulation.ScreenOrientationType.LandscapePrimary,
resetPageScaleFactor);
this.applyUserAgent(mobile ? defaultMobileUserAgent : '', mobile ? defaultMobileUserAgentMetadata : null);
this.applyTouch(
this.#uaSettingInternal.get() === UA.DesktopTouch || this.#uaSettingInternal.get() === UA.Mobile,
this.#uaSettingInternal.get() === UA.Mobile);
}
if (overlayModel) {
overlayModel.setShowViewportSizeOnResize(this.#typeInternal === Type.None);
}
this.dispatchEventToListeners(Events.Updated);
}
private calculateFitScale(screenWidth: number, screenHeight: number, outline?: Insets, insets?: Insets): number {
const outlineWidth = outline ? outline.left + outline.right : 0;
const outlineHeight = outline ? outline.top + outline.bottom : 0;
const insetsWidth = insets ? insets.left + insets.right : 0;
const insetsHeight = insets ? insets.top + insets.bottom : 0;
let scale = Math.min(
screenWidth ? this.#preferredSize.width / (screenWidth + outlineWidth) : 1,
screenHeight ? this.#preferredSize.height / (screenHeight + outlineHeight) : 1);
scale = Math.min(Math.floor(scale * 100), 100);
let sharpScale = scale;
while (sharpScale > scale * 0.7) {
let sharp = true;
if (screenWidth) {
sharp = sharp && Number.isInteger((screenWidth - insetsWidth) * sharpScale / 100);
}
if (screenHeight) {
sharp = sharp && Number.isInteger((screenHeight - insetsHeight) * sharpScale / 100);
}
if (sharp) {
return sharpScale / 100;
}
sharpScale -= 1;
}
return scale / 100;
}
setSizeAndScaleToFit(width: number, height: number): void {
this.#scaleSettingInternal.set(this.calculateFitScale(width, height));
this.setWidth(width);
this.setHeight(height);
}
private applyUserAgent(userAgent: string, userAgentMetadata: Protocol.Emulation.UserAgentMetadata|null): void {
SDK.NetworkManager.MultitargetNetworkManager.instance().setUserAgentOverride(userAgent, userAgentMetadata);
}
private applyDeviceMetrics(
screenSize: UI.Geometry.Size, insets: Insets, outline: Insets, scale: number, deviceScaleFactor: number,
mobile: boolean, screenOrientation: Protocol.Emulation.ScreenOrientationType|null, resetPageScaleFactor: boolean,
forceMetricsOverride: boolean|undefined = false): void {
screenSize.width = Math.max(1, Math.floor(screenSize.width));
screenSize.height = Math.max(1, Math.floor(screenSize.height));
let pageWidth: 0|number = screenSize.width - insets.left - insets.right;
let pageHeight: 0|number = screenSize.height - insets.top - insets.bottom;
this.#emulatedPageSize = new UI.Geometry.Size(pageWidth, pageHeight);
const positionX = insets.left;
const positionY = insets.top;
const screenOrientationAngle =
screenOrientation === Protocol.Emulation.ScreenOrientationType.LandscapePrimary ? 90 : 0;
this.#appliedDeviceSizeInternal = screenSize;
this.#appliedDeviceScaleFactorInternal = deviceScaleFactor || window.devicePixelRatio;
this.#screenRectInternal = new Rect(
Math.max(0, (this.#availableSize.width - screenSize.width * scale) / 2), outline.top * scale,
screenSize.width * scale, screenSize.height * scale);
this.#outlineRectInternal = new Rect(
this.#screenRectInternal.left - outline.left * scale, 0,
(outline.left + screenSize.width + outline.right) * scale,
(outline.top + screenSize.height + outline.bottom) * scale);
this.#visiblePageRectInternal = new Rect(
positionX * scale, positionY * scale,
Math.min(pageWidth * scale, this.#availableSize.width - this.#screenRectInternal.left - positionX * scale),
Math.min(pageHeight * scale, this.#availableSize.height - this.#screenRectInternal.top - positionY * scale));
this.#scaleInternal = scale;
if (!forceMetricsOverride) {
// When sending displayFeature, we cannot use the optimization below due to backend restrictions.
if (scale === 1 && this.#availableSize.width >= screenSize.width &&
this.#availableSize.height >= screenSize.height) {
// When we have enough space, no page size override is required. This will speed things up and remove lag.
pageWidth = 0;
pageHeight = 0;
}
if (this.#visiblePageRectInternal.width === pageWidth * scale &&
this.#visiblePageRectInternal.height === pageHeight * scale && Number.isInteger(pageWidth * scale) &&
Number.isInteger(pageHeight * scale)) {
// When we only have to apply scale, do not resize the page. This will speed things up and remove lag.
pageWidth = 0;
pageHeight = 0;
}
}
if (!this.#emulationModel) {
return;
}
if (resetPageScaleFactor) {
this.#emulationModel.resetPageScaleFactor();
}
if (pageWidth || pageHeight || mobile || deviceScaleFactor || scale !== 1 || screenOrientation ||
forceMetricsOverride) {
const metrics: Protocol.Emulation.SetDeviceMetricsOverrideRequest = {
width: pageWidth,
height: pageHeight,
deviceScaleFactor: deviceScaleFactor,
mobile: mobile,
scale: scale,
screenWidth: screenSize.width,
screenHeight: screenSize.height,
positionX: positionX,
positionY: positionY,
dontSetVisibleSize: true,
displayFeature: undefined,
screenOrientation: undefined,
};
const displayFeature = this.getDisplayFeature();
if (displayFeature) {
metrics.displayFeature = displayFeature;
}
if (screenOrientation) {
metrics.screenOrientation = {type: screenOrientation, angle: screenOrientationAngle};
}
this.#emulationModel.emulateDevice(metrics);
} else {
this.#emulationModel.emulateDevice(null);
}
}
exitHingeMode(): void {
const overlayModel = this.#emulationModel ? this.#emulationModel.overlayModel() : null;
if (overlayModel) {
overlayModel.showHingeForDualScreen(null);
}
}
webPlatformExperimentalFeaturesEnabled(): boolean {
return this.#webPlatformExperimentalFeaturesEnabledInternal;
}
shouldReportDisplayFeature(): boolean {
return this.#webPlatformExperimentalFeaturesEnabledInternal && this.#experimentDualScreenSupport;
}
async captureScreenshot(fullSize: boolean, clip?: Protocol.Page.Viewport): Promise<string|null> {
const screenCaptureModel =
this.#emulationModel ? this.#emulationModel.target().model(SDK.ScreenCaptureModel.ScreenCaptureModel) : null;
if (!screenCaptureModel) {
return null;
}
const overlayModel = this.#emulationModel ? this.#emulationModel.overlayModel() : null;
if (overlayModel) {
overlayModel.setShowViewportSizeOnResize(false);
}
// Define the right clipping area for fullsize screenshots.
if (fullSize) {
const metrics = await screenCaptureModel.fetchLayoutMetrics();
if (!metrics) {
return null;
}
// Cap the height to not hit the GPU limit.
const contentHeight = Math.min((1 << 14), metrics.contentHeight);
clip = {x: 0, y: 0, width: Math.floor(metrics.contentWidth), height: Math.floor(contentHeight), scale: 1};
}
const screenshot =
await screenCaptureModel.captureScreenshot(Protocol.Page.CaptureScreenshotRequestFormat.Png, 100, clip);
const deviceMetrics: Protocol.Page.SetDeviceMetricsOverrideRequest = {
width: 0,
height: 0,
deviceScaleFactor: 0,
mobile: false,
};
if (fullSize && this.#emulationModel) {
if (this.#deviceInternal && this.#modeInternal) {
const orientation = this.#deviceInternal.orientationByName(this.#modeInternal.orientation);
deviceMetrics.width = orientation.width;
deviceMetrics.height = orientation.height;
const dispFeature = this.getDisplayFeature();
if (dispFeature) {
// @ts-ignore: displayFeature isn't in protocol.d.ts but is an
// experimental flag:
// https://chromedevtools.github.io/devtools-protocol/tot/Emulation/#method-setDeviceMetricsOverride
deviceMetrics.displayFeature = dispFeature;
}
} else {
deviceMetrics.width = 0;
deviceMetrics.height = 0;
}
await this.#emulationModel.emulateDevice(deviceMetrics);
}
this.calculateAndEmulate(false);
return screenshot;
}
private applyTouch(touchEnabled: boolean, mobile: boolean): void {
this.#touchEnabled = touchEnabled;
this.#touchMobile = mobile;
for (const emulationModel of SDK.TargetManager.TargetManager.instance().models(SDK.EmulationModel.EmulationModel)) {
emulationModel.emulateTouch(touchEnabled, mobile);
}
}
private showHingeIfApplicable(overlayModel: SDK.OverlayModel.OverlayModel): void {
const orientation = (this.#deviceInternal && this.#modeInternal) ?
this.#deviceInternal.orientationByName(this.#modeInternal.orientation) :
null;
if (this.#experimentDualScreenSupport && orientation && orientation.hinge) {
overlayModel.showHingeForDualScreen(orientation.hinge);
return;
}
overlayModel.showHingeForDualScreen(null);
}
private getDisplayFeatureOrientation(): Protocol.Emulation.DisplayFeatureOrientation {
if (!this.#modeInternal) {
throw new Error('Mode required to get display feature orientation.');
}
switch (this.#modeInternal.orientation) {
case VerticalSpanned:
case Vertical:
return Protocol.Emulation.DisplayFeatureOrientation.Vertical;
case HorizontalSpanned:
case Horizontal:
default:
return Protocol.Emulation.DisplayFeatureOrientation.Horizontal;
}
}
private getDisplayFeature(): Protocol.Emulation.DisplayFeature|null {
if (!this.shouldReportDisplayFeature()) {
return null;
}
if (!this.#deviceInternal || !this.#modeInternal ||
(this.#modeInternal.orientation !== VerticalSpanned && this.#modeInternal.orientation !== HorizontalSpanned)) {
return null;
}
const orientation = this.#deviceInternal.orientationByName(this.#modeInternal.orientation);
if (!orientation || !orientation.hinge) {
return null;
}
const hinge = orientation.hinge;
return {
orientation: this.getDisplayFeatureOrientation(),
offset: (this.#modeInternal.orientation === VerticalSpanned) ? hinge.x : hinge.y,
maskLength: (this.#modeInternal.orientation === VerticalSpanned) ? hinge.width : hinge.height,
};
}
}
export class Insets {
constructor(public left: number, public top: number, public right: number, public bottom: number) {
}
isEqual(insets: Insets|null): boolean {
return insets !== null && this.left === insets.left && this.top === insets.top && this.right === insets.right &&
this.bottom === insets.bottom;
}
}
export class Rect {
constructor(public left: number, public top: number, public width: number, public height: number) {
}
isEqual(rect: Rect|null): boolean {
return rect !== null && this.left === rect.left && this.top === rect.top && this.width === rect.width &&
this.height === rect.height;
}
scale(scale: number): Rect {
return new Rect(this.left * scale, this.top * scale, this.width * scale, this.height * scale);
}
relativeTo(origin: Rect): Rect {
return new Rect(this.left - origin.left, this.top - origin.top, this.width, this.height);
}
rebaseTo(origin: Rect): Rect {
return new Rect(this.left + origin.left, this.top + origin.top, this.width, this.height);
}
}
export const enum Events {
Updated = 'Updated',
}
export type EventTypes = {
[Events.Updated]: void,
};
// TODO(crbug.com/1167717): Make this a const enum again
// eslint-disable-next-line rulesdir/const_enum
export enum Type {
None = 'None',
Responsive = 'Responsive',
Device = 'Device',
}
// TODO(crbug.com/1167717): Make this a const enum again
// eslint-disable-next-line rulesdir/const_enum
export enum UA {
// TODO(crbug.com/1136655): This enum is used for both display and code functionality.
// we should refactor this so localization of these strings only happens for user display.
Mobile = 'Mobile',
MobileNoTouch = 'Mobile (no touch)',
Desktop = 'Desktop',
DesktopTouch = 'Desktop (touch)',
}
export const MinDeviceSize = 50;
export const MaxDeviceSize = 9999;
export const MinDeviceScaleFactor = 0;
export const MaxDeviceScaleFactor = 10;
export const MaxDeviceNameLength = 50;
const mobileUserAgent =
'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Mobile Safari/537.36';
const defaultMobileUserAgent =
SDK.NetworkManager.MultitargetNetworkManager.patchUserAgentWithChromeVersion(mobileUserAgent);
const defaultMobileUserAgentMetadata = {
platform: 'Android',
platformVersion: '6.0',
architecture: '',
model: 'Nexus 5',
mobile: true,
};
export const defaultMobileScaleFactor = 2; | the_stack |
import {
Component, OnInit, Input, Output,
EventEmitter, ElementRef, OnDestroy,
HostListener, OnChanges, SimpleChanges, ViewChild,
Renderer, AfterContentInit
} from '@angular/core';
import { Store } from '@ngrx/store';
import { PerfectScrollbarComponent, PerfectScrollbarDirective } from 'ngx-perfect-scrollbar';
import {
global, emojiConfig, jpushConfig, imgRouter,
pageNumber, authPayload, StorageService
} from '../../services/common';
import { Util } from '../../services/util';
import { Emoji } from '../../services/tools';
import { chatAction } from '../../pages/chat/actions';
import { roomAction } from '../../pages/room/actions';
import * as download from 'downloadjs';
@Component({
selector: 'room-panel-component',
templateUrl: './room-panel.component.html',
styleUrls: ['./room-panel.component.scss']
})
export class RoomPanelComponent implements OnInit, OnChanges, AfterContentInit, OnDestroy {
@ViewChild(PerfectScrollbarComponent) private componentScroll;
@ViewChild('contentDiv') private contentDiv;
@Input()
private enter;
@Input()
private messageList;
@Input()
private selfInfo;
@Input()
private scrollToBottom;
@Input()
private otherScrollTobottom;
@Output()
private showRoomInfomation: EventEmitter<any> = new EventEmitter();
@Output()
private sendFile: EventEmitter<any> = new EventEmitter();
@Output()
private sendPic: EventEmitter<any> = new EventEmitter();
@Output()
private businessCardSend: EventEmitter<any> = new EventEmitter();
@Output()
private sendMsg: EventEmitter<any> = new EventEmitter();
@Output()
private msgTransmit: EventEmitter<any> = new EventEmitter();
@Output()
private selfInfoEmit: EventEmitter<any> = new EventEmitter();
@Output()
private otherInfo: EventEmitter<any> = new EventEmitter();
@Output()
private videoPlay: EventEmitter<any> = new EventEmitter();
@Output()
private voiceHasPlay: EventEmitter<any> = new EventEmitter();
private viewer = {};
private imageViewer = {
result: [],
active: {
index: -1
},
show: false,
};
private loadFlag = true;
private roomInfomationHover = {
tip: '聊天室资料',
position: {
left: -40,
top: 27
},
show: false
};
private emojiInfo = {
show: false,
position: {
left: 0,
top: 0
},
emojiAlias: emojiConfig,
jpushAlias: jpushConfig,
contentId: 'contentDiv2'
};
private inputNoBlur = true;
private inputToLast = false;
private flag = false;
private businessCard = {
show: false,
info: []
};
private pasteImage: any = {
show: false,
info: {
src: '',
width: 0,
height: 0,
pasteFile: {}
}
};
private dropFileInfo: any = {
show: false,
info: {}
};
private global = global;
private moreMenu = {
show: false,
top: 0,
left: 0,
info: [
{
key: 0,
name: '转发',
show: true,
isFirst: true
},
{
key: 1,
name: '复制',
show: true,
isFirst: false
}
],
item: null
};
private roomPanelStream$;
private mainMenu;
constructor(
private elementRef: ElementRef,
private store$: Store<any>,
private storageService: StorageService,
private renderer: Renderer
) { }
public ngOnInit() {
this.roomPanelStream$ = this.store$.select((state) => {
const roomState = state['roomReducer'];
const contactState = state['contactReducer'];
this.stateChanged(roomState, contactState);
return state;
}).subscribe((state) => {
// pass
});
}
public ngOnChanges(changes: SimpleChanges) {
if (changes.scrollToBottom) {
if (this.contentDiv.nativeElement) {
this.contentDiv.nativeElement.innerHTML = '';
}
this.scrollBottom(150, false, () => {
if (this.contentDiv.nativeElement) {
this.contentDiv.nativeElement.focus();
}
});
}
if (changes.otherScrollTobottom) {
this.scrollBottom(150, true);
}
}
public ngAfterContentInit() {
this.mainMenu = document.getElementById('mainMenu');
}
public ngOnDestroy() {
this.roomPanelStream$.unsubscribe();
}
@HostListener('document:drop', ['$event']) private onDrop(event) {
event.preventDefault();
}
@HostListener('document:dragleave', ['$event']) private onDragleave(event) {
event.preventDefault();
}
@HostListener('document:dragenter', ['$event']) private ondDagenter(event) {
event.preventDefault();
}
@HostListener('document:dragover', ['$event']) private onDragover(event) {
event.preventDefault();
}
@HostListener('window:click') private onClickWindow() {
this.inputToLast = true;
this.inputNoBlur = true;
}
@HostListener('window:keyup', ['$event']) private onKeyupWindow(event) {
// 回车发送复制的图片或者拖拽的文件
if (this.pasteImage.show && event.keyCode === 13) {
this.pasteImageEmit();
this.pasteImage = {
show: false,
info: {
src: '',
width: 0,
height: 0,
pasteFile: {}
}
};
} else if (this.dropFileInfo.show && event.keyCode === 13) {
this.dropFileEmit();
this.dropFileInfo = {
show: false,
info: {}
};
}
}
private scrollBottom(time: number, isLoad?: boolean, callback?: () => void) {
if (!isLoad) {
this.loadFlag = false;
}
setTimeout(() => {
this.componentScroll.directiveRef.update();
this.componentScroll.directiveRef.scrollToBottom();
if (!isLoad) {
this.loadFlag = true;
}
if (callback) {
callback();
}
}, time);
}
private stateChanged(roomState, contactState) {
switch (roomState.actionType) {
case chatAction.dispatchFriendList:
this.businessCard.info = contactState.friendList;
break;
case roomAction.receiveMessageSuccess:
this.pointerToMap(roomState);
case roomAction.sendTextMsg:
case roomAction.sendFileMsg:
case roomAction.sendPicMsg:
case roomAction.transmitPicMsg:
this.imageViewer.result = roomState.imageViewer;
break;
default:
}
}
// 接收到地图消息渲染地图
private pointerToMap(roomState) {
if (roomState.newMessage.content.msg_type === 'location') {
const length = roomState.messageList.length;
const newMessage = Util.deepCopyObj(roomState.newMessage);
const msgBody = newMessage.content.msg_body;
setTimeout(() => {
Util.theLocation({
id: 'allmap2' + (length - 1).toString(),
longitude: msgBody.longitude,
latitude: msgBody.latitude,
scale: msgBody.scale
});
});
}
}
private msgContentClick(event) {
event.stopPropagation();
this.inputToLast = false;
}
private msgMouseleave() {
this.moreMenu.show = false;
}
private menuItemEnterEmit() {
this.menuMouse(true);
}
private menuItemLeaveEmit() {
this.menuMouse(false);
}
private menuMouse(isShow) {
for (let item of this.messageList) {
if (this.moreMenu.item.msg_id === item.msg_id) {
item.showMoreIcon = isShow;
break;
}
}
}
// 显示图片预览
private imageViewerShow(item) {
for (let i = 0; i < this.imageViewer.result.length; i++) {
const msgIdFlag = item.msg_id && this.imageViewer.result[i].msg_id === item.msg_id;
const msgKeyFlag = item.msgKey && this.imageViewer.result[i].msgKey === item.msgKey;
if (msgIdFlag || msgKeyFlag) {
this.imageViewer.active = Util.deepCopyObj(this.imageViewer.result[i]);
this.imageViewer.active.index = i;
break;
}
}
this.imageViewer.show = true;
this.viewer = this.imageViewer;
this.mainMenu.style.zIndex = '3';
}
// 关闭图片预览
private closeImageViewerEmit() {
this.mainMenu.style.zIndex = '4';
}
// 点击更多列表的元素
private selectMoreMenuItemEmit(item) {
if (item.key === 0) {
this.msgTransmit.emit(this.moreMenu.item);
}
this.moreMenu.show = false;
}
private showYouMoreText(event, item) {
const showArr = [true, true];
const isFirstArr = [true, false];
this.menuOption(showArr, isFirstArr);
this.moreOperation(event, item);
}
private showYouMoreOther(event, item) {
const showArr = [true, false];
const isFirstArr = [true, false];
this.menuOption(showArr, isFirstArr);
this.moreOperation(event, item);
}
private showMeMoreText(event, item) {
const showArr = [true, true];
const isFirstArr = [true, false];
this.menuOption(showArr, isFirstArr);
this.moreOperation(event, item);
}
private showMeMoreOther(event, item) {
const showArr = [true, false];
const isFirstArr = [true, false];
this.menuOption(showArr, isFirstArr);
this.moreOperation(event, item);
}
// 更多列表的配置
private menuOption(showArr, isFirstArr) {
for (let i = 0; i < showArr.length; i++) {
this.moreMenu.info[i].show = showArr[i];
}
for (let i = 0; i < isFirstArr.length; i++) {
this.moreMenu.info[i].isFirst = isFirstArr[i];
}
}
// 更多列表的位置
private moreOperation(event, item) {
this.moreMenu.show = !this.moreMenu.show;
if (this.moreMenu.show) {
this.moreMenu.top = event.clientY - event.offsetY + 20;
this.moreMenu.left = event.clientX - event.offsetX;
this.moreMenu.item = item;
}
}
private showRoomInfomationAction() {
this.showRoomInfomation.emit();
}
// 显示隐藏emoji面板
private showEmojiPanel(event) {
this.inputNoBlur = false;
event.stopPropagation();
this.contentDiv.nativeElement.focus();
if (this.inputToLast) {
Util.focusLast(this.contentDiv.nativeElement);
}
if (this.emojiInfo.show) {
setTimeout(() => {
this.inputNoBlur = true;
}, 200);
}
this.emojiInfo.show = !this.emojiInfo.show;
}
private showBusinessCardModal() {
this.businessCard.show = true;
this.mainMenu.style.zIndex = '3';
}
private businessCardSendEmit(user) {
this.businessCardSend.emit(user);
this.mainMenu.style.zIndex = '4';
}
private closeBusinessCardEmit() {
this.mainMenu.style.zIndex = '4';
}
// 粘贴图片发送
private pasteImageEmit() {
let img = new FormData();
img.append(this.pasteImage.info.pasteFile.name, this.pasteImage.info.pasteFile);
this.sendPic.emit({
img,
type: 'paste',
info: this.pasteImage.info
});
}
// 粘贴文本,将文本多余的样式代码去掉/粘贴图片
private pasteMessage(event) {
const clipboardData = event.clipboardData || (<any>window).clipboardData;
const items = clipboardData.items;
const files = clipboardData.files;
let item;
// 粘贴图片不兼容safari
if (!Util.isSafari()) {
if (files && files.length) {
this.getImgObj(files[0]);
} else if (items) {
for (let i = 0; i < items.length; i++) {
if (items[i].kind === 'file' && items[i].type.match(/^image\//i)) {
item = items[i];
break;
}
}
}
if (item) {
this.getImgObj(item.getAsFile());
}
}
let pastedData = clipboardData.getData('Text');
pastedData = pastedData.replace(/</g, '<');
pastedData = pastedData.replace(/>/g, '>');
pastedData = pastedData.replace(/\n/g, '<br>');
pastedData = pastedData.replace(/ /g, ' ');
pastedData = Emoji.emoji(pastedData, 18);
Util.insertAtCursor(this.contentDiv.nativeElement, pastedData, false);
return false;
}
// 拖拽预览文件或者图片
private dropArea(event) {
event.preventDefault();
let fileList = event.dataTransfer.files;
if (fileList.length === 0) {
return false;
}
// 检测文件是不是图片
if (fileList[0].type.indexOf('image') === -1) {
this.dropFileInfo.info = fileList[0];
this.dropFileInfo.show = true;
} else {
this.getImgObj(fileList[0]);
}
}
private dropFileEmit() {
let file = new FormData();
file.append(this.dropFileInfo.info.name, this.dropFileInfo.info);
this.sendFile.emit({
file,
fileData: this.dropFileInfo.info
});
}
// 获取拖拽时或者粘贴图片时的图片对象
private getImgObj(file) {
const that = this;
let img = new Image();
let pasteFile = file;
let reader = new FileReader();
reader.readAsDataURL(pasteFile);
reader.onload = function (e) {
img.src = this.result;
const _this = this;
img.onload = function () {
that.pasteImage.info = {
src: _this.result,
width: img.naturalWidth,
height: img.naturalHeight,
pasteFile
};
that.pasteImage.show = true;
};
};
}
private fileDownload(url) {
// 为了兼容火狐下a链接下载,引入downloadjs
download(url);
}
// 发送文本
private sendMsgAction() {
let draft = this.contentDiv.nativeElement.innerHTML;
if (draft) {
draft = draft.replace(/^(<br>){1,}$/g, '');
draft = draft.replace(/ /g, ' ');
draft = draft.replace(/<br>/g, '\n');
const imgReg = new RegExp(`<img.+?${imgRouter}.{1,}?\.png".*?>`, 'g');
if (draft.match(imgReg)) {
let arr = draft.match(imgReg);
for (let item of arr) {
let str = item.split(`src="${imgRouter}`)[1];
let str2 = str.split('.png"')[0];
draft = draft.replace(item, Emoji.convert(str2));
}
}
draft = draft.replace(new RegExp('<', 'g'), '<');
draft = draft.replace(new RegExp('>', 'g'), '>');
this.sendMsg.emit({
content: draft
});
this.flag = true;
this.contentDiv.nativeElement.innerHTML = '';
}
}
// 重新发送文本消息和名片消息
private repeatSendMsgAction(item) {
item.success = 1;
this.sendMsg.emit({
repeatSend: item
});
}
// 发送文件
private sendFileAction(event) {
// 为了防止首次选择了文件,第二次选择文件的时候点击取消按钮时触发change事件的报错
if (!event.target.files[0]) {
return;
}
let file = Util.getFileFormData(event.target);
this.sendFile.emit({
file,
fileData: event.target.files[0]
});
this.contentDiv.nativeElement.focus();
Util.focusLast(this.contentDiv.nativeElement);
event.target.value = '';
}
private repeatSendFileAction(item) {
item.success = 1;
this.sendFile.emit({
repeatSend: item
});
}
// 发送图片
private sendPicAction(event) {
// 为了防止首次选择了文件,第二次选择文件的时候点击取消按钮时触发change事件的报错
if (!event.target.files[0]) {
return;
}
let img = Util.getFileFormData(event.target);
this.sendPic.emit({
img,
type: 'img'
});
this.contentDiv.nativeElement.focus();
Util.focusLast(this.contentDiv.nativeElement);
event.target.value = '';
}
private repeatSendPicAction(item) {
item.success = 1;
this.sendPic.emit({
repeatSend: item
});
}
private jpushEmojiSelectEmit(jpushEmoji) {
this.sendPic.emit({
jpushEmoji,
type: 'jpushEmoji'
});
}
private imgLoaded(i) {
i.content.msg_body.loading = true;
}
// 查看自己的资料
private watchSelfInfo() {
this.selfInfoEmit.emit();
}
// 查看对方用户资料
private watchOtherInfo(content) {
let username = content.from_id ? content.from_id : content.name;
let info: any = {
username
};
if (content.hasOwnProperty('avatarUrl')) {
info.avatarUrl = content.avatarUrl;
}
this.otherInfo.emit(info);
}
// 点击查看名片
private watchBusinessCardInfo(extras) {
let info: any = {
username: extras.userName
};
if (extras.avatarUrl) {
info.avatarUrl = extras.avatarUrl;
}
if (extras.userName === global.user) {
this.selfInfoEmit.emit();
} else {
this.otherInfo.emit(info);
}
}
// 输入框keydown,ctrl + enter换行,enter发送消息
private preKeydown(event) {
if (event.keyCode === 13 && event.ctrlKey) {
let insertHtml = '<br>';
if (window.getSelection) {
let next = window.getSelection().focusNode.nextSibling;
do {
if (!next || next.nodeValue || 'BR' === (next as HTMLElement).tagName) {
break;
}
} while (next = next.nextSibling);
next || (insertHtml += insertHtml);
if (next && next.nodeName === '#text' && insertHtml !== '<br><br>' &&
event.target.innerHTML && !event.target.innerHTML.match(/<br>$/ig)) {
insertHtml += insertHtml;
}
if (!event.target.innerHTML) {
insertHtml += insertHtml;
}
}
// safari自身可以换行,不用处理
if (!Util.isSafari()) {
Util.insertAtCursor(this.contentDiv.nativeElement, insertHtml, false);
}
} else if (event.keyCode === 13) {
this.sendMsgAction();
event.preventDefault();
}
}
private contentFocus() {
this.contentDiv.nativeElement.focus();
Util.focusLast(this.contentDiv.nativeElement);
}
// 视频开始加载
private videoLoadStart(index) {
const that = this;
this.messageList[index].content.timer4 = setInterval(function () {
if (!that.messageList[index] || !that.messageList[index].content) {
clearInterval(this);
return;
}
if (that.messageList[index].content.range < 90) {
that.messageList[index].content.range++;
} else {
clearInterval(this);
}
}, 100);
}
// 视频加载完成
private videoLoad(index) {
this.messageList[index].content.duration =
Math.ceil(this.elementRef.nativeElement.querySelector('#video2' + index).duration);
this.messageList[index].content.load = 1;
clearInterval(this.messageList[index].content.timer4);
this.messageList[index].content.range = 0;
}
private playVideo(url) {
this.videoPlay.emit(url);
}
// 播放语音
private playVoice(index) {
const audio = this.elementRef.nativeElement.querySelector('#audio2' + index);
if (audio.paused) {
this.clearVoicePlay(index);
audio.play();
this.messageList[index].content.playing = true;
// 如果是未读
if (!this.messageList[index].content.havePlay) {
let voiceState = {
id: this.enter.id,
msgId: this.messageList[index].msg_id
};
this.messageList[index].content.havePlay = true;
this.voiceHasPlay.emit(voiceState);
}
} else {
audio.pause();
this.messageList[index].content.playing = false;
}
}
// 清除语音播放
private clearVoicePlay(index) {
for (let i = 0; i < this.messageList.length; i++) {
let content = this.messageList[i].content;
if (content.msg_type === 'voice' && content.playing && i !== index) {
const otherAudio = this.elementRef.nativeElement.querySelector('#audio2' + i);
otherAudio.pause();
otherAudio.currentTime = 0;
content.playing = false;
}
}
}
// 语音播放完成
private voiceEnded(index) {
const audio = this.elementRef.nativeElement.querySelector('#audio2' + index);
this.messageList[index].content.playing = false;
audio.currentTime = 0;
audio.pause();
}
// 语音加载完成
private voiceLoad(index) {
const audio = this.elementRef.nativeElement.querySelector('#audio' + index);
this.messageList[index].content.load = 1;
}
} | the_stack |
import { NgChat } from '../ng-chat/ng-chat.component';
import { User } from '../ng-chat/core/user';
import { ParticipantResponse } from '../ng-chat/core/participant-response';
import { Window } from '../ng-chat/core/window';
import { ChatAdapter } from '../ng-chat/core/chat-adapter';
import { IChatGroupAdapter } from '../ng-chat/core/chat-group-adapter';
import { Observable, of } from 'rxjs';
import { Message } from '../ng-chat/core/message';
import { MessageType } from '../ng-chat/core/message-type.enum';
import { Theme } from '../ng-chat/core/theme.enum';
import { ChatParticipantType } from '../ng-chat/core/chat-participant-type.enum';
import { Group } from '../ng-chat/core/group';
import { IChatOption } from '../ng-chat/core/chat-option';
import { NgChatWindowComponent } from '../ng-chat/components/ng-chat-window/ng-chat-window.component';
class MockableAdapter extends ChatAdapter {
public listFriends(): Observable<ParticipantResponse[]> {
throw new Error("Method not implemented.");
}
public getMessageHistory(destinataryId: any): Observable<Message[]> {
throw new Error("Method not implemented.");
}
public sendMessage(message: Message): void {
throw new Error("Method not implemented.");
}
}
class MockableGroupAdapter implements IChatGroupAdapter {
groupCreated(group: Group): void {
throw new Error("Method not implemented.");
}
}
class MockableHTMLAudioElement {
public play(): void { }
public load(): void { }
}
// As "any" we allow private methods to be stubbed. Another option would be => spyOn<any>()
let subject: any = null;
describe('NgChat', () => {
beforeEach(() => {
subject = new NgChat(null); // HttpClient related methods are tested elsewhere
subject.userId = 123;
subject.adapter = new MockableAdapter();
subject.groupAdapter = new MockableGroupAdapter();
subject.audioFile = new MockableHTMLAudioElement();
});
it('Should have default title', () => {
expect(subject.title).toBe('Friends');
});
it('Should have default message placeholder', () => {
expect(subject.messagePlaceholder).toBe('Type a message');
});
it('Should have default friends search placeholder', () => {
expect(subject.searchPlaceholder).toBe('Search');
});
it('Should have default polling interval', () => {
expect(subject.pollingInterval).toBe(5000);
});
it('Must have history enabled by default', () => {
expect(subject.historyEnabled).not.toBeFalsy();
});
it('Must have emojis enabled by default', () => {
expect(subject.emojisEnabled).not.toBeFalsy();
});
it('Audio notification must be enabled by default', () => {
expect(subject.audioEnabled).not.toBeFalsy();
});
it('Audio notification must have a default source', () => {
expect(subject.audioSource).not.toBeUndefined();
});
it('Friends list search must be enabled by default', () => {
expect(subject.searchEnabled).not.toBeFalsy();
});
it('Persistent windows state must be enabled by default', () => {
expect(subject.persistWindowsState).toBeTruthy();
});
it('Is viewport mobile case state must be disabled by default', () => {
expect(subject.isViewportOnMobileEnabled).toBeFalsy();
});
it('isCollapsed must be disabled by default', () => {
expect(subject.isCollapsed).toBeFalsy();
});
it('maximizeWindowOnNewMessage must be enabled by default', () => {
expect(subject.maximizeWindowOnNewMessage).toBeTruthy();
});
it('Must use current user id as part of the localStorageKey identifier', () => {
expect(subject.localStorageKey).toBe(`ng-chat-users-${subject.userId}`);
});
it('Browser notifications must be enabled by default', () => {
expect(subject.browserNotificationsEnabled).not.toBeFalsy();
});
it('Browser notifications must have a default source', () => {
expect(subject.browserNotificationIconSource).not.toBeUndefined();
});
it('Browser notifications must not be bootstrapped before initialization', () => {
expect(subject.browserNotificationsBootstrapped).toBeFalsy();
});
it('Browser notifications must have a default title', () => {
expect(subject.browserNotificationTitle).toBe('New message from');
});
it('onParticipantClicked must have a default event emitter', () => {
expect(subject.onParticipantClicked).toBeDefined();
});
it('onParticipantChatClosed must have a default event emitter', () => {
expect(subject.onParticipantChatClosed).toBeDefined();
});
it('onParticipantChatClosed must have a default event emitter', () => {
expect(subject.onParticipantChatClosed).toBeDefined();
});
it('File upload url must be undefined by default', () => {
expect(subject.fileUploadAdapter).toBeUndefined();
});
it('Default theme must be Light', () => {
expect(subject.theme).toBe(Theme.Light);
});
it('Custom theme must be undefined by default', () => {
expect(subject.customTheme).toBeUndefined();
});
it('Must display max visible windows on viewport', () => {
subject.viewPortTotalArea = 960; // Just enough for 2 windows based on the default window size of 320
expect(subject.windows.length).toBe(0);
spyOn(subject, 'updateWindowsState');
subject.windows = [
new Window(null, false, false),
new Window(null, false, false),
new Window(null, false, false)
];
subject.NormalizeWindows();
expect(subject.windows.length).toBe(2);
expect(subject.updateWindowsState).toHaveBeenCalledTimes(1);
expect(subject.updateWindowsState).toHaveBeenCalledWith(subject.windows);
});
it('Must display max visible windows on viewport when "hideFriendsList" is enabled', () => {
subject.viewPortTotalArea = 960;
subject.hideFriendsList = true
expect(subject.windows.length).toBe(0);
spyOn(subject, 'updateWindowsState');
subject.windows = [
new Window(null, false, false),
new Window(null, false, false),
new Window(null, false, false),
new Window(null, false, false)
];
subject.NormalizeWindows();
expect(subject.windows.length).toBe(3);
expect(subject.updateWindowsState).toHaveBeenCalledTimes(1);
expect(subject.updateWindowsState).toHaveBeenCalledWith(subject.windows);
});
it('Must hide friends list when there is not enough viewport to display at least one chat window ', () => {
subject.viewPortTotalArea = 400;
expect(subject.windows.length).toBe(0);
subject.windows = [
new Window(null, false, false),
new Window(null, false, false)
];
subject.NormalizeWindows();
expect(subject.windows.length).toBe(0);
expect(subject.unsupportedViewport).toBe(true);
});
it('Must invoke adapter on fetchFriendsList', () => {
spyOn(MockableAdapter.prototype, 'listFriends').and.returnValue(of([]));
subject.fetchFriendsList(false);
expect(MockableAdapter.prototype.listFriends).toHaveBeenCalledTimes(1);
});
it('Must invoke restore windows state on fetchFriendsList when bootstrapping', () => {
spyOn(MockableAdapter.prototype, 'listFriends').and.returnValue(of([]));
spyOn(subject, 'restoreWindowsState');
subject.fetchFriendsList(true);
expect(subject.restoreWindowsState).toHaveBeenCalledTimes(1);
});
it('Must not invoke restore windows state on fetchFriendsList when not bootstrapping', () => {
spyOn(MockableAdapter.prototype, 'listFriends').and.returnValue(of([]));
spyOn(subject, 'restoreWindowsState');
subject.fetchFriendsList(false);
expect(subject.restoreWindowsState).not.toHaveBeenCalled();
});
it('Must update participants property when onFriendsListChanged is invoked', () => {
expect(subject.participantsResponse).toBeUndefined();
subject.participantsInteractedWith = [new User()];
subject.onFriendsListChanged([
new ParticipantResponse(),
new ParticipantResponse()
]);
expect(subject.participantsResponse.length).toBe(2);
expect(subject.participants.length).toBe(2);
expect(subject.participantsInteractedWith.length).toBe(0);
});
it('Must return existing open chat window when requesting a chat window instance', () => {
let user: User = {
participantType: ChatParticipantType.User,
id: 999,
displayName: 'Test user',
status: 1,
avatar: ''
};
subject.windows = [
{
participant: user
}
];
let result = subject.openChatWindow(user);
expect(result).not.toBeUndefined();
expect(result.length).toBe(2);
expect(result[0]).not.toBeUndefined();
expect(result[1]).toBeFalsy();
expect(result[0].participant.id).toEqual(user.id);
expect(result[0].participant.displayName).toEqual(user.displayName);
});
it('Must open a new window on a openChatWindow request when it is not opened yet', () => {
subject.historyEnabled = false;
let user: User = {
participantType: ChatParticipantType.User,
id: 999,
displayName: 'Test user',
status: 1,
avatar: ''
};
let result = subject.openChatWindow(user);
expect(result).not.toBeUndefined();
expect(result.length).toBe(2);
expect(result[0]).not.toBeUndefined();
expect(result[1]).not.toBeFalsy();
expect(result[0].participant.id).toEqual(user.id);
expect(result[0].participant.displayName).toEqual(user.displayName);
});
it('Must focus on the new window on a openChatWindow request when argument is supplied', () => {
subject.historyEnabled = false;
let user: User = {
participantType: ChatParticipantType.User,
id: 999,
displayName: 'Test user',
status: 1,
avatar: ''
};
spyOn(subject, 'focusOnWindow');
let result = subject.openChatWindow(user, true);
expect(result).not.toBeUndefined();
expect(subject.focusOnWindow).toHaveBeenCalledTimes(1);
});
it('Must not focus on the new window on a openChatWindow request when argument is not supplied', () => {
subject.historyEnabled = false;
let user: User = {
participantType: ChatParticipantType.User,
id: 999,
displayName: 'Test user',
status: 1,
avatar: ''
};
spyOn(subject, 'focusOnWindow');
let result = subject.openChatWindow(user);
expect(result).not.toBeUndefined();
expect(subject.focusOnWindow).not.toHaveBeenCalled();
});
it('Must load history from ChatAdapter when opening a window that is not yet opened', () => {
let user: User = {
participantType: ChatParticipantType.User,
id: 999,
displayName: 'Test user',
status: 1,
avatar: ''
};
spyOn(MockableAdapter.prototype, 'getMessageHistory').and.returnValue(of([]));
let result = subject.openChatWindow(user);
expect(result).not.toBeUndefined();
expect(result.length).toBe(2);
expect(result[0]).not.toBeUndefined();
expect(result[1]).not.toBeFalsy();
expect(result[0].participant.id).toEqual(user.id);
expect(result[0].participant.displayName).toEqual(user.displayName);
expect(MockableAdapter.prototype.getMessageHistory).toHaveBeenCalledTimes(1);
});
it('Mark messages as seen exercise', () => {
let messages: Message[] = [{
fromId: 1,
message: 'Test',
toId: 2
},
{
fromId: 1,
message: 'Test 2',
toId: 2
}]
subject.markMessagesAsRead(messages);
expect(messages.length).toBe(2);
expect(messages[0].dateSeen).not.toBeUndefined();
expect(messages[0].dateSeen.getTime()).toBeGreaterThan(new Date().getTime() - 60000);
expect(messages[1].dateSeen).not.toBeUndefined();
expect(messages[1].dateSeen.getTime()).toBeGreaterThan(new Date().getTime() - 60000);
});
it('Should play HTMLAudioElement when emitting a message sound on an unfocused window', () => {
let window = new Window(null, false, false);
spyOn(MockableHTMLAudioElement.prototype, 'play');
subject.emitMessageSound(window);
expect(MockableHTMLAudioElement.prototype.play).toHaveBeenCalledTimes(1);
});
it('Should not play HTMLAudioElement when emitting a message sound on a focused window', () => {
let window = new Window(null, false, false);
window.hasFocus = true;
spyOn(MockableHTMLAudioElement.prototype, 'play');
subject.emitMessageSound(window);
expect(MockableHTMLAudioElement.prototype.play).not.toHaveBeenCalled();
});
it('Should not play HTMLAudioElement when audio notification is disabled', () => {
let window = new Window(null, false, false);
subject.audioEnabled = false;
spyOn(MockableHTMLAudioElement.prototype, 'play');
subject.emitMessageSound(window);
expect(MockableHTMLAudioElement.prototype.play).not.toHaveBeenCalled();
});
it('Must invoke message notification method on new messages', () => {
let message = new Message();
let user = new User();
spyOn(subject, 'emitMessageSound');
spyOn(subject, 'openChatWindow').and.returnValue([null, true]);
spyOn(subject, 'scrollChatWindow'); // Masking this call as we're not testing this part on this spec
subject.onMessageReceived(user, message);
expect(subject.emitMessageSound).toHaveBeenCalledTimes(1);
});
it('Must invoke message type assertion method on new messages', () => {
let message = new Message();
let user = new User();
spyOn(subject, 'assertMessageType');
// Masking these calls as we're not testing this part on this spec
spyOn(subject, 'emitMessageSound');
spyOn(subject, 'openChatWindow').and.returnValue([null, true]);
spyOn(subject, 'scrollChatWindow');
subject.onMessageReceived(user, message);
expect(subject.assertMessageType).toHaveBeenCalledTimes(1);
});
it('Must mark message as seen on new messages if the current window has focus', () => {
let message = new Message();
let user = new User();
let window = new Window(null, false, false);
window.hasFocus = true;
spyOn(subject, 'markMessagesAsRead');
spyOn(subject, 'openChatWindow').and.returnValue([window, false]);
spyOn(subject, 'scrollChatWindow'); // Masking this call as we're not testing this part on this spec
spyOn(subject, 'emitMessageSound'); // Masking this call as we're not testing this part on this spec
subject.onMessageReceived(user, message);
expect(subject.markMessagesAsRead).toHaveBeenCalledTimes(1);
});
it('Must not mark message as seen on new messages if the current window does not have focus', () => {
let message = new Message();
let user = new User();
let window = new Window(null, false, false);
window.hasFocus = false;
let eventSpy = spyOn(subject.onMessagesSeen, 'emit');
spyOn(subject, 'markMessagesAsRead');
spyOn(subject, 'openChatWindow').and.returnValue([window, false]);
spyOn(subject, 'scrollChatWindow'); // Masking this call as we're not testing this part on this spec
spyOn(subject, 'emitMessageSound'); // Masking this call as we're not testing this part on this spec
subject.onMessageReceived(user, message);
expect(subject.markMessagesAsRead).not.toHaveBeenCalled();
expect(eventSpy).not.toHaveBeenCalled();
});
it('Should not use local storage persistency if persistWindowsState is disabled', () => {
let windows = [new Window(null, false, false)];
subject.persistWindowsState = false;
spyOn(localStorage, 'setItem');
subject.updateWindowsState(windows);
expect(localStorage.setItem).not.toHaveBeenCalled();
});
it('Update windows state exercise', () => {
let persistedValue = null;
spyOn(localStorage, 'setItem').and.callFake((key, value) => {
persistedValue = value;
});
let firstUser = new User();
let secondUser = new User();
firstUser.id = 88;
secondUser.id = 99;
let firstWindow = new Window(firstUser, false, false);
let secondWindow = new Window(secondUser, false, false);
let windows = [firstWindow, secondWindow];
subject.updateWindowsState(windows);
expect(localStorage.setItem).toHaveBeenCalledTimes(1);
expect(persistedValue).toBe(JSON.stringify([88, 99]));
});
it('Should not restore windows state from local storage if persistWindowsState is disabled', () => {
subject.persistWindowsState = false;
spyOn(subject, 'openChatWindow');
subject.restoreWindowsState();
expect(subject.openChatWindow).not.toHaveBeenCalled();
});
it('Restore windows state exercise', () => {
let firstUser = new User();
let secondUser = new User();
firstUser.id = 88;
secondUser.id = 99;
localStorage.setItem(subject.localStorageKey, JSON.stringify([firstUser.id, secondUser.id]));
subject.participants = [firstUser, secondUser];
let pushedParticipants = [];
spyOn(subject, 'openChatWindow').and.callFake((participant) => {
pushedParticipants.push(participant);
});
subject.restoreWindowsState();
expect(subject.openChatWindow).toHaveBeenCalledTimes(2);
expect(pushedParticipants).not.toBeNull();
expect(pushedParticipants.length).toBe(2);
expect(pushedParticipants[0]).toBe(firstUser);
expect(pushedParticipants[1]).toBe(secondUser);
});
it('Must invoke window state update when closing a chat window', () => {
subject.windows = [new Window(null, false, false)];
spyOn(subject, 'updateWindowsState');
subject.closeWindow(subject.windows[0]);
expect(subject.updateWindowsState).toHaveBeenCalledTimes(1);
});
it('Must focus on closest window when a chat window closed event is triggered via ESC key', () => {
const currentWindow = new Window(null, false, false);
const closestWindow = new Window(null, false, false);
spyOn(subject, 'closeWindow');
spyOn(subject, 'getClosestWindow').and.returnValue(closestWindow);
spyOn(subject, 'focusOnWindow').and.callFake((window: Window, callback: Function) => {
callback(); // This should invoke closeWindow
});;
subject.onWindowChatClosed({ closedWindow: currentWindow, closedViaEscapeKey: true });
expect(subject.closeWindow).toHaveBeenCalledTimes(1);
expect(subject.getClosestWindow).toHaveBeenCalledTimes(1);
expect(subject.focusOnWindow).toHaveBeenCalledTimes(1);
});
it('Must not focus on closest window when the ESC key is pressed and there is no other window opened', () => {
const currentWindow = new Window(null, false, false);
spyOn(subject, 'closeWindow');
spyOn(subject, 'getClosestWindow').and.returnValue(undefined);
spyOn(subject, 'focusOnWindow');
subject.onWindowChatClosed({ closedWindow: currentWindow, closedViaEscapeKey: true });
expect(subject.closeWindow).toHaveBeenCalledTimes(1);
expect(subject.getClosestWindow).toHaveBeenCalledTimes(1);
expect(subject.focusOnWindow).not.toHaveBeenCalled();
});
it('Must move to the next chat window when the TAB key is pressed', () => {
subject.windows = [
new Window(null, false, false),
new Window(null, false, false),
new Window(null, false, false)
];
let focusedWindow: Window = null;
const focusSpy = spyOn(subject, 'focusOnWindow').and.callFake((windowToFocus: Window) => focusedWindow = windowToFocus);
subject.onWindowTabTriggered({ triggeringWindow: subject.windows[1], shiftKeyPressed: false });
expect(focusSpy).toHaveBeenCalledTimes(1);
expect(focusedWindow).toBe(subject.windows[0]);
});
it('Must move to the previous chat window when SHIFT + TAB keys are pressed', () => {
subject.windows = [
new Window(null, false, false),
new Window(null, false, false),
new Window(null, false, false)
];
let focusedWindow: Window = null;
const focusSpy = spyOn(subject, 'focusOnWindow').and.callFake((windowToFocus: Window) => focusedWindow = windowToFocus);
subject.onWindowTabTriggered({ triggeringWindow: subject.windows[1], shiftKeyPressed: true });
expect(focusSpy).toHaveBeenCalledTimes(1);
expect(focusedWindow).toBe(subject.windows[2]);
});
it('Must copy default text when a localization object was not supplied while initializing default text', () => {
expect(subject.localization).toBeUndefined();
subject.initializeDefaultText();
expect(subject.localization).not.toBeUndefined();
expect(subject.localization.title).toBe(subject.title);
expect(subject.localization.searchPlaceholder).toBe(subject.searchPlaceholder);
expect(subject.localization.messagePlaceholder).toBe(subject.messagePlaceholder);
expect(subject.localization.statusDescription).toBe(subject.statusDescription);
expect(subject.localization.browserNotificationTitle).toBe(subject.browserNotificationTitle);
});
it('Must not copy default text when a localization object was supplied while initializing default text', () => {
subject.localization = {
title: 'test 01',
searchPlaceholder: 'test 02',
messagePlaceholder: 'test 03',
statusDescription: {
online: 'test 04',
busy: 'test 05',
away: 'test 06',
offline: 'test 07'
},
browserNotificationTitle: 'test 08',
loadMessageHistoryPlaceholder: 'Load more messages'
};
subject.initializeDefaultText();
expect(subject.localization).not.toBeUndefined();
expect(subject.localization.title).not.toBe(subject.title);
expect(subject.localization.searchPlaceholder).not.toBe(subject.searchPlaceholder);
expect(subject.localization.messagePlaceholder).not.toBe(subject.messagePlaceholder);
expect(subject.localization.statusDescription).not.toBe(subject.statusDescription);
expect(subject.localization.browserNotificationTitle).not.toBe(subject.browserNotificationTitle);
expect(subject.localization.loadMessageHistoryPlaceholder).not.toBe('Load older messages');
});
it('FocusOnWindow exercise', () => {
subject.windows = [
new Window(null, false, false),
new Window(null, false, false),
new Window(null, false, false)
];
subject.chatWindows = {
toArray: () => { }
};
let fakeChatInputs = [
{
chatWindowInput: {
nativeElement:
{
focus: () => { }
}
}
},
{
chatWindowInput: {
nativeElement:
{
focus: () => { }
}
}
},
{
chatWindowInput: {
nativeElement:
{
focus: () => { }
}
}
}
];
spyOn(fakeChatInputs[1].chatWindowInput.nativeElement, 'focus');
spyOn(subject.chatWindows, 'toArray').and.returnValue(fakeChatInputs);
// @ts-ignore
spyOn(window, 'setTimeout').and.callFake((fn) => {
// @ts-ignore
fn();
});
subject.focusOnWindow(subject.windows[1]);
expect(fakeChatInputs[1].chatWindowInput.nativeElement.focus).toHaveBeenCalledTimes(1);
});
it('Must not focus on native element if a window is not found to focus when focusOnWindow is invoked', () => {
subject.windows = [];
subject.chatWindowInputs = {
toArray: () => { }
};
subject.focusOnWindow(new Window(null, false, false));
});
it('GetClosestWindow must return next relative right chat window', () => {
subject.windows = [
new Window(null, false, false),
new Window(null, false, false),
new Window(null, false, false)
];
let result = subject.getClosestWindow(subject.windows[2]);
expect(result).toBe(subject.windows[1]);
});
it('GetClosestWindow must return previous chat window on 0 based index', () => {
subject.windows = [
new Window(null, false, false),
new Window(null, false, false),
new Window(null, false, false)
];
let result = subject.getClosestWindow(subject.windows[0]);
expect(result).toBe(subject.windows[1]);
});
it('GetClosestWindow must return undefined when there is only one chat window opened on the chat', () => {
subject.windows = [
new Window(null, false, false)
];
let result = subject.getClosestWindow(subject.windows[0]);
expect(result).toBe(undefined);
});
it('GetClosestWindow must return undefined when there is no open chat window on the chat', () => {
subject.windows = [];
let result = subject.getClosestWindow(new Window(null, false, false));
expect(result).toBe(undefined);
});
it('Must bootstrap browser notifications when user permission is granted', async () => {
subject.browserNotificationsBootstrapped = false;
spyOn(Notification, 'requestPermission').and.returnValue(Promise.resolve("granted"));
await subject.initializeBrowserNotifications();
expect(subject.browserNotificationsBootstrapped).toBeTruthy();
expect(Notification.requestPermission).toHaveBeenCalledTimes(1);
});
it('Must not bootstrap browser notifications when user permission is not granted', async () => {
subject.browserNotificationsBootstrapped = false;
spyOn(Notification, 'requestPermission').and.returnValue(Promise.resolve("denied"));
await subject.initializeBrowserNotifications();
expect(subject.browserNotificationsBootstrapped).toBeFalsy();
expect(Notification.requestPermission).toHaveBeenCalledTimes(1);
});
it('Must invoke emitBrowserNotification on new messages', () => {
let message = new Message();
let user = new User();
spyOn(subject, 'emitBrowserNotification');
spyOn(subject, 'openChatWindow').and.returnValue([null, true]);
spyOn(subject, 'scrollChatWindow'); // Masking this call as we're not testing this part on this spec
spyOn(subject, 'emitMessageSound'); // Masking this call as we're not testing this part on this spec
subject.onMessageReceived(user, message);
expect(subject.emitBrowserNotification).toHaveBeenCalledTimes(1);
});
it('Must delegate message argument when invoking emitBrowserNotification on new messages', () => {
let message = new Message();
let argMessage = null;
message.message = 'Test message';
let user = new User();
subject.historyEnabled = true;
spyOn(subject, 'emitBrowserNotification').and.callFake((window, message) => {
argMessage = message;
});
spyOn(subject, 'openChatWindow').and.returnValue([null, true]);
spyOn(subject, 'emitMessageSound'); // Masking this call as we're not testing this part on this spec
subject.onMessageReceived(user, message);
expect(subject.emitBrowserNotification).toHaveBeenCalledTimes(1);
expect(argMessage).toBe(message);
});
it('Must not invoke emitBrowserNotification when the maximizeWindowOnNewMessage setting is disabled', () => {
let message = new Message();
let user = new User();
subject.maximizeWindowOnNewMessage = false;
spyOn(subject, 'emitBrowserNotification');
spyOn(subject, 'openChatWindow').and.returnValue([null, true]);
spyOn(subject, 'scrollChatWindow'); // Masking this call as we're not testing this part on this spec
spyOn(subject, 'emitMessageSound'); // Masking this call as we're not testing this part on this spec
subject.onMessageReceived(user, message);
expect(subject.emitBrowserNotification).not.toHaveBeenCalled();
});
it('Must invoke emitBrowserNotification when the maximizeWindowOnNewMessage setting is disabled but the window is maximized', () => {
let message = new Message();
let user = new User();
let window = new Window(null, false, false);
subject.maximizeWindowOnNewMessage = false;
spyOn(subject, 'emitBrowserNotification');
spyOn(subject, 'openChatWindow').and.returnValue([window, false]);
spyOn(subject, 'scrollChatWindow'); // Masking this call as we're not testing this part on this spec
spyOn(subject, 'emitMessageSound'); // Masking this call as we're not testing this part on this spec
subject.onMessageReceived(user, message);
expect(subject.emitBrowserNotification).toHaveBeenCalledTimes(1);
});
it('Must not invoke emitBrowserNotification when the maximizeWindowOnNewMessage setting is disabled and the window is collapsed', () => {
let message = new Message();
let user = new User();
let window = new Window(null, false, true);
subject.maximizeWindowOnNewMessage = false;
spyOn(subject, 'emitBrowserNotification');
spyOn(subject, 'openChatWindow').and.returnValue([window, false]);
spyOn(subject, 'scrollChatWindow'); // Masking this call as we're not testing this part on this spec
spyOn(subject, 'emitMessageSound'); // Masking this call as we're not testing this part on this spec
subject.onMessageReceived(user, message);
expect(subject.emitBrowserNotification).not.toHaveBeenCalled();
});
it('Must not invoke emitBrowserNotification when the maximizeWindowOnNewMessage setting is disabled and the window was freshly opened', () => {
let message = new Message();
let user = new User();
let window = new Window(null, false, false);
subject.maximizeWindowOnNewMessage = false;
spyOn(subject, 'emitBrowserNotification');
spyOn(subject, 'openChatWindow').and.returnValue([window, true]);
spyOn(subject, 'scrollChatWindow'); // Masking this call as we're not testing this part on this spec
spyOn(subject, 'emitMessageSound'); // Masking this call as we're not testing this part on this spec
subject.onMessageReceived(user, message);
expect(subject.emitBrowserNotification).not.toHaveBeenCalled();
});
it('Must invoke onParticipantChatOpened event when a chat window is open via user click', () => {
subject.historyEnabled = false;
subject.windows = [];
spyOn(subject, 'updateWindowsState');
spyOn(subject, 'focusOnWindow');
let eventInvoked = false;
let eventArgument = null;
subject.onParticipantChatOpened.subscribe(e => {
eventInvoked = true;
eventArgument = e;
});
let user: User = {
participantType: ChatParticipantType.User,
id: 999,
displayName: 'Test user',
status: 1,
avatar: ''
};
subject.openChatWindow(user, false, true);
expect(eventInvoked).toBeTruthy();
expect(eventArgument).toBe(user);
});
it('Must not invoke onParticipantChatOpened event when a window is already open for the user', () => {
subject.historyEnabled = false;
let eventInvoked = false;
let eventArgument = null;
subject.onParticipantChatOpened.subscribe(e => {
eventInvoked = true;
eventArgument = e;
});
let user: User = {
participantType: ChatParticipantType.User,
id: 999,
displayName: 'Test user',
status: 1,
avatar: ''
};
subject.windows = [
{
participant: user
}
];
subject.openChatWindow(user, true, true);
expect(eventInvoked).toBeFalsy();
expect(eventArgument).toBe(null);
});
it('Must pop existing window when viewport does not have enough space for another window', () => {
const user: User = {
participantType: ChatParticipantType.User,
id: 777,
displayName: 'Test user',
status: 1,
avatar: ''
};
const newUser: User = {
participantType: ChatParticipantType.User,
id: 888,
displayName: 'Test user 2',
status: 1,
avatar: ''
};
const userToBeRemoved: User = {
participantType: ChatParticipantType.User,
id: 999,
displayName: 'Test user 2',
status: 1,
avatar: ''
};
const remainingWindow = new Window(user, false, false);
const windowToBeRemoved = new Window(userToBeRemoved, false, false);
subject.viewPortTotalArea = 960;
subject.historyEnabled = false;
subject.windows = [
remainingWindow,
windowToBeRemoved
];
spyOn(subject, 'updateWindowsState');
spyOn(subject, 'focusOnWindow');
subject.openChatWindow(newUser, false, true);
expect(subject.windows.length).toBe(2);
expect(subject.windows[0].participant).toBe(newUser);
expect(subject.windows[1].participant).toBe(user);
});
it('Must push to viewport when friends list is disabled exercise', () => {
const user: User = {
participantType: ChatParticipantType.User,
id: 777,
displayName: 'Test user',
status: 1,
avatar: ''
};
const newUser: User = {
participantType: ChatParticipantType.User,
id: 888,
displayName: 'Test user 2',
status: 1,
avatar: ''
};
const userThatWouldBeRemoved: User = {
participantType: ChatParticipantType.User,
id: 999,
displayName: 'Test user 2',
status: 1,
avatar: ''
};
const remainingWindow = new Window(user, false, false);
const windowThatWouldBeRemoved = new Window(userThatWouldBeRemoved, false, false);
subject.hideFriendsList = true;
subject.viewPortTotalArea = 961; // Would be enough for only 2 if the friends list was enabled. 1px more than window factor * 3
subject.historyEnabled = false;
subject.windows = [
remainingWindow,
windowThatWouldBeRemoved
];
spyOn(subject, 'updateWindowsState');
spyOn(subject, 'focusOnWindow');
subject.openChatWindow(newUser, false, true);
expect(subject.windows.length).toBe(3);
expect(subject.windows[0].participant).toBe(newUser);
expect(subject.windows[1].participant).toBe(user);
expect(subject.windows[2].participant).toBe(userThatWouldBeRemoved);
});
it('Must invoke onParticipantChatClosed event when a window is closed', () => {
const window = new Window({
participantType: ChatParticipantType.User,
id: 999,
displayName: 'Test user',
status: 1,
avatar: ''
}, false, false);
subject.windows = [window];
spyOn(subject, 'updateWindowsState'); // Bypassing this
let eventInvoked = false;
let eventArgument = null;
subject.onParticipantChatClosed.subscribe(e => {
eventInvoked = true;
eventArgument = e;
});
subject.closeWindow(subject.windows[0]);
expect(eventInvoked).toBeTruthy();
expect(eventArgument).toBe(window.participant);
});
it('Must not invoke onParticipantClicked event when a user is clicked on the friend list and the window is already open', () => {
subject.historyEnabled = false;
let eventInvoked = false;
let eventArgument = null;
subject.onParticipantClicked.subscribe(e => {
eventInvoked = true;
eventArgument = e;
});
let user: User = {
participantType: ChatParticipantType.User,
id: 999,
displayName: 'Test user',
status: 1,
avatar: ''
};
subject.windows = [
{
participant: user
}
];
subject.openChatWindow(user, true, true);
expect(eventInvoked).toBeFalsy();
expect(eventArgument).toBe(null);
});
it('Must not invoke onParticipantClicked event when a window is open but not triggered directly via user click', () => {
subject.historyEnabled = false;
let eventInvoked = false;
let eventArgument = null;
subject.onParticipantClicked.subscribe(e => {
eventInvoked = true;
eventArgument = e;
});
let user: User = {
participantType: ChatParticipantType.User,
id: 999,
displayName: 'Test user',
status: 1,
avatar: ''
};
subject.openChatWindow(user, true, false);
expect(eventInvoked).toBeFalsy();
expect(eventArgument).toBe(null);
});
it('Must invoke onParticipantClicked event when a user is clicked on the friend list', () => {
subject.historyEnabled = false;
subject.windows = [];
let eventInvoked = false;
let eventArgument = null;
subject.onParticipantClicked.subscribe(e => {
eventInvoked = true;
eventArgument = e;
});
let user: User = {
participantType: ChatParticipantType.User,
id: 999,
displayName: 'Test user',
status: 1,
avatar: ''
};
subject.openChatWindow(user, true, true);
expect(eventInvoked).toBeTruthy();
expect(eventArgument).toBe(user);
});
it('Must invoke openChatWindow when triggerOpenChatWindow is invoked', () => {
let spy = spyOn(subject, 'openChatWindow');
let user: User = {
participantType: ChatParticipantType.User,
id: 999,
displayName: 'Test user',
status: 1,
avatar: ''
};
subject.triggerOpenChatWindow(user);
expect(spy).toHaveBeenCalled();
expect(spy).toHaveBeenCalledTimes(1);
expect(spy.calls.mostRecent().args.length).toBe(1);
});
it('Must not invoke openChatWindow when triggerOpenChatWindow is invoked but user is undefined', () => {
let spy = spyOn(subject, 'openChatWindow');
subject.triggerOpenChatWindow(null);
expect(spy).not.toHaveBeenCalled();
});
it('Must invoke closeWindow when triggerCloseChatWindow is invoked', () => {
let spy = spyOn(subject, 'closeWindow');
let user: User = {
participantType: ChatParticipantType.User,
id: 999,
displayName: 'Test user',
status: 1,
avatar: ''
};
let window: Window = new Window(user, false, false);
subject.windows.push(window);
subject.triggerCloseChatWindow(user.id);
expect(spy).toHaveBeenCalled();
expect(spy).toHaveBeenCalledTimes(1);
expect(spy.calls.mostRecent().args.length).toBe(1);
});
it('Must not invoke closeWindow when triggerCloseChatWindow is invoked but user is not found', () => {
let spy = spyOn(subject, 'closeWindow');
subject.windows = [];
subject.triggerCloseChatWindow(1);
expect(spy).not.toHaveBeenCalled();
});
it('Must invoke onChatWindowClicked when triggerToggleChatWindowVisibility is invoked', () => {
const currentUser = new User();
currentUser.id = 1;
const stubChatWindowComponent = new NgChatWindowComponent();
subject.windows = [
new Window(currentUser, false, false)
];
spyOn(subject, 'getChatWindowComponentInstance').and.returnValue(stubChatWindowComponent);
let spy = spyOn(stubChatWindowComponent, 'onChatWindowClicked');
subject.triggerToggleChatWindowVisibility(currentUser.id);
expect(spy).toHaveBeenCalled();
expect(spy).toHaveBeenCalledTimes(1);
expect(spy.calls.mostRecent().args.length).toBe(1);
expect(spy.calls.mostRecent().args[0]).toBe(subject.windows[0]);
});
it('Must not invoke onChatWindowClicked when triggerToggleChatWindowVisibility is invoked but user is not found', () => {
let spy = spyOn(NgChatWindowComponent.prototype, 'onChatWindowClicked');
subject.windows = [];
subject.triggerToggleChatWindowVisibility(1);
expect(spy).not.toHaveBeenCalled();
});
it('Assert message type must default to text when no message type is defined in a message instance', () => {
let nullMessageType = new Message();
nullMessageType.type = null; // Overriding the default value
let undefinedMessageType: Message = {
fromId: 1,
toId: 2,
message: 'test'
};
let fileMessageType = new Message();
fileMessageType.type = MessageType.File; // This must remain as it is
subject.assertMessageType(nullMessageType);
subject.assertMessageType(undefinedMessageType);
subject.assertMessageType(fileMessageType);
expect(nullMessageType.type).toBe(MessageType.Text);
expect(undefinedMessageType.type).toBe(MessageType.Text);
expect(fileMessageType.type).toBe(MessageType.File);
});
it('Must set theme to "Custom" if a custom theme URL is set', () => {
subject.customTheme = "https://sample.test/custom-theme.css";
subject.initializeTheme();
expect(subject.theme).toBe(Theme.Custom);
});
it('Must throw Error on theme initialization if a unknown theme schema is set', () => {
subject.theme = "invalid-theme";
expect(() => subject.initializeTheme()).toThrow(new Error(`Invalid theme configuration for ng-chat. "${subject.theme}" is not a valid theme value.`));
});
it('onOptionPromptCanceled invoked should clear selection state', () => {
let mockedUser = new User();
mockedUser.id = 999;
let mockedOption = {
isActive: false,
displayLabel: 'Test',
action: null,
validateContext: null
} as IChatOption;
subject.currentActiveOption = mockedOption;
subject.onOptionPromptCanceled();
expect(subject.currentActiveOption).toBeNull();
expect(mockedOption.isActive).toBeFalsy();
});
it('onOptionPromptConfirmed invoked exercise', () => {
let mockedFirstUser = new User();
let mockedSecondUser = new User();
let createdGroup: Group = null;
mockedFirstUser.id = 888;
mockedSecondUser.id = 999;
// To test sorting of the name
mockedFirstUser.displayName = "ZZZ";
mockedSecondUser.displayName = "AAA";
const participants = [mockedFirstUser, mockedSecondUser];
spyOn(MockableGroupAdapter.prototype, 'groupCreated').and.callFake((group: Group) => {
createdGroup = group;
});
spyOn(subject, 'openChatWindow').and.returnValue([null, true]);
subject.onOptionPromptConfirmed(participants);
expect(createdGroup).not.toBeNull();
expect(createdGroup.chattingTo).not.toBeNull();
expect(createdGroup.chattingTo.length).toBe(2);
expect(createdGroup.chattingTo[0]).toBe(mockedFirstUser);
expect(createdGroup.chattingTo[1]).toBe(mockedSecondUser);
expect(createdGroup.displayName).toBe("AAA, ZZZ");
expect(MockableGroupAdapter.prototype.groupCreated).toHaveBeenCalledTimes(1);
expect(subject.openChatWindow).toHaveBeenCalledTimes(1);
});
}); | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.