text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import dagre from 'dagre';
import { LeafNodes, LineagePos, LoadingNodeState } from 'Models';
import React, { MouseEvent as ReactMouseEvent } from 'react';
import {
ArrowHeadType,
Edge,
Elements,
FlowElement,
isNode,
Node,
OnLoadParams,
Position,
} from 'react-flow-renderer';
import { Link } from 'react-router-dom';
import {
CustomEdgeData,
SelectedEdge,
SelectedNode,
} from '../components/EntityLineage/EntityLineage.interface';
import Loader from '../components/Loader/Loader';
import {
nodeHeight,
nodeWidth,
positionX,
positionY,
} from '../constants/constants';
import { EntityLineageDirection } from '../enums/entity.enum';
import {
Edge as LineageEdge,
EntityLineage,
} from '../generated/type/entityLineage';
import { EntityReference } from '../generated/type/entityReference';
import { getPartialNameFromFQN } from './CommonUtils';
import { isLeafNode } from './EntityUtils';
import { getEntityLink } from './TableUtils';
export const getHeaderLabel = (
v = '',
type: string,
isMainNode: boolean,
separator = '.'
) => {
const length = v.split(separator).length;
return (
<>
{isMainNode ? (
<span
className="tw-break-words description-text tw-self-center tw-font-medium"
data-testid="lineage-entity">
{v.split(separator)[length - 1]}
</span>
) : (
<span
className="tw-break-words description-text tw-self-center link-text tw-font-medium"
data-testid="lineage-entity">
<Link to={getEntityLink(type, v)}>
{v.split(separator)[length - 1]}
</Link>
</span>
)}
</>
);
};
export const onLoad = (reactFlowInstance: OnLoadParams) => {
reactFlowInstance.fitView();
reactFlowInstance.zoomTo(1);
};
/* eslint-disable-next-line */
export const onNodeMouseEnter = (_event: ReactMouseEvent, _node: Node) => {
return;
};
/* eslint-disable-next-line */
export const onNodeMouseMove = (_event: ReactMouseEvent, _node: Node) => {
return;
};
/* eslint-disable-next-line */
export const onNodeMouseLeave = (_event: ReactMouseEvent, _node: Node) => {
return;
};
/* eslint-disable-next-line */
export const onNodeContextMenu = (event: ReactMouseEvent, _node: Node) => {
event.preventDefault();
};
export const dragHandle = (event: ReactMouseEvent) => {
event.stopPropagation();
};
export const getLineageData = (
entityLineage: EntityLineage,
onSelect: (state: boolean, value: SelectedNode) => void,
loadNodeHandler: (node: EntityReference, pos: LineagePos) => void,
lineageLeafNodes: LeafNodes,
isNodeLoading: LoadingNodeState,
getNodeLable: (node: EntityReference) => React.ReactNode,
isEditMode: boolean,
edgeType: string,
onEdgeClick: (
evt: React.MouseEvent<HTMLButtonElement>,
data: CustomEdgeData
) => void
) => {
const [x, y] = [0, 0];
const nodes = entityLineage['nodes'];
let upstreamEdges: Array<LineageEdge & { isMapped: boolean }> =
entityLineage['upstreamEdges']?.map((up) => ({ isMapped: false, ...up })) ||
[];
let downstreamEdges: Array<LineageEdge & { isMapped: boolean }> =
entityLineage['downstreamEdges']?.map((down) => ({
isMapped: false,
...down,
})) || [];
const mainNode = entityLineage['entity'];
const UPStreamNodes: Elements = [];
const DOWNStreamNodes: Elements = [];
const lineageEdges: Elements = [];
const makeNode = (
node: EntityReference,
pos: LineagePos,
depth: number,
posDepth: number
) => {
const [xVal, yVal] = [positionX * 2 * depth, y + positionY * posDepth];
return {
id: `${node.id}`,
sourcePosition: Position.Right,
targetPosition: Position.Left,
type: 'default',
className: 'leaf-node',
data: {
label: getNodeLable(node),
entityType: node.type,
},
position: {
x: pos === 'from' ? -xVal : xVal,
y: yVal,
},
};
};
const getNodes = (
id: string,
pos: LineagePos,
depth: number,
NodesArr: Array<EntityReference & { lDepth: number }> = []
): Array<EntityReference & { lDepth: number }> => {
if (pos === 'to') {
let upDepth = NodesArr.filter((nd) => nd.lDepth === depth).length;
const UPNodes: Array<EntityReference> = [];
const updatedUpStreamEdge = upstreamEdges.map((up) => {
if (up.toEntity === id) {
const edg = UPStreamNodes.find((up) => up.id.includes(`node-${id}`));
const node = nodes?.find((nd) => nd.id === up.fromEntity);
if (node) {
UPNodes.push(node);
UPStreamNodes.push(makeNode(node, 'from', depth, upDepth));
lineageEdges.push({
id: `edge-${up.fromEntity}-${id}-${depth}`,
source: `${node.id}`,
target: edg ? edg.id : `${id}`,
type: isEditMode ? edgeType : 'custom',
arrowHeadType: ArrowHeadType.ArrowClosed,
data: {
id: `edge-${up.fromEntity}-${id}-${depth}`,
source: `${node.id}`,
target: edg ? edg.id : `${id}`,
sourceType: node.type,
targetType: edg?.data?.entityType,
onEdgeClick,
},
});
}
upDepth += 1;
return {
...up,
isMapped: true,
};
} else {
return up;
}
});
upstreamEdges = updatedUpStreamEdge;
return UPNodes?.map((upNd) => ({ lDepth: depth, ...upNd })) || [];
} else {
let downDepth = NodesArr.filter((nd) => nd.lDepth === depth).length;
const DOWNNodes: Array<EntityReference> = [];
const updatedDownStreamEdge = downstreamEdges.map((down) => {
if (down.fromEntity === id) {
const edg = DOWNStreamNodes.find((down) =>
down.id.includes(`node-${id}`)
);
const node = nodes?.find((nd) => nd.id === down.toEntity);
if (node) {
DOWNNodes.push(node);
DOWNStreamNodes.push(makeNode(node, 'to', depth, downDepth));
lineageEdges.push({
id: `edge-${id}-${down.toEntity}`,
source: edg ? edg.id : `${id}`,
target: `${node.id}`,
type: isEditMode ? edgeType : 'custom',
arrowHeadType: ArrowHeadType.ArrowClosed,
data: {
id: `edge-${id}-${down.toEntity}`,
source: edg ? edg.id : `${id}`,
target: `${node.id}`,
sourceType: edg?.data?.entityType,
targetType: node.type,
onEdgeClick,
},
});
}
downDepth += 1;
return {
...down,
isMapped: true,
};
} else {
return down;
}
});
downstreamEdges = updatedDownStreamEdge;
return DOWNNodes?.map((downNd) => ({ lDepth: depth, ...downNd })) || [];
}
};
const getUpStreamData = (
Entity: EntityReference,
depth = 1,
upNodesArr: Array<EntityReference & { lDepth: number }> = []
) => {
const upNodes = getNodes(Entity.id, 'to', depth, upNodesArr);
upNodesArr.push(...upNodes);
upNodes.forEach((up) => {
if (
upstreamEdges.some((upE) => upE.toEntity === up.id && !upE.isMapped)
) {
getUpStreamData(up, depth + 1, upNodesArr);
}
});
return upNodesArr;
};
const getDownStreamData = (
Entity: EntityReference,
depth = 1,
downNodesArr: Array<EntityReference & { lDepth: number }> = []
) => {
const downNodes = getNodes(Entity.id, 'from', depth, downNodesArr);
downNodesArr.push(...downNodes);
downNodes.forEach((down) => {
if (
downstreamEdges.some(
(downE) => downE.fromEntity === down.id && !downE.isMapped
)
) {
getDownStreamData(down, depth + 1, downNodesArr);
}
});
return downNodesArr;
};
getUpStreamData(mainNode);
getDownStreamData(mainNode);
const lineageData = [
{
id: `${mainNode.id}`,
sourcePosition: 'right',
targetPosition: 'left',
type:
lineageEdges.find((ed: FlowElement) =>
(ed as Edge).target.includes(mainNode.id)
) || isEditMode
? lineageEdges.find((ed: FlowElement) =>
(ed as Edge).source.includes(mainNode.id)
) || isEditMode
? 'default'
: 'output'
: 'input',
className: `leaf-node ${!isEditMode ? 'core' : ''}`,
data: {
label: getNodeLable(mainNode),
},
position: { x: x, y: y },
},
...UPStreamNodes.map((up) => {
const node = entityLineage?.nodes?.find((d) => up.id.includes(d.id));
return lineageEdges.find(
(ed: FlowElement) => (ed as Edge).target === up.id
)
? up
: {
...up,
type: isEditMode ? 'default' : 'input',
data: {
label: (
<div className="tw-flex">
<div
className="tw-pr-2 tw-self-center tw-cursor-pointer "
onClick={(e) => {
e.stopPropagation();
onSelect(false, {} as SelectedNode);
if (node) {
loadNodeHandler(node, 'from');
}
}}>
{!isLeafNode(
lineageLeafNodes,
node?.id as string,
'from'
) && !up.id.includes(isNodeLoading.id as string) ? (
<i className="fas fa-chevron-left tw-text-primary tw-mr-2" />
) : null}
{isNodeLoading.state &&
up.id.includes(isNodeLoading.id as string) ? (
<Loader size="small" type="default" />
) : null}
</div>
<div>{up?.data?.label}</div>
</div>
),
},
};
}),
...DOWNStreamNodes.map((down) => {
const node = entityLineage?.nodes?.find((d) => down.id.includes(d.id));
return lineageEdges.find((ed: FlowElement) =>
(ed as Edge).source.includes(down.id)
)
? down
: {
...down,
type: isEditMode ? 'default' : 'output',
data: {
label: (
<div className="tw-flex tw-justify-between">
<div>{down?.data?.label}</div>
<div
className="tw-pl-2 tw-self-center tw-cursor-pointer "
onClick={(e) => {
e.stopPropagation();
onSelect(false, {} as SelectedNode);
if (node) {
loadNodeHandler(node, 'to');
}
}}>
{!isLeafNode(lineageLeafNodes, node?.id as string, 'to') &&
!down.id.includes(isNodeLoading.id as string) ? (
<i className="fas fa-chevron-right tw-text-primary tw-ml-2" />
) : null}
{isNodeLoading.state &&
down.id.includes(isNodeLoading.id as string) ? (
<Loader size="small" type="default" />
) : null}
</div>
</div>
),
},
};
}),
...lineageEdges,
];
return lineageData;
};
export const getDataLabel = (
displayName?: string,
name = '',
separator = '.',
isTextOnly = false
) => {
let label = '';
if (displayName) {
label = displayName;
} else {
const length = name.split(separator).length;
label = name.split(separator)[length - 1];
}
if (isTextOnly) {
return label;
}
return (
<span
className="tw-break-words description-text tw-self-center"
data-testid="lineage-entity">
{label}
</span>
);
};
export const getNoLineageDataPlaceholder = () => {
return (
<div className="tw-mt-4 tw-ml-4 tw-flex tw-justify-center tw-font-medium tw-items-center tw-border tw-border-main tw-rounded-md tw-p-8">
<span>
Lineage is currently supported for Airflow. To enable lineage collection
from Airflow, please follow the documentation
</span>
<Link
className="tw-ml-1"
target="_blank"
to={{
pathname:
'https://docs.open-metadata.org/install/metadata-ingestion/airflow/configure-airflow-lineage',
}}>
here.
</Link>
</div>
);
};
const dagreGraph = new dagre.graphlib.Graph();
dagreGraph.setDefaultEdgeLabel(() => ({}));
export const getLayoutedElements = (
elements: Elements,
direction = EntityLineageDirection.LEFT_RIGHT
) => {
const isHorizontal = direction === EntityLineageDirection.LEFT_RIGHT;
dagreGraph.setGraph({ rankdir: direction });
elements.forEach((el) => {
if (isNode(el)) {
dagreGraph.setNode(el.id, {
width: el?.__rf?.width ?? nodeWidth,
height: el?.__rf?.height ?? nodeHeight,
});
} else {
dagreGraph.setEdge(el.source, el.target);
}
});
dagre.layout(dagreGraph);
return elements.map((el) => {
if (isNode(el)) {
const nodeWithPosition = dagreGraph.node(el.id);
el.targetPosition = isHorizontal ? Position.Left : Position.Top;
el.sourcePosition = isHorizontal ? Position.Right : Position.Bottom;
el.position = {
x:
nodeWithPosition.x -
(el?.__rf?.width ?? nodeWidth) / 2 +
Math.random() / 1000,
y: nodeWithPosition.y - (el?.__rf?.height ?? nodeHeight) / 2,
};
}
return el;
});
};
export const getModalBodyText = (selectedEdge: SelectedEdge) => {
return `Are you sure you want to remove the edge between "${
selectedEdge.source.displayName
? selectedEdge.source.displayName
: getPartialNameFromFQN(
selectedEdge.source.name as string,
selectedEdge.source.type === 'table' ? ['table'] : ['database']
)
} and ${
selectedEdge.target.displayName
? selectedEdge.target.displayName
: getPartialNameFromFQN(
selectedEdge.target.name as string,
selectedEdge.target.type === 'table' ? ['table'] : ['database']
)
}"?`;
}; | the_stack |
import {
AfterViewInit,
Directive,
ElementRef,
HostListener,
Inject,
Injector,
Input,
OnDestroy,
Optional,
Provider,
Renderer2,
forwardRef
} from '@angular/core';
import {
COMPOSITION_BUFFER_MODE,
DefaultValueAccessor,
NG_VALUE_ACCESSOR,
NgControl,
Validators,
AbstractControl
} from '@angular/forms';
/**
* An interface for determining if an element is a checkbox.
*/
export interface CheckedElementLike {
checked?: boolean;
}
/**
* An interface for determining if an element is selectable.
*/
export interface SelectableLike {
multi?: boolean;
selected?: string | number;
selectedItem?: any;
}
/**
* An interface for determining if an element is multi selectable.
*/
export interface MultiSelectableLike {
multi?: boolean;
selectedValues?: Array<string | number>;
selectedItems?: any[];
}
/**
* An interface for determining if an element is validatable.
*/
export interface ValidatableLike {
invalid?: boolean;
validate?(): void;
}
/**
* OrigamiControlValueAccessor provider.
*/
export const ORIGAMI_CONTROL_VALUE_ACCESSOR: Provider = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => OrigamiControlValueAccessor),
multi: true
};
/**
* A value accessor for `ngModel`, `formControl`, and `formControlName`, on
* custom elements. In addition to one of the above directives, `origami`
* should be added to the element to denote that this value accessor should
* control it.
*
* Example: `<paper-input [(ngModel)]="value" origami></paper-input>`
*
* The connected element should implement one of the below
* properties:
*
* - `checked` as a boolean for checkbox-like elements.
* - `selected` for single selectable elements. It must be an index or string
* name attribute.
* - `selectedItem` for single selectable elements. It may be any type.
* - `selectedValues` for multi selectable elements. It must be an array of
* indices or string name attributes.
* - `selectedItems` for multi selectable elements. It must be an array of any
* type.
* - `value` for any basic form element. It may be any type.
*
* For selectable and multi selectable elements, the attribute `useKey` should
* be specified if the control bindings an index or name value to the element
* instead of an object.
*
* Additionally, an element may implement one or more of the following
* properties:
*
* - `disabled` as a boolean
* - `invalid` as a boolean to indicate validity
* - `validate()` as a function to run custom validation
*
* To listen for changes to these events, an element should implement one or
* more of the following events to notify Angular of any updates.
*
* - `input` - will update any of the above properties
* - `blur`
* - `checked-changed`
* - `selected-changed`
* - `selected-item-changed`
* - `selected-values-changed`
* - `selected-items-changed`
* - `value-changed`
* - `invalid-changed`
*/
@Directive({
selector:
'[ngModel][origami],[formControlName][origami],[formControl][origami]',
providers: [ORIGAMI_CONTROL_VALUE_ACCESSOR]
})
export class OrigamiControlValueAccessor extends DefaultValueAccessor
implements AfterViewInit, OnDestroy {
/**
* Overrides the logic to determine what to set an element's `invalid`
* property to given the provided `AbstractControl`. The default is to set the
* element as `invalid` whenever the control is both invalid and dirty.
*/
@Input()
isInvalid?: (control: AbstractControl) => boolean;
/**
* The key to use when reporting that an element's `validate()` function
* returns false. When this happens, the control's `errors` object will be
* set with this key and a value of true.
*
* The default key is "validate".
*/
@Input()
validationErrorsKey = 'validate';
/**
* The `AbstractControl` attached to this element.
*/
get control(): AbstractControl | undefined {
if (!this._control) {
this._control = (<NgControl>this.injector.get(NgControl)).control!;
}
return this._control;
}
/**
* Subscription to the NgControl's statusChanges.
*/
protected statusSub?: { unsubscribe(): void };
/**
* Most custom elements property will emit a `property-changed` event when
* their value is set. This flag informs the value accessor to ignore the
* next event while it is in the middle of writing a value.
*/
private isWritingValue = false;
/**
* Flag that informs the value accessor that it is currently updating an
* element and should ignore additional `invalid` property changes until it is
* complete.
*/
private ignoreInvalidChanges = false;
/**
* Indicates whether or not to use the value property or index property for a
* select or mulit-select element. When undefined, it indicates that the
* determination of which property to use has not occurred yet.
*/
private useSelectableValueProp?: boolean;
/**
* Cached `control` value.
*/
private _control: AbstractControl | undefined;
constructor(
public elementRef: ElementRef,
protected injector: Injector,
protected renderer: Renderer2,
@Optional()
@Inject(COMPOSITION_BUFFER_MODE)
compositionMode: boolean
) {
super(renderer, elementRef, compositionMode);
}
/**
* Lifecycle callback that will connect an element's validatable properties
* (if they are implemented) to the Angular control.
*/
ngAfterViewInit() {
const element = this.elementRef.nativeElement;
if (this.isValidatable(element)) {
// The control will always be set by ngAfterViewInit due to the nature of
// the directive's selectors
const control = this.control!;
// Allows Angular validators to update the custom element's validity
this.statusSub = control.statusChanges!.subscribe(() => {
if (typeof this.isInvalid === 'function') {
element.invalid = this.isInvalid(control);
} else {
element.invalid = !!control.invalid && !!control.dirty;
}
});
// Allows custom element validate function to update Angular control's
// validity
if (this.shouldUseValidate(element)) {
control.setValidators(
Validators.compose([
control.validator,
() => {
if (element.validate()) {
return null;
} else {
return { [this.validationErrorsKey]: true };
}
}
])
);
}
}
}
/**
* Lifecycle callback to clean up subscriptions.
*/
ngOnDestroy() {
if (this.statusSub) {
this.statusSub.unsubscribe();
}
}
/**
* Writes a value to a custom element's correct value property, based on what
* kind of element the directive controls.
*
* @param value the value to write
*/
writeValue(value: any) {
this.isWritingValue = true;
const element = this.elementRef.nativeElement;
if (this.isMultiSelectable(element) || this.isSelectable(element)) {
const property = this.getSelectableProperty(element, value);
if (property) {
(<any>element)[property] = value;
}
} else if (this.isCheckedElement(element)) {
element.checked = Boolean(value);
} else {
super.writeValue(value);
}
this.isWritingValue = false;
}
/**
* Listen for custom element events and notify Angular of any changes.
*
* @param event the change event
*/
@HostListener('selected-items-changed', ['$event'])
@HostListener('selected-item-changed', ['$event'])
@HostListener('selected-values-changed', ['$event'])
@HostListener('selected-changed', ['$event'])
@HostListener('checked-changed', ['$event'])
@HostListener('value-changed', ['$event'])
onChangedEvent(event: Event) {
if (!this.isWritingValue) {
const element = this.elementRef.nativeElement;
let changed = false;
switch (event.type) {
case 'selected-items-changed':
case 'selected-item-changed': {
const property = this.getSelectableProperty(element);
changed = property === 'selectedItems' || property === 'selectedItem';
break;
}
case 'selected-values-changed':
case 'selected-changed': {
const property = this.getSelectableProperty(element);
changed = property === 'selectedValues' || property === 'selected';
break;
}
default:
changed = true;
}
if (changed) {
let property: string;
if (this.isMultiSelectable(element) || this.isSelectable(element)) {
// property will be defined if we reach this since changed can only
// be true if the property is defined for selectable elements
property = this.getSelectableProperty(element)!;
} else if (this.isCheckedElement(element)) {
property = 'checked';
} else {
property = 'value';
}
// Don't use `event.detail.value`, since we cannot assume that all
// change events will provide that. Additionally, some event details
// may be splices of an array or object instead of the current value.
this.onChange(element[property]);
}
}
}
/**
* Listen for `invalid` property changes. Some elements, such as
* `<vaadin-date-picker>` have multiple "values". Setting the primary value
* (ex. the date string) may result in a temporarily invalid element until
* subsequent values (ex. the selected date) have been updated.
*
* Since this value accessor only listens for value changes, it may not be
* notified of the change in validity. This listener will listen for any
* explicity validity changes from the element and re-evaluate a control's
* validity if it and the element's validity are out of sync.
*/
@HostListener('invalid-changed')
onInvalidChanged() {
if (!this.ignoreInvalidChanges) {
const element = this.elementRef.nativeElement;
if (
this.isValidatable(element) &&
this.control &&
this.control.invalid !== element.invalid
) {
this.ignoreInvalidChanges = true;
this.control.updateValueAndValidity();
this.ignoreInvalidChanges = false;
}
}
}
/**
* Determines whether or not an element is checkbox-like.
*
* @param element the element to check
*/
isCheckedElement(element: any): element is CheckedElementLike {
return this.isPropertyDefined(element, 'checked');
}
/**
* Determines whether or not an element is selectable-like.
*
* @param element the element to check
*/
isSelectable(element: any): element is SelectableLike {
return (
this.isPropertyDefined(element, 'selected') ||
this.isPropertyDefined(element, 'selectedItem')
);
}
/**
* Determines whether or not an element is multi selectable-like.
*
* @param element the element to check
*/
isMultiSelectable(element: any): element is MultiSelectableLike {
if (
element &&
(this.isPropertyDefined(element, 'selectedValues') ||
this.isPropertyDefined(element, 'selectedItems'))
) {
return this.isSelectable(element) ? element.multi === true : true;
} else {
return false;
}
}
/**
* Determines whether or not an element is validatable-like.
*
* @param element the element to check
*/
isValidatable(element: any): element is ValidatableLike {
return this.isPropertyDefined(element, 'invalid');
}
shouldUseValidate(element: any): element is { validate(): boolean } {
if (typeof element.validate === 'function') {
// Some element's (such as `<vaadin-text-field>`) may not actually mutate
// the `invalid` property when `validate()` is called. In these
// situations, it's possible for Angular to set an element as invalid and
// never be able to recover since the element's `validate()` will always
// report it is invalid.
//
// In these situations, Origami should ignore the element's validate()
// function.
this.ignoreInvalidChanges = true;
const wasInvalid = element.invalid;
// If the element does mutate `invalid`, ask it to do so first to get a
// baseline.
element.validate();
// When `validate()` is called next, we will know if the element mutates
// `invalid` if the expected value matches `invalid` after changing
// `invalid` to something else.
const expected = element.invalid;
element.invalid = !element.invalid;
element.validate();
const validateMutatesInvalid = element.invalid === expected;
element.invalid = wasInvalid;
this.ignoreInvalidChanges = false;
return validateMutatesInvalid;
} else {
return false;
}
}
/**
* Determines whether or not a property is defined anywhere in the provided
* element's prototype chain.
*
* @param element the element to check
* @param property the property to check for
*/
private isPropertyDefined(element: any, property: string): boolean {
return !!element && property in element;
}
/**
* Retrieves the property name of the selectable or multi-selectable element
* that should be updated. This method will use defined properties and the
* value type to determine which property should be used. If it cannot
* determine which property to use, it will return undefined.
*
* @param element the element to get the property for
* @param value a value for the element's property
* @returns the property name, or undefined if it cannot be determined
*/
private getSelectableProperty(element: any, value?: any): string | undefined {
const isMulti = this.isMultiSelectable(element);
const valueProp = isMulti ? 'selectedItems' : 'selectedItem';
const indexProp = isMulti ? 'selectedValues' : 'selected';
if (typeof this.useSelectableValueProp !== 'boolean') {
// Determine whether we should be setting the index or value property for
// a selectable element
const hasValueProp = valueProp in element;
const hasIndexProp = indexProp in element;
if (hasValueProp && !hasIndexProp) {
this.useSelectableValueProp = true;
} else if (!hasValueProp && hasIndexProp) {
this.useSelectableValueProp = false;
} else if (typeof value !== 'undefined' && value !== null) {
const previousValue = element[valueProp];
// When the element has both properties, try to set it to the value
// property first. If it fails, then use the index property
try {
element[valueProp] = value;
} catch (error) {
// Could throw if the value is an unexpected type
}
// Check to see if the value we set it to is still accurate. If it's
// not then the element silently rejected the new value.
this.useSelectableValueProp = element[valueProp] === value;
element[valueProp] = previousValue;
} else {
return undefined;
}
}
if (element.itemValuePath) {
// <vaadin-combo-box> will want to use selectedItem for object values.
// However, if `itemValuePath` is set then the control value is not the
// item itself, but the `value` property.
return 'value';
} else {
return this.useSelectableValueProp ? valueProp : indexProp;
}
}
} | the_stack |
import {Event} from '../util/evented';
import DOM from '../util/dom';
import Map, {CompleteMapOptions} from './map';
import HandlerInertia from './handler_inertia';
import {MapEventHandler, BlockableMapEventHandler} from './handler/map_event';
import BoxZoomHandler from './handler/box_zoom';
import TapZoomHandler from './handler/tap_zoom';
import {MousePanHandler, MouseRotateHandler, MousePitchHandler} from './handler/mouse';
import TouchPanHandler from './handler/touch_pan';
import {TouchZoomHandler, TouchRotateHandler, TouchPitchHandler} from './handler/touch_zoom_rotate';
import KeyboardHandler from './handler/keyboard';
import ScrollZoomHandler from './handler/scroll_zoom';
import DoubleClickZoomHandler from './handler/shim/dblclick_zoom';
import ClickZoomHandler from './handler/click_zoom';
import TapDragZoomHandler from './handler/tap_drag_zoom';
import DragPanHandler from './handler/shim/drag_pan';
import DragRotateHandler from './handler/shim/drag_rotate';
import TouchZoomRotateHandler from './handler/shim/touch_zoom_rotate';
import {bindAll, extend} from '../util/util';
import Point from '@mapbox/point-geometry';
import LngLat from '../geo/lng_lat';
import assert from 'assert';
export type InputEvent = MouseEvent | TouchEvent | KeyboardEvent | WheelEvent;
const isMoving = p => p.zoom || p.drag || p.pitch || p.rotate;
class RenderFrameEvent extends Event {
type: 'renderFrame';
timeStamp: number;
}
// Handlers interpret dom events and return camera changes that should be
// applied to the map (`HandlerResult`s). The camera changes are all deltas.
// The handler itself should have no knowledge of the map's current state.
// This makes it easier to merge multiple results and keeps handlers simpler.
// For example, if there is a mousedown and mousemove, the mousePan handler
// would return a `panDelta` on the mousemove.
export interface Handler {
enable(): void;
disable(): void;
isEnabled(): boolean;
isActive(): boolean;
// `reset` can be called by the manager at any time and must reset everything to it's original state
reset(): void;
// Handlers can optionally implement these methods.
// They are called with dom events whenever those dom evens are received.
readonly touchstart?: (e: TouchEvent, points: Array<Point>, mapTouches: Array<Touch>) => HandlerResult | void;
readonly touchmove?: (e: TouchEvent, points: Array<Point>, mapTouches: Array<Touch>) => HandlerResult | void;
readonly touchend?: (e: TouchEvent, points: Array<Point>, mapTouches: Array<Touch>) => HandlerResult | void;
readonly touchcancel?: (e: TouchEvent, points: Array<Point>, mapTouches: Array<Touch>) => HandlerResult | void;
readonly mousedown?: (e: MouseEvent, point: Point) => HandlerResult | void;
readonly mousemove?: (e: MouseEvent, point: Point) => HandlerResult | void;
readonly mouseup?: (e: MouseEvent, point: Point) => HandlerResult | void;
readonly dblclick?: (e: MouseEvent, point: Point) => HandlerResult | void;
readonly wheel?: (e: WheelEvent, point: Point) => HandlerResult | void;
readonly keydown?: (e: KeyboardEvent) => HandlerResult | void;
readonly keyup?: (e: KeyboardEvent) => HandlerResult | void;
// `renderFrame` is the only non-dom event. It is called during render
// frames and can be used to smooth camera changes (see scroll handler).
readonly renderFrame?: () => HandlerResult | void;
}
// All handler methods that are called with events can optionally return a `HandlerResult`.
export type HandlerResult = {
panDelta?: Point;
zoomDelta?: number;
bearingDelta?: number;
pitchDelta?: number;
// the point to not move when changing the camera
around?: Point | null;
// same as above, except for pinch actions, which are given higher priority
pinchAround?: Point | null;
// A method that can fire a one-off easing by directly changing the map's camera.
cameraAnimation?: (map: Map) => any;
// The last three properties are needed by only one handler: scrollzoom.
// The DOM event to be used as the `originalEvent` on any camera change events.
originalEvent?: any;
// Makes the manager trigger a frame, allowing the handler to return multiple results over time (see scrollzoom).
needsRenderFrame?: boolean;
// The camera changes won't get recorded for inertial zooming.
noInertia?: boolean;
};
function hasChange(result: HandlerResult) {
return (result.panDelta && result.panDelta.mag()) || result.zoomDelta || result.bearingDelta || result.pitchDelta;
}
class HandlerManager {
_map: Map;
_el: HTMLElement;
_handlers: Array<{
handlerName: string;
handler: Handler;
allowed: any;
}>;
_eventsInProgress: any;
_frameId: number;
_inertia: HandlerInertia;
_bearingSnap: number;
_handlersById: {[x: string]: Handler};
_updatingCamera: boolean;
_changes: Array<[HandlerResult, any, any]>;
_drag: {center: Point; lngLat: LngLat; point: Point; handlerName: string};
_previousActiveHandlers: {[x: string]: Handler};
_listeners: Array<[Window | Document | HTMLElement, string, {
passive?: boolean;
capture?: boolean;
} | undefined]>;
constructor(map: Map, options: CompleteMapOptions) {
this._map = map;
this._el = this._map.getCanvasContainer();
this._handlers = [];
this._handlersById = {};
this._changes = [];
this._inertia = new HandlerInertia(map);
this._bearingSnap = options.bearingSnap;
this._previousActiveHandlers = {};
// Track whether map is currently moving, to compute start/move/end events
this._eventsInProgress = {};
this._addDefaultHandlers(options);
bindAll(['handleEvent', 'handleWindowEvent'], this);
const el = this._el;
this._listeners = [
// This needs to be `passive: true` so that a double tap fires two
// pairs of touchstart/end events in iOS Safari 13. If this is set to
// `passive: false` then the second pair of events is only fired if
// preventDefault() is called on the first touchstart. Calling preventDefault()
// undesirably prevents click events.
[el, 'touchstart', {passive: true}],
// This needs to be `passive: false` so that scrolls and pinches can be
// prevented in browsers that don't support `touch-actions: none`, for example iOS Safari 12.
[el, 'touchmove', {passive: false}],
[el, 'touchend', undefined],
[el, 'touchcancel', undefined],
[el, 'mousedown', undefined],
[el, 'mousemove', undefined],
[el, 'mouseup', undefined],
// Bind window-level event listeners for move and up/end events. In the absence of
// the pointer capture API, which is not supported by all necessary platforms,
// window-level event listeners give us the best shot at capturing events that
// fall outside the map canvas element. Use `{capture: true}` for the move event
// to prevent map move events from being fired during a drag.
[document, 'mousemove', {capture: true}],
[document, 'mouseup', undefined],
[el, 'mouseover', undefined],
[el, 'mouseout', undefined],
[el, 'dblclick', undefined],
[el, 'click', undefined],
[el, 'keydown', {capture: false}],
[el, 'keyup', undefined],
[el, 'wheel', {passive: false}],
[el, 'contextmenu', undefined],
[window, 'blur', undefined]
];
for (const [target, type, listenerOptions] of this._listeners) {
DOM.addEventListener(target, type, target === document ? this.handleWindowEvent : this.handleEvent, listenerOptions);
}
}
destroy() {
for (const [target, type, listenerOptions] of this._listeners) {
DOM.removeEventListener(target, type, target === document ? this.handleWindowEvent : this.handleEvent, listenerOptions);
}
}
_addDefaultHandlers(options: CompleteMapOptions) {
const map = this._map;
const el = map.getCanvasContainer();
this._add('mapEvent', new MapEventHandler(map, options));
const boxZoom = map.boxZoom = new BoxZoomHandler(map, options);
this._add('boxZoom', boxZoom);
const tapZoom = new TapZoomHandler();
const clickZoom = new ClickZoomHandler();
map.doubleClickZoom = new DoubleClickZoomHandler(clickZoom, tapZoom);
this._add('tapZoom', tapZoom);
this._add('clickZoom', clickZoom);
const tapDragZoom = new TapDragZoomHandler();
this._add('tapDragZoom', tapDragZoom);
const touchPitch = map.touchPitch = new TouchPitchHandler();
this._add('touchPitch', touchPitch);
const mouseRotate = new MouseRotateHandler(options);
const mousePitch = new MousePitchHandler(options);
map.dragRotate = new DragRotateHandler(options, mouseRotate, mousePitch);
this._add('mouseRotate', mouseRotate, ['mousePitch']);
this._add('mousePitch', mousePitch, ['mouseRotate']);
const mousePan = new MousePanHandler(options);
const touchPan = new TouchPanHandler(options);
map.dragPan = new DragPanHandler(el, mousePan, touchPan);
this._add('mousePan', mousePan);
this._add('touchPan', touchPan, ['touchZoom', 'touchRotate']);
const touchRotate = new TouchRotateHandler();
const touchZoom = new TouchZoomHandler();
map.touchZoomRotate = new TouchZoomRotateHandler(el, touchZoom, touchRotate, tapDragZoom);
this._add('touchRotate', touchRotate, ['touchPan', 'touchZoom']);
this._add('touchZoom', touchZoom, ['touchPan', 'touchRotate']);
const scrollZoom = map.scrollZoom = new ScrollZoomHandler(map, this);
this._add('scrollZoom', scrollZoom, ['mousePan']);
const keyboard = map.keyboard = new KeyboardHandler();
this._add('keyboard', keyboard);
this._add('blockableMapEvent', new BlockableMapEventHandler(map));
for (const name of ['boxZoom', 'doubleClickZoom', 'tapDragZoom', 'touchPitch', 'dragRotate', 'dragPan', 'touchZoomRotate', 'scrollZoom', 'keyboard']) {
if (options.interactive && options[name]) {
map[name].enable(options[name]);
}
}
}
_add(handlerName: string, handler: Handler, allowed?: Array<string>) {
this._handlers.push({handlerName, handler, allowed});
this._handlersById[handlerName] = handler;
}
stop(allowEndAnimation: boolean) {
// do nothing if this method was triggered by a gesture update
if (this._updatingCamera) return;
for (const {handler} of this._handlers) {
handler.reset();
}
this._inertia.clear();
this._fireEvents({}, {}, allowEndAnimation);
this._changes = [];
}
isActive() {
for (const {handler} of this._handlers) {
if (handler.isActive()) return true;
}
return false;
}
isZooming() {
return !!this._eventsInProgress.zoom || this._map.scrollZoom.isZooming();
}
isRotating() {
return !!this._eventsInProgress.rotate;
}
isMoving() {
return Boolean(isMoving(this._eventsInProgress)) || this.isZooming();
}
_blockedByActive(activeHandlers: {[x: string]: Handler}, allowed: Array<string>, myName: string) {
for (const name in activeHandlers) {
if (name === myName) continue;
if (!allowed || allowed.indexOf(name) < 0) {
return true;
}
}
return false;
}
handleWindowEvent(e: InputEvent) {
this.handleEvent(e, `${e.type}Window`);
}
_getMapTouches(touches: TouchList) {
const mapTouches = [];
for (const t of touches) {
const target = (t.target as any as Node);
if (this._el.contains(target)) {
mapTouches.push(t);
}
}
return mapTouches as any as TouchList;
}
handleEvent(e: InputEvent | RenderFrameEvent, eventName?: string) {
if (e.type === 'blur') {
this.stop(true);
return;
}
this._updatingCamera = true;
assert(e.timeStamp !== undefined);
const inputEvent = e.type === 'renderFrame' ? undefined : (e as any as InputEvent);
/*
* We don't call e.preventDefault() for any events by default.
* Handlers are responsible for calling it where necessary.
*/
const mergedHandlerResult: HandlerResult = {needsRenderFrame: false};
const eventsInProgress = {};
const activeHandlers = {};
const eventTouches = (e as any as TouchEvent).touches;
const mapTouches = eventTouches ? this._getMapTouches(eventTouches) : undefined;
const points = mapTouches ? DOM.touchPos(this._el, mapTouches) : DOM.mousePos(this._el, ((e as any as MouseEvent)));
for (const {handlerName, handler, allowed} of this._handlers) {
if (!handler.isEnabled()) continue;
let data: HandlerResult;
if (this._blockedByActive(activeHandlers, allowed, handlerName)) {
handler.reset();
} else {
if ((handler as any)[eventName || e.type]) {
data = (handler as any)[eventName || e.type](e, points, mapTouches);
this.mergeHandlerResult(mergedHandlerResult, eventsInProgress, data, handlerName, inputEvent);
if (data && data.needsRenderFrame) {
this._triggerRenderFrame();
}
}
}
if (data || handler.isActive()) {
activeHandlers[handlerName] = handler;
}
}
const deactivatedHandlers = {};
for (const name in this._previousActiveHandlers) {
if (!activeHandlers[name]) {
deactivatedHandlers[name] = inputEvent;
}
}
this._previousActiveHandlers = activeHandlers;
if (Object.keys(deactivatedHandlers).length || hasChange(mergedHandlerResult)) {
this._changes.push([mergedHandlerResult, eventsInProgress, deactivatedHandlers]);
this._triggerRenderFrame();
}
if (Object.keys(activeHandlers).length || hasChange(mergedHandlerResult)) {
this._map._stop(true);
}
this._updatingCamera = false;
const {cameraAnimation} = mergedHandlerResult;
if (cameraAnimation) {
this._inertia.clear();
this._fireEvents({}, {}, true);
this._changes = [];
cameraAnimation(this._map);
}
}
mergeHandlerResult(mergedHandlerResult: HandlerResult, eventsInProgress: any, handlerResult: HandlerResult, name: string, e?: InputEvent) {
if (!handlerResult) return;
extend(mergedHandlerResult, handlerResult);
const eventData = {handlerName: name, originalEvent: handlerResult.originalEvent || e};
// track which handler changed which camera property
if (handlerResult.zoomDelta !== undefined) {
eventsInProgress.zoom = eventData;
}
if (handlerResult.panDelta !== undefined) {
eventsInProgress.drag = eventData;
}
if (handlerResult.pitchDelta !== undefined) {
eventsInProgress.pitch = eventData;
}
if (handlerResult.bearingDelta !== undefined) {
eventsInProgress.rotate = eventData;
}
}
_applyChanges() {
const combined: {[k: string]: any} = {};
const combinedEventsInProgress = {};
const combinedDeactivatedHandlers = {};
for (const [change, eventsInProgress, deactivatedHandlers] of this._changes) {
if (change.panDelta) combined.panDelta = (combined.panDelta || new Point(0, 0))._add(change.panDelta);
if (change.zoomDelta) combined.zoomDelta = (combined.zoomDelta || 0) + change.zoomDelta;
if (change.bearingDelta) combined.bearingDelta = (combined.bearingDelta || 0) + change.bearingDelta;
if (change.pitchDelta) combined.pitchDelta = (combined.pitchDelta || 0) + change.pitchDelta;
if (change.around !== undefined) combined.around = change.around;
if (change.pinchAround !== undefined) combined.pinchAround = change.pinchAround;
if (change.noInertia) combined.noInertia = change.noInertia;
extend(combinedEventsInProgress, eventsInProgress);
extend(combinedDeactivatedHandlers, deactivatedHandlers);
}
this._updateMapTransform(combined, combinedEventsInProgress, combinedDeactivatedHandlers);
this._changes = [];
}
_updateMapTransform(combinedResult: any, combinedEventsInProgress: any, deactivatedHandlers: any) {
const map = this._map;
const tr = map.transform;
const terrain = map.style && map.style.terrain;
if (!hasChange(combinedResult) && !(terrain && this._drag)) {
return this._fireEvents(combinedEventsInProgress, deactivatedHandlers, true);
}
let {panDelta, zoomDelta, bearingDelta, pitchDelta, around, pinchAround} = combinedResult;
if (pinchAround !== undefined) {
around = pinchAround;
}
// stop any ongoing camera animations (easeTo, flyTo)
map._stop(true);
around = around || map.transform.centerPoint;
const loc = tr.pointLocation(panDelta ? around.sub(panDelta) : around);
if (bearingDelta) tr.bearing += bearingDelta;
if (pitchDelta) tr.pitch += pitchDelta;
if (zoomDelta) tr.zoom += zoomDelta;
if (!terrain) {
tr.setLocationAtPoint(loc, around);
} else {
// when 3d-terrain is enabled act a litte different:
// - draging do not drag the picked point itself, instead it drags the map by pixel-delta.
// With this approach it is no longer possible to pick a point from somewhere near
// the horizon to the center in one move.
// So this logic avoids the problem, that in such cases you easily loose orientation.
// - scrollzoom does not zoom into the mouse-point, instead it zooms into map-center
// this should be fixed in future-version
// when dragging starts, remember mousedown-location and panDelta from this point
if (combinedEventsInProgress.drag && !this._drag) {
this._drag = {
center: tr.centerPoint,
lngLat: tr.pointLocation(around),
point: around,
handlerName: combinedEventsInProgress.drag.handlerName
};
map.fire(new Event('freezeElevation', {freeze: true}));
// when dragging ends, recalcuate the zoomlevel for the new center coordinate
} else if (this._drag && deactivatedHandlers[this._drag.handlerName]) {
map.fire(new Event('freezeElevation', {freeze: false}));
this._drag = null;
// drag map
} else if (combinedEventsInProgress.drag && this._drag) {
tr.center = tr.pointLocation(tr.centerPoint.sub(panDelta));
}
}
this._map._update();
if (!combinedResult.noInertia) this._inertia.record(combinedResult);
this._fireEvents(combinedEventsInProgress, deactivatedHandlers, true);
}
_fireEvents(newEventsInProgress: {[x: string]: any}, deactivatedHandlers: any, allowEndAnimation: boolean) {
const wasMoving = isMoving(this._eventsInProgress);
const nowMoving = isMoving(newEventsInProgress);
const startEvents = {};
for (const eventName in newEventsInProgress) {
const {originalEvent} = newEventsInProgress[eventName];
if (!this._eventsInProgress[eventName]) {
startEvents[`${eventName}start`] = originalEvent;
}
this._eventsInProgress[eventName] = newEventsInProgress[eventName];
}
// fire start events only after this._eventsInProgress has been updated
if (!wasMoving && nowMoving) {
this._fireEvent('movestart', nowMoving.originalEvent);
}
for (const name in startEvents) {
this._fireEvent(name, startEvents[name]);
}
if (nowMoving) {
this._fireEvent('move', nowMoving.originalEvent);
}
for (const eventName in newEventsInProgress) {
const {originalEvent} = newEventsInProgress[eventName];
this._fireEvent(eventName, originalEvent);
}
const endEvents = {};
let originalEndEvent;
for (const eventName in this._eventsInProgress) {
const {handlerName, originalEvent} = this._eventsInProgress[eventName];
if (!this._handlersById[handlerName].isActive()) {
delete this._eventsInProgress[eventName];
originalEndEvent = deactivatedHandlers[handlerName] || originalEvent;
endEvents[`${eventName}end`] = originalEndEvent;
}
}
for (const name in endEvents) {
this._fireEvent(name, endEvents[name]);
}
const stillMoving = isMoving(this._eventsInProgress);
if (allowEndAnimation && (wasMoving || nowMoving) && !stillMoving) {
this._updatingCamera = true;
const inertialEase = this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions);
const shouldSnapToNorth = bearing => bearing !== 0 && -this._bearingSnap < bearing && bearing < this._bearingSnap;
if (inertialEase) {
if (shouldSnapToNorth(inertialEase.bearing || this._map.getBearing())) {
inertialEase.bearing = 0;
}
this._map.easeTo(inertialEase, {originalEvent: originalEndEvent});
} else {
this._map.fire(new Event('moveend', {originalEvent: originalEndEvent}));
if (shouldSnapToNorth(this._map.getBearing())) {
this._map.resetNorth();
}
}
this._updatingCamera = false;
}
}
_fireEvent(type: string, e: any) {
this._map.fire(new Event(type, e ? {originalEvent: e} : {}));
}
_requestFrame() {
this._map.triggerRepaint();
return this._map._renderTaskQueue.add(timeStamp => {
delete this._frameId;
this.handleEvent(new RenderFrameEvent('renderFrame', {timeStamp}));
this._applyChanges();
});
}
_triggerRenderFrame() {
if (this._frameId === undefined) {
this._frameId = this._requestFrame();
}
}
}
export default HandlerManager; | the_stack |
import * as PropertyAction from '../actions/property'
import * as PropertyEffects from './effects/property'
import * as InterfaceAction from '../actions/interface'
import * as InterfaceEffects from './effects/interface'
import * as ModuleAction from '../actions/module'
import * as ModuleEffects from './effects/module'
import * as RepositoryAction from '../actions/repository'
import * as RepositoryEffects from './effects/repository'
import _ from 'lodash'
export default {
reducers: {
repository(
state: any = {
data: {
modules: [],
},
fetching: false,
},
action: any
) {
let modules, itfId: any, locker: any, properties: any, itf: any, mod: any
switch (action.type) {
case RepositoryAction.fetchRepository({
id: undefined,
repository: undefined,
}).type:
return {
data: {
...state.data,
},
fetching: true,
}
case RepositoryAction.fetchRepositorySucceeded({}).type:
return {
data: action.repository,
fetching: false,
}
case RepositoryAction.fetchRepositoryFailed('').type:
case RepositoryAction.clearRepository().type:
return {
data: {},
fetching: false,
}
case InterfaceAction.lockInterfaceSucceeded(undefined, undefined).type:
modules = state.data.modules
itfId = action.payload.itfId
locker = action.payload.locker
return {
...state,
data: {
...state.data,
modules: modules.map((mod: any) => ({
...mod,
interfaces: mod.interfaces.map((itf: any) => {
if (itf.id !== itfId) {
return itf
}
return {
...itf,
lockerId: locker.id,
locker,
updatedAt: new Date(),
}
}),
})),
},
}
case 'INTERFACE_FETCH_SUCCEEDED': {
modules = state.data.modules
const fetchedItf = _.omit(action.payload, ['requestProperties', 'responseProperties'])
return {
...state,
data: {
...state.data,
modules: modules.map((mod: any) => ({
...mod,
interfaces: mod.interfaces.map((itf: any) => {
if (itf.id !== fetchedItf.id) {
return itf
}
return {
...itf,
...fetchedItf,
}
}),
})),
},
}
}
case InterfaceAction.unlockInterfaceSucceeded(undefined).type:
modules = state.data.modules
itfId = action.payload.itfId
return {
...state,
data: {
...state.data,
modules: modules.map((mod: any) => ({
...mod,
interfaces: mod.interfaces.map((itf: any) => {
if (itf.id !== itfId) {
return itf
}
return {
...itf,
lockerId: null,
locker: null,
updatedAt: new Date(),
}
}),
})),
},
}
case PropertyAction.updatePropertiesSucceeded(undefined).type:
modules = state.data.modules
itfId = action.payload.itfId
properties = action.payload.properties
return {
...state,
data: {
...state.data,
modules: modules.map((mod: any) => ({
...mod,
interfaces: mod.interfaces.map((itf: any) => {
if (itf.id !== itfId) {
return itf
}
return {
...itf,
properties,
updatedAt: new Date(),
}
}),
})),
},
}
case InterfaceAction.updateInterfaceSucceeded(undefined).type:
modules = state.data.modules
itf = action.payload.itf
return {
...state,
data: {
...state.data,
modules: modules.map((mod: any) => ({
...mod,
interfaces: mod.interfaces.map((x: any) => {
if (x.id !== itf.id) {
return x
}
return {
...itf,
locker: x.locker,
properties: x.properties,
}
}),
})),
},
}
case InterfaceAction.deleteInterfaceSucceeded(undefined).type:
modules = state.data.modules
itfId = action.payload.id
return {
...state,
data: {
...state.data,
modules: modules.map((mod: any) => ({
...mod,
interfaces: mod.interfaces.filter((x: any) => x.id !== itfId),
})),
},
}
case InterfaceAction.addInterfaceSucceeded(undefined).type:
modules = state.data.modules
itf = action.payload.itf
return {
...state,
data: {
...state.data,
modules: modules.map((mod: any) =>
mod.id === itf.moduleId
? {
...mod,
interfaces: [...mod.interfaces, itf],
}
: mod,
),
},
}
case ModuleAction.updateModuleSucceeded(undefined).type:
modules = state.data.modules
mod = action.payload
return {
...state,
data: {
...state.data,
modules: modules.map((x: any) =>
x.id === mod.id
? {
...x,
name: mod.name,
description: mod.description,
}
: x,
),
},
}
case 'INTERFACE_LIST_SORT_SUCCEEDED': {
const modules = state.data.modules
const iftIds = action.ids
const itfIdsMap: any = {}
iftIds.forEach((id: number, index: number) => {
itfIdsMap[id] = index
})
const moduleId = action.moduleId
return {
...state,
data: {
...state.data,
modules: modules.map((mod: any) =>
mod.id === moduleId
? {
...mod,
interfaces: [...mod.interfaces].sort(
(a: any, b: any) => itfIdsMap[a.id] - itfIdsMap[b.id],
),
}
: mod,
),
},
}
}
case 'MODULE_LIST_SORT_SUCCEEDED': {
const modules = state.data.modules
const moduleIds = action.ids
const moduleIdsMap: any = {}
moduleIds.forEach((id: number, index: number) => {
moduleIdsMap[id] = index
})
return {
...state,
data: {
...state.data,
modules: [...modules].sort(
(a: any, b: any) => moduleIdsMap[a.id] - moduleIdsMap[b.id],
),
},
}
}
default:
return state
}
},
ownedRepositories(
state: any = {
data: [],
pagination: {
total: 0,
cursor: 1,
limit: 100,
},
fetching: false,
},
action: any
) {
switch (action.type) {
case RepositoryAction.fetchOwnedRepositoryList().type:
return {
data: [...state.data],
pagination: {
...state.pagination,
},
fetching: true,
}
case RepositoryAction.fetchOwnedRepositoryListSucceeded(undefined).type:
return {
data: action.repositories.data,
pagination: {
...state.pagination,
...action.repositories.pagination,
},
fetching: false,
}
case RepositoryAction.fetchOwnedRepositoryListFailed(undefined).type:
return {
data: [],
pagination: {
...state.pagination,
},
fetching: false,
}
default:
return state
}
},
joinedRepositories(
state: any = {
data: [],
pagination: {
total: 0,
cursor: 1,
limit: 100,
},
fetching: false,
},
action: any
) {
switch (action.type) {
case RepositoryAction.fetchJoinedRepositoryList().type:
return {
data: [...state.data],
pagination: {
...state.pagination,
},
fetching: true,
}
case RepositoryAction.fetchJoinedRepositoryListSucceeded(undefined)
.type:
return {
data: action.repositories.data,
pagination: {
...state.pagination,
...action.repositories.pagination,
},
fetching: false,
}
case RepositoryAction.fetchJoinedRepositoryListFailed(undefined).type:
return {
data: [],
pagination: {
...state.pagination,
},
fetching: false,
}
default:
return state
}
},
repositories(
state: any = {
data: [],
pagination: {
total: 0,
limit: 10,
},
fetching: false,
},
action: any
) {
switch (action.type) {
case '...':
return state
case 'REPOSITORIES_ADD_SUCCEEDED':
return {
data: [...state.data, action.repository],
pagination: state.pagination,
fetching: state.fetching,
}
case 'REPOSITORY_COUNT_FETCH_SUCCEEDED':
return {
data: [...state.data],
pagination: {
...state.pagination,
total: action.count,
},
fetching: state.fetching,
}
case RepositoryAction.fetchRepositoryList().type:
return {
data: [...state.data],
pagination: {
...state.pagination,
},
fetching: true,
}
case RepositoryAction.fetchRepositoryListSucceeded(undefined).type:
return {
data: action.repositories.data,
pagination: action.repositories.pagination,
fetching: false,
}
case RepositoryAction.fetchRepositoryListFailed(undefined).type:
return {
data: [],
pagination: {
...state.pagination,
},
fetching: false,
}
default:
return state
}
},
interfaces(
state: any = {
data: [],
pagination: {
total: 0,
limit: 10,
},
},
action: any
) {
switch (action.type) {
case 'INTERFACE_COUNT_FETCH_SUCCEEDED':
return {
data: [...state.data],
pagination: {
...state.pagination,
total: action.count,
},
}
default:
return state
}
},
dashboard(
state: any = {
my: [],
joined: [],
},
action: any
) {
switch (action.type) {
case '...':
return state
case 'MY_REPOSITORY_LIST_FETCH_SUCCEEDED':
return {
my: action.repositories,
joined: state.joined,
}
case 'JOINED_REPOSITORY_LIST_FETCH_SUCCEEDED':
return {
my: state.my,
joined: action.repositories,
}
default:
return state
}
},
defaultVals(state: any = [], action: any) {
switch (action.type) {
case 'DEFAULT_VALS_SUCCEEDED':
return action.payload.data
}
return state
},
},
sagas: {
[RepositoryAction.addRepository(undefined, undefined).type]:
RepositoryEffects.addRepository,
[RepositoryAction.deleteRepository(undefined).type]:
RepositoryEffects.deleteRepository,
[RepositoryAction.updateRepository(undefined, undefined).type]:
RepositoryEffects.updateRepository,
[RepositoryAction.fetchRepository({ id: undefined, repository: undefined })
.type]: RepositoryEffects.fetchRepository,
REPOSITORY_LOCATION_CHANGE:
RepositoryEffects.handleRepositoryLocationChange,
REPOSITORY_REFRESH:
RepositoryEffects.refreshRepository,
[RepositoryAction.fetchRepositoryCount().type]:
RepositoryEffects.fetchRepositoryCount,
[RepositoryAction.fetchRepositoryList().type]:
RepositoryEffects.fetchRepositoryList,
[RepositoryAction.importRepository(undefined, undefined).type]:
RepositoryEffects.importRepository,
[RepositoryAction.importSwaggerRepository(undefined, undefined).type]:
RepositoryEffects.importSwaggerRepository,
[RepositoryAction.fetchOwnedRepositoryList().type]:
RepositoryEffects.fetchOwnedRepositoryList,
[RepositoryAction.fetchJoinedRepositoryList().type]:
RepositoryEffects.fetchJoinedRepositoryList,
[RepositoryAction.fetchDefaultVals(0).type]:
RepositoryEffects.fetchDefaultVals,
[RepositoryAction.updateDefaultVals(0, []).type]:
RepositoryEffects.updateDefaultVals,
[ModuleAction.sortModuleList(undefined, undefined).type]:
ModuleEffects.sortModuleList,
[InterfaceAction.fetchInterfaceCount().type]:
InterfaceEffects.fetchInterfaceCount,
INTERFACE_LIST_SORT:
InterfaceEffects.sortInterfaceList,
[PropertyAction.sortPropertyList(undefined, undefined).type]:
PropertyEffects.sortPropertyList,
},
listeners: {
'/repository': [
RepositoryAction.fetchOwnedRepositoryList,
RepositoryAction.fetchJoinedRepositoryList,
],
'/repository/joined': [
RepositoryAction.fetchOwnedRepositoryList,
RepositoryAction.fetchJoinedRepositoryList,
],
'/repository/editor': [
// REPOSITORY_LOCATION_CHANGE 判断了如果是当前 repo 的模块或接口切换就不重新获取
// 如果 repo 的 id 发生变化再进行 repo 的重新拉取
RepositoryAction.repositoryLocationChange,
],
'/organization/repository/editor': [
// REPOSITORY_LOCATION_CHANGE 判断了如果是当前 repo 的模块或接口切换就不重新获取
// 如果 repo 的 id 发生变化再进行 repo 的重新拉取
RepositoryAction.repositoryLocationChange,
],
'/repository/all': [RepositoryAction.fetchRepositoryList],
'/repository/tester': [RepositoryAction.fetchRepository],
'/repository/checker': [RepositoryAction.fetchRepository],
'/organization/repository': [RepositoryAction.fetchRepositoryList],
},
} | the_stack |
export default {
defaultToken: '',
ignoreCase: true,
brackets: [
{ open: '[', close: ']', token: 'delimiter.square' },
{ open: '(', close: ')', token: 'delimiter.parenthesis' }
],
keywords: [
// Reserved
'ALL',
'ALTER',
'AND',
'ARRAY',
'AS',
'AUTHORIZATION',
'BETWEEN',
'BIGINT',
'BINARY',
'BOOLEAN',
'BOTH',
'BY',
'CASE',
'CAST',
'CHAR',
'COLUMN',
'CONF',
'CREATE',
'CROSS',
'CUBE',
'CURRENT',
'CURRENT_DATE',
'CURRENT_TIMESTAMP',
'CURSOR',
'DATABASE',
'DATE',
'DECIMAL',
'DELETE',
'DESCRIBE',
'DISTINCT',
'DOUBLE',
'DROP',
'ELSE',
'END',
'EXCHANGE',
'EXISTS',
'EXTENDED',
'EXTERNAL',
'FALSE',
'FETCH',
'FLOAT',
'FOLLOWING',
'FOR',
'FROM',
'FULL',
'FUNCTION',
'GRANT',
'GROUP',
'GROUPING',
'HAVING',
'IF',
'IMPORT',
'IN',
'INNER',
'INSERT',
'INT',
'INTERSECT',
'INTERVAL',
'INTO',
'IS',
'JOIN',
'LATERAL',
'LEFT',
'LESS',
'LIKE',
'LOCAL',
'MACRO',
'MAP',
'MORE',
'NONE',
'NOT',
'NULL',
'OF',
'ON',
'OR',
'ORDER',
'OUT',
'OUTER',
'OVER',
'PARTIALSCAN',
'PARTITION',
'PERCENT',
'PRECEDING',
'PRESERVE',
'PROCEDURE',
'RANGE',
'READS',
'REDUCE',
'REVOKE',
'RIGHT',
'ROLLUP',
'ROW',
'ROWS',
'SELECT',
'SET',
'SMALLINT',
'TABLE',
'TABLESAMPLE',
'THEN',
'TIMESTAMP',
'TO',
'TRANSFORM',
'TRIGGER',
'TRUE',
'TRUNCATE',
'UNBOUNDED',
'UNION',
'UNIQUEJOIN',
'UPDATE',
'USER',
'USING',
'UTC_TMESTAMP',
'VALUES',
'VARCHAR',
'WHEN',
'WHERE',
'WINDOW',
'WITH',
// added hive 2.0.0
'COMMIT',
'ONLY',
'REGEXP',
'RLIKE',
'ROLLBACK',
'START',
// added hive 2.1.0
'CACHE',
'CONSTRAINT',
'FOREIGN',
'PRIMARY',
'REFERENCES',
// added hive 2.2.0
'DAYOFWEEK',
'EXTRACT',
'FLOOR',
'INTEGER',
'PRECISION',
'VIEWS',
// added hive 3.0.0
'TIME',
'NUMERIC',
'SYNC',
// Non-reserved
'ADD',
'ADMIN',
'AFTER',
'ANALYZE',
'ARCHIVE',
'ASC',
'BEFORE',
'BUCKET',
'BUCKETS',
'CASCADE',
'CHANGE',
'CLUSTER',
'CLUSTERED',
'CLUSTERSTATUS',
'COLLECTION',
'COLUMNS',
'COMMENT',
'COMPACT',
'COMPACTIONS',
'COMPUTE',
'CONCATENATE',
'CONTINUE',
'DATA',
'DATABASES',
'DATETIME',
'DAY',
'DBPROPERTIES',
'DEFERRED',
'DEFINED',
'DELIMITED',
'DEPENDENCY',
'DESC',
'DIRECTORIES',
'DIRECTORY',
'DISABLE',
'DISTRIBUTE',
'ELEM_TYPE',
'ENABLE',
'ESCAPED',
'EXCLUSIVE',
'EXPLAIN',
'EXPORT',
'FIELDS',
'FILE',
'FILEFORMAT',
'FIRST',
'FORMAT',
'FORMATTED',
'FUNCTIONS',
'HOLD_DDLTIME',
'HOUR',
'IDXPROPERTIES',
'IGNORE',
'INDEX',
'INDEXES',
'INPATH',
'INPUTDRIVER',
'INPUTFORMAT',
'ITEMS',
'JAR',
'KEYS',
'KEY_TYPE',
'LIMIT',
'LINES',
'LOAD',
'LOCATION',
'LOCK',
'LOCKS',
'LOGICAL',
'LONG',
'MAPJOIN',
'MATERIALIZED',
'METADATA',
'MINUS',
'MINUTE',
'MONTH',
'MSCK',
'NOSCAN',
'NO_DROP',
'OFFLINE',
'OPTION',
'OUTPUTDRIVER',
'OUTPUTFORMAT',
'OVERWRITE',
'OWNER',
'PARTITIONED',
'PARTITIONS',
'PLUS',
'PRETTY',
'PRINCIPALS',
'PROTECTION',
'PURGE',
'READ',
'READONLY',
'REBUILD',
'RECORDREADER',
'RECORDWRITER',
'RELOAD',
'RENAME',
'REPAIR',
'REPLACE',
'REPLICATION',
'RESTRICT',
'REWRITE',
'ROLE',
'ROLES',
'SCHEMA',
'SCHEMAS',
'SECOND',
'SEMI',
'SERDE',
'SERDEPROPERTIES',
'SERVER',
'SETS',
'SHARED',
'SHOW',
'SHOW_DATABASE',
'SKEWED',
'SORT',
'SORTED',
'SSL',
'STATISTICS',
'STORED',
'STREAMTABLE',
'STRING',
'STRUCT',
'TABLES',
'TBLPROPERTIES',
'TEMPORARY',
'TERMINATED',
'TINYINT',
'TOUCH',
'TRANSACTIONS',
'UNARCHIVE',
'UNDO',
'UNIONTYPE',
'UNLOCK',
'UNSET',
'UNSIGNED',
'URI',
'USE',
'UTC',
'UTCTIMESTAMP',
'VALUE_TYPE',
'VIEW',
'WHILE',
'YEAR',
// added hive 2.0.0
'AUTOCOMMIT',
'ISOLATION',
'LEVEL',
'OFFSET',
'SNAPSHOT',
'TRANSACTION',
'WORK',
'WRITE',
// added hive 2.1.0
'ABORT',
'KEY',
'LAST',
'NORELY',
'NOVALIDATE',
'NULLS',
'RELY',
'VALIDATE',
// added hive 2.2.0
'DETAIL',
'DOW',
'EXPRESSION',
'OPERATOR',
'QUARTER',
'SUMMARY',
'VECTORIZATION',
'WEEK',
'YEARS',
'MONTHS',
'WEEKS',
'DAYS',
'HOURS',
'MINUTES',
'SECONDS',
// added hive 3.0.0
'TIMESTAMPTZ',
'ZONE'
],
operators: [
// Relational
'BETWEEN',
'IS',
'NULL',
'LIKE',
'RLIKE',
'REGEXP',
// Arithmetic
'DIV',
// Logical
'AND',
'OR',
'NOT',
'IN',
'EXISTS'
],
builtinFunctions: [
'any',
'approx_count_distinct',
'approx_percentile',
'avg',
'bit_or',
'bit_xor',
'bool_and',
'bool_or',
'collect_list',
'collect_set',
'corr',
'count',
'count_if',
'count_min_sketch',
'covar_pop',
'covar_samp',
'every',
'first',
'first_value',
'kurtosis',
'last',
'last_value',
'max',
'max_by',
'mean',
'min',
'min_by',
'percentile',
'percentile_approx',
'skewness',
'some',
'std',
'stddev',
'stddev_pop',
'stddev_samp',
'sum',
'var_pop',
'var_samp',
'variance',
'cume_dist',
'dense_rank',
'lag',
'lead',
'ntile',
'percent_rank',
'rank',
'row_number',
'array_contains',
'array_distinct',
'array_except',
'array_intersect',
'array_join',
'array_max',
'array_min',
'array_position',
'array_remove',
'array_repeat',
'array_union',
'arrays_overlap',
'arrays_zip',
'concat',
'flatten',
'reverse',
'sequence',
'shuffle',
'slice',
'sort_array',
'map_concat',
'map_entries',
'map_from_entries',
'map_keys',
'map_values',
'add_months',
'current_date',
'current_timestamp',
'date_add',
'date_format',
'date_part',
'date_sub',
'date_trunc',
'datediff',
'dayofweek',
'dayofyear',
'from_unixtime',
'from_utc_timestamp',
'hour',
'last_day',
'make_date',
'make_timestamp',
'minute',
'month',
'months_between',
'next_day',
'now',
'quarter',
'second',
'to_date',
'to_timestamp',
'to_unix_timestamp',
'to_utc_timestamp',
'trunc',
'unix_timestamp',
'weekday',
'weekofyear',
'year',
'from_json',
'get_json_object',
'json_tuple',
'schema_of_json',
'to_json',
'map',
'struct',
'named_struct',
'array',
'create_union',
'round',
'bround',
'floor',
'ceil',
'rand',
'exp',
'ln',
'log10',
'log2',
'log',
'pow',
'power',
'sqrt',
'bin',
'hex',
'unhex',
'conv',
'abs',
'pmod',
'sin',
'asin',
'cos',
'acos',
'tan',
'atan',
'degrees',
'radians',
'positive',
'negative',
'sign',
'e',
'pi',
'factorial',
'cbrt',
'shiftleft',
'shiftright',
'shiftrightunsigned',
'greatest',
'least',
'width_bucket',
'size',
'binary',
'cast',
'day',
'extract',
'if',
'isnull',
'isnotnull',
'nvl',
'coalesce',
'case',
'case when',
'nullif',
'assert_true',
'ascii',
'base64',
'character_length',
'chr',
'context_ngrams',
'concat_ws',
'decode',
'elt',
'encode',
'field',
'find_in_set',
'format_number',
'in_file',
'instr',
'length',
'locate',
'lower',
'lpad',
'ltrim',
'ngrams',
'octet_length',
'parse_url',
'printf',
'quote',
'regexp_extract',
'regexp_replace',
'repeat',
'replace',
'rpad',
'rtrim',
'sentences',
'space',
'split',
'str_to_map',
'substr',
'substring_index',
'translate',
'trim',
'unbase64',
'upper',
'initcap',
'levenshtein',
'soundex',
'mask',
'mask_first_n',
'mask_last_n',
'mask_show_first_n',
'mask_show_last_n',
'mask_hash',
'java_method',
'reflect',
'hash',
'current_user',
'logged_in_user',
'current_database',
'md5',
'sha1',
'sha',
'crc32',
'sha2',
'aes_encrypt',
'aes_decrypt',
'version',
'buildversion',
'surrogate_key',
'regr_avgx',
'regr_avgy',
'regr_count',
'regr_intercept',
'regr_r2',
'regr_slope',
'regr_sxx',
'regr_sxy',
'regr_syy',
'histogram_numeric',
'explode',
'posexplode',
'inline',
'stack',
'parse_url_tuple'
],
builtinVariables: [],
pseudoColumns: [],
tokenizer: {
root: [
{ include: '@comments' },
{ include: '@whitespace' },
{ include: '@pseudoColumns' },
{ include: '@numbers' },
{ include: '@strings' },
{ include: '@complexIdentifiers' },
{ include: '@scopes' },
[/[;,.]/, 'delimiter'],
[/[()]/, '@brackets'],
[/\{\{[0-9a-zA-Z\-_]{21}( as \w+)?\}\}/, 'transclusion'],
[
/[\w@#$]+/,
{
cases: {
'@keywords': 'keyword',
'@operators': 'operator',
'@builtinVariables': 'predefined',
'@builtinFunctions': 'predefined',
'@default': 'identifier'
}
}
],
[/[<>=!%&+\-*/|~^]/, 'operator']
],
whitespace: [[/\s+/, 'white']],
comments: [
[/--+.*/, 'comment'],
[/\/\*/, { token: 'comment.quote', next: '@comment' }]
],
comment: [
[/[^*/]+/, 'comment'],
// Not supporting nested comments, as nested comments seem to not be standard?
// i.e. http://stackoverflow.com/questions/728172/are-there-multiline-comment-delimiters-in-sql-that-are-vendor-agnostic
// [/\/\*/, { token: 'comment.quote', next: '@push' }], // nested comment not allowed :-(
[/\*\//, { token: 'comment.quote', next: '@pop' }],
[/./, 'comment']
],
pseudoColumns: [
[
/[$][A-Za-z_][\w@#$]*/,
{
cases: {
'@pseudoColumns': 'predefined',
'@default': 'identifier'
}
}
]
],
numbers: [
[/0[xX][0-9a-fA-F]*/, 'number'],
[/[$][+-]*\d*(\.\d*)?/, 'number'],
[/((\d+(\.\d*)?)|(\.\d+))([eE][-+]?\d+)?/, 'number']
],
strings: [
[/'/, { token: 'string', next: '@singleQuotedString' }],
[/"/, { token: 'string', next: '@doubleQuotedString' }]
],
singleQuotedString: [
[/[^']+/, 'string'],
[/''/, 'string'],
[/'/, { token: 'string', next: '@pop' }]
],
doubleQuotedString: [
[/[^"]+/, 'string'],
[/""/, 'string'],
[/"/, { token: 'string', next: '@pop' }]
],
complexIdentifiers: [['`', { token: 'identifier.quote', next: '@backquotedIdentifier' }]],
backquotedIdentifier: [
[/[^`]+/, 'identifier'],
[/``/, 'identifier'],
[/`/, { token: 'identifier.quote', next: '@pop' }]
],
scopes: [
[/(BEGIN|CASE)\b/i, { token: 'keyword.block' }],
[/END\b/i, { token: 'keyword.block' }],
[/WHEN\b/i, { token: 'keyword.choice' }],
[/THEN\b/i, { token: 'keyword.choice' }]
]
}
} | the_stack |
interface Options {
url: string;
body: string;
method: 'GET' | 'POST' | 'DELETE' | 'PUT';
timeout: number;
headers: {
[key: string]: any;
'Content-Type': 'application/json';
'Accept': 'application/json';
'User-Agent': string;
'X-CC-Api-Key': string;
'X-CC-Version': string;
};
}
/**
* Omit a property from the given type.
*/
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
/**
* Node callback
*/
type Callback<T> = (error: any, response: T) => void;
/**
* Pagination callback.
*/
type PaginationCallback<T> = (error: any, response: T[], pagination: Pagination) => void;
/**
* Fiat currency.
*/
type FiatCurrency = 'USD' | 'GBP' | 'EUR' | string;
/**
* Crypto currency.
*/
type CryptoCurrency = 'BTC' | 'ETH' | 'BCH' | 'LTC' | 'USDC';
/**
* Full crypto currency name.
*/
type CryptoName = 'bitcoin' | 'ethereum' | 'bitcoincash' | 'litecoin' | 'usdc';
/**
* Pricing type.
*/
type PricingType = 'no_price' | 'fixed_price';
/**
* Timestamp string.
* ISO 8601
*/
type Timestamp = string;
/**
* Payment status.
*/
type PaymentStatus = 'NEW' | 'PENDING' | 'CONFIRMED' | 'UNRESOLVED' | 'RESOLVED' | 'EXPIRED' | 'CANCELED';
/**
* Crypto pricing object.
*/
type CryptoPricing = {
[key in CryptoName]?: Price<CryptoCurrency>;
};
/**
* Key-value object.
*/
interface KeyVal {
[key: string]: any;
}
/**
* Price object.
*/
interface Price<Currency = CryptoCurrency | FiatCurrency> {
amount: string;
currency: Currency;
}
/**
* Pricing object.
*/
interface Pricing extends CryptoPricing {
local: Price<FiatCurrency>;
}
/**
* Pagination request.
*
* @link https://commerce.coinbase.com/docs/api/#pagination
*/
interface PaginationRequest {
/**
* Order of resources in the response.
*
* default: desc
*/
order?: 'asc' | 'desc';
/**
* Number of results per call.
*
* Accepted values: 0 - 100
* Default: 25
*/
limit?: number;
/**
* A cursor for use in pagination.
* This is a resource ID that defines your place in the list.
*/
starting_after?: string | null;
/**
* A cursor for use in pagination.
* This is a resource ID that defines your place in the list.
*/
ending_before?: string | null;
}
/**
* Pagination response.
*
* @link https://commerce.coinbase.com/docs/api/#pagination
*/
interface Pagination extends Pick<PaginationRequest, 'order' | 'starting_after' | 'ending_before' | 'limit'> {
total: number;
yielded: number;
previous_uri: null | string;
next_uri: null | string;
cursor_range: [string, string];
}
/**
* No price resource.
*/
interface NoPrice {
/**
* Pricing type.
*/
pricing_type: 'no_price';
}
/**
* Fixed price resource.
*/
interface FixedPrice {
/**
* Pricing type
*/
pricing_type: 'fixed_price';
/**
* Local price in fiat currency.
*/
local_price: Price<FiatCurrency>;
}
/**
* Base charge properties.
*/
interface BaseCharge {
/**
* Charge name.
* 100 characters or less.
*/
name: string;
/**
* More detailed description of the charge.
* 200 characters or less.
*/
description: string;
/**
* Charge pricing type.
*/
pricing_type: PricingType;
/**
* Optional key value pairs for your own use.
*/
metadata?: KeyVal;
/**
* Redirect the user to this URL on completion.
*/
redirect_url?: string;
/**
* Redirect the user to this URL on cancel.
*/
cancel_url?: string;
}
/**
* Create a charge.
*
* @link https://commerce.coinbase.com/docs/api/#charge-resource
*/
type CreateCharge = BaseCharge & (FixedPrice | NoPrice);
/**
* Charge creation response.
*
* @link https://commerce.coinbase.com/docs/api/#charge-resource
*/
interface ChargeResource extends BaseCharge {
/**
* Charge UUID
*/
id: string;
/**
* Resource name.
*/
resource: 'charge';
/**
* User fiendly primary key.
*/
code: string;
/**
* Charge image URL.
*/
logo_url?: string;
/**
* Hosted charge URL.
*/
hosted_url: string;
/**
* Charge creation time.
*/
created_at: Timestamp;
/**
* Charge expiration time.
*/
expires_at: Timestamp;
/**
* Charge confirmation time.
*/
confirmed_at?: Timestamp;
/**
* Associated checkout resource.
*/
checkout?: {
id: string;
};
/**
* Array of status update objects.
*/
timeline: Array<{
/**
* Timeline entry timestamp.
*/
time: Timestamp;
/**
* Timeline entry status.
*/
status: PaymentStatus;
/**
* Timeline entry context.
*/
context?: 'UNDERPAID' | 'OVERPAID' | 'DELAYED' | 'MULTIPLE' | 'MANUAL' | 'OTHER';
}>;
/**
* Charge metadata provided by you, the developer.
*/
metadata: KeyVal;
/**
* Charge price information object.
*/
pricing: Pricing;
/**
* Array of charge payment objects.
*/
payments: Array<{
network: CryptoName;
transaction_id: string;
status: PaymentStatus;
value: {
local: Price<FiatCurrency>;
crypto: Price<CryptoCurrency>;
};
block: {
height: number;
hash: string;
confirmations_accumulated: number;
confirmations_required: number;
}
}>;
/**
* Set of addresses associated with the charge.
*/
addresses: Partial<Record<CryptoName, string>>;
}
/**
* Base checkout properties.
*/
interface BaseCheckout {
/**
* Checkout name.
* 100 characters or less.
*/
name: string;
/**
* More detailed description.
* 200 characters or less.
*/
description: string;
/**
* Checkout pricing type.
*/
pricing_type: PricingType;
/**
* Information to collect from the customer.
*/
requested_info?: Array<'email' | 'name'>;
}
/**
* Create a checkout.
*
* @link https://commerce.coinbase.com/docs/api/#create-a-checkout
*/
type CreateCheckout = BaseCheckout & (FixedPrice | NoPrice);
/**
* Update a checkout resource.
*
* @link https://commerce.coinbase.com/docs/api/#update-a-checkout
*/
type UpdateCheckout = Omit<CreateCheckout, 'pricing_type'>;
/**
* Checkout Resource.
*
* @link https://commerce.coinbase.com/docs/api/#checkout-resource
*/
interface CheckoutResource extends BaseCheckout {
/**
* Checkout UUID.
*/
id: string;
/**
* Resource name.
*/
resource: 'checkout';
/**
* Checkout image URL.
*/
logo_url?: string;
/**
* Price in local fiat currency.
*/
local_price?: Price<FiatCurrency>;
}
/**
* Event Resource.
*
* @link
*/
interface EventResource<T = ChargeResource | CheckoutResource> {
/**
* Event UUID.
*/
id: string;
/**
* Resource name.
*/
resource: 'event';
/**
* Event type.
*/
type: 'charge:created' | 'charge:confirmed' | 'charge:failed' | 'charge:delayed' | 'charge:pending' | 'charge:resolved';
/**
* Event creation time.
*/
created_at: Timestamp;
/**
* API version of the `data` payload.
*/
api_version: string;
/**
* Event Payload.
* Resource of the associated object at the time of the event.
*/
data: T;
}
/**
* Coinbase-Commerce-Node entry point.
*
* @link https://github.com/coinbase/coinbase-commerce-node#usage
*/
export namespace Client {
/**
* Setup client.
*/
function init(apiKey: string, baseApiUrl?: string, apiVersion?: string, timeout?: number): Options;
}
export namespace resources {
/**
* Resource object
* All coinbase-commerce-node resources implement the following static methods.
*
* @link https://github.com/coinbase/coinbase-commerce-node#documentation
*/
abstract class Resource<Request> {
/**
* Charge constructor.
*/
constructor(data: Request);
/**
* Save the current resource.
* Creates a new resource if it doesn't already exist in Coinbase Commerce's systems.
*/
save(callback?: Callback<this>): Promise<this>;
/**
* Delete the current resource.
*/
delete(callback?: Callback<this>): Promise<this>;
/**
* Save new resource to Coinbase Commerce.
*/
insert(callback?: Callback<this>): Promise<this>;
/**
* Update the current resource.
*/
update(callback?: Callback<this>): Promise<this>;
}
/**
* Merge CreateACharge with Charge class.
*/
interface Charge extends ChargeResource {}
/**
* Charge Class
*
* @link https://github.com/coinbase/coinbase-commerce-node#charges
*/
class Charge extends Resource<CreateCharge> {
/**
* Create a charge.
*/
static create(chargeData: CreateCharge, callback?: Callback<Charge>): Promise<Charge>;
/**
* List charges.
*/
static list(paginationOptions: PaginationRequest, callback?: PaginationCallback<Charge>): Promise<[Charge[], Pagination]>;
/**
* Fetch all charges.
*/
static all(paginationOptions: PaginationRequest, callback?: Callback<Charge[]>): Promise<Charge[]>;
/**
* Retrieve a charge by ID.
*/
static retrieve(chargeId: ChargeResource['id'], callback?: Callback<Charge>): Promise<Charge>;
}
/**
* Merge CheckoutResource with Checkout class.
*/
interface Checkout extends CheckoutResource {}
/**
* Checkout class.
*
* @link https://github.com/coinbase/coinbase-commerce-node#checkouts
*/
class Checkout extends Resource<CreateCheckout> {
/**
* Create a checkout.
*/
static create(checkoutData: CreateCheckout, callback?: Callback<Checkout>): Promise<Checkout>;
/**
* List checkouts.
*/
static list(paginationOptions: PaginationRequest, callback?: PaginationCallback<Checkout>): Promise<[Checkout[], Pagination]>;
/**
* Fetch all checkouts.
*/
static all(paginationOptions: PaginationRequest, callback?: Callback<Checkout[]>): Promise<Checkout[]>;
/**
* Retrieve a checkout by ID.
*/
static retrieve(checkoutId: CheckoutResource['id'], callback?: Callback<Checkout>): Promise<Checkout>;
/**
* Update a checkout by ID.
*/
static updateById(checkoutId: CheckoutResource['id'], update: UpdateCheckout, callback?: Callback<Checkout>): Promise<Checkout>;
/**
* Delete a checkout by ID.
*/
static deleteById(checkoutId: CheckoutResource['id'], callback?: Callback<Checkout>): Promise<Checkout>;
}
/**
* Merge EventResource with Event class.
*/
interface Event extends EventResource {}
/**
* Event class.
*
* @link https://github.com/coinbase/coinbase-commerce-node#events
*/
class Event extends Resource<EventResource> {
/**
* Retrieve a event by ID.
*/
static retrieve(eventId: EventResource['id'], callback?: Callback<Event>): Promise<Event>;
/**
* List events.
*/
static list(paginationOptions: PaginationRequest, callback?: PaginationCallback<Event>): Promise<[Event[], Pagination]>;
/**
* Fetch all events.
*/
static all(paginationOptions: PaginationRequest, callback?: Callback<Event[]>): Promise<Event[]>;
}
export {
Event,
Charge,
Checkout,
};
}
/**
* Webhook class.
*
* @link https://github.com/coinbase/coinbase-commerce-node#webhooks
*/
declare namespace Webhook {
/**
* Verify a signature header.
*
* @link https://github.com/coinbase/coinbase-commerce-node#verify-signature-header
*/
function verifySigHeader(rawBody: string, signature: string, sharedSecret: string): void;
}
export {
Webhook,
Pagination,
ChargeResource,
CheckoutResource,
CreateCheckout,
EventResource,
CreateCharge,
}; | the_stack |
import { AST } from './core';
import { identifierPattern } from './lexer';
import { assertUnreachable, CompileError, partition } from './util';
export type SimpleASTAlt = { type: 'alt'; exprs: Array<SimpleASTSeq> };
export type SimpleASTSeq = { type: 'seq'; exprs: SimpleASTNode[] };
type SeqFn = (...xs: unknown[]) => unknown;
export type SimpleASTNode =
| { type: 'literal'; value: string }
| { type: 'identifier' }
| { type: 'value' }
| { type: 'nonterminal'; value: symbol }
| { type: 'reduce'; arity: number; fn: SeqFn };
export type SimpleAST = SimpleASTNode | SimpleASTSeq | SimpleASTAlt;
const _2 = (_, x) => x;
const cons = (h, t: unknown[]) => [h, ...t];
const pushNull: SimpleASTSeq = {
type: 'seq',
exprs: [{ type: 'reduce', arity: 0, fn: () => null }],
};
const pushArr: SimpleASTSeq = {
type: 'seq',
exprs: [{ type: 'reduce', arity: 0, fn: () => [] }],
};
/**
* factor out direct left recursion, using the algorithm:
* ```
* A = A "+" B | B
* -->
* A = B A_
* A_ = "+" B A_ | nil
* ```
*/
export function fixLeftRecursion(rules: Map<symbol, SimpleASTAlt>): void {
for (const [ruleName, rule] of rules) {
const [leftRecursiveBranches, safeBranches] = partition(
rule.exprs,
expr => {
const node = expr.exprs[0];
return node && node.type === 'nonterminal' && node.value === ruleName;
}
);
if (leftRecursiveBranches.length > 0) {
const newRule = Symbol();
// make a self-recursive rule here (instead of using * repeater)
// so that you don't have to transform the reduce fns
rules.set(newRule, {
type: 'alt',
exprs: leftRecursiveBranches
.map(
(seq): SimpleASTSeq => ({
type: 'seq',
exprs: seq.exprs
.slice(1)
.concat([{ type: 'nonterminal', value: newRule }]),
})
)
.concat({ type: 'seq', exprs: [] }),
});
rules.set(ruleName, {
type: 'alt',
exprs: safeBranches.map(seq => ({
type: 'seq',
exprs: seq.exprs.concat([{ type: 'nonterminal', value: newRule }]),
})),
});
}
}
}
/**
* factor out shared left prefixes, using the algorithm:
* ```
* A = a X | a Y
* -->
* A = a A_
* A_ = X | Y
* ```
*/
export function factorLeft(rules: Map<symbol, SimpleASTAlt>): void {
// eslint-disable-next-line no-constant-condition
while (true) {
const toRewrite: Array<[
symbol,
Map<SimpleASTNode | null, SimpleASTAlt>
]> = [];
for (const [ruleName, rule] of rules) {
const byPrefix = groupByPrefix(rule);
if (byPrefix) {
toRewrite.push([ruleName, byPrefix]);
}
}
if (toRewrite.length === 0) return;
for (const [ruleName, byPrefix] of toRewrite) {
const updatedRule: SimpleASTAlt = { type: 'alt', exprs: [] };
for (const [prefix, rest] of byPrefix) {
if (
rest.exprs.length > 0 &&
rest.exprs.some(expr => expr.exprs.length > 0)
) {
const key = Symbol();
rules.set(key, rest);
updatedRule.exprs.push({
type: 'seq',
exprs: [prefix, { type: 'nonterminal', value: key }].filter(
Boolean
) as SimpleASTNode[],
});
} else {
updatedRule.exprs.push({
type: 'seq',
exprs: [prefix].filter(Boolean) as SimpleASTNode[],
});
}
}
rules.set(ruleName, updatedRule);
}
}
}
// a X | a Y | b -> { a -> X | Y, b -> nil }
function groupByPrefix(
rule: SimpleASTAlt
): Map<SimpleASTNode | null, SimpleASTAlt> | null {
const map = new Map<SimpleASTNode | null, SimpleASTAlt>();
let needsFactoring = false;
for (const expr of rule.exprs) {
const [prefix, ...rest] = expr.exprs;
let found = false;
for (const [key, alt] of map) {
if (isEqual(prefix, key)) {
alt.exprs.push({ type: 'seq', exprs: rest });
needsFactoring = true;
found = true;
break;
}
}
if (!found) {
map.set(prefix || null, {
type: 'alt',
exprs: [{ type: 'seq', exprs: rest }],
});
}
}
if (needsFactoring) return map;
return null;
}
// TODO: coverage?
// istanbul ignore next
function isEqual(l: SimpleASTNode | null, rIn: SimpleASTNode | null) {
if (l === rIn) return true;
if (!l || !rIn) return false;
if (l.type !== rIn.type) return false;
const r = rIn as any; // :(
switch (l.type) {
case 'identifier':
case 'value':
return true;
case 'literal':
return l.value === r.value;
case 'nonterminal':
return l.value === r.value;
case 'reduce':
return l.arity === r.arity && l.fn === r.fn;
// istanbul ignore next
default:
assertUnreachable(l);
}
}
/**
* Flatten nested grammars into a single grammar, using the rules of lexical scope, and replacing string identifiers with symbols.
*/
class ScopeManager {
private stack: Array<Map<string, symbol>> = [];
public lookup(value: string): symbol {
for (let i = this.stack.length - 1; i >= 0; i--) {
const scope = this.stack[i];
if (scope.has(value)) return scope.get(value)!;
}
throw new CompileError(`unknown identifier ${value}`);
}
public compileRuleset(
rules: Array<{ name: string; expr: AST }>,
addRule: (name: symbol, expr: AST) => void
): SimpleASTNode {
// istanbul ignore next
if (!rules.length) {
throw new CompileError('should be unreachable');
}
// build scope lookup
const nextScope = new Map<string, symbol>();
const mappedRules: Array<{ name: symbol; expr: AST }> = [];
for (const { name, expr } of rules) {
const symName = Symbol(name);
nextScope.set(name, symName);
mappedRules.push({ name: symName, expr });
}
// build rules in scope
this.stack.push(nextScope);
for (const { name, expr } of mappedRules) {
addRule(name, expr);
}
this.stack.pop();
// return first rule as identifier
const firstRuleName = nextScope.get(rules[0].name)!;
return { type: 'nonterminal', value: firstRuleName };
}
}
/**
* Track the literals used in the grammar so they can be correctly tokenized by the lexer, and convert references to the 'keyword' and 'operator' token with rules that match all keywords or operators.
*/
class LiteralManager {
private keywords: Set<string> = new Set();
private operators: Set<string> = new Set();
private keywordRule = Symbol('keyword');
private operatorRule = Symbol('operator');
private usedKeywordRule = false;
private usedOperatorRule = false;
public add(literal: string): SimpleASTNode {
if (literal.match(identifierPattern)) {
this.keywords.add(literal);
} else {
this.operators.add(literal);
}
return { type: 'literal', value: literal };
}
public terminal(node: AST & { type: 'terminal' }): SimpleASTNode {
switch (node.value) {
case 'keyword':
this.usedKeywordRule = true;
return { type: 'nonterminal', value: this.keywordRule };
case 'operator':
this.usedOperatorRule = true;
return { type: 'nonterminal', value: this.operatorRule };
default:
return { type: node.value };
}
}
public compile(map: Map<symbol, SimpleASTAlt>) {
if (this.usedKeywordRule) {
map.set(this.keywordRule, createAlts(this.keywords));
}
if (this.usedOperatorRule) {
map.set(this.operatorRule, createAlts(this.operators));
}
return { keywords: this.keywords, operators: this.operators };
}
}
function createAlts(lits: Set<string>): SimpleASTAlt {
return {
type: 'alt',
exprs: Array.from(lits).map(value => ({
type: 'seq',
exprs: [{ type: 'literal', value }],
})),
};
}
/**
* Transform a Zebu AST into a flat grammar, using only alternation, sequence, and recursion.
*/
export class ASTSimplifier {
rules = new Map<symbol, SimpleASTAlt>();
scope = new ScopeManager();
literals = new LiteralManager();
static simplifyAll(node: AST) {
return new ASTSimplifier().simplifyAll(node);
}
private simplifyAll(node: AST) {
const startRule = Symbol('start');
this.rules.set(startRule, this.simplifyAlt(node));
fixLeftRecursion(this.rules);
factorLeft(this.rules);
const { keywords, operators } = this.literals.compile(this.rules);
return {
startRule,
rules: this.rules,
keywords,
operators,
};
}
private simplifyAlt(node: AST): SimpleASTAlt {
switch (node.type) {
case 'alt':
return {
type: 'alt',
exprs: node.exprs.map(expr => this.simplifySeq(expr)),
};
case 'maybe':
return {
type: 'alt',
exprs: [this.simplifySeq(node.expr), pushNull],
};
case 'sepBy0':
return {
type: 'alt',
exprs: [
{
type: 'seq',
exprs: [
this.simplifyNode({
type: 'sepBy1',
expr: node.expr,
separator: node.separator,
}),
],
},
pushArr,
],
};
default:
return { type: 'alt', exprs: [this.simplifySeq(node)] };
}
}
private simplifySeq(node: AST): SimpleASTSeq {
switch (node.type) {
case 'structure':
return {
type: 'seq',
exprs: [
this.literals.add(node.startToken),
this.simplifyNode(node.expr),
this.literals.add(node.endToken),
{ type: 'reduce', arity: 3, fn: _2 },
],
};
case 'seq':
return {
type: 'seq',
exprs: node.exprs
.map(expr => this.simplifyNode(expr))
.concat([
{ type: 'reduce', arity: node.exprs.length, fn: node.fn },
]),
};
case 'repeat1':
return {
type: 'seq',
exprs: [
this.simplifyNode(node.expr),
this.simplifyNode({ type: 'repeat0', expr: node.expr }),
{ type: 'reduce', arity: 2, fn: cons },
],
};
default:
return { type: 'seq', exprs: [this.simplifyNode(node)] };
}
}
private simplifyNode(node: AST): SimpleASTNode {
switch (node.type) {
case 'error':
throw new CompileError(node.message);
case 'repeat1':
case 'structure':
case 'seq':
case 'alt':
case 'sepBy0':
case 'maybe': {
const ruleName = Symbol();
this.rules.set(ruleName, this.simplifyAlt(node));
return { type: 'nonterminal', value: ruleName };
}
case 'ruleset':
return this.scope.compileRuleset(node.rules, (name, expr) => {
this.rules.set(name, this.simplifyAlt(expr));
});
case 'literal':
return this.literals.add(node.value);
case 'terminal':
return this.literals.terminal(node);
case 'identifier':
return { type: 'nonterminal', value: this.scope.lookup(node.value) };
case 'repeat0': {
// A = Expr* ---> A = Expr A | nil
const recur: SimpleASTNode = {
type: 'nonterminal',
value: Symbol('Repeat'),
};
this.rules.set(recur.value, {
type: 'alt',
exprs: [
{
type: 'seq',
exprs: [
this.simplifyNode(node.expr),
recur,
{ type: 'reduce', arity: 2, fn: cons },
],
},
pushArr,
],
});
return recur;
}
case 'sepBy1': {
// A = Expr (Sep Expr)* Sep?
// --->
// A = Expr B
// B = Sep C | nil
// C = A | nil
const A: SimpleASTNode = { type: 'nonterminal', value: Symbol() };
const B: SimpleASTNode = { type: 'nonterminal', value: Symbol() };
const C: SimpleASTNode = { type: 'nonterminal', value: Symbol() };
const expr = this.simplifyNode(node.expr);
const sep = this.simplifyNode(node.separator);
this.rules.set(A.value, {
type: 'alt',
exprs: [
{
type: 'seq',
exprs: [expr, B, { type: 'reduce', arity: 2, fn: cons }],
},
],
});
this.rules.set(B.value, {
type: 'alt',
exprs: [
{
type: 'seq',
exprs: [sep, C, { type: 'reduce', arity: 2, fn: _2 }],
},
pushArr,
],
});
this.rules.set(C.value, {
type: 'alt',
exprs: [{ type: 'seq', exprs: [A] }, pushArr],
});
return A;
}
// istanbul ignore next
default:
assertUnreachable(node);
}
}
} | the_stack |
import { Component, Input, OnInit, QueryList, ViewChild, ViewChildren, ViewEncapsulation } from '@angular/core';
import { ViewModel } from '../viewmodels.service';
import { DataService, Tactic, Technique, VersionChangelog } from '../data.service';
import { DndDropEvent } from 'ngx-drag-drop';
import { MatExpansionPanel } from '@angular/material/expansion';
import { MatPaginator } from '@angular/material/paginator';
import { MatStepper } from '@angular/material/stepper';
@Component({
selector: 'layer-upgrade',
templateUrl: './layer-upgrade.component.html',
styleUrls: ['./layer-upgrade.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class LayerUpgradeComponent implements OnInit {
@Input() viewModel: ViewModel; // view model of new version
@ViewChildren(MatPaginator) paginators = new QueryList<MatPaginator>();
public paginator_map: Map<string, number> = new Map(); // section name mapped to index of paginator
public filteredIDs: string[] = [];
@ViewChild('stepper') stepper: MatStepper;
public changelog: VersionChangelog;
public compareTo: ViewModel; // view model of old version
public sections: string[] = [
"additions", "changes", "minor_changes",
"revocations", "deprecations", "unchanged"
];
public filter: any = {
"changes": false,
"minor_changes": false,
"revocations": false,
"deprecations": false,
"unchanged": false
}
public loading: boolean = false;
constructor(public dataService: DataService) { }
ngOnInit(): void {
this.changelog = this.viewModel.versionChangelog;
this.compareTo = this.viewModel.compareTo;
// map sections with techniques to paginator index
let i = 0;
for (let s of this.sections) {
if (this.changelog[s].length) this.paginator_map.set(s, i++);
}
this.applyFilters(this.sections[0]);
this.wait();
}
wait(): void {
this.loading = true;
setTimeout(() => this.loading = false, 1000);
}
/**
* Get a readable version for the name of the changelog section
* @param section name of the changelog section
* @returns {string} readable section header text
*/
public getHeader(section: string): string {
return section.split(/[_-]+/).map((s) => s.charAt(0).toUpperCase() + s.substring(1)).join(' ');
}
/**
* Retrieve the URL for a given technique in the previous ATT&CK version
* @param attackID the ATT&CK ID of the technique
* @returns {string} the URL
*/
public getPreservedURL(attackID: string): string {
let url = this.getTechnique(attackID, this.compareTo).url;
let i = url.search('/techniques');
return url.substring(0, i) + '/versions/' + this.compareTo.version + url.substring(i);
}
/**
* Disable the annotated techniques filter?
* @param section the name of the changelog section
* @returns true if there are no annotated techniques in the given section, false otherwise
*/
public disableFilter(section: string): boolean {
return !this.changelog[section].filter(id => this.anyAnnotated(id)).length
}
/**
* Apply filters to the changelog section
* @returns the list of filtered ATT&CK IDs in the changelog section
*/
public applyFilters(section: string): void {
let sectionIDs = this.changelog[section];
if (this.filter[section]) sectionIDs = sectionIDs.filter(id => this.anyAnnotated(id));
let i = this.paginator_map.get(section);
let paginator = this.paginators.toArray()[i];
if (paginator && (paginator.pageIndex * paginator.pageSize > sectionIDs.length)) {
paginator.pageIndex = 0;
}
let start = paginator? paginator.pageIndex * paginator.pageSize : 0;
let end = paginator? start + paginator.pageSize : 10;
this.filteredIDs = sectionIDs.slice(start, end);
}
/**
* Update the list of IDs to render on step change
* @param section the name of the changelog section
* @param offset -1 if moving to the previous step, 1 if moving to the next step
*/
public onStepChange(section: string, offset: number): void {
let i = this.sections.findIndex(s => s === section);
if (i + offset < this.sections.length) {
let nextSection = this.sections[i + offset];
this.applyFilters(nextSection);
if (this.changelog[nextSection].length > 0) this.wait();
}
}
/**
* Get the technique object in the domain of the given view model
* @param attackID the ATT&CK ID of the technique
* @param vm the view model
* @param section name of the changelog section
* @returns {Technique} the technique object
*/
public getTechnique(attackID: string, vm: ViewModel, section?: string): Technique {
let domain = this.dataService.getDomain(vm.domainVersionID);
let all_techniques = domain.techniques.concat(domain.subtechniques);
let technique = all_techniques.find(t => t.attackID == attackID);
if (section == 'revocations' && this.viewModel.version == vm.version) {
// get revoking object
let revokedByID = technique.revoked_by(vm.domainVersionID);
let revokingObject = all_techniques.find(t => t.id == revokedByID);
return revokingObject;
} else return technique;
}
/**
* Get the list of tactic objects the given technique is found under
* @param attackID the ATT&CK ID of the object
* @param vm the view model used to identify the domain
* @param section name of the changelog section
* @returns {Tactic[]} list of tactic objects the object is found under
*/
public getTactics(attackID: string, vm: ViewModel, section?: string): Tactic[] {
if (section == 'additions') vm = this.viewModel;
let technique = this.getTechnique(attackID, vm, section);
let domain = this.dataService.getDomain(vm.domainVersionID);
return technique.tactics.map(shortname => domain.tactics.find(t => t.shortname == shortname));
}
/**
* Determine if the lists of tactics between the technique in the new version and
* old version are the same
* @param attackID the ATT&CK ID of the object
* @param section name of the changelog section
* @returns {boolean} true if the list of tactics are not identical
*/
public tacticsChanged(attackID: string, section: string): boolean {
if (section == 'deprecations' || section == 'additions') return false;
let oldTechnique = this.getTechnique(attackID, this.compareTo);
let newTechnique = this.getTechnique(attackID, this.viewModel, section);
if (!oldTechnique.tactics && !newTechnique.tactics) return false;
if (oldTechnique.tactics.length !== newTechnique.tactics.length) return true;
// order lists and compare
let sortArray = function (a, b) {
if (a < b) return -1;
if (a > b) return 1;
return 0;
};
let oldTactics = oldTechnique.tactics.sort(sortArray);
let newTactics = newTechnique.tactics.sort(sortArray);
if (oldTactics.every((value, i) => value === newTactics[i])) return false;
return true;
}
/**
* Determine if the technique is marked as reviewed
* @param attackID the ATT&CK ID of the technique
* @returns {boolean} true if the technique has been marked as reviewed
*/
public isReviewed(attackID: string): boolean {
return this.changelog.reviewed.has(attackID);
}
/**
* Marks or unmarks a single given technique as reviewed
* @param attackID the ATT&CK ID of the technique
* @param panel the object's expansion panel
*/
public reviewedChanged(attackID: string, panel: MatExpansionPanel): void {
if (this.isReviewed(attackID)) {
this.changelog.reviewed.delete(attackID);
} else {
this.changelog.reviewed.add(attackID);
panel.expanded = false; // close on review
}
}
/**
* Get the number of techniques marked as reviewed in the given section
* @param section the name of the changelog section
* @returns number of reviewed techniques
*/
public countReviewed(section: string): number {
return this.changelog[section].filter(attackID => this.changelog.reviewed.has(attackID)).length;
}
// changelog section descriptions
private descriptions: any = {
"additions": "The following techniques have been added to the dataset since the layer was created. You can review the techniques below to identify which may require annotations. Annotations may be added using the 'technique controls' in the toolbar.",
"changes": "The following techniques have undergone major changes since the layer was created such as changes to scope or technique name. You can view the annotations you had previously added, map them to the current ATT&CK version, and adjust them as needed. You can also review the previous and current technique definitions by clicking the version numbers in each row.",
"minor_changes": "The following techniques have had minor revisions since the layer was created such as typo corrections. The annotations have automatically been copied for these techniques, but you can review them if desired. You can also view the previous and current technique definitions by clicking the version numbers under the technique.",
"revocations": "These are techniques which have been replaced by other techniques since the layer was created. You can view the replacing techniques and transfer annotations from the replaced techniques, adjusting them as nessecary. You can also review the replaced and replacing technique definitions by clicking the version numbers under the technique.",
"deprecations": "These are techniques which have been removed from the dataset. You can view any annotations you had previously added to these techniques.",
"unchanged": "These are techniques which have not changed since the uploaded layer's ATT&CK version. The annotations have automatically been copied for these techniques, but you can review them if desired.",
"finish": "The overview below indicates either the number of techniques you have reviewed in a section, if you have skipped a section, or if there are no techniques to review in that section. Annotations mapped to the current version have been saved to the new layer.\n\nVerify your changes and click 'Done' to complete the layer upgrade workflow. Once completed you cannot return to this workflow."
}
/**
* Get the changelog section description
* @param section the name of the changelog section
* @returns the section description
*/
public getDescription(section: string): string {
return this.descriptions[section];
}
/**
* Determine if any techniqueVM in the old version with the given
* ATT&CK ID has annotations
* @param attackID the ATT&CK ID of the technique
* @returns {boolean} true if any TechniqueVM for this technique is annotated
*/
public anyAnnotated(attackID: string): boolean {
let oldTechnique = this.getTechnique(attackID, this.compareTo);
if (oldTechnique) {
let technique_tactic_ids = oldTechnique.get_all_technique_tactic_ids();
for (let id of technique_tactic_ids) {
if (this.compareTo.getTechniqueVM_id(id).annotated()) return true;
}
}
return false;
}
/**
* Is the TechniqueVM for this technique-tactic annotated?
* @param technique the technique in the old version
* @param tactic the tactic the technique is found under
* @param vm the view model
* @returns {boolean} true if the TechniqueVM is annotated, false otherwise
*/
public isAnnotated(technique: Technique, tactic: Tactic, vm: ViewModel): boolean {
return vm.getTechniqueVM(technique, tactic).annotated();
}
/**
* Get the total number of techniques currently displayed in a given section
* @param section the name of the changelog section
* @returns the total number of annotated techniques in the section if the filter is enabled,
* otherwise the total number of techniques in the seciton
*/
public sectionLength(section: string): number {
if (this.filter[section]) return this.changelog[section].filter(attackID => this.anyAnnotated(attackID)).length;
else return this.changelog[section].length;
}
/**
* Determine if the annotations of the technique under the given tactic
* in the old version have been copied to the new version
* @param technique the technique in the old version
* @param tactic the tactic the technique is found under
* @returns {boolean} true if the annotations have been copied to the
* object in the new version
*/
public isCopied(technique: Technique, tactic: Tactic): boolean {
if (this.changelog.copied.has(technique.get_technique_tactic_id(tactic))) return true;
return false;
}
/**
* Copy the annotations from the technique in the old version
* to the technique in the new version
* @param attackID the ATT&CK ID of the technique
* @param tactic the tactic the technique is found under
*/
public copyAnnotations(attackID: string, tactic: Tactic, section: string): void {
let fromTechnique = this.getTechnique(attackID, this.compareTo);
let toTechnique = this.getTechnique(attackID, this.viewModel, section);
this.viewModel.copyAnnotations(fromTechnique, toTechnique, tactic);
}
/**
* Re-enable the annotations on the technique in the old version and
* reset the annotations on the technique in the new version
* @param attackID the ATT&CK ID of the technique
* @param tactic the tactic the technique is found under
*/
public revertCopy(attackID: string, tactic: Tactic, section: string): void {
let fromTechnique = this.getTechnique(attackID, this.compareTo);
let toTechnique = this.getTechnique(attackID, this.viewModel, section);
this.viewModel.revertCopy(fromTechnique, toTechnique, tactic);
}
/**
* Copy the annotations from the TechniqueVM in the old version
* to the TechniqueVM that the element was dropped over
* @param event the ngx drop event
* @param toTechnique the technique object to copy annotations to
* @param toTactic the tactic object to copy annotations to
* @param section the name of the changelog section
*/
public onDrop(event: DndDropEvent, toTechnique: Technique, toTactic: Tactic, section: string): void {
let attackID = event.data.split("^")[0];
let validTechnique = this.getTechnique(attackID, this.viewModel, section);
if (validTechnique.id === toTechnique.id) { // copying annotations to a valid target?
// retrieve relevant technique VMs
let fromTvm = this.compareTo.getTechniqueVM_id(event.data);
let toTvm = this.viewModel.getTechniqueVM(toTechnique, toTactic);
// copy annotations
let rep = fromTvm.serialize();
toTvm.resetAnnotations();
toTvm.deSerialize(rep, toTechnique.attackID, toTactic.shortname);
this.viewModel.updateScoreColor(toTvm);
} else {} // invalid target
}
/**
* Remove all annotations from the VM
* @param technique the technique object to remove annotations from
* @param tactic the tactic the technique is found under
*/
public clearAnnotations(technique: Technique, tactic: Tactic): void {
this.viewModel.getTechniqueVM(technique, tactic).resetAnnotations();
}
/**
* Close the layer upgrade sidebar
*/
public closeSidebar(): void {
this.viewModel.sidebarOpened = !this.viewModel.sidebarOpened;
this.viewModel.sidebarContentType = '';
}
} | the_stack |
import { Observable } from 'graphql-typed-client'
/** query root */
export interface query_root {
hello: String | null
/** fetch data from the table: "todos" */
todos: todos[]
/** fetch aggregated fields from the table: "todos" */
todos_aggregate: todos_aggregate
/** fetch data from the table: "todos" using primary key columns */
todos_by_pk: todos | null
/** fetch data from the table: "users" */
users: users[]
/** fetch aggregated fields from the table: "users" */
users_aggregate: users_aggregate
/** fetch data from the table: "users" using primary key columns */
users_by_pk: users | null
__typename: 'query_root'
}
/** The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text. */
export type String = string
/** select columns of table "todos" */
export enum todos_select_column {
/** column name */
id = 'id',
/** column name */
is_completed = 'is_completed',
/** column name */
text = 'text',
/** column name */
user_authID = 'user_authID',
}
/** The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1. */
export type Int = number
/** column ordering options */
export enum order_by {
/** in the ascending order, nulls last */
asc = 'asc',
/** in the ascending order, nulls first */
asc_nulls_first = 'asc_nulls_first',
/** in the ascending order, nulls last */
asc_nulls_last = 'asc_nulls_last',
/** in the descending order, nulls first */
desc = 'desc',
/** in the descending order, nulls first */
desc_nulls_first = 'desc_nulls_first',
/** in the descending order, nulls last */
desc_nulls_last = 'desc_nulls_last',
}
/** The `Boolean` scalar type represents `true` or `false`. */
export type Boolean = boolean
/** columns and relationships of "todos" */
export interface todos {
id: Int
is_completed: Boolean
text: String
/** An object relationship */
user: users
user_authID: String
__typename: 'todos'
}
/** columns and relationships of "users" */
export interface users {
authID: String
id: Int
name: String
/** An array relationship */
todos: todos[]
/** An aggregated array relationship */
todos_aggregate: todos_aggregate
__typename: 'users'
}
/** aggregated selection of "todos" */
export interface todos_aggregate {
aggregate: todos_aggregate_fields | null
nodes: todos[]
__typename: 'todos_aggregate'
}
/** aggregate fields of "todos" */
export interface todos_aggregate_fields {
avg: todos_avg_fields | null
count: Int | null
max: todos_max_fields | null
min: todos_min_fields | null
stddev: todos_stddev_fields | null
stddev_pop: todos_stddev_pop_fields | null
stddev_samp: todos_stddev_samp_fields | null
sum: todos_sum_fields | null
var_pop: todos_var_pop_fields | null
var_samp: todos_var_samp_fields | null
variance: todos_variance_fields | null
__typename: 'todos_aggregate_fields'
}
/** aggregate avg on columns */
export interface todos_avg_fields {
id: Float | null
__typename: 'todos_avg_fields'
}
/** The `Float` scalar type represents signed double-precision fractional values as specified by [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point). */
export type Float = number
/** aggregate max on columns */
export interface todos_max_fields {
id: Int | null
text: String | null
user_authID: String | null
__typename: 'todos_max_fields'
}
/** aggregate min on columns */
export interface todos_min_fields {
id: Int | null
text: String | null
user_authID: String | null
__typename: 'todos_min_fields'
}
/** aggregate stddev on columns */
export interface todos_stddev_fields {
id: Float | null
__typename: 'todos_stddev_fields'
}
/** aggregate stddev_pop on columns */
export interface todos_stddev_pop_fields {
id: Float | null
__typename: 'todos_stddev_pop_fields'
}
/** aggregate stddev_samp on columns */
export interface todos_stddev_samp_fields {
id: Float | null
__typename: 'todos_stddev_samp_fields'
}
/** aggregate sum on columns */
export interface todos_sum_fields {
id: Int | null
__typename: 'todos_sum_fields'
}
/** aggregate var_pop on columns */
export interface todos_var_pop_fields {
id: Float | null
__typename: 'todos_var_pop_fields'
}
/** aggregate var_samp on columns */
export interface todos_var_samp_fields {
id: Float | null
__typename: 'todos_var_samp_fields'
}
/** aggregate variance on columns */
export interface todos_variance_fields {
id: Float | null
__typename: 'todos_variance_fields'
}
/** select columns of table "users" */
export enum users_select_column {
/** column name */
authID = 'authID',
/** column name */
id = 'id',
/** column name */
name = 'name',
}
/** aggregated selection of "users" */
export interface users_aggregate {
aggregate: users_aggregate_fields | null
nodes: users[]
__typename: 'users_aggregate'
}
/** aggregate fields of "users" */
export interface users_aggregate_fields {
avg: users_avg_fields | null
count: Int | null
max: users_max_fields | null
min: users_min_fields | null
stddev: users_stddev_fields | null
stddev_pop: users_stddev_pop_fields | null
stddev_samp: users_stddev_samp_fields | null
sum: users_sum_fields | null
var_pop: users_var_pop_fields | null
var_samp: users_var_samp_fields | null
variance: users_variance_fields | null
__typename: 'users_aggregate_fields'
}
/** aggregate avg on columns */
export interface users_avg_fields {
id: Float | null
__typename: 'users_avg_fields'
}
/** aggregate max on columns */
export interface users_max_fields {
authID: String | null
id: Int | null
name: String | null
__typename: 'users_max_fields'
}
/** aggregate min on columns */
export interface users_min_fields {
authID: String | null
id: Int | null
name: String | null
__typename: 'users_min_fields'
}
/** aggregate stddev on columns */
export interface users_stddev_fields {
id: Float | null
__typename: 'users_stddev_fields'
}
/** aggregate stddev_pop on columns */
export interface users_stddev_pop_fields {
id: Float | null
__typename: 'users_stddev_pop_fields'
}
/** aggregate stddev_samp on columns */
export interface users_stddev_samp_fields {
id: Float | null
__typename: 'users_stddev_samp_fields'
}
/** aggregate sum on columns */
export interface users_sum_fields {
id: Int | null
__typename: 'users_sum_fields'
}
/** aggregate var_pop on columns */
export interface users_var_pop_fields {
id: Float | null
__typename: 'users_var_pop_fields'
}
/** aggregate var_samp on columns */
export interface users_var_samp_fields {
id: Float | null
__typename: 'users_var_samp_fields'
}
/** aggregate variance on columns */
export interface users_variance_fields {
id: Float | null
__typename: 'users_variance_fields'
}
/** mutation root */
export interface mutation_root {
/** delete data from the table: "todos" */
delete_todos: todos_mutation_response | null
/** delete data from the table: "users" */
delete_users: users_mutation_response | null
/** insert data into the table: "todos" */
insert_todos: todos_mutation_response | null
/** insert data into the table: "users" */
insert_users: users_mutation_response | null
/** update data of the table: "todos" */
update_todos: todos_mutation_response | null
/** update data of the table: "users" */
update_users: users_mutation_response | null
__typename: 'mutation_root'
}
/** response of any mutation on the table "todos" */
export interface todos_mutation_response {
/** number of affected rows by the mutation */
affected_rows: Int
/** data of the affected rows by the mutation */
returning: todos[]
__typename: 'todos_mutation_response'
}
/** response of any mutation on the table "users" */
export interface users_mutation_response {
/** number of affected rows by the mutation */
affected_rows: Int
/** data of the affected rows by the mutation */
returning: users[]
__typename: 'users_mutation_response'
}
/** unique or primary key constraints on table "todos" */
export enum todos_constraint {
/** unique or primary key constraint */
todos_pkey = 'todos_pkey',
}
/** update columns of table "todos" */
export enum todos_update_column {
/** column name */
id = 'id',
/** column name */
is_completed = 'is_completed',
/** column name */
text = 'text',
/** column name */
user_authID = 'user_authID',
}
/** unique or primary key constraints on table "users" */
export enum users_constraint {
/** unique or primary key constraint */
users_authID_key = 'users_authID_key',
/** unique or primary key constraint */
users_pkey = 'users_pkey',
}
/** update columns of table "users" */
export enum users_update_column {
/** column name */
authID = 'authID',
/** column name */
id = 'id',
/** column name */
name = 'name',
}
/** subscription root */
export interface subscription_root {
/** fetch data from the table: "todos" */
todos: todos[]
/** fetch aggregated fields from the table: "todos" */
todos_aggregate: todos_aggregate
/** fetch data from the table: "todos" using primary key columns */
todos_by_pk: todos | null
/** fetch data from the table: "users" */
users: users[]
/** fetch aggregated fields from the table: "users" */
users_aggregate: users_aggregate
/** fetch data from the table: "users" using primary key columns */
users_by_pk: users | null
__typename: 'subscription_root'
}
export enum CacheControlScope {
PRIVATE = 'PRIVATE',
PUBLIC = 'PUBLIC',
}
/** The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `"4"`) or integer (such as `4`) input value will be accepted as an ID. */
export type ID = string
export interface Query {
hello: String | null
__typename: 'Query'
}
/** The `Upload` scalar type represents a file upload. */
export type Upload = any
/** conflict action */
export enum conflict_action {
/** ignore the insert on this row */
ignore = 'ignore',
/** update the row with the given values */
update = 'update',
}
/** query root */
export interface query_rootRequest {
hello?: boolean | number
/** fetch data from the table: "todos" */
todos?:
| [
{
/** distinct select on columns */
distinct_on?: todos_select_column[] | null
/** limit the nuber of rows returned */
limit?: Int | null
/** skip the first n rows. Use only with order_by */
offset?: Int | null
/** sort the rows by one or more columns */
order_by?: todos_order_by[] | null
/** filter the rows returned */
where?: todos_bool_exp | null
},
todosRequest,
]
| todosRequest
/** fetch aggregated fields from the table: "todos" */
todos_aggregate?:
| [
{
/** distinct select on columns */
distinct_on?: todos_select_column[] | null
/** limit the nuber of rows returned */
limit?: Int | null
/** skip the first n rows. Use only with order_by */
offset?: Int | null
/** sort the rows by one or more columns */
order_by?: todos_order_by[] | null
/** filter the rows returned */
where?: todos_bool_exp | null
},
todos_aggregateRequest,
]
| todos_aggregateRequest
/** fetch data from the table: "todos" using primary key columns */
todos_by_pk?: [{ id: Int }, todosRequest]
/** fetch data from the table: "users" */
users?:
| [
{
/** distinct select on columns */
distinct_on?: users_select_column[] | null
/** limit the nuber of rows returned */
limit?: Int | null
/** skip the first n rows. Use only with order_by */
offset?: Int | null
/** sort the rows by one or more columns */
order_by?: users_order_by[] | null
/** filter the rows returned */
where?: users_bool_exp | null
},
usersRequest,
]
| usersRequest
/** fetch aggregated fields from the table: "users" */
users_aggregate?:
| [
{
/** distinct select on columns */
distinct_on?: users_select_column[] | null
/** limit the nuber of rows returned */
limit?: Int | null
/** skip the first n rows. Use only with order_by */
offset?: Int | null
/** sort the rows by one or more columns */
order_by?: users_order_by[] | null
/** filter the rows returned */
where?: users_bool_exp | null
},
users_aggregateRequest,
]
| users_aggregateRequest
/** fetch data from the table: "users" using primary key columns */
users_by_pk?: [{ id: Int }, usersRequest]
__typename?: boolean | number
__scalar?: boolean | number
}
/** ordering options when selecting data from "todos" */
export interface todos_order_by {
id?: order_by | null
is_completed?: order_by | null
text?: order_by | null
user?: users_order_by | null
user_authID?: order_by | null
}
/** ordering options when selecting data from "users" */
export interface users_order_by {
authID?: order_by | null
id?: order_by | null
name?: order_by | null
todos_aggregate?: todos_aggregate_order_by | null
}
/** order by aggregate values of table "todos" */
export interface todos_aggregate_order_by {
avg?: todos_avg_order_by | null
count?: order_by | null
max?: todos_max_order_by | null
min?: todos_min_order_by | null
stddev?: todos_stddev_order_by | null
stddev_pop?: todos_stddev_pop_order_by | null
stddev_samp?: todos_stddev_samp_order_by | null
sum?: todos_sum_order_by | null
var_pop?: todos_var_pop_order_by | null
var_samp?: todos_var_samp_order_by | null
variance?: todos_variance_order_by | null
}
/** order by avg() on columns of table "todos" */
export interface todos_avg_order_by {
id?: order_by | null
}
/** order by max() on columns of table "todos" */
export interface todos_max_order_by {
id?: order_by | null
text?: order_by | null
user_authID?: order_by | null
}
/** order by min() on columns of table "todos" */
export interface todos_min_order_by {
id?: order_by | null
text?: order_by | null
user_authID?: order_by | null
}
/** order by stddev() on columns of table "todos" */
export interface todos_stddev_order_by {
id?: order_by | null
}
/** order by stddev_pop() on columns of table "todos" */
export interface todos_stddev_pop_order_by {
id?: order_by | null
}
/** order by stddev_samp() on columns of table "todos" */
export interface todos_stddev_samp_order_by {
id?: order_by | null
}
/** order by sum() on columns of table "todos" */
export interface todos_sum_order_by {
id?: order_by | null
}
/** order by var_pop() on columns of table "todos" */
export interface todos_var_pop_order_by {
id?: order_by | null
}
/** order by var_samp() on columns of table "todos" */
export interface todos_var_samp_order_by {
id?: order_by | null
}
/** order by variance() on columns of table "todos" */
export interface todos_variance_order_by {
id?: order_by | null
}
/** Boolean expression to filter rows from the table "todos". All fields are combined with a logical 'AND'. */
export interface todos_bool_exp {
_and?: (todos_bool_exp | null)[] | null
_not?: todos_bool_exp | null
_or?: (todos_bool_exp | null)[] | null
id?: Int_comparison_exp | null
is_completed?: Boolean_comparison_exp | null
text?: String_comparison_exp | null
user?: users_bool_exp | null
user_authID?: String_comparison_exp | null
}
/** expression to compare columns of type Int. All fields are combined with logical 'AND'. */
export interface Int_comparison_exp {
_eq?: Int | null
_gt?: Int | null
_gte?: Int | null
_in?: Int[] | null
_is_null?: Boolean | null
_lt?: Int | null
_lte?: Int | null
_neq?: Int | null
_nin?: Int[] | null
}
/** expression to compare columns of type Boolean. All fields are combined with logical 'AND'. */
export interface Boolean_comparison_exp {
_eq?: Boolean | null
_gt?: Boolean | null
_gte?: Boolean | null
_in?: Boolean[] | null
_is_null?: Boolean | null
_lt?: Boolean | null
_lte?: Boolean | null
_neq?: Boolean | null
_nin?: Boolean[] | null
}
/** expression to compare columns of type String. All fields are combined with logical 'AND'. */
export interface String_comparison_exp {
_eq?: String | null
_gt?: String | null
_gte?: String | null
_ilike?: String | null
_in?: String[] | null
_is_null?: Boolean | null
_like?: String | null
_lt?: String | null
_lte?: String | null
_neq?: String | null
_nilike?: String | null
_nin?: String[] | null
_nlike?: String | null
_nsimilar?: String | null
_similar?: String | null
}
/** Boolean expression to filter rows from the table "users". All fields are combined with a logical 'AND'. */
export interface users_bool_exp {
_and?: (users_bool_exp | null)[] | null
_not?: users_bool_exp | null
_or?: (users_bool_exp | null)[] | null
authID?: String_comparison_exp | null
id?: Int_comparison_exp | null
name?: String_comparison_exp | null
todos?: todos_bool_exp | null
}
/** columns and relationships of "todos" */
export interface todosRequest {
id?: boolean | number
is_completed?: boolean | number
text?: boolean | number
/** An object relationship */
user?: usersRequest
user_authID?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** columns and relationships of "users" */
export interface usersRequest {
authID?: boolean | number
id?: boolean | number
name?: boolean | number
/** An array relationship */
todos?:
| [
{
/** distinct select on columns */
distinct_on?: todos_select_column[] | null
/** limit the nuber of rows returned */
limit?: Int | null
/** skip the first n rows. Use only with order_by */
offset?: Int | null
/** sort the rows by one or more columns */
order_by?: todos_order_by[] | null
/** filter the rows returned */
where?: todos_bool_exp | null
},
todosRequest,
]
| todosRequest
/** An aggregated array relationship */
todos_aggregate?:
| [
{
/** distinct select on columns */
distinct_on?: todos_select_column[] | null
/** limit the nuber of rows returned */
limit?: Int | null
/** skip the first n rows. Use only with order_by */
offset?: Int | null
/** sort the rows by one or more columns */
order_by?: todos_order_by[] | null
/** filter the rows returned */
where?: todos_bool_exp | null
},
todos_aggregateRequest,
]
| todos_aggregateRequest
__typename?: boolean | number
__scalar?: boolean | number
}
/** aggregated selection of "todos" */
export interface todos_aggregateRequest {
aggregate?: todos_aggregate_fieldsRequest
nodes?: todosRequest
__typename?: boolean | number
__scalar?: boolean | number
}
/** aggregate fields of "todos" */
export interface todos_aggregate_fieldsRequest {
avg?: todos_avg_fieldsRequest
count?: [{ columns?: todos_select_column[] | null; distinct?: Boolean | null }] | boolean | number
max?: todos_max_fieldsRequest
min?: todos_min_fieldsRequest
stddev?: todos_stddev_fieldsRequest
stddev_pop?: todos_stddev_pop_fieldsRequest
stddev_samp?: todos_stddev_samp_fieldsRequest
sum?: todos_sum_fieldsRequest
var_pop?: todos_var_pop_fieldsRequest
var_samp?: todos_var_samp_fieldsRequest
variance?: todos_variance_fieldsRequest
__typename?: boolean | number
__scalar?: boolean | number
}
/** aggregate avg on columns */
export interface todos_avg_fieldsRequest {
id?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** aggregate max on columns */
export interface todos_max_fieldsRequest {
id?: boolean | number
text?: boolean | number
user_authID?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** aggregate min on columns */
export interface todos_min_fieldsRequest {
id?: boolean | number
text?: boolean | number
user_authID?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** aggregate stddev on columns */
export interface todos_stddev_fieldsRequest {
id?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** aggregate stddev_pop on columns */
export interface todos_stddev_pop_fieldsRequest {
id?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** aggregate stddev_samp on columns */
export interface todos_stddev_samp_fieldsRequest {
id?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** aggregate sum on columns */
export interface todos_sum_fieldsRequest {
id?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** aggregate var_pop on columns */
export interface todos_var_pop_fieldsRequest {
id?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** aggregate var_samp on columns */
export interface todos_var_samp_fieldsRequest {
id?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** aggregate variance on columns */
export interface todos_variance_fieldsRequest {
id?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** aggregated selection of "users" */
export interface users_aggregateRequest {
aggregate?: users_aggregate_fieldsRequest
nodes?: usersRequest
__typename?: boolean | number
__scalar?: boolean | number
}
/** aggregate fields of "users" */
export interface users_aggregate_fieldsRequest {
avg?: users_avg_fieldsRequest
count?: [{ columns?: users_select_column[] | null; distinct?: Boolean | null }] | boolean | number
max?: users_max_fieldsRequest
min?: users_min_fieldsRequest
stddev?: users_stddev_fieldsRequest
stddev_pop?: users_stddev_pop_fieldsRequest
stddev_samp?: users_stddev_samp_fieldsRequest
sum?: users_sum_fieldsRequest
var_pop?: users_var_pop_fieldsRequest
var_samp?: users_var_samp_fieldsRequest
variance?: users_variance_fieldsRequest
__typename?: boolean | number
__scalar?: boolean | number
}
/** aggregate avg on columns */
export interface users_avg_fieldsRequest {
id?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** aggregate max on columns */
export interface users_max_fieldsRequest {
authID?: boolean | number
id?: boolean | number
name?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** aggregate min on columns */
export interface users_min_fieldsRequest {
authID?: boolean | number
id?: boolean | number
name?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** aggregate stddev on columns */
export interface users_stddev_fieldsRequest {
id?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** aggregate stddev_pop on columns */
export interface users_stddev_pop_fieldsRequest {
id?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** aggregate stddev_samp on columns */
export interface users_stddev_samp_fieldsRequest {
id?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** aggregate sum on columns */
export interface users_sum_fieldsRequest {
id?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** aggregate var_pop on columns */
export interface users_var_pop_fieldsRequest {
id?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** aggregate var_samp on columns */
export interface users_var_samp_fieldsRequest {
id?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** aggregate variance on columns */
export interface users_variance_fieldsRequest {
id?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** mutation root */
export interface mutation_rootRequest {
/** delete data from the table: "todos" */
delete_todos?: [
{
/** filter the rows which have to be deleted */
where: todos_bool_exp
},
todos_mutation_responseRequest,
]
/** delete data from the table: "users" */
delete_users?: [
{
/** filter the rows which have to be deleted */
where: users_bool_exp
},
users_mutation_responseRequest,
]
/** insert data into the table: "todos" */
insert_todos?: [
{
/** the rows to be inserted */
objects: todos_insert_input[]
/** on conflict condition */
on_conflict?: todos_on_conflict | null
},
todos_mutation_responseRequest,
]
/** insert data into the table: "users" */
insert_users?: [
{
/** the rows to be inserted */
objects: users_insert_input[]
/** on conflict condition */
on_conflict?: users_on_conflict | null
},
users_mutation_responseRequest,
]
/** update data of the table: "todos" */
update_todos?: [
{
/** increments the integer columns with given value of the filtered values */
_inc?: todos_inc_input | null
/** sets the columns of the filtered rows to the given values */
_set?: todos_set_input | null
/** filter the rows which have to be updated */
where: todos_bool_exp
},
todos_mutation_responseRequest,
]
/** update data of the table: "users" */
update_users?: [
{
/** increments the integer columns with given value of the filtered values */
_inc?: users_inc_input | null
/** sets the columns of the filtered rows to the given values */
_set?: users_set_input | null
/** filter the rows which have to be updated */
where: users_bool_exp
},
users_mutation_responseRequest,
]
__typename?: boolean | number
__scalar?: boolean | number
}
/** response of any mutation on the table "todos" */
export interface todos_mutation_responseRequest {
/** number of affected rows by the mutation */
affected_rows?: boolean | number
/** data of the affected rows by the mutation */
returning?: todosRequest
__typename?: boolean | number
__scalar?: boolean | number
}
/** response of any mutation on the table "users" */
export interface users_mutation_responseRequest {
/** number of affected rows by the mutation */
affected_rows?: boolean | number
/** data of the affected rows by the mutation */
returning?: usersRequest
__typename?: boolean | number
__scalar?: boolean | number
}
/** input type for inserting data into table "todos" */
export interface todos_insert_input {
id?: Int | null
is_completed?: Boolean | null
text?: String | null
user?: users_obj_rel_insert_input | null
user_authID?: String | null
}
/** input type for inserting object relation for remote table "users" */
export interface users_obj_rel_insert_input {
data: users_insert_input
on_conflict?: users_on_conflict | null
}
/** input type for inserting data into table "users" */
export interface users_insert_input {
authID?: String | null
id?: Int | null
name?: String | null
todos?: todos_arr_rel_insert_input | null
}
/** input type for inserting array relation for remote table "todos" */
export interface todos_arr_rel_insert_input {
data: todos_insert_input[]
on_conflict?: todos_on_conflict | null
}
/** on conflict condition type for table "todos" */
export interface todos_on_conflict {
constraint: todos_constraint
update_columns: todos_update_column[]
}
/** on conflict condition type for table "users" */
export interface users_on_conflict {
constraint: users_constraint
update_columns: users_update_column[]
}
/** input type for incrementing integer columne in table "todos" */
export interface todos_inc_input {
id?: Int | null
}
/** input type for updating data in table "todos" */
export interface todos_set_input {
id?: Int | null
is_completed?: Boolean | null
text?: String | null
user_authID?: String | null
}
/** input type for incrementing integer columne in table "users" */
export interface users_inc_input {
id?: Int | null
}
/** input type for updating data in table "users" */
export interface users_set_input {
authID?: String | null
id?: Int | null
name?: String | null
}
/** subscription root */
export interface subscription_rootRequest {
/** fetch data from the table: "todos" */
todos?:
| [
{
/** distinct select on columns */
distinct_on?: todos_select_column[] | null
/** limit the nuber of rows returned */
limit?: Int | null
/** skip the first n rows. Use only with order_by */
offset?: Int | null
/** sort the rows by one or more columns */
order_by?: todos_order_by[] | null
/** filter the rows returned */
where?: todos_bool_exp | null
},
todosRequest,
]
| todosRequest
/** fetch aggregated fields from the table: "todos" */
todos_aggregate?:
| [
{
/** distinct select on columns */
distinct_on?: todos_select_column[] | null
/** limit the nuber of rows returned */
limit?: Int | null
/** skip the first n rows. Use only with order_by */
offset?: Int | null
/** sort the rows by one or more columns */
order_by?: todos_order_by[] | null
/** filter the rows returned */
where?: todos_bool_exp | null
},
todos_aggregateRequest,
]
| todos_aggregateRequest
/** fetch data from the table: "todos" using primary key columns */
todos_by_pk?: [{ id: Int }, todosRequest]
/** fetch data from the table: "users" */
users?:
| [
{
/** distinct select on columns */
distinct_on?: users_select_column[] | null
/** limit the nuber of rows returned */
limit?: Int | null
/** skip the first n rows. Use only with order_by */
offset?: Int | null
/** sort the rows by one or more columns */
order_by?: users_order_by[] | null
/** filter the rows returned */
where?: users_bool_exp | null
},
usersRequest,
]
| usersRequest
/** fetch aggregated fields from the table: "users" */
users_aggregate?:
| [
{
/** distinct select on columns */
distinct_on?: users_select_column[] | null
/** limit the nuber of rows returned */
limit?: Int | null
/** skip the first n rows. Use only with order_by */
offset?: Int | null
/** sort the rows by one or more columns */
order_by?: users_order_by[] | null
/** filter the rows returned */
where?: users_bool_exp | null
},
users_aggregateRequest,
]
| users_aggregateRequest
/** fetch data from the table: "users" using primary key columns */
users_by_pk?: [{ id: Int }, usersRequest]
__typename?: boolean | number
__scalar?: boolean | number
}
export interface QueryRequest {
hello?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
/** input type for inserting object relation for remote table "todos" */
export interface todos_obj_rel_insert_input {
data: todos_insert_input
on_conflict?: todos_on_conflict | null
}
/** order by aggregate values of table "users" */
export interface users_aggregate_order_by {
avg?: users_avg_order_by | null
count?: order_by | null
max?: users_max_order_by | null
min?: users_min_order_by | null
stddev?: users_stddev_order_by | null
stddev_pop?: users_stddev_pop_order_by | null
stddev_samp?: users_stddev_samp_order_by | null
sum?: users_sum_order_by | null
var_pop?: users_var_pop_order_by | null
var_samp?: users_var_samp_order_by | null
variance?: users_variance_order_by | null
}
/** order by avg() on columns of table "users" */
export interface users_avg_order_by {
id?: order_by | null
}
/** order by max() on columns of table "users" */
export interface users_max_order_by {
authID?: order_by | null
id?: order_by | null
name?: order_by | null
}
/** order by min() on columns of table "users" */
export interface users_min_order_by {
authID?: order_by | null
id?: order_by | null
name?: order_by | null
}
/** order by stddev() on columns of table "users" */
export interface users_stddev_order_by {
id?: order_by | null
}
/** order by stddev_pop() on columns of table "users" */
export interface users_stddev_pop_order_by {
id?: order_by | null
}
/** order by stddev_samp() on columns of table "users" */
export interface users_stddev_samp_order_by {
id?: order_by | null
}
/** order by sum() on columns of table "users" */
export interface users_sum_order_by {
id?: order_by | null
}
/** order by var_pop() on columns of table "users" */
export interface users_var_pop_order_by {
id?: order_by | null
}
/** order by var_samp() on columns of table "users" */
export interface users_var_samp_order_by {
id?: order_by | null
}
/** order by variance() on columns of table "users" */
export interface users_variance_order_by {
id?: order_by | null
}
/** input type for inserting array relation for remote table "users" */
export interface users_arr_rel_insert_input {
data: users_insert_input[]
on_conflict?: users_on_conflict | null
}
const query_root_possibleTypes = ['query_root']
export const isquery_root = (obj: { __typename: String }): obj is query_root => {
if (!obj.__typename) throw new Error('__typename is missing')
return query_root_possibleTypes.includes(obj.__typename)
}
const todos_possibleTypes = ['todos']
export const istodos = (obj: { __typename: String }): obj is todos => {
if (!obj.__typename) throw new Error('__typename is missing')
return todos_possibleTypes.includes(obj.__typename)
}
const users_possibleTypes = ['users']
export const isusers = (obj: { __typename: String }): obj is users => {
if (!obj.__typename) throw new Error('__typename is missing')
return users_possibleTypes.includes(obj.__typename)
}
const todos_aggregate_possibleTypes = ['todos_aggregate']
export const istodos_aggregate = (obj: { __typename: String }): obj is todos_aggregate => {
if (!obj.__typename) throw new Error('__typename is missing')
return todos_aggregate_possibleTypes.includes(obj.__typename)
}
const todos_aggregate_fields_possibleTypes = ['todos_aggregate_fields']
export const istodos_aggregate_fields = (obj: { __typename: String }): obj is todos_aggregate_fields => {
if (!obj.__typename) throw new Error('__typename is missing')
return todos_aggregate_fields_possibleTypes.includes(obj.__typename)
}
const todos_avg_fields_possibleTypes = ['todos_avg_fields']
export const istodos_avg_fields = (obj: { __typename: String }): obj is todos_avg_fields => {
if (!obj.__typename) throw new Error('__typename is missing')
return todos_avg_fields_possibleTypes.includes(obj.__typename)
}
const todos_max_fields_possibleTypes = ['todos_max_fields']
export const istodos_max_fields = (obj: { __typename: String }): obj is todos_max_fields => {
if (!obj.__typename) throw new Error('__typename is missing')
return todos_max_fields_possibleTypes.includes(obj.__typename)
}
const todos_min_fields_possibleTypes = ['todos_min_fields']
export const istodos_min_fields = (obj: { __typename: String }): obj is todos_min_fields => {
if (!obj.__typename) throw new Error('__typename is missing')
return todos_min_fields_possibleTypes.includes(obj.__typename)
}
const todos_stddev_fields_possibleTypes = ['todos_stddev_fields']
export const istodos_stddev_fields = (obj: { __typename: String }): obj is todos_stddev_fields => {
if (!obj.__typename) throw new Error('__typename is missing')
return todos_stddev_fields_possibleTypes.includes(obj.__typename)
}
const todos_stddev_pop_fields_possibleTypes = ['todos_stddev_pop_fields']
export const istodos_stddev_pop_fields = (obj: { __typename: String }): obj is todos_stddev_pop_fields => {
if (!obj.__typename) throw new Error('__typename is missing')
return todos_stddev_pop_fields_possibleTypes.includes(obj.__typename)
}
const todos_stddev_samp_fields_possibleTypes = ['todos_stddev_samp_fields']
export const istodos_stddev_samp_fields = (obj: { __typename: String }): obj is todos_stddev_samp_fields => {
if (!obj.__typename) throw new Error('__typename is missing')
return todos_stddev_samp_fields_possibleTypes.includes(obj.__typename)
}
const todos_sum_fields_possibleTypes = ['todos_sum_fields']
export const istodos_sum_fields = (obj: { __typename: String }): obj is todos_sum_fields => {
if (!obj.__typename) throw new Error('__typename is missing')
return todos_sum_fields_possibleTypes.includes(obj.__typename)
}
const todos_var_pop_fields_possibleTypes = ['todos_var_pop_fields']
export const istodos_var_pop_fields = (obj: { __typename: String }): obj is todos_var_pop_fields => {
if (!obj.__typename) throw new Error('__typename is missing')
return todos_var_pop_fields_possibleTypes.includes(obj.__typename)
}
const todos_var_samp_fields_possibleTypes = ['todos_var_samp_fields']
export const istodos_var_samp_fields = (obj: { __typename: String }): obj is todos_var_samp_fields => {
if (!obj.__typename) throw new Error('__typename is missing')
return todos_var_samp_fields_possibleTypes.includes(obj.__typename)
}
const todos_variance_fields_possibleTypes = ['todos_variance_fields']
export const istodos_variance_fields = (obj: { __typename: String }): obj is todos_variance_fields => {
if (!obj.__typename) throw new Error('__typename is missing')
return todos_variance_fields_possibleTypes.includes(obj.__typename)
}
const users_aggregate_possibleTypes = ['users_aggregate']
export const isusers_aggregate = (obj: { __typename: String }): obj is users_aggregate => {
if (!obj.__typename) throw new Error('__typename is missing')
return users_aggregate_possibleTypes.includes(obj.__typename)
}
const users_aggregate_fields_possibleTypes = ['users_aggregate_fields']
export const isusers_aggregate_fields = (obj: { __typename: String }): obj is users_aggregate_fields => {
if (!obj.__typename) throw new Error('__typename is missing')
return users_aggregate_fields_possibleTypes.includes(obj.__typename)
}
const users_avg_fields_possibleTypes = ['users_avg_fields']
export const isusers_avg_fields = (obj: { __typename: String }): obj is users_avg_fields => {
if (!obj.__typename) throw new Error('__typename is missing')
return users_avg_fields_possibleTypes.includes(obj.__typename)
}
const users_max_fields_possibleTypes = ['users_max_fields']
export const isusers_max_fields = (obj: { __typename: String }): obj is users_max_fields => {
if (!obj.__typename) throw new Error('__typename is missing')
return users_max_fields_possibleTypes.includes(obj.__typename)
}
const users_min_fields_possibleTypes = ['users_min_fields']
export const isusers_min_fields = (obj: { __typename: String }): obj is users_min_fields => {
if (!obj.__typename) throw new Error('__typename is missing')
return users_min_fields_possibleTypes.includes(obj.__typename)
}
const users_stddev_fields_possibleTypes = ['users_stddev_fields']
export const isusers_stddev_fields = (obj: { __typename: String }): obj is users_stddev_fields => {
if (!obj.__typename) throw new Error('__typename is missing')
return users_stddev_fields_possibleTypes.includes(obj.__typename)
}
const users_stddev_pop_fields_possibleTypes = ['users_stddev_pop_fields']
export const isusers_stddev_pop_fields = (obj: { __typename: String }): obj is users_stddev_pop_fields => {
if (!obj.__typename) throw new Error('__typename is missing')
return users_stddev_pop_fields_possibleTypes.includes(obj.__typename)
}
const users_stddev_samp_fields_possibleTypes = ['users_stddev_samp_fields']
export const isusers_stddev_samp_fields = (obj: { __typename: String }): obj is users_stddev_samp_fields => {
if (!obj.__typename) throw new Error('__typename is missing')
return users_stddev_samp_fields_possibleTypes.includes(obj.__typename)
}
const users_sum_fields_possibleTypes = ['users_sum_fields']
export const isusers_sum_fields = (obj: { __typename: String }): obj is users_sum_fields => {
if (!obj.__typename) throw new Error('__typename is missing')
return users_sum_fields_possibleTypes.includes(obj.__typename)
}
const users_var_pop_fields_possibleTypes = ['users_var_pop_fields']
export const isusers_var_pop_fields = (obj: { __typename: String }): obj is users_var_pop_fields => {
if (!obj.__typename) throw new Error('__typename is missing')
return users_var_pop_fields_possibleTypes.includes(obj.__typename)
}
const users_var_samp_fields_possibleTypes = ['users_var_samp_fields']
export const isusers_var_samp_fields = (obj: { __typename: String }): obj is users_var_samp_fields => {
if (!obj.__typename) throw new Error('__typename is missing')
return users_var_samp_fields_possibleTypes.includes(obj.__typename)
}
const users_variance_fields_possibleTypes = ['users_variance_fields']
export const isusers_variance_fields = (obj: { __typename: String }): obj is users_variance_fields => {
if (!obj.__typename) throw new Error('__typename is missing')
return users_variance_fields_possibleTypes.includes(obj.__typename)
}
const mutation_root_possibleTypes = ['mutation_root']
export const ismutation_root = (obj: { __typename: String }): obj is mutation_root => {
if (!obj.__typename) throw new Error('__typename is missing')
return mutation_root_possibleTypes.includes(obj.__typename)
}
const todos_mutation_response_possibleTypes = ['todos_mutation_response']
export const istodos_mutation_response = (obj: { __typename: String }): obj is todos_mutation_response => {
if (!obj.__typename) throw new Error('__typename is missing')
return todos_mutation_response_possibleTypes.includes(obj.__typename)
}
const users_mutation_response_possibleTypes = ['users_mutation_response']
export const isusers_mutation_response = (obj: { __typename: String }): obj is users_mutation_response => {
if (!obj.__typename) throw new Error('__typename is missing')
return users_mutation_response_possibleTypes.includes(obj.__typename)
}
const subscription_root_possibleTypes = ['subscription_root']
export const issubscription_root = (obj: { __typename: String }): obj is subscription_root => {
if (!obj.__typename) throw new Error('__typename is missing')
return subscription_root_possibleTypes.includes(obj.__typename)
}
const Query_possibleTypes = ['Query']
export const isQuery = (obj: { __typename: String }): obj is Query => {
if (!obj.__typename) throw new Error('__typename is missing')
return Query_possibleTypes.includes(obj.__typename)
}
/** query root */
export interface query_rootPromiseChain {
hello: { execute: (request?: boolean | number, defaultValue?: String | null) => Promise<String | null> }
/** fetch data from the table: "todos" */
todos: ((args?: {
/** distinct select on columns */
distinct_on?: todos_select_column[] | null
/** limit the nuber of rows returned */
limit?: Int | null
/** skip the first n rows. Use only with order_by */
offset?: Int | null
/** sort the rows by one or more columns */
order_by?: todos_order_by[] | null
/** filter the rows returned */
where?: todos_bool_exp | null
}) => { execute: (request: todosRequest, defaultValue?: todos[]) => Promise<todos[]> }) & {
execute: (request: todosRequest, defaultValue?: todos[]) => Promise<todos[]>
}
/** fetch aggregated fields from the table: "todos" */
todos_aggregate: ((args?: {
/** distinct select on columns */
distinct_on?: todos_select_column[] | null
/** limit the nuber of rows returned */
limit?: Int | null
/** skip the first n rows. Use only with order_by */
offset?: Int | null
/** sort the rows by one or more columns */
order_by?: todos_order_by[] | null
/** filter the rows returned */
where?: todos_bool_exp | null
}) => todos_aggregatePromiseChain & {
execute: (request: todos_aggregateRequest, defaultValue?: todos_aggregate) => Promise<todos_aggregate>
}) &
(todos_aggregatePromiseChain & {
execute: (request: todos_aggregateRequest, defaultValue?: todos_aggregate) => Promise<todos_aggregate>
})
/** fetch data from the table: "todos" using primary key columns */
todos_by_pk: (args: {
id: Int
}) => todosPromiseChain & { execute: (request: todosRequest, defaultValue?: todos | null) => Promise<todos | null> }
/** fetch data from the table: "users" */
users: ((args?: {
/** distinct select on columns */
distinct_on?: users_select_column[] | null
/** limit the nuber of rows returned */
limit?: Int | null
/** skip the first n rows. Use only with order_by */
offset?: Int | null
/** sort the rows by one or more columns */
order_by?: users_order_by[] | null
/** filter the rows returned */
where?: users_bool_exp | null
}) => { execute: (request: usersRequest, defaultValue?: users[]) => Promise<users[]> }) & {
execute: (request: usersRequest, defaultValue?: users[]) => Promise<users[]>
}
/** fetch aggregated fields from the table: "users" */
users_aggregate: ((args?: {
/** distinct select on columns */
distinct_on?: users_select_column[] | null
/** limit the nuber of rows returned */
limit?: Int | null
/** skip the first n rows. Use only with order_by */
offset?: Int | null
/** sort the rows by one or more columns */
order_by?: users_order_by[] | null
/** filter the rows returned */
where?: users_bool_exp | null
}) => users_aggregatePromiseChain & {
execute: (request: users_aggregateRequest, defaultValue?: users_aggregate) => Promise<users_aggregate>
}) &
(users_aggregatePromiseChain & {
execute: (request: users_aggregateRequest, defaultValue?: users_aggregate) => Promise<users_aggregate>
})
/** fetch data from the table: "users" using primary key columns */
users_by_pk: (args: {
id: Int
}) => usersPromiseChain & { execute: (request: usersRequest, defaultValue?: users | null) => Promise<users | null> }
}
/** query root */
export interface query_rootObservableChain {
hello: { execute: (request?: boolean | number, defaultValue?: String | null) => Observable<String | null> }
/** fetch data from the table: "todos" */
todos: ((args?: {
/** distinct select on columns */
distinct_on?: todos_select_column[] | null
/** limit the nuber of rows returned */
limit?: Int | null
/** skip the first n rows. Use only with order_by */
offset?: Int | null
/** sort the rows by one or more columns */
order_by?: todos_order_by[] | null
/** filter the rows returned */
where?: todos_bool_exp | null
}) => { execute: (request: todosRequest, defaultValue?: todos[]) => Observable<todos[]> }) & {
execute: (request: todosRequest, defaultValue?: todos[]) => Observable<todos[]>
}
/** fetch aggregated fields from the table: "todos" */
todos_aggregate: ((args?: {
/** distinct select on columns */
distinct_on?: todos_select_column[] | null
/** limit the nuber of rows returned */
limit?: Int | null
/** skip the first n rows. Use only with order_by */
offset?: Int | null
/** sort the rows by one or more columns */
order_by?: todos_order_by[] | null
/** filter the rows returned */
where?: todos_bool_exp | null
}) => todos_aggregateObservableChain & {
execute: (request: todos_aggregateRequest, defaultValue?: todos_aggregate) => Observable<todos_aggregate>
}) &
(todos_aggregateObservableChain & {
execute: (request: todos_aggregateRequest, defaultValue?: todos_aggregate) => Observable<todos_aggregate>
})
/** fetch data from the table: "todos" using primary key columns */
todos_by_pk: (args: {
id: Int
}) => todosObservableChain & { execute: (request: todosRequest, defaultValue?: todos | null) => Observable<todos | null> }
/** fetch data from the table: "users" */
users: ((args?: {
/** distinct select on columns */
distinct_on?: users_select_column[] | null
/** limit the nuber of rows returned */
limit?: Int | null
/** skip the first n rows. Use only with order_by */
offset?: Int | null
/** sort the rows by one or more columns */
order_by?: users_order_by[] | null
/** filter the rows returned */
where?: users_bool_exp | null
}) => { execute: (request: usersRequest, defaultValue?: users[]) => Observable<users[]> }) & {
execute: (request: usersRequest, defaultValue?: users[]) => Observable<users[]>
}
/** fetch aggregated fields from the table: "users" */
users_aggregate: ((args?: {
/** distinct select on columns */
distinct_on?: users_select_column[] | null
/** limit the nuber of rows returned */
limit?: Int | null
/** skip the first n rows. Use only with order_by */
offset?: Int | null
/** sort the rows by one or more columns */
order_by?: users_order_by[] | null
/** filter the rows returned */
where?: users_bool_exp | null
}) => users_aggregateObservableChain & {
execute: (request: users_aggregateRequest, defaultValue?: users_aggregate) => Observable<users_aggregate>
}) &
(users_aggregateObservableChain & {
execute: (request: users_aggregateRequest, defaultValue?: users_aggregate) => Observable<users_aggregate>
})
/** fetch data from the table: "users" using primary key columns */
users_by_pk: (args: {
id: Int
}) => usersObservableChain & { execute: (request: usersRequest, defaultValue?: users | null) => Observable<users | null> }
}
/** columns and relationships of "todos" */
export interface todosPromiseChain {
id: { execute: (request?: boolean | number, defaultValue?: Int) => Promise<Int> }
is_completed: { execute: (request?: boolean | number, defaultValue?: Boolean) => Promise<Boolean> }
text: { execute: (request?: boolean | number, defaultValue?: String) => Promise<String> }
/** An object relationship */
user: usersPromiseChain & { execute: (request: usersRequest, defaultValue?: users) => Promise<users> }
user_authID: { execute: (request?: boolean | number, defaultValue?: String) => Promise<String> }
}
/** columns and relationships of "todos" */
export interface todosObservableChain {
id: { execute: (request?: boolean | number, defaultValue?: Int) => Observable<Int> }
is_completed: { execute: (request?: boolean | number, defaultValue?: Boolean) => Observable<Boolean> }
text: { execute: (request?: boolean | number, defaultValue?: String) => Observable<String> }
/** An object relationship */
user: usersObservableChain & { execute: (request: usersRequest, defaultValue?: users) => Observable<users> }
user_authID: { execute: (request?: boolean | number, defaultValue?: String) => Observable<String> }
}
/** columns and relationships of "users" */
export interface usersPromiseChain {
authID: { execute: (request?: boolean | number, defaultValue?: String) => Promise<String> }
id: { execute: (request?: boolean | number, defaultValue?: Int) => Promise<Int> }
name: { execute: (request?: boolean | number, defaultValue?: String) => Promise<String> }
/** An array relationship */
todos: ((args?: {
/** distinct select on columns */
distinct_on?: todos_select_column[] | null
/** limit the nuber of rows returned */
limit?: Int | null
/** skip the first n rows. Use only with order_by */
offset?: Int | null
/** sort the rows by one or more columns */
order_by?: todos_order_by[] | null
/** filter the rows returned */
where?: todos_bool_exp | null
}) => { execute: (request: todosRequest, defaultValue?: todos[]) => Promise<todos[]> }) & {
execute: (request: todosRequest, defaultValue?: todos[]) => Promise<todos[]>
}
/** An aggregated array relationship */
todos_aggregate: ((args?: {
/** distinct select on columns */
distinct_on?: todos_select_column[] | null
/** limit the nuber of rows returned */
limit?: Int | null
/** skip the first n rows. Use only with order_by */
offset?: Int | null
/** sort the rows by one or more columns */
order_by?: todos_order_by[] | null
/** filter the rows returned */
where?: todos_bool_exp | null
}) => todos_aggregatePromiseChain & {
execute: (request: todos_aggregateRequest, defaultValue?: todos_aggregate) => Promise<todos_aggregate>
}) &
(todos_aggregatePromiseChain & {
execute: (request: todos_aggregateRequest, defaultValue?: todos_aggregate) => Promise<todos_aggregate>
})
}
/** columns and relationships of "users" */
export interface usersObservableChain {
authID: { execute: (request?: boolean | number, defaultValue?: String) => Observable<String> }
id: { execute: (request?: boolean | number, defaultValue?: Int) => Observable<Int> }
name: { execute: (request?: boolean | number, defaultValue?: String) => Observable<String> }
/** An array relationship */
todos: ((args?: {
/** distinct select on columns */
distinct_on?: todos_select_column[] | null
/** limit the nuber of rows returned */
limit?: Int | null
/** skip the first n rows. Use only with order_by */
offset?: Int | null
/** sort the rows by one or more columns */
order_by?: todos_order_by[] | null
/** filter the rows returned */
where?: todos_bool_exp | null
}) => { execute: (request: todosRequest, defaultValue?: todos[]) => Observable<todos[]> }) & {
execute: (request: todosRequest, defaultValue?: todos[]) => Observable<todos[]>
}
/** An aggregated array relationship */
todos_aggregate: ((args?: {
/** distinct select on columns */
distinct_on?: todos_select_column[] | null
/** limit the nuber of rows returned */
limit?: Int | null
/** skip the first n rows. Use only with order_by */
offset?: Int | null
/** sort the rows by one or more columns */
order_by?: todos_order_by[] | null
/** filter the rows returned */
where?: todos_bool_exp | null
}) => todos_aggregateObservableChain & {
execute: (request: todos_aggregateRequest, defaultValue?: todos_aggregate) => Observable<todos_aggregate>
}) &
(todos_aggregateObservableChain & {
execute: (request: todos_aggregateRequest, defaultValue?: todos_aggregate) => Observable<todos_aggregate>
})
}
/** aggregated selection of "todos" */
export interface todos_aggregatePromiseChain {
aggregate: todos_aggregate_fieldsPromiseChain & {
execute: (
request: todos_aggregate_fieldsRequest,
defaultValue?: todos_aggregate_fields | null,
) => Promise<todos_aggregate_fields | null>
}
nodes: { execute: (request: todosRequest, defaultValue?: todos[]) => Promise<todos[]> }
}
/** aggregated selection of "todos" */
export interface todos_aggregateObservableChain {
aggregate: todos_aggregate_fieldsObservableChain & {
execute: (
request: todos_aggregate_fieldsRequest,
defaultValue?: todos_aggregate_fields | null,
) => Observable<todos_aggregate_fields | null>
}
nodes: { execute: (request: todosRequest, defaultValue?: todos[]) => Observable<todos[]> }
}
/** aggregate fields of "todos" */
export interface todos_aggregate_fieldsPromiseChain {
avg: todos_avg_fieldsPromiseChain & {
execute: (request: todos_avg_fieldsRequest, defaultValue?: todos_avg_fields | null) => Promise<todos_avg_fields | null>
}
count: ((args?: {
columns?: todos_select_column[] | null
distinct?: Boolean | null
}) => { execute: (request?: boolean | number, defaultValue?: Int | null) => Promise<Int | null> }) & {
execute: (request?: boolean | number, defaultValue?: Int | null) => Promise<Int | null>
}
max: todos_max_fieldsPromiseChain & {
execute: (request: todos_max_fieldsRequest, defaultValue?: todos_max_fields | null) => Promise<todos_max_fields | null>
}
min: todos_min_fieldsPromiseChain & {
execute: (request: todos_min_fieldsRequest, defaultValue?: todos_min_fields | null) => Promise<todos_min_fields | null>
}
stddev: todos_stddev_fieldsPromiseChain & {
execute: (
request: todos_stddev_fieldsRequest,
defaultValue?: todos_stddev_fields | null,
) => Promise<todos_stddev_fields | null>
}
stddev_pop: todos_stddev_pop_fieldsPromiseChain & {
execute: (
request: todos_stddev_pop_fieldsRequest,
defaultValue?: todos_stddev_pop_fields | null,
) => Promise<todos_stddev_pop_fields | null>
}
stddev_samp: todos_stddev_samp_fieldsPromiseChain & {
execute: (
request: todos_stddev_samp_fieldsRequest,
defaultValue?: todos_stddev_samp_fields | null,
) => Promise<todos_stddev_samp_fields | null>
}
sum: todos_sum_fieldsPromiseChain & {
execute: (request: todos_sum_fieldsRequest, defaultValue?: todos_sum_fields | null) => Promise<todos_sum_fields | null>
}
var_pop: todos_var_pop_fieldsPromiseChain & {
execute: (
request: todos_var_pop_fieldsRequest,
defaultValue?: todos_var_pop_fields | null,
) => Promise<todos_var_pop_fields | null>
}
var_samp: todos_var_samp_fieldsPromiseChain & {
execute: (
request: todos_var_samp_fieldsRequest,
defaultValue?: todos_var_samp_fields | null,
) => Promise<todos_var_samp_fields | null>
}
variance: todos_variance_fieldsPromiseChain & {
execute: (
request: todos_variance_fieldsRequest,
defaultValue?: todos_variance_fields | null,
) => Promise<todos_variance_fields | null>
}
}
/** aggregate fields of "todos" */
export interface todos_aggregate_fieldsObservableChain {
avg: todos_avg_fieldsObservableChain & {
execute: (
request: todos_avg_fieldsRequest,
defaultValue?: todos_avg_fields | null,
) => Observable<todos_avg_fields | null>
}
count: ((args?: {
columns?: todos_select_column[] | null
distinct?: Boolean | null
}) => { execute: (request?: boolean | number, defaultValue?: Int | null) => Observable<Int | null> }) & {
execute: (request?: boolean | number, defaultValue?: Int | null) => Observable<Int | null>
}
max: todos_max_fieldsObservableChain & {
execute: (
request: todos_max_fieldsRequest,
defaultValue?: todos_max_fields | null,
) => Observable<todos_max_fields | null>
}
min: todos_min_fieldsObservableChain & {
execute: (
request: todos_min_fieldsRequest,
defaultValue?: todos_min_fields | null,
) => Observable<todos_min_fields | null>
}
stddev: todos_stddev_fieldsObservableChain & {
execute: (
request: todos_stddev_fieldsRequest,
defaultValue?: todos_stddev_fields | null,
) => Observable<todos_stddev_fields | null>
}
stddev_pop: todos_stddev_pop_fieldsObservableChain & {
execute: (
request: todos_stddev_pop_fieldsRequest,
defaultValue?: todos_stddev_pop_fields | null,
) => Observable<todos_stddev_pop_fields | null>
}
stddev_samp: todos_stddev_samp_fieldsObservableChain & {
execute: (
request: todos_stddev_samp_fieldsRequest,
defaultValue?: todos_stddev_samp_fields | null,
) => Observable<todos_stddev_samp_fields | null>
}
sum: todos_sum_fieldsObservableChain & {
execute: (
request: todos_sum_fieldsRequest,
defaultValue?: todos_sum_fields | null,
) => Observable<todos_sum_fields | null>
}
var_pop: todos_var_pop_fieldsObservableChain & {
execute: (
request: todos_var_pop_fieldsRequest,
defaultValue?: todos_var_pop_fields | null,
) => Observable<todos_var_pop_fields | null>
}
var_samp: todos_var_samp_fieldsObservableChain & {
execute: (
request: todos_var_samp_fieldsRequest,
defaultValue?: todos_var_samp_fields | null,
) => Observable<todos_var_samp_fields | null>
}
variance: todos_variance_fieldsObservableChain & {
execute: (
request: todos_variance_fieldsRequest,
defaultValue?: todos_variance_fields | null,
) => Observable<todos_variance_fields | null>
}
}
/** aggregate avg on columns */
export interface todos_avg_fieldsPromiseChain {
id: { execute: (request?: boolean | number, defaultValue?: Float | null) => Promise<Float | null> }
}
/** aggregate avg on columns */
export interface todos_avg_fieldsObservableChain {
id: { execute: (request?: boolean | number, defaultValue?: Float | null) => Observable<Float | null> }
}
/** aggregate max on columns */
export interface todos_max_fieldsPromiseChain {
id: { execute: (request?: boolean | number, defaultValue?: Int | null) => Promise<Int | null> }
text: { execute: (request?: boolean | number, defaultValue?: String | null) => Promise<String | null> }
user_authID: { execute: (request?: boolean | number, defaultValue?: String | null) => Promise<String | null> }
}
/** aggregate max on columns */
export interface todos_max_fieldsObservableChain {
id: { execute: (request?: boolean | number, defaultValue?: Int | null) => Observable<Int | null> }
text: { execute: (request?: boolean | number, defaultValue?: String | null) => Observable<String | null> }
user_authID: { execute: (request?: boolean | number, defaultValue?: String | null) => Observable<String | null> }
}
/** aggregate min on columns */
export interface todos_min_fieldsPromiseChain {
id: { execute: (request?: boolean | number, defaultValue?: Int | null) => Promise<Int | null> }
text: { execute: (request?: boolean | number, defaultValue?: String | null) => Promise<String | null> }
user_authID: { execute: (request?: boolean | number, defaultValue?: String | null) => Promise<String | null> }
}
/** aggregate min on columns */
export interface todos_min_fieldsObservableChain {
id: { execute: (request?: boolean | number, defaultValue?: Int | null) => Observable<Int | null> }
text: { execute: (request?: boolean | number, defaultValue?: String | null) => Observable<String | null> }
user_authID: { execute: (request?: boolean | number, defaultValue?: String | null) => Observable<String | null> }
}
/** aggregate stddev on columns */
export interface todos_stddev_fieldsPromiseChain {
id: { execute: (request?: boolean | number, defaultValue?: Float | null) => Promise<Float | null> }
}
/** aggregate stddev on columns */
export interface todos_stddev_fieldsObservableChain {
id: { execute: (request?: boolean | number, defaultValue?: Float | null) => Observable<Float | null> }
}
/** aggregate stddev_pop on columns */
export interface todos_stddev_pop_fieldsPromiseChain {
id: { execute: (request?: boolean | number, defaultValue?: Float | null) => Promise<Float | null> }
}
/** aggregate stddev_pop on columns */
export interface todos_stddev_pop_fieldsObservableChain {
id: { execute: (request?: boolean | number, defaultValue?: Float | null) => Observable<Float | null> }
}
/** aggregate stddev_samp on columns */
export interface todos_stddev_samp_fieldsPromiseChain {
id: { execute: (request?: boolean | number, defaultValue?: Float | null) => Promise<Float | null> }
}
/** aggregate stddev_samp on columns */
export interface todos_stddev_samp_fieldsObservableChain {
id: { execute: (request?: boolean | number, defaultValue?: Float | null) => Observable<Float | null> }
}
/** aggregate sum on columns */
export interface todos_sum_fieldsPromiseChain {
id: { execute: (request?: boolean | number, defaultValue?: Int | null) => Promise<Int | null> }
}
/** aggregate sum on columns */
export interface todos_sum_fieldsObservableChain {
id: { execute: (request?: boolean | number, defaultValue?: Int | null) => Observable<Int | null> }
}
/** aggregate var_pop on columns */
export interface todos_var_pop_fieldsPromiseChain {
id: { execute: (request?: boolean | number, defaultValue?: Float | null) => Promise<Float | null> }
}
/** aggregate var_pop on columns */
export interface todos_var_pop_fieldsObservableChain {
id: { execute: (request?: boolean | number, defaultValue?: Float | null) => Observable<Float | null> }
}
/** aggregate var_samp on columns */
export interface todos_var_samp_fieldsPromiseChain {
id: { execute: (request?: boolean | number, defaultValue?: Float | null) => Promise<Float | null> }
}
/** aggregate var_samp on columns */
export interface todos_var_samp_fieldsObservableChain {
id: { execute: (request?: boolean | number, defaultValue?: Float | null) => Observable<Float | null> }
}
/** aggregate variance on columns */
export interface todos_variance_fieldsPromiseChain {
id: { execute: (request?: boolean | number, defaultValue?: Float | null) => Promise<Float | null> }
}
/** aggregate variance on columns */
export interface todos_variance_fieldsObservableChain {
id: { execute: (request?: boolean | number, defaultValue?: Float | null) => Observable<Float | null> }
}
/** aggregated selection of "users" */
export interface users_aggregatePromiseChain {
aggregate: users_aggregate_fieldsPromiseChain & {
execute: (
request: users_aggregate_fieldsRequest,
defaultValue?: users_aggregate_fields | null,
) => Promise<users_aggregate_fields | null>
}
nodes: { execute: (request: usersRequest, defaultValue?: users[]) => Promise<users[]> }
}
/** aggregated selection of "users" */
export interface users_aggregateObservableChain {
aggregate: users_aggregate_fieldsObservableChain & {
execute: (
request: users_aggregate_fieldsRequest,
defaultValue?: users_aggregate_fields | null,
) => Observable<users_aggregate_fields | null>
}
nodes: { execute: (request: usersRequest, defaultValue?: users[]) => Observable<users[]> }
}
/** aggregate fields of "users" */
export interface users_aggregate_fieldsPromiseChain {
avg: users_avg_fieldsPromiseChain & {
execute: (request: users_avg_fieldsRequest, defaultValue?: users_avg_fields | null) => Promise<users_avg_fields | null>
}
count: ((args?: {
columns?: users_select_column[] | null
distinct?: Boolean | null
}) => { execute: (request?: boolean | number, defaultValue?: Int | null) => Promise<Int | null> }) & {
execute: (request?: boolean | number, defaultValue?: Int | null) => Promise<Int | null>
}
max: users_max_fieldsPromiseChain & {
execute: (request: users_max_fieldsRequest, defaultValue?: users_max_fields | null) => Promise<users_max_fields | null>
}
min: users_min_fieldsPromiseChain & {
execute: (request: users_min_fieldsRequest, defaultValue?: users_min_fields | null) => Promise<users_min_fields | null>
}
stddev: users_stddev_fieldsPromiseChain & {
execute: (
request: users_stddev_fieldsRequest,
defaultValue?: users_stddev_fields | null,
) => Promise<users_stddev_fields | null>
}
stddev_pop: users_stddev_pop_fieldsPromiseChain & {
execute: (
request: users_stddev_pop_fieldsRequest,
defaultValue?: users_stddev_pop_fields | null,
) => Promise<users_stddev_pop_fields | null>
}
stddev_samp: users_stddev_samp_fieldsPromiseChain & {
execute: (
request: users_stddev_samp_fieldsRequest,
defaultValue?: users_stddev_samp_fields | null,
) => Promise<users_stddev_samp_fields | null>
}
sum: users_sum_fieldsPromiseChain & {
execute: (request: users_sum_fieldsRequest, defaultValue?: users_sum_fields | null) => Promise<users_sum_fields | null>
}
var_pop: users_var_pop_fieldsPromiseChain & {
execute: (
request: users_var_pop_fieldsRequest,
defaultValue?: users_var_pop_fields | null,
) => Promise<users_var_pop_fields | null>
}
var_samp: users_var_samp_fieldsPromiseChain & {
execute: (
request: users_var_samp_fieldsRequest,
defaultValue?: users_var_samp_fields | null,
) => Promise<users_var_samp_fields | null>
}
variance: users_variance_fieldsPromiseChain & {
execute: (
request: users_variance_fieldsRequest,
defaultValue?: users_variance_fields | null,
) => Promise<users_variance_fields | null>
}
}
/** aggregate fields of "users" */
export interface users_aggregate_fieldsObservableChain {
avg: users_avg_fieldsObservableChain & {
execute: (
request: users_avg_fieldsRequest,
defaultValue?: users_avg_fields | null,
) => Observable<users_avg_fields | null>
}
count: ((args?: {
columns?: users_select_column[] | null
distinct?: Boolean | null
}) => { execute: (request?: boolean | number, defaultValue?: Int | null) => Observable<Int | null> }) & {
execute: (request?: boolean | number, defaultValue?: Int | null) => Observable<Int | null>
}
max: users_max_fieldsObservableChain & {
execute: (
request: users_max_fieldsRequest,
defaultValue?: users_max_fields | null,
) => Observable<users_max_fields | null>
}
min: users_min_fieldsObservableChain & {
execute: (
request: users_min_fieldsRequest,
defaultValue?: users_min_fields | null,
) => Observable<users_min_fields | null>
}
stddev: users_stddev_fieldsObservableChain & {
execute: (
request: users_stddev_fieldsRequest,
defaultValue?: users_stddev_fields | null,
) => Observable<users_stddev_fields | null>
}
stddev_pop: users_stddev_pop_fieldsObservableChain & {
execute: (
request: users_stddev_pop_fieldsRequest,
defaultValue?: users_stddev_pop_fields | null,
) => Observable<users_stddev_pop_fields | null>
}
stddev_samp: users_stddev_samp_fieldsObservableChain & {
execute: (
request: users_stddev_samp_fieldsRequest,
defaultValue?: users_stddev_samp_fields | null,
) => Observable<users_stddev_samp_fields | null>
}
sum: users_sum_fieldsObservableChain & {
execute: (
request: users_sum_fieldsRequest,
defaultValue?: users_sum_fields | null,
) => Observable<users_sum_fields | null>
}
var_pop: users_var_pop_fieldsObservableChain & {
execute: (
request: users_var_pop_fieldsRequest,
defaultValue?: users_var_pop_fields | null,
) => Observable<users_var_pop_fields | null>
}
var_samp: users_var_samp_fieldsObservableChain & {
execute: (
request: users_var_samp_fieldsRequest,
defaultValue?: users_var_samp_fields | null,
) => Observable<users_var_samp_fields | null>
}
variance: users_variance_fieldsObservableChain & {
execute: (
request: users_variance_fieldsRequest,
defaultValue?: users_variance_fields | null,
) => Observable<users_variance_fields | null>
}
}
/** aggregate avg on columns */
export interface users_avg_fieldsPromiseChain {
id: { execute: (request?: boolean | number, defaultValue?: Float | null) => Promise<Float | null> }
}
/** aggregate avg on columns */
export interface users_avg_fieldsObservableChain {
id: { execute: (request?: boolean | number, defaultValue?: Float | null) => Observable<Float | null> }
}
/** aggregate max on columns */
export interface users_max_fieldsPromiseChain {
authID: { execute: (request?: boolean | number, defaultValue?: String | null) => Promise<String | null> }
id: { execute: (request?: boolean | number, defaultValue?: Int | null) => Promise<Int | null> }
name: { execute: (request?: boolean | number, defaultValue?: String | null) => Promise<String | null> }
}
/** aggregate max on columns */
export interface users_max_fieldsObservableChain {
authID: { execute: (request?: boolean | number, defaultValue?: String | null) => Observable<String | null> }
id: { execute: (request?: boolean | number, defaultValue?: Int | null) => Observable<Int | null> }
name: { execute: (request?: boolean | number, defaultValue?: String | null) => Observable<String | null> }
}
/** aggregate min on columns */
export interface users_min_fieldsPromiseChain {
authID: { execute: (request?: boolean | number, defaultValue?: String | null) => Promise<String | null> }
id: { execute: (request?: boolean | number, defaultValue?: Int | null) => Promise<Int | null> }
name: { execute: (request?: boolean | number, defaultValue?: String | null) => Promise<String | null> }
}
/** aggregate min on columns */
export interface users_min_fieldsObservableChain {
authID: { execute: (request?: boolean | number, defaultValue?: String | null) => Observable<String | null> }
id: { execute: (request?: boolean | number, defaultValue?: Int | null) => Observable<Int | null> }
name: { execute: (request?: boolean | number, defaultValue?: String | null) => Observable<String | null> }
}
/** aggregate stddev on columns */
export interface users_stddev_fieldsPromiseChain {
id: { execute: (request?: boolean | number, defaultValue?: Float | null) => Promise<Float | null> }
}
/** aggregate stddev on columns */
export interface users_stddev_fieldsObservableChain {
id: { execute: (request?: boolean | number, defaultValue?: Float | null) => Observable<Float | null> }
}
/** aggregate stddev_pop on columns */
export interface users_stddev_pop_fieldsPromiseChain {
id: { execute: (request?: boolean | number, defaultValue?: Float | null) => Promise<Float | null> }
}
/** aggregate stddev_pop on columns */
export interface users_stddev_pop_fieldsObservableChain {
id: { execute: (request?: boolean | number, defaultValue?: Float | null) => Observable<Float | null> }
}
/** aggregate stddev_samp on columns */
export interface users_stddev_samp_fieldsPromiseChain {
id: { execute: (request?: boolean | number, defaultValue?: Float | null) => Promise<Float | null> }
}
/** aggregate stddev_samp on columns */
export interface users_stddev_samp_fieldsObservableChain {
id: { execute: (request?: boolean | number, defaultValue?: Float | null) => Observable<Float | null> }
}
/** aggregate sum on columns */
export interface users_sum_fieldsPromiseChain {
id: { execute: (request?: boolean | number, defaultValue?: Int | null) => Promise<Int | null> }
}
/** aggregate sum on columns */
export interface users_sum_fieldsObservableChain {
id: { execute: (request?: boolean | number, defaultValue?: Int | null) => Observable<Int | null> }
}
/** aggregate var_pop on columns */
export interface users_var_pop_fieldsPromiseChain {
id: { execute: (request?: boolean | number, defaultValue?: Float | null) => Promise<Float | null> }
}
/** aggregate var_pop on columns */
export interface users_var_pop_fieldsObservableChain {
id: { execute: (request?: boolean | number, defaultValue?: Float | null) => Observable<Float | null> }
}
/** aggregate var_samp on columns */
export interface users_var_samp_fieldsPromiseChain {
id: { execute: (request?: boolean | number, defaultValue?: Float | null) => Promise<Float | null> }
}
/** aggregate var_samp on columns */
export interface users_var_samp_fieldsObservableChain {
id: { execute: (request?: boolean | number, defaultValue?: Float | null) => Observable<Float | null> }
}
/** aggregate variance on columns */
export interface users_variance_fieldsPromiseChain {
id: { execute: (request?: boolean | number, defaultValue?: Float | null) => Promise<Float | null> }
}
/** aggregate variance on columns */
export interface users_variance_fieldsObservableChain {
id: { execute: (request?: boolean | number, defaultValue?: Float | null) => Observable<Float | null> }
}
/** mutation root */
export interface mutation_rootPromiseChain {
/** delete data from the table: "todos" */
delete_todos: (args: {
/** filter the rows which have to be deleted */
where: todos_bool_exp
}) => todos_mutation_responsePromiseChain & {
execute: (
request: todos_mutation_responseRequest,
defaultValue?: todos_mutation_response | null,
) => Promise<todos_mutation_response | null>
}
/** delete data from the table: "users" */
delete_users: (args: {
/** filter the rows which have to be deleted */
where: users_bool_exp
}) => users_mutation_responsePromiseChain & {
execute: (
request: users_mutation_responseRequest,
defaultValue?: users_mutation_response | null,
) => Promise<users_mutation_response | null>
}
/** insert data into the table: "todos" */
insert_todos: (args: {
/** the rows to be inserted */
objects: todos_insert_input[]
/** on conflict condition */
on_conflict?: todos_on_conflict | null
}) => todos_mutation_responsePromiseChain & {
execute: (
request: todos_mutation_responseRequest,
defaultValue?: todos_mutation_response | null,
) => Promise<todos_mutation_response | null>
}
/** insert data into the table: "users" */
insert_users: (args: {
/** the rows to be inserted */
objects: users_insert_input[]
/** on conflict condition */
on_conflict?: users_on_conflict | null
}) => users_mutation_responsePromiseChain & {
execute: (
request: users_mutation_responseRequest,
defaultValue?: users_mutation_response | null,
) => Promise<users_mutation_response | null>
}
/** update data of the table: "todos" */
update_todos: (args: {
/** increments the integer columns with given value of the filtered values */
_inc?: todos_inc_input | null
/** sets the columns of the filtered rows to the given values */
_set?: todos_set_input | null
/** filter the rows which have to be updated */
where: todos_bool_exp
}) => todos_mutation_responsePromiseChain & {
execute: (
request: todos_mutation_responseRequest,
defaultValue?: todos_mutation_response | null,
) => Promise<todos_mutation_response | null>
}
/** update data of the table: "users" */
update_users: (args: {
/** increments the integer columns with given value of the filtered values */
_inc?: users_inc_input | null
/** sets the columns of the filtered rows to the given values */
_set?: users_set_input | null
/** filter the rows which have to be updated */
where: users_bool_exp
}) => users_mutation_responsePromiseChain & {
execute: (
request: users_mutation_responseRequest,
defaultValue?: users_mutation_response | null,
) => Promise<users_mutation_response | null>
}
}
/** mutation root */
export interface mutation_rootObservableChain {
/** delete data from the table: "todos" */
delete_todos: (args: {
/** filter the rows which have to be deleted */
where: todos_bool_exp
}) => todos_mutation_responseObservableChain & {
execute: (
request: todos_mutation_responseRequest,
defaultValue?: todos_mutation_response | null,
) => Observable<todos_mutation_response | null>
}
/** delete data from the table: "users" */
delete_users: (args: {
/** filter the rows which have to be deleted */
where: users_bool_exp
}) => users_mutation_responseObservableChain & {
execute: (
request: users_mutation_responseRequest,
defaultValue?: users_mutation_response | null,
) => Observable<users_mutation_response | null>
}
/** insert data into the table: "todos" */
insert_todos: (args: {
/** the rows to be inserted */
objects: todos_insert_input[]
/** on conflict condition */
on_conflict?: todos_on_conflict | null
}) => todos_mutation_responseObservableChain & {
execute: (
request: todos_mutation_responseRequest,
defaultValue?: todos_mutation_response | null,
) => Observable<todos_mutation_response | null>
}
/** insert data into the table: "users" */
insert_users: (args: {
/** the rows to be inserted */
objects: users_insert_input[]
/** on conflict condition */
on_conflict?: users_on_conflict | null
}) => users_mutation_responseObservableChain & {
execute: (
request: users_mutation_responseRequest,
defaultValue?: users_mutation_response | null,
) => Observable<users_mutation_response | null>
}
/** update data of the table: "todos" */
update_todos: (args: {
/** increments the integer columns with given value of the filtered values */
_inc?: todos_inc_input | null
/** sets the columns of the filtered rows to the given values */
_set?: todos_set_input | null
/** filter the rows which have to be updated */
where: todos_bool_exp
}) => todos_mutation_responseObservableChain & {
execute: (
request: todos_mutation_responseRequest,
defaultValue?: todos_mutation_response | null,
) => Observable<todos_mutation_response | null>
}
/** update data of the table: "users" */
update_users: (args: {
/** increments the integer columns with given value of the filtered values */
_inc?: users_inc_input | null
/** sets the columns of the filtered rows to the given values */
_set?: users_set_input | null
/** filter the rows which have to be updated */
where: users_bool_exp
}) => users_mutation_responseObservableChain & {
execute: (
request: users_mutation_responseRequest,
defaultValue?: users_mutation_response | null,
) => Observable<users_mutation_response | null>
}
}
/** response of any mutation on the table "todos" */
export interface todos_mutation_responsePromiseChain {
/** number of affected rows by the mutation */
affected_rows: { execute: (request?: boolean | number, defaultValue?: Int) => Promise<Int> }
/** data of the affected rows by the mutation */
returning: { execute: (request: todosRequest, defaultValue?: todos[]) => Promise<todos[]> }
}
/** response of any mutation on the table "todos" */
export interface todos_mutation_responseObservableChain {
/** number of affected rows by the mutation */
affected_rows: { execute: (request?: boolean | number, defaultValue?: Int) => Observable<Int> }
/** data of the affected rows by the mutation */
returning: { execute: (request: todosRequest, defaultValue?: todos[]) => Observable<todos[]> }
}
/** response of any mutation on the table "users" */
export interface users_mutation_responsePromiseChain {
/** number of affected rows by the mutation */
affected_rows: { execute: (request?: boolean | number, defaultValue?: Int) => Promise<Int> }
/** data of the affected rows by the mutation */
returning: { execute: (request: usersRequest, defaultValue?: users[]) => Promise<users[]> }
}
/** response of any mutation on the table "users" */
export interface users_mutation_responseObservableChain {
/** number of affected rows by the mutation */
affected_rows: { execute: (request?: boolean | number, defaultValue?: Int) => Observable<Int> }
/** data of the affected rows by the mutation */
returning: { execute: (request: usersRequest, defaultValue?: users[]) => Observable<users[]> }
}
/** subscription root */
export interface subscription_rootPromiseChain {
/** fetch data from the table: "todos" */
todos: ((args?: {
/** distinct select on columns */
distinct_on?: todos_select_column[] | null
/** limit the nuber of rows returned */
limit?: Int | null
/** skip the first n rows. Use only with order_by */
offset?: Int | null
/** sort the rows by one or more columns */
order_by?: todos_order_by[] | null
/** filter the rows returned */
where?: todos_bool_exp | null
}) => { execute: (request: todosRequest, defaultValue?: todos[]) => Promise<todos[]> }) & {
execute: (request: todosRequest, defaultValue?: todos[]) => Promise<todos[]>
}
/** fetch aggregated fields from the table: "todos" */
todos_aggregate: ((args?: {
/** distinct select on columns */
distinct_on?: todos_select_column[] | null
/** limit the nuber of rows returned */
limit?: Int | null
/** skip the first n rows. Use only with order_by */
offset?: Int | null
/** sort the rows by one or more columns */
order_by?: todos_order_by[] | null
/** filter the rows returned */
where?: todos_bool_exp | null
}) => todos_aggregatePromiseChain & {
execute: (request: todos_aggregateRequest, defaultValue?: todos_aggregate) => Promise<todos_aggregate>
}) &
(todos_aggregatePromiseChain & {
execute: (request: todos_aggregateRequest, defaultValue?: todos_aggregate) => Promise<todos_aggregate>
})
/** fetch data from the table: "todos" using primary key columns */
todos_by_pk: (args: {
id: Int
}) => todosPromiseChain & { execute: (request: todosRequest, defaultValue?: todos | null) => Promise<todos | null> }
/** fetch data from the table: "users" */
users: ((args?: {
/** distinct select on columns */
distinct_on?: users_select_column[] | null
/** limit the nuber of rows returned */
limit?: Int | null
/** skip the first n rows. Use only with order_by */
offset?: Int | null
/** sort the rows by one or more columns */
order_by?: users_order_by[] | null
/** filter the rows returned */
where?: users_bool_exp | null
}) => { execute: (request: usersRequest, defaultValue?: users[]) => Promise<users[]> }) & {
execute: (request: usersRequest, defaultValue?: users[]) => Promise<users[]>
}
/** fetch aggregated fields from the table: "users" */
users_aggregate: ((args?: {
/** distinct select on columns */
distinct_on?: users_select_column[] | null
/** limit the nuber of rows returned */
limit?: Int | null
/** skip the first n rows. Use only with order_by */
offset?: Int | null
/** sort the rows by one or more columns */
order_by?: users_order_by[] | null
/** filter the rows returned */
where?: users_bool_exp | null
}) => users_aggregatePromiseChain & {
execute: (request: users_aggregateRequest, defaultValue?: users_aggregate) => Promise<users_aggregate>
}) &
(users_aggregatePromiseChain & {
execute: (request: users_aggregateRequest, defaultValue?: users_aggregate) => Promise<users_aggregate>
})
/** fetch data from the table: "users" using primary key columns */
users_by_pk: (args: {
id: Int
}) => usersPromiseChain & { execute: (request: usersRequest, defaultValue?: users | null) => Promise<users | null> }
}
/** subscription root */
export interface subscription_rootObservableChain {
/** fetch data from the table: "todos" */
todos: ((args?: {
/** distinct select on columns */
distinct_on?: todos_select_column[] | null
/** limit the nuber of rows returned */
limit?: Int | null
/** skip the first n rows. Use only with order_by */
offset?: Int | null
/** sort the rows by one or more columns */
order_by?: todos_order_by[] | null
/** filter the rows returned */
where?: todos_bool_exp | null
}) => { execute: (request: todosRequest, defaultValue?: todos[]) => Observable<todos[]> }) & {
execute: (request: todosRequest, defaultValue?: todos[]) => Observable<todos[]>
}
/** fetch aggregated fields from the table: "todos" */
todos_aggregate: ((args?: {
/** distinct select on columns */
distinct_on?: todos_select_column[] | null
/** limit the nuber of rows returned */
limit?: Int | null
/** skip the first n rows. Use only with order_by */
offset?: Int | null
/** sort the rows by one or more columns */
order_by?: todos_order_by[] | null
/** filter the rows returned */
where?: todos_bool_exp | null
}) => todos_aggregateObservableChain & {
execute: (request: todos_aggregateRequest, defaultValue?: todos_aggregate) => Observable<todos_aggregate>
}) &
(todos_aggregateObservableChain & {
execute: (request: todos_aggregateRequest, defaultValue?: todos_aggregate) => Observable<todos_aggregate>
})
/** fetch data from the table: "todos" using primary key columns */
todos_by_pk: (args: {
id: Int
}) => todosObservableChain & { execute: (request: todosRequest, defaultValue?: todos | null) => Observable<todos | null> }
/** fetch data from the table: "users" */
users: ((args?: {
/** distinct select on columns */
distinct_on?: users_select_column[] | null
/** limit the nuber of rows returned */
limit?: Int | null
/** skip the first n rows. Use only with order_by */
offset?: Int | null
/** sort the rows by one or more columns */
order_by?: users_order_by[] | null
/** filter the rows returned */
where?: users_bool_exp | null
}) => { execute: (request: usersRequest, defaultValue?: users[]) => Observable<users[]> }) & {
execute: (request: usersRequest, defaultValue?: users[]) => Observable<users[]>
}
/** fetch aggregated fields from the table: "users" */
users_aggregate: ((args?: {
/** distinct select on columns */
distinct_on?: users_select_column[] | null
/** limit the nuber of rows returned */
limit?: Int | null
/** skip the first n rows. Use only with order_by */
offset?: Int | null
/** sort the rows by one or more columns */
order_by?: users_order_by[] | null
/** filter the rows returned */
where?: users_bool_exp | null
}) => users_aggregateObservableChain & {
execute: (request: users_aggregateRequest, defaultValue?: users_aggregate) => Observable<users_aggregate>
}) &
(users_aggregateObservableChain & {
execute: (request: users_aggregateRequest, defaultValue?: users_aggregate) => Observable<users_aggregate>
})
/** fetch data from the table: "users" using primary key columns */
users_by_pk: (args: {
id: Int
}) => usersObservableChain & { execute: (request: usersRequest, defaultValue?: users | null) => Observable<users | null> }
}
export interface QueryPromiseChain {
hello: { execute: (request?: boolean | number, defaultValue?: String | null) => Promise<String | null> }
}
export interface QueryObservableChain {
hello: { execute: (request?: boolean | number, defaultValue?: String | null) => Observable<String | null> }
} | the_stack |
import { useEffect, useState, useRef, useMemo, forwardRef } from 'react';
import { styled, css, keyframes } from '~/theme/stitches.config';
import { useShareForwardedRef } from '~/hooks/useShareForwardedRef';
import { Link } from '~/components/router/client';
// Button style is a mix of
// a) Material Buttons: https://material.io/components/buttons
// b) Tailwind UI Buttons: https://tailwindui.com/components/application-ui/elements/buttons
interface Coordinates {
x: number;
y: number;
}
interface Translation {
start: Coordinates;
end: Coordinates;
}
const RIPPLE_DURATION_MS = 225; // Corresponds to ripple translate duration (i.e. activation animation duration)
const DEACTIVATION_MS = 150; // Corresponds to ripple fade-out duration (i.e. deactivation animation duration)
const INITIAL_ORIGIN_SCALE = 0.2;
enum ButtonState {
Idle,
Pressed,
Released,
}
const fgRadiusIn = keyframes({
from: {
animationTimingFunction: 'cubic-bezier(0.4, 0, 0.2, 1)',
transform: 'translate(var(--ripple-translate-start, 0)) scale(1)',
},
to: {
transform: 'translate(var(--ripple-translate-end, 0)) scale(var(--ripple-scale, 1))',
},
});
const fgOpacityIn = keyframes({
from: {
animationTimingFunction: 'linear',
opacity: 0,
},
to: {
opacity: 1,
},
});
const fgOpacityOut = keyframes({
from: {
animationTimingFunction: 'linear',
opacity: 1,
},
to: {
opacity: 0,
},
});
const ButtonCss = css({
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
fontWeight: '$medium',
userSelect: 'none',
touchAction: 'pan-y',
border: '1px solid transparent',
// willChange: 'transform,background-color,border-color,opacity,box-shadow',
// transition: 'border-color 150ms cubic-bezier(0.4, 0, 0.2, 1)', // Transition only box-shadow instead of all like Tailwind does, feels faster
position: 'relative', // for Ripple
'-webkit-font-smoothing': 'antialiased',
'-webkit-user-drag': 'none',
'--ripple-size': 0, // initial circle size
'--ripple-scale': 1, // target scale
'--ripple-left': 0,
'--ripple-top': 0,
'--ripple-translate-start': 0,
'--ripple-translate-end': 0,
'&:active,&:focus': {
outline: 'none',
},
'&:active,&.pressed': {
transform: 'translateY(1px)',
},
'&[disabled]': {
pointerEvents: 'none',
filter: 'grayscale(50%)',
boxShadow: 'none',
opacity: 0.45,
},
// Tones
$$buttonShadow: 'none',
$$buttonFocusVisible: 'transparent',
boxShadow: '$$buttonShadow',
// Don't do this since it's not supported in recent browsers
// Use the double fallback trick, see below:
// '&:focus-visible': {
// boxShadow: `0 0 0 3px $$buttonFocusVisible`,
// },
'&:focus': {
boxShadow: '0 0 0 3px $$buttonFocusVisible',
},
'&:focus:not(:focus-visible)': {
boxShadow: '$$buttonShadow',
},
'&:focus-visible': {
boxShadow: '0 0 0 3px $$buttonFocusVisible',
},
variants: {
size: {
xs: {
fontSize: '$xs',
},
sm: {
fontSize: '$sm',
},
base: {
fontSize: '$sm',
},
lg: {
fontSize: '$base',
},
xl: {
fontSize: '$base',
},
},
variant: {
contained: {
$$buttonShadow: '$shadows$sm',
// '.light &:not([disabled])': {
// textShadow: '1px 1px 1px rgba(0,0,0,.2)',
// },
// '.dark &:not([disabled])': {
// textShadow: '1px 1px 1px rgba(0,0,0,.1)',
// },
},
outline: {
backgroundColor: 'transparent',
// $$buttonShadow: '$shadows$sm',
},
text: {
backgroundColor: 'transparent',
},
},
tone: {
accent: {
$$buttonFocusVisible: '$colors$accent7',
},
neutral: {
$$buttonFocusVisible: '$colors$neutral7',
},
// positive: {
// $$buttonFocusVisible: '$colors$positive7',
// },
// info: {
// $$buttonFocusVisible: '$colors$info7',
// },
caution: {
$$buttonFocusVisible: '$colors$caution6',
},
critical: {
$$buttonFocusVisible: '$colors$critical7',
},
},
rounding: {
normal: {
padding: '$xsm $sm',
borderRadius: '$md',
lineHeight: '1.5rem',
},
icon: {
borderRadius: '$full',
square: '2em',
},
},
fill: {
auto: {
display: 'flex',
'@sm': {
display: 'inline-flex',
},
},
full: {
display: 'flex',
},
},
},
compoundVariants: [
{ rounding: 'normal', size: 'xs', css: { borderRadius: '$rounded', padding: '$xxsm $xsm', lineHeight: '1rem' } },
{ rounding: 'normal', size: 'sm', css: { lineHeight: '1rem' } },
{ rounding: 'normal', size: 'xl', css: { padding: '$sm $gutter' } },
{ rounding: 'icon', size: 'xs', css: { square: '1.7rem' } },
{ rounding: 'icon', size: 'sm', css: { square: '2.1rem' } },
{ rounding: 'icon', size: 'base', css: { square: '2.5rem' } },
{ rounding: 'icon', size: 'lg', css: { square: '2.5rem' } },
{ rounding: 'icon', size: 'xl', css: { square: '3rem' } },
// Accent
{
variant: 'contained',
tone: 'accent',
css: {
color: '$accent2',
backgroundColor: '$accent9',
// '&:focus,&:hover,&:active': { backgroundColor: '$accent10' },
'.light &': {
borderColor: '$accent10',
},
'.dark &': {
backgroundColor: '$accent10',
borderColor: '$accent9',
},
},
},
{
variant: 'outline',
tone: 'accent',
css: {
color: '$accent11',
borderColor: '$accent8',
// '&:focus,&:hover,&:active': { backgroundColor: '$accent4', borderColor: '$accent8' },
},
},
{
variant: 'text',
tone: 'accent',
css: {
color: '$accent11',
'&:focus,&:hover,&:active': { backgroundColor: '$accent3' },
},
},
// Neutral
{
variant: 'contained',
tone: 'neutral',
css: {
color: '$neutral2',
backgroundColor: '$neutral12',
borderColor: '$neutral12',
},
},
{
variant: 'outline',
tone: 'neutral',
css: {
color: '$neutral11',
borderColor: '$neutral8',
},
},
{
variant: 'text',
tone: 'neutral',
css: {
color: '$neutral11',
'&:focus,&:hover,&:active': { backgroundColor: '$neutral4' },
},
},
// Caution
{
variant: 'contained',
tone: 'caution',
css: {
color: '$caution11',
backgroundColor: '$caution9',
borderColor: '$caution10',
'.dark &': {
color: '$caution2',
},
},
},
{
variant: 'outline',
tone: 'caution',
css: {
color: '$caution11',
borderColor: '$caution8',
},
},
{
variant: 'text',
tone: 'caution',
css: {
color: '$caution11',
'&:focus,&:hover,&:active': { backgroundColor: '$caution3' },
},
},
// Critical
{
variant: 'contained',
tone: 'critical',
css: {
color: '$critical2',
backgroundColor: '$critical9',
borderColor: '$critical10',
'.dark &': {
borderColor: '$critical9',
},
},
},
{
variant: 'outline',
tone: 'critical',
css: {
color: '$critical11',
borderColor: '$critical9',
},
},
{
variant: 'text',
tone: 'critical',
css: {
color: '$critical11',
'&:focus,&:hover,&:active': { backgroundColor: '$critical3' },
},
},
],
});
const Ripple = styled('span', {
position: 'absolute',
square: '100%',
overflow: 'clip',
borderRadius: '$md',
top: 0,
left: 0,
boxSizing: 'content-box',
pointerEvents: 'none',
zIndex: 0,
$$bgColor: 'rgba(0,0,0,.2)',
$$bgColorDark: 'rgba(255,255,255,.2)',
'&::after': {
content: `""`,
position: 'absolute',
borderRadius: '50%',
opacity: 0,
backgroundColor: '$$bgColor',
top: 0,
left: 0,
transformOrigin: 'center center',
square: 'var(--ripple-size, 100%)',
transition: 'opacity 75ms linear',
// willChange: 'transform,opacity',
// transform: 'scale(1)',
animation: `${fgOpacityOut} ${DEACTIVATION_MS}ms`,
transform: 'translate(var(--ripple-translate-end, 0)) scale(var(--ripple-scale, 1))',
},
'&.pressed::after': {
animation: `${fgRadiusIn} ${RIPPLE_DURATION_MS}ms forwards,${fgOpacityIn} 75ms forwards`,
},
variants: {
size: {
xs: {},
sm: {},
base: {},
lg: {},
xl: {},
},
tone: {
accent: {},
neutral: {},
// positive: {},
// info: {},
caution: {},
critical: {},
},
variant: {
contained: {},
outline: {},
text: {},
},
rounding: {
normal: {},
icon: {
borderRadius: '$full',
},
},
},
compoundVariants: [
{ rounding: 'normal', size: 'xs', css: { borderRadius: '$rounded' } },
// Primary
{ variant: 'outline', tone: 'accent', css: { $$bgColor: '$colors$accent5' } },
{ variant: 'text', tone: 'accent', css: { $$bgColor: '$colors$accent5' } },
// Neutral
{ variant: 'contained', tone: 'neutral', css: { '.light &': { $$bgColor: '$$bgColorDark' } } },
{ variant: 'outline', tone: 'neutral', css: { $$bgColor: '$colors$neutral5' } },
{ variant: 'text', tone: 'neutral', css: { $$bgColor: '$colors$neutral5' } },
// // Positive
// { variant: 'outline', tone: 'positive', css: { $$bgColor: '$colors$positive4' } },
// { variant: 'text', tone: 'positive', css: { $$bgColor: '$colors$positive4' } },
// // Info
// { variant: 'outline', tone: 'info', css: { $$bgColor: '$colors$info4' } },
// { variant: 'text', tone: 'info', css: { $$bgColor: '$colors$info4' } },
// Caution
// { variant: 'contained', tone: 'caution', css: { '.light &': { $$bgColor: '$$bgColorDark' } } },
{ variant: 'outline', tone: 'caution', css: { $$bgColor: '$colors$caution5' } },
{ variant: 'text', tone: 'caution', css: { $$bgColor: '$colors$caution5' } },
// Critical
{ variant: 'outline', tone: 'critical', css: { $$bgColor: '$colors$critical5' } },
{ variant: 'text', tone: 'critical', css: { $$bgColor: '$colors$critical5' } },
],
});
function getBoundedRadius(frame: DOMRect): number {
return Math.sqrt(Math.pow(frame.width, 2) + Math.pow(frame.height, 2)) + 10;
}
function getNormalizedEventCoords(e: React.PointerEvent, frame: DOMRect): Coordinates {
const x = window.pageXOffset;
const y = window.pageYOffset;
const documentX = x + frame.left;
const documentY = y + frame.top;
let normalizedX = e.nativeEvent.pageX - documentX;
let normalizedY = e.nativeEvent.pageY - documentY;
return { x: normalizedX, y: normalizedY };
}
function getTranslationCoordinates(
e: React.PointerEvent | React.KeyboardEvent,
frame: DOMRect,
initialSize: number
): Translation {
const halfSize = initialSize / 2;
const start: Coordinates =
e.type === 'pointerdown'
? getNormalizedEventCoords(e as React.PointerEvent, frame)
: {
x: frame.width / 2,
y: frame.height / 2,
};
// Center the element around the start point.
start.x -= halfSize;
start.y -= halfSize;
const end = {
x: frame.width / 2 - halfSize,
y: frame.height / 2 - halfSize,
};
return {
start,
end,
};
}
const ButtonLabel = styled('span', {
position: 'relative',
});
// type ButtonHTMLProps = JSX.IntrinsicElements['button'];
// type AnchorHTMLProps = JSX.IntrinsicElements['a'];
// type ButtonVariants = VariantProps<typeof ButtonCss>;
// type ButtonProps = ButtonHTMLProps & ButtonStyledVariants;
const ButtonStyled = styled('button', ButtonCss);
const AnchorStyled = styled('a', ButtonCss);
const LinkStyled = styled(Link, ButtonCss);
type ButtonStyledProps = React.ComponentProps<typeof ButtonStyled>;
type AnchorStyledProps = React.ComponentProps<typeof AnchorStyled>;
type LinkStyledProps = React.ComponentProps<typeof LinkStyled>;
function initTransition(
e: React.PointerEvent | React.KeyboardEvent,
element: HTMLElement,
rounding?: ButtonStyledProps['rounding']
) {
const isUnbounded = rounding === 'icon';
const frame = element.getBoundingClientRect();
const maxDim = Math.max(frame.height, frame.width);
const maxRadius = isUnbounded ? maxDim : getBoundedRadius(frame);
// Ripple is sized as a fraction of the largest dimension of the surface, then scales up using a CSS scale transform
let initialSize = Math.floor(maxDim * INITIAL_ORIGIN_SCALE);
// Unbounded ripple size should always be even number to equally center align.
if (isUnbounded && initialSize % 2 !== 0) {
initialSize -= 1;
}
const { start, end } = getTranslationCoordinates(e, frame, initialSize);
const translateStart = `${start.x}px, ${start.y}px`;
const translateEnd = `${end.x}px, ${end.y}px`;
// Update Custom Properties
element.style.setProperty('--ripple-size', `${initialSize}px`);
element.style.setProperty('--ripple-scale', (maxRadius / initialSize).toString(10));
element.style.setProperty('--ripple-translate-start', translateStart);
element.style.setProperty('--ripple-translate-end', translateEnd);
}
function useMaterialButton(
ref: React.RefObject<HTMLButtonElement | HTMLAnchorElement>,
rippleRef: React.RefObject<HTMLSpanElement>,
rounding: ButtonStyledProps['rounding'],
props: any
) {
// Use timeout to allow for the ripple animation to complete even when we release the button
const animationTimeout = useRef(0);
// Keep a reference to the current state so we can read it in our timeout handler
const currentState = useRef(ButtonState.Idle);
// Simple state machine, we initially use the Idle state to avoid unecessary DOM mutations
const [state, setState] = useState<ButtonState>(ButtonState.Idle);
const { onKeyDown, onKeyUp, onPointerDown, onPointerUp, onClick, ...otherProps } = props;
useEffect(() => {
function activate() {
if (rippleRef.current !== null) {
// Adding the class fires the ripple animation
rippleRef.current.classList.add('pressed');
animationTimeout.current = window.setTimeout(reset, RIPPLE_DURATION_MS);
}
}
function deactivate() {
if (rippleRef.current !== null) {
// Removing the class fires the fade-out animation
rippleRef.current.classList.remove('pressed');
}
}
function reset() {
clearTimeout(animationTimeout.current);
animationTimeout.current = 0;
// If we released the button during the animation
// we should now revert the pressed state on the DOM
// ! Warning: we do not always call deactivate because we may hold the pointerdown,
// in this case the .pressed class should be preserved on the button
if (currentState.current === ButtonState.Released) {
deactivate();
}
}
currentState.current = state;
switch (state) {
case ButtonState.Pressed: {
if (animationTimeout.current) {
reset();
deactivate();
requestAnimationFrame(activate);
} else {
activate();
}
break;
}
case ButtonState.Released: {
if (animationTimeout.current === 0) {
deactivate();
}
break;
}
}
}, [state, rippleRef]);
const eventHandlers = useMemo(
() => ({
onPointerDown: (e: React.PointerEvent<HTMLButtonElement>) => {
if (ref.current === null) {
return;
}
if (onPointerDown) {
onPointerDown.call(ref.current, e);
}
e.currentTarget.setPointerCapture(e.nativeEvent.pointerId);
initTransition(e, ref.current, rounding);
setState(ButtonState.Pressed);
},
// onPointerUp: (e: React.SyntheticEvent<HTMLButtonElement, PointerEvent>) => {
onPointerUp: (e: React.PointerEvent<HTMLButtonElement>) => {
if (ref.current === null) {
return;
}
if (onPointerUp) {
onPointerUp.call(ref.current, e);
}
e.currentTarget.releasePointerCapture(e.nativeEvent.pointerId);
setState(ButtonState.Released);
},
onClick: (e: React.MouseEvent<HTMLButtonElement>) => {
// Because we've enabled pointer capturing, click is always fired
// Make sure pointer is released inside Button's bounding box, otherwise abort click
const { detail, clientX, clientY } = e.nativeEvent;
// Detail will be 0 if we pressed Enter key, use this to distinguish between pointer and simulated clicks (see onKeyUp)
if (detail > 0) {
const { x, y, width, height } = e.currentTarget.getBoundingClientRect();
if (clientX < x || clientX > x + width || clientY < y || clientY > y + height) {
e.preventDefault();
e.stopPropagation();
return false;
}
}
if (onClick && ref.current !== null) {
onClick.call(ref.current, e);
}
},
onKeyDown: (e: React.KeyboardEvent<HTMLButtonElement>) => {
if (ref.current === null) {
return;
}
if (onKeyDown) {
onKeyDown.call(ref.current, e);
}
if (e.nativeEvent.key === 'Enter' || e.nativeEvent.key === ' ') {
e.preventDefault();
// Check if we are in a Pressed state already to avoid key repeat
// TODO: This behavior should be customizable
if (currentState.current !== ButtonState.Pressed) {
initTransition(e, ref.current, rounding);
ref.current.classList.add('pressed');
setState(ButtonState.Pressed);
}
}
},
onKeyUp: (e: React.KeyboardEvent<HTMLButtonElement>) => {
if (ref.current === null) {
return;
}
if (onKeyUp) {
onKeyUp.call(ref.current, e);
}
if (currentState.current !== ButtonState.Released) {
if (e.nativeEvent.key === 'Enter' || e.nativeEvent.key === ' ') {
ref.current.classList.remove('pressed');
setState(ButtonState.Released);
ref.current.click();
}
}
},
}),
[ref, onPointerDown, onPointerUp, onKeyDown, onKeyUp, onClick, rounding]
);
return [eventHandlers, otherProps];
}
export const Button = forwardRef<HTMLButtonElement, ButtonStyledProps>(
(
{ variant = 'contained', tone = 'neutral', size = 'base', rounding = 'normal', children, ...rest },
forwardedRef
) => {
const ref = useShareForwardedRef<HTMLButtonElement>(forwardedRef);
const rippleRef = useRef<HTMLSpanElement>(null);
const [eventHandlers, otherProps] = useMaterialButton(ref, rippleRef, rounding, rest);
if (rest.type === undefined) {
rest.type = 'button';
}
return (
<ButtonStyled
ref={ref}
className={ButtonCss({ size, variant, tone, rounding })}
{...eventHandlers}
{...otherProps}
>
<Ripple ref={rippleRef} size={size} variant={variant} tone={tone} rounding={rounding} />
<ButtonLabel>{children}</ButtonLabel>
</ButtonStyled>
);
}
);
export const AnchorButton = forwardRef<HTMLAnchorElement, AnchorStyledProps>(
(
{ variant = 'contained', tone = 'neutral', size = 'base', rounding = 'normal', children, ...rest },
forwardedRef
) => {
const ref = useShareForwardedRef<HTMLAnchorElement>(forwardedRef);
const rippleRef = useRef<HTMLSpanElement>(null);
const [eventHandlers, otherProps] = useMaterialButton(ref, rippleRef, rounding, rest);
return (
<AnchorStyled
ref={ref}
className={ButtonCss({ size, variant, tone, rounding })}
draggable="false"
{...eventHandlers}
{...otherProps}
>
<Ripple ref={rippleRef} size={size} variant={variant} tone={tone} rounding={rounding} />
<ButtonLabel>{children}</ButtonLabel>
</AnchorStyled>
);
}
);
export const LinkButton = forwardRef<HTMLAnchorElement, LinkStyledProps>(
(
{ variant = 'contained', tone = 'neutral', size = 'base', rounding = 'normal', children, ...rest },
forwardedRef
) => {
const ref = useShareForwardedRef<HTMLAnchorElement>(forwardedRef);
const rippleRef = useRef<HTMLSpanElement>(null);
const [eventHandlers, otherProps] = useMaterialButton(ref, rippleRef, rounding, rest);
return (
<LinkStyled
ref={ref}
className={ButtonCss({ size, variant, tone, rounding })}
draggable="false"
{...eventHandlers}
{...otherProps}
>
<Ripple ref={rippleRef} size={size} variant={variant} tone={tone} rounding={rounding} />
<ButtonLabel>{children}</ButtonLabel>
</LinkStyled>
);
}
); | the_stack |
import React from 'react'
// fontawesome icons in svg format: https://github.com/Rush/Font-Awesome-SVG-PNG
// https://github.com/feathericons/feather
type WrapperProps = {
onClick?: (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;
color?: string;
hoverColor?: string;
width?: number;
height?: number;
iconname: string;
tooltip?: string | undefined;
}
type IconProps = {
getMouseOver?: boolean;
color?: string;
hoverColor?: string;
width?: number;
height?: number;
}
export const Icon: React.FC<WrapperProps> = ({
onClick = () => {
},
color = "#c4c4c4",
hoverColor = "#00ff00",
width = 20,
height = 20,
tooltip = undefined,
...props
}) => {
const [getMouseOver, setMouseOver] = React.useState(false)
const iconProps = {width, height, hoverColor, color, getMouseOver}
return (
<div
title={tooltip}
onClick={onClick}
onMouseOver={() => setMouseOver(true)}
onMouseLeave={() => setMouseOver(false)}
>
{(props.iconname === "IconQuestionmark") && <IconQuestionmark {...iconProps}/>}
{(props.iconname === "IconUpload") && <IconUpload {...iconProps}/>}
{(props.iconname === "IconCopy") && <IconCopy {...iconProps}/>}
{(props.iconname === "IconRename") && <IconRename {...iconProps}/>}
{(props.iconname === "IconDelete") && <IconDelete {...iconProps}/>}
{(props.iconname === "IconNewfile") && <IconNewfile {...iconProps}/>}
{(props.iconname === "IconNewfolder") && <IconNewfolder {...iconProps}/>}
{(props.iconname === "IconClosedDirectory") && <IconClosedDirectory {...iconProps}/>}
{(props.iconname === "IconOpenDirectory") && <IconOpenDirectory {...iconProps}/>}
{(props.iconname === "IconJs") && <IconJs {...iconProps}/>}
{(props.iconname === "IconCss") && <IconCss {...iconProps}/>}
{(props.iconname === "IconJson") && <IconJson {...iconProps}/>}
{(props.iconname === "IconHtml") && <IconHtml {...iconProps}/>}
{(props.iconname === "IconFile") && <IconFile {...iconProps}/>}
</div>
)
}
export const IconDelete = (props: IconProps) => (
<svg width={props.width} height={props.height} viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg">
<path
d="M1277 1122q0-26-19-45l-181-181 181-181q19-19 19-45 0-27-19-46l-90-90q-19-19-46-19-26 0-45 19l-181 181-181-181q-19-19-45-19-27 0-46 19l-90 90q-19 19-19 46 0 26 19 45l181 181-181 181q-19 19-19 45 0 27 19 46l90 90q19 19 46 19 26 0 45-19l181-181 181 181q19 19 45 19 27 0 46-19l90-90q19-19 19-46zm387-226q0 209-103 385.5t-279.5 279.5-385.5 103-385.5-103-279.5-279.5-103-385.5 103-385.5 279.5-279.5 385.5-103 385.5 103 279.5 279.5 103 385.5z"
fill={(props.getMouseOver) ? props.hoverColor : props.color}
/>
</svg>
)
export const IconRename = (props: IconProps) => (
<svg width={props.width} height={props.height} viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg">
<path
d="M491 1536l91-91-235-235-91 91v107h128v128h107zm523-928q0-22-22-22-10 0-17 7l-542 542q-7 7-7 17 0 22 22 22 10 0 17-7l542-542q7-7 7-17zm-54-192l416 416-832 832h-416v-416zm683 96q0 53-37 90l-166 166-416-416 166-165q36-38 90-38 53 0 91 38l235 234q37 39 37 91z"
fill={(props.getMouseOver) ? props.hoverColor : props.color}
/>
</svg>
)
// source: https://raw.githubusercontent.com/feathericons/feather/master/icons/file-plus.svg
export const IconNewfile = (props: IconProps) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width={props.width}
height={props.height}
viewBox="0 0 24 24"
fill="none"
stroke={(props.getMouseOver) ? props.hoverColor : props.color}
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
<polyline points="14 2 14 8 20 8"/>
<line x1="12" y1="18" x2="12" y2="12"/>
<line x1="9" y1="15" x2="15" y2="15"/>
</svg>
)
// source: https://raw.githubusercontent.com/feathericons/feather/master/icons/folder-plus.svg
export const IconNewfolder = (props: IconProps) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width={props.width}
height={props.height}
viewBox="0 0 24 24"
fill="none"
stroke={(props.getMouseOver) ? props.hoverColor : props.color}
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>
<line x1="12" y1="11" x2="12" y2="17"/>
<line x1="9" y1="14" x2="15" y2="14"/>
</svg>
)
export const IconQuestionmark = (props: IconProps) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width={props.width}
height={props.height}
viewBox="0 0 5000 5000"
fill="none"
stroke={(props.getMouseOver) ? props.hoverColor : props.color}
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<circle cx="2500" cy="2500" r="2500" fill={(props.getMouseOver) ? props.hoverColor : props.color}/>
<g id="f67e395f-30cf-4d34-b795-7406cd3cb388" data-name="Icon">
<path
d="M2536.78,647C1796.08,647,1318,1140.77,1234,1855.2l725,105.06c21-309.93,141.82-661.9,514.81-661.9,262.65,0,436,162.86,436,425.51,0,236.39-120.83,357.2-299.43,488.54-457,336.2-472.79,409.76-472.79,971.85v99.81h677.66c-10.5-373,78.79-425.51,367.72-614.63C3519.11,2448.8,3766,2144.13,3766,1723.87,3766,1035.71,3177.66,647,2536.78,647ZM2092.77,4253h774V3463.15h-774Z"
fill="#000000"/>
</g>
</svg>
)
// source: https://raw.githubusercontent.com/feathericons/feather/master/icons/upload.svg
export const IconUpload = (props: IconProps) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width={props.width}
height={props.height}
viewBox="0 0 24 24"
fill="none"
stroke={(props.getMouseOver) ? props.hoverColor : props.color}
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
<polyline points="17 8 12 3 7 8"/>
<line x1="12" y1="3" x2="12" y2="15"/>
</svg>
)
// source: https://raw.githubusercontent.com/feathericons/feather/master/icons/copy.svg
export const IconCopy = (props: IconProps) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width={props.width}
height={props.height}
viewBox="0 0 24 24"
fill="none"
stroke={(props.getMouseOver) ? props.hoverColor : props.color}
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
</svg>
)
export const IconClosedDirectory = (props: IconProps) => (
<svg
width="32"
height="32"
viewBox="0 0 32 32"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M15.6674 9.70666L15.8096 9.83333H16H26C26.2761 9.83333 26.5 10.0572 26.5 10.3333V25C26.5 25.2761 26.2761 25.5 26 25.5H6C5.72386 25.5 5.5 25.2761 5.5 25V8C5.5 7.72386 5.72386 7.5 6 7.5H13.0001C13.1228 7.5 13.2411 7.54508 13.3327 7.62667L15.6674 9.70666Z"
fill="#64D2FF"
stroke="#64D2FF"
/>
</svg>
)
export const IconOpenDirectory = (props: IconProps) => (
<svg
width="32"
height="32"
viewBox="0 0 32 32"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M15.6674 9.70666L15.8096 9.83333H16H26C26.2761 9.83333 26.5 10.0572 26.5 10.3333V25C26.5 25.2761 26.2761 25.5 26 25.5H6C5.72386 25.5 5.5 25.2761 5.5 25V8C5.5 7.72386 5.72386 7.5 6 7.5H13.0001C13.1228 7.5 13.2411 7.54508 13.3327 7.62667L15.6674 9.70666Z"
fill="transparent"
stroke="#64D2FF"
/>
</svg>
)
export const IconJs = (props: IconProps) => (
<svg
width="24"
height="24"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="m3 3h18v18h-18v-18m4.73 15.04c.4.85 1.19 1.55 2.54 1.55 1.5 0 2.53-.8 2.53-2.55v-5.78h-1.7v5.74c0 .86-.35 1.08-.9 1.08-.58 0-.82-.4-1.09-.87l-1.38.83m5.98-.18c.5.98 1.51 1.73 3.09 1.73 1.6 0 2.8-.83 2.8-2.36 0-1.41-.81-2.04-2.25-2.66l-.42-.18c-.73-.31-1.04-.52-1.04-1.02 0-.41.31-.73.81-.73.48 0 .8.21 1.09.73l1.31-.87c-.55-.96-1.33-1.33-2.4-1.33-1.51 0-2.48.96-2.48 2.23 0 1.38.81 2.03 2.03 2.55l.42.18c.78.34 1.24.55 1.24 1.13 0 .48-.45.83-1.15.83-.83 0-1.31-.43-1.67-1.03l-1.38.8z"
fill="#ffca28"
/>
</svg>
)
export const IconCss = (props: IconProps) => (
<svg
width="24"
height="24"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="m5 3l-.65 3.34h13.59l-.44 2.16h-13.58l-.66 3.33h13.59l-.76 3.81-5.48 1.81-4.75-1.81.33-1.64h-3.34l-.79 4 7.85 3 9.05-3 1.2-6.03.24-1.21 1.54-7.76h-16.94z"
fill="#42a5f5"
/>
</svg>
)
export const IconJson = (props: IconProps) => (
<svg
width="24"
height="24"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="m5 3h2v2h-2v5a2 2 0 0 1 -2 2 2 2 0 0 1 2 2v5h2v2h-2c-1.07-.27-2-.9-2-2v-4a2 2 0 0 0 -2 -2h-1v-2h1a2 2 0 0 0 2 -2v-4a2 2 0 0 1 2 -2m14 0a2 2 0 0 1 2 2v4a2 2 0 0 0 2 2h1v2h-1a2 2 0 0 0 -2 2v4a2 2 0 0 1 -2 2h-2v-2h2v-5a2 2 0 0 1 2 -2 2 2 0 0 1 -2 -2v-5h-2v-2h2m-7 12a1 1 0 0 1 1 1 1 1 0 0 1 -1 1 1 1 0 0 1 -1 -1 1 1 0 0 1 1 -1m-4 0a1 1 0 0 1 1 1 1 1 0 0 1 -1 1 1 1 0 0 1 -1 -1 1 1 0 0 1 1 -1m8 0a1 1 0 0 1 1 1 1 1 0 0 1 -1 1 1 1 0 0 1 -1 -1 1 1 0 0 1 1 -1z"
fill="#fbc02d"
/>
</svg>
)
export const IconHtml = (props: IconProps) => (
<svg
width="24"
height="24"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="m12 17.56l4.07-1.13.55-6.1h-7.24l-.18-2.03h7.6l.2-1.99h-10l.56 6.01h6.89l-.23 2.58-2.22.6-2.22-.6-.14-1.66h-2l.29 3.19 4.07 1.13m-7.93-14.56h15.86l-1.43 16.2-6.5 1.8-6.5-1.8-1.43-16.2z"
fill="#e44d26"
/>
</svg>
)
export const IconFile = (props: IconProps) => (
<svg
width="32"
height="32"
viewBox="0 0 32 32"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<mask id="path-1-inside-1">
<path
d="M16.5689 5H9C8.44772 5 8 5.44772 8 6V26C8 26.5523 8.44772 27 9 27H23C23.5523 27 24 26.5523 24 26V12.1587L16.5689 5ZM16 6L23 13H16V6Z"/>
</mask>
<path
d="M16.5689 5H9C8.44772 5 8 5.44772 8 6V26C8 26.5523 8.44772 27 9 27H23C23.5523 27 24 26.5523 24 26V12.1587L16.5689 5ZM16 6L23 13H16V6Z"
fill="#eee"
/>
<path
d="M16.0689 5V6.56889H17.0689V5H16.0689ZM22.1587 12.6587H24V11.6587H22.1587V12.6587ZM16.5689 5L17.2627 4.27982L16.9722 4H16.5689V5ZM24 12.1587H25V11.7335L24.6938 11.4385L24 12.1587ZM23 13V14H25.4142L23.7071 12.2929L23 13ZM16 6L16.7071 5.29289L15 3.58579V6H16ZM16 13H15V14H16V13ZM9 6H16.5689V4H9V6ZM9 6L9 6V4C7.89543 4 7 4.89543 7 6H9ZM9 26V6H7V26H9ZM9 26H7C7 27.1046 7.89543 28 9 28V26ZM23 26H9V28H23V26ZM23 26V28C24.1046 28 25 27.1046 25 26H23ZM23 12.1587V26H25V12.1587H23ZM15.8751 5.72018L23.3062 12.8789L24.6938 11.4385L17.2627 4.27982L15.8751 5.72018ZM23.7071 12.2929L16.7071 5.29289L15.2929 6.70711L22.2929 13.7071L23.7071 12.2929ZM16 14H23V12H16V14ZM15 6V13H17V6H15Z"
fill="#eee"
mask="url(#path-1-inside-1)"
/>
</svg>
) | the_stack |
module uk.co.senab.photoview {
import Canvas = android.graphics.Canvas;
import Matrix = android.graphics.Matrix;
import ScaleToFit = android.graphics.Matrix.ScaleToFit;
import RectF = android.graphics.RectF;
import Drawable = android.graphics.drawable.Drawable;
import Log = android.util.Log;
import View = android.view.View;
import OnLongClickListener = android.view.View.OnLongClickListener;
import ViewParent = android.view.ViewParent;
import ViewTreeObserver = android.view.ViewTreeObserver;
import AccelerateDecelerateInterpolator = android.view.animation.AccelerateDecelerateInterpolator;
import Interpolator = android.view.animation.Interpolator;
import ImageView = android.widget.ImageView;
import ScaleType = android.widget.ImageView.ScaleType;
import OverScroller = android.widget.OverScroller;
import WeakReference = java.lang.ref.WeakReference;
import MotionEvent = android.view.MotionEvent;
const ACTION_CANCEL = MotionEvent.ACTION_CANCEL;
const ACTION_DOWN = MotionEvent.ACTION_DOWN;
const ACTION_UP = MotionEvent.ACTION_UP;
import Runnable = java.lang.Runnable;
import System = java.lang.System;
import GestureDetector = uk.co.senab.photoview.GestureDetector;
import IPhotoView = uk.co.senab.photoview.IPhotoView;
import PhotoView = uk.co.senab.photoview.PhotoView;
export class PhotoViewAttacher implements IPhotoView, View.OnTouchListener, GestureDetector.OnGestureListener, ViewTreeObserver.OnGlobalLayoutListener {
private static LOG_TAG:string = "PhotoViewAttacher";
// let debug flag be dynamic, but still Proguard can be used to remove from
// release builds
private static DEBUG:boolean = Log.View_DBG;
static sInterpolator:Interpolator = new AccelerateDecelerateInterpolator();
ZOOM_DURATION:number = IPhotoView.DEFAULT_ZOOM_DURATION;
static EDGE_NONE:number = -1;
static EDGE_LEFT:number = 0;
static EDGE_RIGHT:number = 1;
static EDGE_BOTH:number = 2;
private mMinScale:number = IPhotoView.DEFAULT_MIN_SCALE;
private mMidScale:number = IPhotoView.DEFAULT_MID_SCALE;
private mMaxScale:number = IPhotoView.DEFAULT_MAX_SCALE;
private mAllowParentInterceptOnEdge:boolean = true;
private mBlockParentIntercept:boolean = false;
private static checkZoomLevels(minZoom:number, midZoom:number, maxZoom:number):void {
if (minZoom >= midZoom) {
throw Error(`new IllegalArgumentException("MinZoom has to be less than MidZoom")`);
} else if (midZoom >= maxZoom) {
throw Error(`new IllegalArgumentException("MidZoom has to be less than MaxZoom")`);
}
}
/**
* @return true if the ImageView exists, and it's Drawable existss
*/
private static hasDrawable(imageView:ImageView):boolean {
return null != imageView && null != imageView.getDrawable();
}
/**
* @return true if the ScaleType is supported.
*/
private static isSupportedScaleType(scaleType:ScaleType):boolean {
if (null == scaleType) {
return false;
}
switch (scaleType) {
case ScaleType.MATRIX:
throw Error(`new IllegalArgumentException(ScaleType.MATRIX is not supported in PhotoView)`);
default:
return true;
}
}
/**
* Set's the ImageView's ScaleType to Matrix.
*/
private static setImageViewScaleTypeMatrix(imageView:ImageView):void {
/**
* PhotoView sets it's own ScaleType to Matrix, then diverts all calls
* setScaleType to this.setScaleType automatically.
*/
if (null != imageView && !(IPhotoView.isImpl(imageView))) {
if (ScaleType.MATRIX != (imageView.getScaleType())) {
imageView.setScaleType(ScaleType.MATRIX);
}
}
}
private mImageView:WeakReference<ImageView>;
// Gesture Detectors
private mGestureDetector:android.view.GestureDetector;
private mScaleDragDetector:GestureDetector;
// These are set so we don't keep allocating them on the heap
private mBaseMatrix:Matrix = new Matrix();
private mDrawMatrix:Matrix = new Matrix();
private mSuppMatrix:Matrix = new Matrix();
private mDisplayRect:RectF = new RectF();
private mMatrixValues:number[] = androidui.util.ArrayCreator.newNumberArray(9);
// Listeners
private mMatrixChangeListener:PhotoViewAttacher.OnMatrixChangedListener;
private mPhotoTapListener:PhotoViewAttacher.OnPhotoTapListener;
private mViewTapListener:PhotoViewAttacher.OnViewTapListener;
private mLongClickListener:OnLongClickListener;
private mScaleChangeListener:PhotoViewAttacher.OnScaleChangeListener;
private mIvTop:number = 0;
private mIvRight:number = 0;
private mIvBottom:number = 0;
private mIvLeft:number = 0;
private mCurrentFlingRunnable:PhotoViewAttacher.FlingRunnable;
private mScrollEdge:number = PhotoViewAttacher.EDGE_BOTH;
private mZoomEnabled:boolean;
private mScaleType:ScaleType = ScaleType.FIT_CENTER;
constructor(imageView:ImageView, zoomable = true) {
this.mImageView = new WeakReference(imageView);
//imageView.setDrawingCacheEnabled(true);
imageView.setOnTouchListener(this);
let observer:ViewTreeObserver = imageView.getViewTreeObserver();
if (null != observer)
observer.addOnGlobalLayoutListener(this);
// Make sure we using MATRIX Scale Type
PhotoViewAttacher.setImageViewScaleTypeMatrix(imageView);
//if (imageView.isInEditMode()) {
// return;
//}
// Create Gesture Detectors...
this.mScaleDragDetector = new GestureDetector();
this.mScaleDragDetector.setOnGestureListener(this);
this.mGestureDetector = new android.view.GestureDetector((()=> {
const inner_this = this;
class _Inner extends android.view.GestureDetector.SimpleOnGestureListener {
// forward long click listener
onLongPress(e:MotionEvent):void {
if (null != inner_this.mLongClickListener) {
inner_this.mLongClickListener.onLongClick(inner_this.getImageView());
}
}
}
return new _Inner();
})());
this.mGestureDetector.setOnDoubleTapListener(new PhotoViewAttacher.DefaultOnDoubleTapListener(this));
// Finally, update the UI so that we're zoomable
this.setZoomable(zoomable);
}
setOnDoubleTapListener(newOnDoubleTapListener:android.view.GestureDetector.OnDoubleTapListener):void {
if (newOnDoubleTapListener != null) {
this.mGestureDetector.setOnDoubleTapListener(newOnDoubleTapListener);
} else {
this.mGestureDetector.setOnDoubleTapListener(new PhotoViewAttacher.DefaultOnDoubleTapListener(this));
}
}
setOnScaleChangeListener(onScaleChangeListener:PhotoViewAttacher.OnScaleChangeListener):void {
this.mScaleChangeListener = onScaleChangeListener;
}
canZoom():boolean {
return this.mZoomEnabled;
}
/**
* Clean-up the resources attached to this object. This needs to be called when the ImageView is
* no longer used. A good example is from {@link View#onDetachedFromWindow()} or
* from {@link android.app.Activity#onDestroy()}. This is automatically called if you are using
* {@link uk.co.senab.photoview.PhotoView}.
*/
cleanup():void {
if (null == this.mImageView) {
// cleanup already done
return;
}
const imageView:ImageView = this.mImageView.get();
if (null != imageView) {
// Remove this as a global layout listener
let observer:ViewTreeObserver = imageView.getViewTreeObserver();
if (null != observer && observer.isAlive()) {
observer.removeGlobalOnLayoutListener(this);
}
// Remove the ImageView's reference to this
imageView.setOnTouchListener(null);
// make sure a pending fling runnable won't be run
this.cancelFling();
}
if (null != this.mGestureDetector) {
this.mGestureDetector.setOnDoubleTapListener(null);
}
// Clear listeners too
this.mMatrixChangeListener = null;
this.mPhotoTapListener = null;
this.mViewTapListener = null;
// Finally, clear ImageView
this.mImageView = null;
}
getDisplayRect():RectF {
this.checkMatrixBounds();
return this._getDisplayRect(this.getDrawMatrix());
}
setDisplayMatrix(finalMatrix:Matrix):boolean {
if (finalMatrix == null)
throw Error(`new IllegalArgumentException("Matrix cannot be null")`);
let imageView:ImageView = this.getImageView();
if (null == imageView)
return false;
if (null == imageView.getDrawable())
return false;
this.mSuppMatrix.set(finalMatrix);
this.setImageViewMatrix(this.getDrawMatrix());
this.checkMatrixBounds();
return true;
}
/**
* @deprecated use {@link #setRotationTo(float)}
*/
setPhotoViewRotation(degrees:number):void {
this.mSuppMatrix.setRotate(degrees % 360);
this.checkAndDisplayMatrix();
}
setRotationTo(degrees:number):void {
this.mSuppMatrix.setRotate(degrees % 360);
this.checkAndDisplayMatrix();
}
setRotationBy(degrees:number):void {
this.mSuppMatrix.postRotate(degrees % 360);
this.checkAndDisplayMatrix();
}
getImageView():ImageView {
let imageView:ImageView = null;
if (null != this.mImageView) {
imageView = this.mImageView.get();
}
// If we don't have an ImageView, call cleanup()
if (null == imageView) {
this.cleanup();
if (PhotoViewAttacher.DEBUG)
Log.i(PhotoViewAttacher.LOG_TAG, "ImageView no longer exists. You should not use this PhotoViewAttacher any more.");
}
return imageView;
}
getMinScale():number {
return this.getMinimumScale();
}
getMinimumScale():number {
return this.mMinScale;
}
getMidScale():number {
return this.getMediumScale();
}
getMediumScale():number {
return this.mMidScale;
}
getMaxScale():number {
return this.getMaximumScale();
}
getMaximumScale():number {
return this.mMaxScale;
}
getScale():number {
return <number> Math.sqrt(<number> Math.pow(this.getValue(this.mSuppMatrix, Matrix.MSCALE_X), 2) + <number> Math.pow(this.getValue(this.mSuppMatrix, Matrix.MSKEW_Y), 2));
}
getScaleType():ScaleType {
return this.mScaleType;
}
onDrag(dx:number, dy:number):void {
if (this.mScaleDragDetector.isScaling()) {
// Do not drag if we are already scaling
return;
}
if (PhotoViewAttacher.DEBUG) {
Log.d(PhotoViewAttacher.LOG_TAG, `onDrag: dx: ${dx.toFixed(2)}. dy: ${dy.toFixed(2)}`);
}
let imageView:ImageView = this.getImageView();
this.mSuppMatrix.postTranslate(dx, dy);
this.checkAndDisplayMatrix();
/**
* Here we decide whether to let the ImageView's parent to start taking
* over the touch event.
*
* First we check whether this function is enabled. We never want the
* parent to take over if we're scaling. We then check the edge we're
* on, and the direction of the scroll (i.e. if we're pulling against
* the edge, aka 'overscrolling', let the parent take over).
*/
let parent:ViewParent = imageView.getParent();
if (this.mAllowParentInterceptOnEdge && !this.mScaleDragDetector.isScaling() && !this.mBlockParentIntercept) {
if (this.mScrollEdge == PhotoViewAttacher.EDGE_BOTH || (this.mScrollEdge == PhotoViewAttacher.EDGE_LEFT && dx >= 1) || (this.mScrollEdge == PhotoViewAttacher.EDGE_RIGHT && dx <= -1)) {
if (null != parent)
parent.requestDisallowInterceptTouchEvent(false);
}
} else {
if (null != parent) {
parent.requestDisallowInterceptTouchEvent(true);
}
}
}
onFling(startX:number, startY:number, velocityX:number, velocityY:number):void {
if (PhotoViewAttacher.DEBUG) {
Log.d(PhotoViewAttacher.LOG_TAG, "onFling. sX: " + startX + " sY: " + startY + " Vx: " + velocityX + " Vy: " + velocityY);
}
let imageView:ImageView = this.getImageView();
this.mCurrentFlingRunnable = new PhotoViewAttacher.FlingRunnable(this);
this.mCurrentFlingRunnable.fling(this.getImageViewWidth(imageView), this.getImageViewHeight(imageView), Math.floor(velocityX), Math.floor(velocityY));
imageView.post(this.mCurrentFlingRunnable);
}
onGlobalLayout():void {
let imageView:ImageView = this.getImageView();
if (null != imageView) {
if (this.mZoomEnabled) {
const top:number = imageView.getTop();
const right:number = imageView.getRight();
const bottom:number = imageView.getBottom();
const left:number = imageView.getLeft();
/**
* We need to check whether the ImageView's bounds have changed.
* This would be easier if we targeted API 11+ as we could just use
* View.OnLayoutChangeListener. Instead we have to replicate the
* work, keeping track of the ImageView's bounds and then checking
* if the values change.
*/
if (top != this.mIvTop || bottom != this.mIvBottom || left != this.mIvLeft || right != this.mIvRight) {
// Update our base matrix, as the bounds have changed
this.updateBaseMatrix(imageView.getDrawable());
// Update values as something has changed
this.mIvTop = top;
this.mIvRight = right;
this.mIvBottom = bottom;
this.mIvLeft = left;
}
} else {
this.updateBaseMatrix(imageView.getDrawable());
}
}
}
onScale(scaleFactor:number, focusX:number, focusY:number):void {
if (PhotoViewAttacher.DEBUG) {
Log.d(PhotoViewAttacher.LOG_TAG, `onScale: scale: ${scaleFactor.toFixed(2)}. fX: ${focusX.toFixed(2)}. fY: ${focusY.toFixed(2)}f`);
}
if (this.getScale() < this.mMaxScale || scaleFactor < 1) {
if (null != this.mScaleChangeListener) {
this.mScaleChangeListener.onScaleChange(scaleFactor, focusX, focusY);
}
this.mSuppMatrix.postScale(scaleFactor, scaleFactor, focusX, focusY);
this.checkAndDisplayMatrix();
}
}
onTouch(v:View, ev:MotionEvent):boolean {
let handled:boolean = false;
if (this.mZoomEnabled && PhotoViewAttacher.hasDrawable(<ImageView> v)) {
let parent:ViewParent = v.getParent();
switch (ev.getAction()) {
case ACTION_DOWN:
// event
if (null != parent) {
parent.requestDisallowInterceptTouchEvent(true);
} else {
Log.i(PhotoViewAttacher.LOG_TAG, "onTouch getParent() returned null");
}
// If we're flinging, and the user presses down, cancel
// fling
this.cancelFling();
break;
case ACTION_CANCEL:
case ACTION_UP:
// to min scale
if (this.getScale() < this.mMinScale) {
let rect:RectF = this.getDisplayRect();
if (null != rect) {
v.post(new PhotoViewAttacher.AnimatedZoomRunnable(this, this.getScale(), this.mMinScale, rect.centerX(), rect.centerY()));
handled = true;
}
}
break;
}
// Try the Scale/Drag detector
if (null != this.mScaleDragDetector) {
let wasScaling:boolean = this.mScaleDragDetector.isScaling();
let wasDragging:boolean = this.mScaleDragDetector.isDragging();
handled = this.mScaleDragDetector.onTouchEvent(ev);
let didntScale:boolean = !wasScaling && !this.mScaleDragDetector.isScaling();
let didntDrag:boolean = !wasDragging && !this.mScaleDragDetector.isDragging();
this.mBlockParentIntercept = didntScale && didntDrag;
}
// Check to see if the user double tapped
if (null != this.mGestureDetector && this.mGestureDetector.onTouchEvent(ev)) {
handled = true;
}
}
return handled;
}
setAllowParentInterceptOnEdge(allow:boolean):void {
this.mAllowParentInterceptOnEdge = allow;
}
setMinScale(minScale:number):void {
this.setMinimumScale(minScale);
}
setMinimumScale(minimumScale:number):void {
PhotoViewAttacher.checkZoomLevels(minimumScale, this.mMidScale, this.mMaxScale);
this.mMinScale = minimumScale;
}
setMidScale(midScale:number):void {
this.setMediumScale(midScale);
}
setMediumScale(mediumScale:number):void {
PhotoViewAttacher.checkZoomLevels(this.mMinScale, mediumScale, this.mMaxScale);
this.mMidScale = mediumScale;
}
setMaxScale(maxScale:number):void {
this.setMaximumScale(maxScale);
}
setMaximumScale(maximumScale:number):void {
PhotoViewAttacher.checkZoomLevels(this.mMinScale, this.mMidScale, maximumScale);
this.mMaxScale = maximumScale;
}
setScaleLevels(minimumScale:number, mediumScale:number, maximumScale:number):void {
PhotoViewAttacher.checkZoomLevels(minimumScale, mediumScale, maximumScale);
this.mMinScale = minimumScale;
this.mMidScale = mediumScale;
this.mMaxScale = maximumScale;
}
setOnLongClickListener(listener:OnLongClickListener):void {
this.mLongClickListener = listener;
}
setOnMatrixChangeListener(listener:PhotoViewAttacher.OnMatrixChangedListener):void {
this.mMatrixChangeListener = listener;
}
setOnPhotoTapListener(listener:PhotoViewAttacher.OnPhotoTapListener):void {
this.mPhotoTapListener = listener;
}
getOnPhotoTapListener():PhotoViewAttacher.OnPhotoTapListener {
return this.mPhotoTapListener;
}
setOnViewTapListener(listener:PhotoViewAttacher.OnViewTapListener):void {
this.mViewTapListener = listener;
}
getOnViewTapListener():PhotoViewAttacher.OnViewTapListener {
return this.mViewTapListener;
}
setScale(scale:number, animate?:boolean):void;
setScale(scale:number, focalX:number, focalY:number, animate?:boolean):void;
setScale(...args):void {
if (args.length >= 3) {
(<any>this).setScale_4(...args);
} else {
(<any>this).setScale_2(...args);
}
}
private setScale_2(scale:number, animate = false):void {
let imageView:ImageView = this.getImageView();
if (null != imageView) {
this.setScale(scale, (imageView.getRight()) / 2, (imageView.getBottom()) / 2, animate);
}
}
private setScale_4(scale:number, focalX:number, focalY:number, animate = false):void {
let imageView:ImageView = this.getImageView();
if (null != imageView) {
// Check to see if the scale is within bounds
if (scale < this.mMinScale || scale > this.mMaxScale) {
Log.i(PhotoViewAttacher.LOG_TAG, "Scale must be within the range of minScale and maxScale");
return;
}
if (animate) {
imageView.post(new PhotoViewAttacher.AnimatedZoomRunnable(this, this.getScale(), scale, focalX, focalY));
} else {
this.mSuppMatrix.setScale(scale, scale, focalX, focalY);
this.checkAndDisplayMatrix();
}
}
}
setScaleType(scaleType:ScaleType):void {
if (PhotoViewAttacher.isSupportedScaleType(scaleType) && scaleType != this.mScaleType) {
this.mScaleType = scaleType;
// Finally update
this.update();
}
}
setZoomable(zoomable:boolean):void {
this.mZoomEnabled = zoomable;
this.update();
}
update():void {
let imageView:ImageView = this.getImageView();
if (null != imageView) {
if (this.mZoomEnabled) {
// Make sure we using MATRIX Scale Type
PhotoViewAttacher.setImageViewScaleTypeMatrix(imageView);
// Update the base matrix using the current drawable
this.updateBaseMatrix(imageView.getDrawable());
} else {
// Reset the Matrix...
this.resetMatrix();
}
}
}
getDisplayMatrix():Matrix {
return new Matrix(this.getDrawMatrix());
}
getDrawMatrix():Matrix {
this.mDrawMatrix.set(this.mBaseMatrix);
this.mDrawMatrix.postConcat(this.mSuppMatrix);
return this.mDrawMatrix;
}
private cancelFling():void {
if (null != this.mCurrentFlingRunnable) {
this.mCurrentFlingRunnable.cancelFling();
this.mCurrentFlingRunnable = null;
}
}
/**
* Helper method that simply checks the Matrix, and then displays the result
*/
private checkAndDisplayMatrix():void {
if (this.checkMatrixBounds()) {
this.setImageViewMatrix(this.getDrawMatrix());
}
}
private checkImageViewScaleType():void {
let imageView:ImageView = this.getImageView();
/**
* PhotoView's getScaleType() will just divert to this.getScaleType() so
* only call if we're not attached to a PhotoView.
*/
if (null != imageView && !(IPhotoView.isImpl(imageView))) {
if (ScaleType.MATRIX != (imageView.getScaleType())) {
throw Error(`new IllegalStateException("The ImageView's ScaleType has been changed since attaching a PhotoViewAttacher")`);
}
}
}
private checkMatrixBounds():boolean {
const imageView:ImageView = this.getImageView();
if (null == imageView) {
return false;
}
const rect:RectF = this._getDisplayRect(this.getDrawMatrix());
if (null == rect) {
return false;
}
const height:number = rect.height(), width:number = rect.width();
let deltaX:number = 0, deltaY:number = 0;
const viewHeight:number = this.getImageViewHeight(imageView);
if (height <= viewHeight) {
switch (this.mScaleType) {
case ScaleType.FIT_START:
deltaY = -rect.top;
break;
case ScaleType.FIT_END:
deltaY = viewHeight - height - rect.top;
break;
default:
deltaY = (viewHeight - height) / 2 - rect.top;
break;
}
} else if (rect.top > 0) {
deltaY = -rect.top;
} else if (rect.bottom < viewHeight) {
deltaY = viewHeight - rect.bottom;
}
const viewWidth:number = this.getImageViewWidth(imageView);
if (width <= viewWidth) {
switch (this.mScaleType) {
case ScaleType.FIT_START:
deltaX = -rect.left;
break;
case ScaleType.FIT_END:
deltaX = viewWidth - width - rect.left;
break;
default:
deltaX = (viewWidth - width) / 2 - rect.left;
break;
}
this.mScrollEdge = PhotoViewAttacher.EDGE_BOTH;
} else if (rect.left > 0) {
this.mScrollEdge = PhotoViewAttacher.EDGE_LEFT;
deltaX = -rect.left;
} else if (rect.right < viewWidth) {
deltaX = viewWidth - rect.right;
this.mScrollEdge = PhotoViewAttacher.EDGE_RIGHT;
} else {
this.mScrollEdge = PhotoViewAttacher.EDGE_NONE;
}
// Finally actually translate the matrix
this.mSuppMatrix.postTranslate(deltaX, deltaY);
return true;
}
/**
* Helper method that maps the supplied Matrix to the current Drawable
*
* @param matrix - Matrix to map Drawable against
* @return RectF - Displayed Rectangle
*/
private _getDisplayRect(matrix:Matrix):RectF {
let imageView:ImageView = this.getImageView();
if (null != imageView) {
let d:Drawable = imageView.getDrawable();
if (null != d) {
this.mDisplayRect.set(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
matrix.mapRect(this.mDisplayRect);
return this.mDisplayRect;
}
}
return null;
}
getVisibleRectangleBitmap():Canvas {
let imageView:ImageView = this.getImageView();
return imageView == null ? null : imageView.getDrawingCache();
}
setZoomTransitionDuration(milliseconds:number):void {
if (milliseconds < 0)
milliseconds = IPhotoView.DEFAULT_ZOOM_DURATION;
this.ZOOM_DURATION = milliseconds;
}
getIPhotoViewImplementation():IPhotoView {
return this;
}
/**
* Helper method that 'unpacks' a Matrix and returns the required value
*
* @param matrix - Matrix to unpack
* @param whichValue - Which value from Matrix.M* to return
* @return float - returned value
*/
private getValue(matrix:Matrix, whichValue:number):number {
matrix.getValues(this.mMatrixValues);
return this.mMatrixValues[whichValue];
}
/**
* Resets the Matrix back to FIT_CENTER, and then displays it.s
*/
private resetMatrix():void {
this.mSuppMatrix.reset();
this.setImageViewMatrix(this.getDrawMatrix());
this.checkMatrixBounds();
}
private setImageViewMatrix(matrix:Matrix):void {
let imageView:ImageView = this.getImageView();
if (null != imageView) {
this.checkImageViewScaleType();
imageView.setImageMatrix(matrix);
// Call MatrixChangedListener if needed
if (null != this.mMatrixChangeListener) {
let displayRect:RectF = this._getDisplayRect(matrix);
if (null != displayRect) {
this.mMatrixChangeListener.onMatrixChanged(displayRect);
}
}
}
}
/**
* Calculate Matrix for FIT_CENTER
*
* @param d - Drawable being displayed
*/
private updateBaseMatrix(d:Drawable):void {
let imageView:ImageView = this.getImageView();
if (null == imageView || null == d) {
return;
}
const viewWidth:number = this.getImageViewWidth(imageView);
const viewHeight:number = this.getImageViewHeight(imageView);
const drawableWidth:number = d.getIntrinsicWidth();
const drawableHeight:number = d.getIntrinsicHeight();
this.mBaseMatrix.reset();
const widthScale:number = viewWidth / drawableWidth;
const heightScale:number = viewHeight / drawableHeight;
if (this.mScaleType == ScaleType.CENTER) {
this.mBaseMatrix.postTranslate((viewWidth - drawableWidth) / 2, (viewHeight - drawableHeight) / 2);
} else if (this.mScaleType == ScaleType.CENTER_CROP) {
let scale:number = Math.max(widthScale, heightScale);
this.mBaseMatrix.postScale(scale, scale);
this.mBaseMatrix.postTranslate((viewWidth - drawableWidth * scale) / 2, (viewHeight - drawableHeight * scale) / 2);
} else if (this.mScaleType == ScaleType.CENTER_INSIDE) {
let scale:number = Math.min(1.0, Math.min(widthScale, heightScale));
this.mBaseMatrix.postScale(scale, scale);
this.mBaseMatrix.postTranslate((viewWidth - drawableWidth * scale) / 2, (viewHeight - drawableHeight * scale) / 2);
} else {
let mTempSrc:RectF = new RectF(0, 0, drawableWidth, drawableHeight);
let mTempDst:RectF = new RectF(0, 0, viewWidth, viewHeight);
switch (this.mScaleType) {
case ScaleType.FIT_CENTER:
this.mBaseMatrix.setRectToRect(mTempSrc, mTempDst, ScaleToFit.CENTER);
break;
case ScaleType.FIT_START:
this.mBaseMatrix.setRectToRect(mTempSrc, mTempDst, ScaleToFit.START);
break;
case ScaleType.FIT_END:
this.mBaseMatrix.setRectToRect(mTempSrc, mTempDst, ScaleToFit.END);
break;
case ScaleType.FIT_XY:
this.mBaseMatrix.setRectToRect(mTempSrc, mTempDst, ScaleToFit.FILL);
break;
default:
break;
}
}
this.resetMatrix();
}
private getImageViewWidth(imageView:ImageView):number {
if (null == imageView)
return 0;
return imageView.getWidth() - imageView.getPaddingLeft() - imageView.getPaddingRight();
}
private getImageViewHeight(imageView:ImageView):number {
if (null == imageView)
return 0;
return imageView.getHeight() - imageView.getPaddingTop() - imageView.getPaddingBottom();
}
}
export module PhotoViewAttacher {
/**
* Interface definition for a callback to be invoked when the internal Matrix has changed for
* this View.
*
* @author Chris Banes
*/
export interface OnMatrixChangedListener {
/**
* Callback for when the Matrix displaying the Drawable has changed. This could be because
* the View's bounds have changed, or the user has zoomed.
*
* @param rect - Rectangle displaying the Drawable's new bounds.
*/
onMatrixChanged(rect:RectF):void ;
}
/**
* Interface definition for callback to be invoked when attached ImageView scale changes
*
* @author Marek Sebera
*/
export interface OnScaleChangeListener {
/**
* Callback for when the scale changes
*
* @param scaleFactor the scale factor (less than 1 for zoom out, greater than 1 for zoom in)
* @param focusX focal point X position
* @param focusY focal point Y position
*/
onScaleChange(scaleFactor:number, focusX:number, focusY:number):void ;
}
/**
* Interface definition for a callback to be invoked when the Photo is tapped with a single
* tap.
*
* @author Chris Banes
*/
export interface OnPhotoTapListener {
/**
* A callback to receive where the user taps on a photo. You will only receive a callback if
* the user taps on the actual photo, tapping on 'whitespace' will be ignored.
*
* @param view - View the user tapped.
* @param x - where the user tapped from the of the Drawable, as percentage of the
* Drawable width.
* @param y - where the user tapped from the top of the Drawable, as percentage of the
* Drawable height.
*/
onPhotoTap(view:View, x:number, y:number):void ;
}
/**
* Interface definition for a callback to be invoked when the ImageView is tapped with a single
* tap.
*
* @author Chris Banes
*/
export interface OnViewTapListener {
/**
* A callback to receive where the user taps on a ImageView. You will receive a callback if
* the user taps anywhere on the view, tapping on 'whitespace' will not be ignored.
*
* @param view - View the user tapped.
* @param x - where the user tapped from the left of the View.
* @param y - where the user tapped from the top of the View.
*/
onViewTap(view:View, x:number, y:number):void ;
}
export class AnimatedZoomRunnable implements Runnable {
_PhotoViewAttacher_this:PhotoViewAttacher;
private mFocalX:number = 0;
private mFocalY:number = 0;
private mStartTime:number = 0;
private mZoomStart:number = 0;
private mZoomEnd:number = 0;
constructor(arg:PhotoViewAttacher, currentZoom:number, targetZoom:number, focalX:number, focalY:number) {
this._PhotoViewAttacher_this = arg;
this.mFocalX = focalX;
this.mFocalY = focalY;
this.mStartTime = System.currentTimeMillis();
this.mZoomStart = currentZoom;
this.mZoomEnd = targetZoom;
}
run():void {
let imageView:ImageView = this._PhotoViewAttacher_this.getImageView();
if (imageView == null) {
return;
}
let t:number = this.interpolate();
let scale:number = this.mZoomStart + t * (this.mZoomEnd - this.mZoomStart);
let deltaScale:number = scale / this._PhotoViewAttacher_this.getScale();
this._PhotoViewAttacher_this.onScale(deltaScale, this.mFocalX, this.mFocalY);
// We haven't hit our target scale yet, so post ourselves again
if (t < 1) {
imageView.postOnAnimation(this);
}
}
private interpolate():number {
let t:number = 1 * (System.currentTimeMillis() - this.mStartTime) / this._PhotoViewAttacher_this.ZOOM_DURATION;
t = Math.min(1, t);
t = PhotoViewAttacher.sInterpolator.getInterpolation(t);
return t;
}
}
export class FlingRunnable implements Runnable {
_PhotoViewAttacher_this:PhotoViewAttacher;
constructor(arg:PhotoViewAttacher) {
this._PhotoViewAttacher_this = arg;
this.mScroller = new OverScroller();
}
private mScroller:OverScroller;
private mCurrentX:number = 0;
private mCurrentY:number = 0;
cancelFling():void {
if (PhotoViewAttacher.DEBUG) {
Log.d(PhotoViewAttacher.LOG_TAG, "Cancel Fling");
}
this.mScroller.forceFinished(true);
}
fling(viewWidth:number, viewHeight:number, velocityX:number, velocityY:number):void {
const rect:RectF = this._PhotoViewAttacher_this.getDisplayRect();
if (null == rect) {
return;
}
const startX:number = Math.round(-rect.left);
let minX:number, maxX:number, minY:number, maxY:number;
if (viewWidth < rect.width()) {
minX = 0;
maxX = Math.round(rect.width() - viewWidth);
} else {
minX = maxX = startX;
}
const startY:number = Math.round(-rect.top);
if (viewHeight < rect.height()) {
minY = 0;
maxY = Math.round(rect.height() - viewHeight);
} else {
minY = maxY = startY;
}
this.mCurrentX = startX;
this.mCurrentY = startY;
if (PhotoViewAttacher.DEBUG) {
Log.d(PhotoViewAttacher.LOG_TAG, "fling. StartX:" + startX + " StartY:" + startY + " MaxX:" + maxX + " MaxY:" + maxY);
}
// If we actually can move, fling the scroller
if (startX != maxX || startY != maxY) {
this.mScroller.fling(startX, startY, velocityX, velocityY, minX, maxX, minY, maxY, 0, 0);
}
}
run():void {
if (this.mScroller.isFinished()) {
// remaining post that should not be handled
return;
}
let imageView:ImageView = this._PhotoViewAttacher_this.getImageView();
if (null != imageView && this.mScroller.computeScrollOffset()) {
const newX:number = this.mScroller.getCurrX();
const newY:number = this.mScroller.getCurrY();
if (PhotoViewAttacher.DEBUG) {
Log.d(PhotoViewAttacher.LOG_TAG, "fling run(). CurrentX:" + this.mCurrentX + " CurrentY:" + this.mCurrentY + " NewX:" + newX + " NewY:" + newY);
}
this._PhotoViewAttacher_this.mSuppMatrix.postTranslate(this.mCurrentX - newX, this.mCurrentY - newY);
this._PhotoViewAttacher_this.setImageViewMatrix(this._PhotoViewAttacher_this.getDrawMatrix());
this.mCurrentX = newX;
this.mCurrentY = newY;
// Post On animation
imageView.postOnAnimation(this);
}
}
}
/**
* Provided default implementation of GestureDetector.OnDoubleTapListener, to be overriden with custom behavior, if needed
* <p> </p>
* To be used via {@link PhotoViewAttacher#setOnDoubleTapListener(android.view.GestureDetector.OnDoubleTapListener)}
*/
export class DefaultOnDoubleTapListener implements android.view.GestureDetector.OnDoubleTapListener {
private photoViewAttacher:PhotoViewAttacher;
/**
* Default constructor
*
* @param photoViewAttacher PhotoViewAttacher to bind to
*/
constructor(photoViewAttacher:PhotoViewAttacher) {
this.setPhotoViewAttacher(photoViewAttacher);
}
/**
* Allows to change PhotoViewAttacher within range of single instance
*
* @param newPhotoViewAttacher PhotoViewAttacher to bind to
*/
setPhotoViewAttacher(newPhotoViewAttacher:PhotoViewAttacher):void {
this.photoViewAttacher = newPhotoViewAttacher;
}
onSingleTapConfirmed(e:MotionEvent):boolean {
if (this.photoViewAttacher == null)
return false;
let imageView:ImageView = this.photoViewAttacher.getImageView();
if (null != this.photoViewAttacher.getOnPhotoTapListener()) {
const displayRect:RectF = this.photoViewAttacher.getDisplayRect();
if (null != displayRect) {
const x:number = e.getX(), y:number = e.getY();
// Check to see if the user tapped on the photo
if (displayRect.contains(x, y)) {
let xResult:number = (x - displayRect.left) / displayRect.width();
let yResult:number = (y - displayRect.top) / displayRect.height();
this.photoViewAttacher.getOnPhotoTapListener().onPhotoTap(imageView, xResult, yResult);
return true;
}
}
}
if (null != this.photoViewAttacher.getOnViewTapListener()) {
this.photoViewAttacher.getOnViewTapListener().onViewTap(imageView, e.getX(), e.getY());
}
return false;
}
onDoubleTap(ev:MotionEvent):boolean {
if (this.photoViewAttacher == null)
return false;
try {
let scale:number = this.photoViewAttacher.getScale();
let x:number = ev.getX();
let y:number = ev.getY();
if (scale < this.photoViewAttacher.getMediumScale()) {
this.photoViewAttacher.setScale(this.photoViewAttacher.getMediumScale(), x, y, true);
} else if (scale >= this.photoViewAttacher.getMediumScale() && scale < this.photoViewAttacher.getMaximumScale()) {
this.photoViewAttacher.setScale(this.photoViewAttacher.getMaximumScale(), x, y, true);
} else {
this.photoViewAttacher.setScale(this.photoViewAttacher.getMinimumScale(), x, y, true);
}
} catch (e) {
}
return true;
}
onDoubleTapEvent(e:MotionEvent):boolean {
// Wait for the confirmed onDoubleTap() instead
return false;
}
}
}
} | the_stack |
import convict from 'convict';
import * as convictFormatWithValidator from 'convict-format-with-validator';
convict.addFormat(convictFormatWithValidator.url);
function assert(assertion: Boolean, msg: string)
{
if (!assertion)
throw new Error(msg);
}
convict.addFormat({
name : 'float',
coerce : (v: string) => parseFloat(v),
validate : (v: number) => assert(Number.isFinite(v), 'must be a number')
});
/**
* The Edumeet configuration schema.
*
* Use `yarn gen-config-docs` to re-generate the README.md and the
* public/config/config.example.js files.
*/
const configSchema = convict({
loginEnabled :
{
doc : 'If the login is enabled.',
format : 'Boolean',
default : false
},
developmentPort :
{
doc : 'The development server listening port.',
format : 'port',
default : 3443
},
productionPort :
{
doc : 'The production server listening port.',
format : 'port',
default : 443
},
serverHostname :
{
doc : 'If the server component runs on a different host than the app you can specify the host name.',
format : 'String',
default : '',
nullable : true
},
/**
* Supported browsers version in bowser satisfy format.
* See more:
* https://www.npmjs.com/package/bowser#filtering-browsers
* Otherwise you got a unsupported browser page
*/
supportedBrowsers :
{
doc : 'Supported browsers version in bowser satisfy format.',
format : Object,
default :
{
'windows' : {
'internet explorer' : '>12',
'microsoft edge' : '>18'
},
'microsoft edge' : '>18',
'safari' : '>12',
'firefox' : '>=60',
'chrome' : '>=74',
'chromium' : '>=74',
'opera' : '>=62',
'samsung internet for android' : '>=11.1.1.52'
}
},
/**
* Network priorities
* DSCP bits set by browser according this priority values.
* ("high" means actually: EF for audio, and AF41 for Video in chrome)
* https://en.wikipedia.org/wiki/Differentiated_services
*/
networkPriorities :
{
doc : 'Network priorities.',
format : Object,
default :
{
audio : 'high',
mainVideo : 'high',
additionalVideos : 'medium',
screenShare : 'medium'
}
},
// The aspect ratio of the videos as shown on the screen.
// This is changeable in client settings.
// This value must match one of the defined values in
// aspectRatios EXACTLY (e.g. 1.333)
aspectRatio :
{
doc : `The aspect ratio of the videos as shown on the screen.
This value must match exactly one of the values defined in aspectRatios.`,
format : 'float',
default : 1.777
},
aspectRatios :
{
doc : 'The selectable aspect ratios in the user settings.',
format : Array,
default :
[
{
value : 1.333, // 4 / 3
label : '4 : 3'
},
{
value : 1.777, // 16 / 9
label : '16 : 9'
}
]
},
resolution :
{
doc : 'The default video camera capture resolution.',
format : [ 'low', 'medium', 'high', 'veryhigh', 'ultra' ],
default : 'medium'
},
frameRate :
{
doc : 'The default video camera capture framerate.',
format : 'nat',
default : 15
},
screenResolution :
{
doc : 'The default screen sharing resolution.',
format : [ 'low', 'medium', 'high', 'veryhigh', 'ultra' ],
default : 'veryhigh'
},
screenSharingFrameRate :
{
doc : 'The default screen sharing framerate.',
format : 'nat',
default : 5
},
simulcast :
{
doc : 'Enable or disable simulcast for webcam video.',
format : 'Boolean',
default : true
},
simulcastSharing :
{
doc : 'Enable or disable simulcast for screen sharing video.',
format : 'Boolean',
default : false
},
simulcastProfiles :
{
doc : 'Define different encodings for various resolutions of the video.',
format : Object,
default :
{
3840 :
[
{ scaleResolutionDownBy: 12, maxBitRate: 150000 },
{ scaleResolutionDownBy: 6, maxBitRate: 500000 },
{ scaleResolutionDownBy: 1, maxBitRate: 10000000 }
],
1920 :
[
{ scaleResolutionDownBy: 6, maxBitRate: 150000 },
{ scaleResolutionDownBy: 3, maxBitRate: 500000 },
{ scaleResolutionDownBy: 1, maxBitRate: 3500000 }
],
1280 :
[
{ scaleResolutionDownBy: 4, maxBitRate: 150000 },
{ scaleResolutionDownBy: 2, maxBitRate: 500000 },
{ scaleResolutionDownBy: 1, maxBitRate: 1200000 }
],
640 :
[
{ scaleResolutionDownBy: 2, maxBitRate: 150000 },
{ scaleResolutionDownBy: 1, maxBitRate: 500000 }
],
320 :
[
{ scaleResolutionDownBy: 1, maxBitRate: 150000 }
]
}
},
// The adaptive spatial layer selection scaling factor (in the range [0.5, 1.0])
// example:
// with level width=640px, the minimum width required to trigger the
// level change will be: 640 * 0.75 = 480px
adaptiveScalingFactor :
{
doc : 'The adaptive spatial layer selection scaling factor in the range [0.5, 1.0].',
format : (value: number) => value >= 0.5 && value <= 1.0,
default : 0.75
},
localRecordingEnabled :
{
doc : 'If set to true Local Recording feature will be enabled.',
format : 'Boolean',
default : false
},
/**
* White listing browsers that support audio output device selection.
* It is not yet fully implemented in Firefox.
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=1498512
*/
audioOutputSupportedBrowsers :
{
doc : 'White listing browsers that support audio output device selection.',
format : Array,
default : [
'chrome',
'opera'
]
},
requestTimeout :
{
doc : 'The Socket.io request timeout.',
format : 'nat',
default : 20000
},
requestRetries :
{
doc : 'The Socket.io request maximum retries.',
format : 'nat',
default : 3
},
transportOptions :
{
doc : 'The Mediasoup transport options.',
format : Object,
default : {
tcp : true
}
},
// audio options
autoGainControl :
{
doc : 'Auto gain control enabled.',
format : 'Boolean',
default : true
},
echoCancellation :
{
doc : 'Echo cancellation enabled.',
format : 'Boolean',
default : true
},
noiseSuppression :
{
doc : 'Noise suppression enabled.',
format : 'Boolean',
default : true
},
voiceActivatedUnmute :
{
doc : 'Automatically unmute speaking above noiseThreshold.',
format : 'Boolean',
default : false
},
noiseThreshold :
{
doc : 'This is only for voiceActivatedUnmute and audio-indicator.',
format : 'int',
default : -60
},
sampleRate :
{
doc : 'The audio sample rate.',
format : [ 8000, 16000, 24000, 44100, 48000 ],
default : 48000
},
channelCount :
{
doc : 'The audio channels count.',
format : [ 1, 2 ],
default : 1
},
sampleSize :
{
doc : 'The audio sample size count.',
format : [ 8, 16, 24, 32 ],
default : 16
},
opusStereo :
{
doc : 'If OPUS FEC stereo be enabled.',
format : 'Boolean',
default : false
},
opusDtx :
{
doc : 'If OPUS DTX should be enabled.',
format : 'Boolean',
default : true
},
opusFec :
{
doc : 'If OPUS FEC should be enabled.',
format : 'Boolean',
default : true
},
opusPtime :
{
doc : 'The OPUS packet time.',
format : [ 3, 5, 10, 20, 30, 40, 50, 60 ],
default : 20
},
opusMaxPlaybackRate :
{
doc : 'The OPUS playback rate.',
format : [ 8000, 16000, 24000, 44100, 48000 ],
default : 48000
},
// audio presets profiles
audioPreset :
{
doc : 'The audio preset',
format : 'String',
default : 'conference'
},
audioPresets :
{
doc : 'The audio presets.',
format : Object,
default :
{
conference :
{
name : 'Conference audio',
autoGainControl : true, // default : true
echoCancellation : true, // default : true
noiseSuppression : true, // default : true
// Automatically unmute speaking above noiseThreshold
voiceActivatedUnmute : false, // default : false
// This is only for voiceActivatedUnmute and audio-indicator
noiseThreshold : -60, // default -60
// will not eat that much bandwidth thanks to opus
sampleRate : 48000, // default : 48000 and don't go higher
// usually mics are mono so this saves bandwidth
channelCount : 1, // default : 1
sampleSize : 16, // default : 16
// usually mics are mono so this saves bandwidth
opusStereo : false, // default : false
opusDtx : true, // default : true / will save bandwidth
opusFec : true, // default : true / forward error correction
opusPtime : 20, // minimum packet time (10, 20, 40, 60)
opusMaxPlaybackRate : 48000 // default : 48000 and don't go higher
},
hifi :
{
name : 'HiFi streaming',
autoGainControl : false, // default : true
echoCancellation : false, // default : true
noiseSuppression : false, // default : true
// Automatically unmute speaking above noiseThreshold
voiceActivatedUnmute : false, // default : false
// This is only for voiceActivatedUnmute and audio-indicator
noiseThreshold : -60, // default -60
// will not eat that much bandwidth thanks to opus
sampleRate : 48000, // default : 48000 and don't go higher
// usually mics are mono so this saves bandwidth
channelCount : 2, // default : 1
sampleSize : 16, // default : 16
// usually mics are mono so this saves bandwidth
opusStereo : true, // default : false
opusDtx : false, // default : true / will save bandwidth
opusFec : true, // default : true / forward error correction
opusPtime : 60, // minimum packet time (10, 20, 40, 60)
opusMaxPlaybackRate : 48000 // default : 48000 and don't go higher
}
}
},
autoMuteThreshold :
{
doc : `It sets the maximum number of participants in one room that can join unmuted.
The next participant will join automatically muted.
Set it to 0 to auto mute all.
Set it to negative (-1) to never automatically auto mute but use it with caution,
full mesh audio strongly decrease room capacity!`,
format : 'nat',
default : 4
},
background :
{
doc : 'The page background image URL',
format : 'String',
default : 'images/background.jpg',
nullable : true
},
defaultLayout :
{
doc : 'The default layout.',
format : [ 'democratic', 'filmstrip' ],
default : 'democratic'
},
buttonControlBar :
{
doc : 'If true, the media control buttons will be shown in separate control bar, not in the ME container.',
format : 'Boolean',
default : false
},
drawerOverlayed :
{
doc : `If false, will push videos away to make room for side drawer.
If true, will overlay side drawer over videos.`,
format : 'Boolean',
default : true
},
notificationPosition :
{
doc : 'The position of the notifications.',
format : [ 'left', 'right' ],
default : 'right'
},
notificationSounds :
{
doc : `It sets the notifications sounds.
Valid keys are: 'parkedPeer', 'parkedPeers', 'raisedHand',
'chatMessage', 'sendFile', 'newPeer' and 'default'.
Not defining a key is equivalent to using the default notification sound.
Setting 'play' to null disables the sound notification.
`,
format : Object,
default :
{
chatMessage : {
play : '/sounds/notify-chat.mp3'
},
raisedHand : {
play : '/sounds/notify-hand.mp3'
},
default : {
delay : 5000, // minimum delay between alert sounds [ms]
play : '/sounds/notify.mp3'
}
}
},
hideTimeout :
{
doc : 'Timeout for auto hiding the topbar and the buttons control bar.',
format : 'int',
default : 3000
},
lastN :
{
doc : 'The maximum number of participants that will be visible in as speaker.',
format : 'nat',
default : 4
},
mobileLastN :
{
doc : 'The maximum number of participants that will be visible in as speaker for mobile users.',
format : 'nat',
default : 1
},
maxLastN :
{
doc : 'The highest number of lastN the user can select manually in the user interface.',
format : 'nat',
default : 5
},
lockLastN :
{
doc : 'If true, the users can not change the number of visible speakers.',
format : 'Boolean',
default : false
},
logo :
{
doc : 'If not null, it shows the logo loaded from the specified URL, otherwise it shows the title.',
format : 'url',
default : 'images/logo.edumeet.svg',
nullable : true
},
title :
{
doc : 'The title to show if the logo is not specified.',
format : 'String',
default : 'edumeet'
},
supportUrl :
{
doc : 'The service & Support URL; if `null`, it will be not displayed on the about dialogs.',
format : 'url',
default : 'https://support.example.com',
nullable : true
},
privacyUrl :
{
doc : 'The privacy and data protection external URL or local HTML path.',
format : 'String',
default : 'privacy/privacy.html',
nullable : true
},
theme :
{
doc : 'UI theme elements colors.',
format : Object,
default :
{
palette :
{
primary :
{
main : '#313131'
}
},
overrides :
{
MuiAppBar :
{
colorPrimary :
{
backgroundColor : '#313131'
}
},
MuiButton :
{
containedPrimary :
{
backgroundColor : '#5F9B2D',
'&:hover' :
{
backgroundColor : '#5F9B2D'
}
},
containedSecondary :
{
backgroundColor : '#f50057',
'&:hover' :
{
backgroundColor : '#f50057'
}
}
},
/*
MuiIconButton :
{
colorPrimary :
{
backgroundColor : '#5F9B2D',
'&:hover' :
{
backgroundColor : '#5F9B2D'
}
},
colorSecondary :
{
backgroundColor : '#f50057',
'&:hover' :
{
backgroundColor : '#f50057'
}
}
},
*/
MuiFab :
{
primary :
{
backgroundColor : '#518029',
'&:hover' :
{
backgroundColor : '#518029'
},
'&:disabled' : {
color : '#999898',
backgroundColor : '#323131'
}
},
secondary :
{
backgroundColor : '#f50057',
'&:hover' :
{
backgroundColor : '#f50057'
},
'&:disabled' : {
color : '#999898',
backgroundColor : '#323131'
}
}
},
MuiBadge :
{
colorPrimary :
{
backgroundColor : '#5F9B2D',
'&:hover' :
{
backgroundColor : '#518029'
}
}
}
},
typography :
{
useNextVariants : true
}
}
}
});
function formatDocs()
{
function _formatDocs(docs: any, property: string | null, schema: any)
{
if (schema._cvtProperties)
{
Object.entries(schema._cvtProperties).forEach(([ name, value ]) =>
{
_formatDocs(docs, `${property ? `${property}.` : ''}${name}`, value);
});
return docs;
}
else if (property)
{
docs[property] =
{
doc : schema.doc,
format : JSON.stringify(schema.format, null, 2),
default : JSON.stringify(schema.default, null, 2)
};
}
return docs;
}
return _formatDocs({}, null, configSchema.getSchema());
}
function formatJson(data: string)
{
return data ? `\`${data.replace(/\n/g, '')}\`` : '';
}
function dumpDocsMarkdown()
{
let data = `#  App Configuration properties list:
| Name | Description | Format | Default value |
| :--- | :---------- | :----- | :------------ |
`;
Object.entries(formatDocs()).forEach((entry: [string, any]) =>
{
const [ name, value ] = entry;
data += `| ${name} | ${value.doc.replace(/\n/g, ' ')} | ${formatJson(value.format)} | \`${formatJson(value.default)}\` |\n`;
});
data += `
---
*Document generated with:* \`yarn gen-config-docs\` *from:* [config.ts](src/config.ts).
`;
return data;
}
function dumpExampleConfigJs()
{
let data = `/**
* Edumeet App Configuration
*
* The configuration documentation is available also:
* - in the app/README.md file in the source tree
* - visiting the /?config=true page in a running instance
*/
// eslint-disable-next-line
var config = {
`;
Object.entries(formatDocs()).forEach((entry: [string, any]) =>
{
// eslint-disable-next-line
let [ name, value ] = entry;
if (name.includes('.'))
name = `'${name}'`;
data += `\n\t// ${value.doc.replace(/\n/g, '\n\t// ')}
\t${name} : ${value.default},
`;
});
data += `};
// Generated with: \`yarn gen-config-docs\` from app/src/config.ts
`;
return data;
}
// run the docs generator
if (typeof window === 'undefined')
{
import('fs').then((fs) =>
{
fs.writeFileSync('public/config/README.md', dumpDocsMarkdown());
fs.writeFileSync('public/config/config.example.js', dumpExampleConfigJs());
});
}
//
let config: any = {};
let configError = '';
// Load config from window object
if (typeof window !== 'undefined' && (window as any).config !== undefined)
{
configSchema.load((window as any).config);
}
// Perform validation
try
{
configSchema.validate({ allowed: 'strict' });
config = configSchema.getProperties();
}
catch (error: any)
{
configError = error.message;
}
// Override the window config with the validated properties.
if (typeof window !== 'undefined')
{
(window as any)['config'] = config;
}
export {
configSchema,
config,
configError,
formatDocs
}; | the_stack |
module WinJSTests {
"use strict";
// @TODO, need tests for release/retain
// NOTE: because of auto-batching in BindingListDataSource you have two options for how to write tests:
//
// 1) explicit dataSource.beginEdits()/endEdits() calls around all edits
//
// 2) using promises and logger.assertEmptyAsync() to make sure you make assertions after the endEdits has occured
//
function errorHandler(msg) {
try {
LiveUnit.Assert.fail('There was an unhandled error in your test: ' + msg);
} catch (ex) { }
}
class LoggingNotificationHandler<T> implements WinJS.UI.IListNotificationHandler<T> {
expected = [];
log = null;
beginNotifications;
changed;
endNotifications;
inserted;
indexChanged;
countChanged;
moved;
removed;
reload;
constructor(retain = false) {
this.beginNotifications = this.assert.bind(this, "beginNotifications");
this.changed = this.assert.bind(this, "changed");
this.endNotifications = this.assert.bind(this, "endNotifications");
if (retain) {
this.inserted = function (itemPromise) {
itemPromise.retain();
this.assert("inserted");
};
} else {
this.inserted = this.assert.bind(this, "inserted");
}
this.indexChanged = this.assert.bind(this, "indexChanged");
this.countChanged = this.assert.bind(this, "countChanged");
this.moved = this.assert.bind(this, "moved");
this.removed = this.assert.bind(this, "removed");
this.reload = this.assert.bind(this, "reload");
}
// Used for developing tests / debugging
startLogging = function () {
this.log = [];
}
stopLogging() {
var l = this.log;
this.log = null;
return l;
}
setExpected(list) {
this.expected = list;
return this;
}
appendExpected(...args) {
args.forEach((arg) => {
this.expected.push(arg);
})
return this;
}
appendExpectedN(entry, n = 1) {
for (var i = 0; i < n; i++) {
this.expected.push(entry);
}
return this;
}
assertEmpty(comment?) {
LiveUnit.Assert.areEqual(0, this.expected.length, "All expected notifications should be fired: " + comment);
}
assertEmptyAsync(comment?) {
return WinJS.Utilities.Scheduler.schedulePromiseHigh(null, "BindingListTests.assertEmptyAsync").then(() => {
this.assertEmpty(comment);
});
}
assert(name) {
var entry = this.expected.shift();
if (entry) {
LiveUnit.Assert.areEqual(entry, name, "Recieved event doesn't match expected event");
}
if (this.log) {
this.log.push(name);
}
}
itemAvailable(item) {
}
}
function CountingNotificationHandler() {
var count = 0;
this.getCount = function () {
return count;
};
this.clearCount = function () {
count = 0;
};
function increment() {
count++;
}
this.beginNotifications = increment;
this.changed = increment;
this.endNotifications = increment;
this.inserted = function (itemPromise) {
itemPromise.retain();
increment();
};
this.indexChanged = increment;
this.countChanged = increment;
this.moved = increment;
this.removed = increment;
this.reload = increment;
}
function listSortedAndFilteredToEvens(count, options) {
// Creating a sorted even number list
var list = new WinJS.Binding.List<number>([], options);
for (var i = 0; i < count; ++i) {
list.push(i);
}
var sorted = list.createSorted(function (l, r) { return l - r; });
return sorted.createFiltered(function (num) { return Math.abs(num) % 2 === 0; });
}
function listGroupedByOddAndEven(count = 0) {
var list = new WinJS.Binding.List<number>();
var compare = function (num) { return (num % 2 === 0) ? "even" : "odd"; };
var sort = function (l, r) { return l.length - r.length; };
for (var i = 0; i < count; ++i) {
list.push(i);
}
return list.createGrouped(compare, compare, sort);
}
function sortedList() {
var list = new WinJS.Binding.List<number>();
return list.createSorted(function (l, r) { return (l - r); });
}
function oddListFilter() {
var list = new WinJS.Binding.List<number>();
return list.createFiltered(function (num) { return !!(num % 2); });
}
export class BindingListTests {
testBindingListDecreasingTheLenghtNotifications(complete) {
var logger = new LoggingNotificationHandler(true);
var list = new WinJS.Binding.List();
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
// Be explicit about setup so that these notifications don't
// get mixed up with the ones we care about.
dataSource.beginEdits();
list.push(1, 2, 3, 4, 5, 6, 7, 8, 9);
dataSource.endEdits();
logger.setExpected([
"beginNotifications",
"removed",
"removed",
"countChanged",
"endNotifications"
]);
list.length = list.length - 2;
logger.assertEmptyAsync()
.then(null, errorHandler)
.then(complete);
}
testReloadNotificationsInListBinding() {
var logger = new LoggingNotificationHandler(true);
var list = new WinJS.Binding.List<number>();
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
dataSource.beginEdits();
list.push(1, 2, 3, -1, 0, 3);
dataSource.endEdits();
logger.setExpected([
"reload"
]);
list.sort(function (l, r) { return l - r; });
logger.assertEmpty();
logger.setExpected([
"reload"
]);
list.reverse();
logger.assertEmpty();
}
testBindingListEditingNotifications(complete) {
var logger = new LoggingNotificationHandler(true);
var list = new WinJS.Binding.List();
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
WinJS.Promise.wrap()
.then(function () {
logger.setExpected([
"beginNotifications",
"inserted",
"inserted",
"inserted",
"countChanged",
"endNotifications"
]);
list.push(1, 2, 3);
return logger.assertEmptyAsync();
})
.then(function () {
logger.setExpected([
"beginNotifications",
"removed",
"countChanged",
"endNotifications"
]);
list.pop();
return logger.assertEmptyAsync();
})
.then(function () {
logger.setExpected([
"beginNotifications",
"indexChanged",
"indexChanged",
"moved",
"endNotifications"
]);
list.move(0, 1);
return logger.assertEmptyAsync();
})
.then(function () {
logger.setExpected([
"beginNotifications",
"removed"
]).
appendExpectedN("indexChanged", list.length - 1).
appendExpected(
"countChanged",
"endNotifications"
);
list.shift();
return logger.assertEmptyAsync("checking correct shift");
})
.then(function () {
logger.setExpected([
"beginNotifications",
"inserted"
]).
appendExpectedN("indexChanged", list.length).
appendExpected(
"countChanged",
"endNotifications"
);
list.unshift(300);
return logger.assertEmptyAsync("checking correct unshift");
})
.then(function () {
logger.setExpected([
"beginNotifications",
"changed",
"endNotifications"
]);
list.setAt(0, 100);
return logger.assertEmptyAsync("checking correct modification");
})
.then(function () {
logger.setExpected([
"beginNotifications",
"inserted",
"countChanged",
"endNotifications"
]);
list.splice(list.length, 0, 100);
return logger.assertEmptyAsync("checking correct splice");
})
.then(function () {
logger.setExpected([
"beginNotifications",
"removed",
"indexChanged",
"indexChanged",
"countChanged",
"endNotifications"
]);
list.splice(list.length - 3, 1);
return logger.assertEmptyAsync("checking correct splice");
})
.then(null, errorHandler)
.then(complete);
}
testBindingListEditingNotificationsWithExplicitBatching() {
var logger = new LoggingNotificationHandler(true);
var list = new WinJS.Binding.List();
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
logger.setExpected([
"beginNotifications"
]);
dataSource.beginEdits();
logger.assertEmpty();
logger.setExpected([
"inserted",
"inserted",
"inserted",
]);
list.push(1, 2, 3);
logger.assertEmpty();
logger.setExpected([
"removed",
]);
list.pop();
logger.assertEmpty();
logger.setExpected([
"countChanged",
"endNotifications"
]);
dataSource.endEdits();
logger.assertEmpty();
logger.setExpected([
"beginNotifications"
]);
dataSource.beginEdits();
logger.assertEmpty();
list.move(0, 1);
logger.assertEmpty();
// We get an index changed notifications for the two items that swapped and a moved
// notification for the one item which was explicitly moved.
//
logger.setExpected([
"indexChanged",
"indexChanged",
"moved",
"endNotifications"
]);
dataSource.endEdits();
logger.assertEmpty();
logger.setExpected([
"beginNotifications"
]);
dataSource.beginEdits();
logger.assertEmpty();
logger.setExpected([
"removed"
]);
list.shift();
logger.assertEmpty("checking correct shift");
logger.setExpected([]).
appendExpectedN("indexChanged", list.length).
appendExpected(
"countChanged",
"endNotifications"
);
dataSource.endEdits();
logger.assertEmpty();
}
}
function verifyListContent(list, expected) {
for (var i = 0, len = list.length; i < len; i++) {
if (list.getAt(i) !== expected[i]) {
return false;
}
}
return list.length === expected.length;
}
function scanFor(listBinding, value) {
return function scan(item) {
if (item.data === value) {
return item;
}
return listBinding.next().then(scan);
};
}
export class BindingListFilteredProjectionTests {
testBindingListFiltersDecreasingTheLenghtNotifications() {
var logger = new LoggingNotificationHandler(true);
var list = oddListFilter();
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
dataSource.beginEdits();
list.push(1, 2, 3, 4, 5, 6, 7, 8, 9);
dataSource.endEdits();
logger.setExpected([
"beginNotifications",
"removed",
"removed",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.length = list.length - 2;
dataSource.endEdits();
logger.assertEmpty("checking correct decreasing length of the list");
}
testBindingListFiltersDecreasingTheLenghtNotificationsAutoBatching(complete) {
var logger = new LoggingNotificationHandler(true);
var list = oddListFilter();
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
list.push(1, 2, 3, 4, 5, 6, 7, 8, 9);
WinJS.Promise.timeout()
.then(function () {
logger.setExpected([
"beginNotifications",
"removed",
"removed",
"countChanged",
"endNotifications"
]);
list.length = list.length - 2;
return logger.assertEmptyAsync("checking correct decreasing length of the list");
})
.then(null, errorHandler)
.then(complete);
}
testBindingListFiltersEditingNotifications(complete) {
var logger = new LoggingNotificationHandler(true);
var list = oddListFilter();
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
WinJS.Promise.wrap()
.then(function () {
logger.setExpected([
"beginNotifications",
"inserted",
"inserted",
"countChanged",
"endNotifications"
]);
list.push(1, 2, 3);
return logger.assertEmptyAsync("checking correct insertion");
})
.then(function () {
logger.setExpected([
"beginNotifications",
"removed",
"removed",
"countChanged",
"endNotifications"
]);
list.pop();
list.pop();
list.pop();
list.pop();
return logger.assertEmptyAsync("checking correct pop");
})
.then(function () {
logger.setExpected([
"beginNotifications",
"inserted",
"inserted",
"countChanged",
"endNotifications"
]);
list.push(1);
list.push(3);
return logger.assertEmptyAsync("checking correct push in empty list");
})
.then(function () {
logger.setExpected([
"beginNotifications",
"indexChanged",
"indexChanged",
"moved",
"endNotifications"
]);
list.move(0, 1);
return logger.assertEmptyAsync("checking correct move");
})
.then(function () {
list.push(5, 7, 9, 10);
return logger.assertEmptyAsync();
})
.then(function () {
logger.setExpected([
"beginNotifications",
"removed"
]).
appendExpectedN("indexChanged", list.length - 1).
appendExpected(
"countChanged",
"endNotifications"
);
list.shift();
return logger.assertEmptyAsync("checking correct shift");
})
.then(function () {
logger.setExpected([]);
list.unshift(300);
return logger.assertEmptyAsync("checking correct unshift element with false predicate");
})
.then(function () {
logger.setExpected([
"beginNotifications",
"inserted"
]).
appendExpectedN("indexChanged", list.length).
appendExpected(
"countChanged",
"endNotifications"
);
list.unshift(17);
return logger.assertEmptyAsync("checking correct unshift element with true predicate");
})
.then(function () {
logger.setExpected([
"beginNotifications",
"removed"
]).
appendExpectedN("indexChanged", list.length - 1).
appendExpected(
"countChanged",
"endNotifications"
);
list.setAt(0, 100);
return logger.assertEmptyAsync("checking correct setAt to false predicate");
})
.then(function () {
logger.setExpected([]);
list.splice(list.length, 0, 100);
return logger.assertEmptyAsync("checking correct splice at the end");
})
.then(function () {
logger.setExpected([
"beginNotifications",
"removed",
"indexChanged",
"indexChanged",
"countChanged",
"endNotifications"
]);
list.splice(list.length - 3, 1);
return logger.assertEmptyAsync("checking correct splice to delete");
})
.then(function () {
logger.setExpected([
"beginNotifications",
"inserted",
"indexChanged",
"indexChanged",
"indexChanged",
"countChanged",
"endNotifications"
]);
list.splice(list.length - 3, 0, 11);
return logger.assertEmptyAsync("checking correct splice to insert in the middle of the list");
})
.then(null, errorHandler)
.then(complete);
}
testBindingListSortedDecreasingTheLenghtNotifications() {
var logger = new LoggingNotificationHandler(true);
var list = sortedList();
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
dataSource.beginEdits();
list.push(9, 8, 7, 6, 5, 4, 3, 2, 1);
dataSource.endEdits();
logger.setExpected([
"beginNotifications",
"removed",
"removed",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.length = list.length - 2;
dataSource.endEdits();
logger.assertEmpty("checking correct decreasing length of the list");
}
testBindingListSortedProjectionUnshiftFunction() {
var logger = new LoggingNotificationHandler(true);
var list = sortedList();
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
logger.setExpected([
"beginNotifications",
"inserted",
"inserted",
"inserted",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.push(1, 2, 3);
dataSource.endEdits();
logger.assertEmpty("checking correct insertion");
logger.setExpected([
"beginNotifications",
"inserted",
"indexChanged",
"indexChanged",
"indexChanged",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.push(0);
dataSource.endEdits();
logger.assertEmpty("checking correct insertion");
logger.setExpected([
"beginNotifications",
"removed",
"removed",
"removed",
"removed",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.pop();
list.pop();
list.pop();
list.pop();
dataSource.endEdits();
logger.assertEmpty("checking correct pop");
dataSource.beginEdits();
list.push(1);
dataSource.endEdits();
logger.setExpected([
"beginNotifications",
"inserted",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.push(3);
dataSource.endEdits();
logger.assertEmpty("checking correct push in empty list");
logger.setExpected([]);
dataSource.beginEdits();
list.move(0, 1);
dataSource.endEdits();
logger.assertEmpty("checking correct move");
dataSource.beginEdits();
list.push(10, 8, 7, 5);
dataSource.endEdits();
logger.setExpected([
"beginNotifications",
"inserted"
]).
appendExpectedN("indexChanged", list.length).
appendExpected(
"countChanged",
"endNotifications"
);
dataSource.beginEdits();
list.unshift(1);
dataSource.endEdits();
logger.assertEmpty("checking correct unshift element in the begining");
logger.setExpected([
"beginNotifications",
"inserted",
"indexChanged",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.unshift(9);
dataSource.endEdits();
logger.assertEmpty("checking correct unshift element in the middle");
logger.setExpected([
"beginNotifications",
"inserted",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.unshift(11);
dataSource.endEdits();
logger.assertEmpty("checking correct unshift element in the end");
logger.setExpected([
"beginNotifications",
"removed",
"inserted"
]).
appendExpectedN("indexChanged", list.length - 1).
appendExpected(
"endNotifications"
);
dataSource.beginEdits();
list.setAt(0, 100);
dataSource.endEdits();
logger.assertEmpty("checking correct setAt to false predicate");
}
testBindingListSortedProjectionSetAtFunction() {
var logger = new LoggingNotificationHandler(true);
var list = sortedList();
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
logger.setExpected([
"beginNotifications",
"inserted",
"inserted",
"inserted",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.push(1, 2, 3);
dataSource.endEdits();
logger.assertEmpty("checking correct insertion");
logger.setExpected([
"beginNotifications",
"inserted",
"indexChanged",
"indexChanged",
"indexChanged",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.push(0);
dataSource.endEdits();
logger.assertEmpty("checking correct insertion");
dataSource.beginEdits();
list.pop();
list.pop();
dataSource.endEdits();
logger.setExpected([
"beginNotifications",
"removed",
"removed",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.pop();
list.pop();
list.pop();
dataSource.endEdits();
logger.assertEmpty("checking correct pop");
dataSource.beginEdits();
list.push(1);
dataSource.endEdits();
logger.setExpected([
"beginNotifications",
"inserted",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.push(3);
dataSource.endEdits();
logger.assertEmpty("checking correct push in empty list");
logger.setExpected([]);
dataSource.beginEdits();
list.move(0, 1);
dataSource.endEdits();
logger.assertEmpty("checking correct move");
dataSource.beginEdits();
list.push(10, 8, 7, 5);
dataSource.endEdits();
logger.setExpected([
"beginNotifications",
"removed",
"inserted",
]).
appendExpectedN("indexChanged", list.length - 1).
appendExpected(
"endNotifications"
);
dataSource.beginEdits();
list.setAt(0, 100);
dataSource.endEdits();
logger.assertEmpty("checking correct setAt to false predicate");
logger.setExpected([]);
dataSource.beginEdits();
list.splice(list.length, 0, 100);
dataSource.endEdits();
logger.assertEmpty("checking correct splice at the end");
logger.setExpected([
"beginNotifications",
"removed",
"indexChanged",
"indexChanged",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.splice(list.length - 3, 1);
dataSource.endEdits();
logger.assertEmpty("checking correct splice to delete");
}
testBindingListSortedProjectionMutationFunction() {
var logger = new LoggingNotificationHandler(true);
var list = sortedList();
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
logger.setExpected([
"beginNotifications",
"inserted",
"inserted",
"inserted",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.push(1, 2, 3);
dataSource.endEdits();
logger.assertEmpty("checking correct insertion");
logger.setExpected([
"beginNotifications",
"inserted",
"indexChanged",
"indexChanged",
"indexChanged",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.push(0);
dataSource.endEdits();
logger.assertEmpty("checking correct insertion");
dataSource.beginEdits();
list.pop();
list.pop();
dataSource.endEdits();
logger.setExpected([
"beginNotifications",
"removed",
"removed",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.pop();
list.pop();
list.pop();
dataSource.endEdits();
logger.assertEmpty("checking correct pop");
dataSource.beginEdits();
list.push(1);
dataSource.endEdits();
logger.setExpected([
"beginNotifications",
"inserted",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.push(3);
dataSource.endEdits();
logger.assertEmpty("checking correct push in empty list");
dataSource.beginEdits();
list.move(0, 1);
list.push(10, 8, 7, 5);
dataSource.endEdits();
logger.setExpected([
"beginNotifications",
"inserted",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.splice(list.length, 0, 100);
dataSource.endEdits();
logger.assertEmpty("checking correct splice at the end");
}
testBindingListSortedProjectionSplice() {
var logger = new LoggingNotificationHandler(true);
var list = sortedList();
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
logger.setExpected([
"beginNotifications",
"inserted",
"inserted",
"inserted",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.push(1, 2, 3);
dataSource.endEdits();
logger.assertEmpty("checking correct insertion");
logger.setExpected([
"beginNotifications",
"inserted",
"indexChanged",
"indexChanged",
"indexChanged",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.push(0);
dataSource.endEdits();
logger.assertEmpty("checking correct insertion");
dataSource.beginEdits();
list.pop();
list.pop();
dataSource.endEdits();
logger.setExpected([
"beginNotifications",
"removed",
"removed",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.pop();
list.pop();
list.pop();
dataSource.endEdits();
logger.assertEmpty("checking correct pop");
dataSource.beginEdits();
list.push(1);
dataSource.endEdits();
logger.setExpected([
"beginNotifications",
"inserted",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.push(3);
dataSource.endEdits();
logger.assertEmpty("checking correct push in empty list");
dataSource.beginEdits();
list.move(0, 1);
list.push(10, 8, 7, 5);
dataSource.endEdits();
logger.setExpected([
"beginNotifications",
"inserted",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.splice(list.length, 0, 100);
dataSource.endEdits();
logger.assertEmpty("checking correct splice at the end");
logger.setExpected([
"beginNotifications",
"inserted",
"indexChanged",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.splice(list.length - 3, 0, 11);
dataSource.endEdits();
logger.assertEmpty("checking correct splice to insert in the middle of the list");
logger.setExpected([
"beginNotifications",
"removed",
"indexChanged",
"indexChanged",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.splice(list.length - 3, 1);
dataSource.endEdits();
logger.assertEmpty("checking correct splice to delete");
logger.setExpected([
"beginNotifications",
"inserted",
]).
appendExpectedN("indexChanged", list.length).
appendExpected(
"countChanged",
"endNotifications"
);
dataSource.beginEdits();
list.splice(list.length - 3, 0, -2);
dataSource.endEdits();
logger.assertEmpty("checking correct splice to insert in the begining of the list");
}
testBindingListSortedWithShift() {
var logger = new LoggingNotificationHandler(true);
var list = sortedList();
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
logger.setExpected([
"beginNotifications",
"inserted",
"inserted",
"inserted",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.push(1, 2, 3);
dataSource.endEdits();
logger.assertEmpty("checking correct insertion");
logger.setExpected([
"beginNotifications",
"inserted",
"indexChanged",
"indexChanged",
"indexChanged",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.push(0);
dataSource.endEdits();
logger.assertEmpty("checking correct insertion");
dataSource.beginEdits();
list.pop();
list.pop();
dataSource.endEdits();
LiveUnit.Assert.areEqual(2, list.length);
logger.setExpected([
"beginNotifications",
"removed",
"removed",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.pop();
list.pop();
list.pop();
dataSource.endEdits();
logger.assertEmpty("checking correct pop");
dataSource.beginEdits();
list.push(1);
dataSource.endEdits();
logger.setExpected([
"beginNotifications",
"inserted",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.push(3);
dataSource.endEdits();
logger.assertEmpty("checking correct push in empty list");
dataSource.beginEdits();
list.move(0, 1);
list.push(10, 8, 7, 5);
dataSource.endEdits();
logger.setExpected([
"beginNotifications",
"removed"
]).
appendExpectedN("indexChanged", list.length - 1).
appendExpected(
"countChanged",
"endNotifications"
);
dataSource.beginEdits();
list.shift();
dataSource.endEdits();
logger.assertEmpty("checking correct shift");
}
testBindingListDecreasingTheLenghInGroupSorted() {
var logger = new LoggingNotificationHandler(true);
var list = listGroupedByOddAndEven();
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
dataSource.beginEdits();
list.push(1, 2, 3, 4, 5, 6, 7, 8, 9);
dataSource.endEdits();
logger.setExpected([
"beginNotifications",
"removed",
"removed",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.length = list.length - 2;
dataSource.endEdits();
logger.assertEmpty("checking correct decreasing length in groupSorted");
}
testBindingListDataSourcePushInGroupSorted() {
var logger = new LoggingNotificationHandler(true);
var list = listGroupedByOddAndEven();
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
logger.setExpected([
"beginNotifications",
"inserted",
"inserted",
"inserted",
"indexChanged",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.push(1, 2, 3);
dataSource.endEdits();
logger.assertEmpty("checking correct push in groupSortedProjection");
}
testBindingListDataSourcePopInGroupSorted() {
var logger = new LoggingNotificationHandler(true);
var list = listGroupedByOddAndEven();
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
dataSource.beginEdits();
list.push(1, 2, 3);
dataSource.endEdits();
logger.setExpected([
"beginNotifications",
"removed",
"removed",
"removed",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.pop();
list.pop();
list.pop();
list.pop();
dataSource.endEdits();
logger.assertEmpty("checking correct pop in groupSortedProjection");
}
testBindingListDataSourceMoveInGroupSorted() {
var logger = new LoggingNotificationHandler(true);
var list = listGroupedByOddAndEven();
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
dataSource.beginEdits();
list.push(1, 2, 3, 4);
dataSource.endEdits();
logger.setExpected([
"beginNotifications",
"indexChanged",
"indexChanged",
"moved",
"endNotifications"
]);
dataSource.beginEdits();
list.move(0, 1);
dataSource.endEdits();
logger.assertEmpty("checking correct move");
dataSource.beginEdits();
list.splice(0, 1);
dataSource.endEdits();
dataSource.beginEdits();
list.move(0, 3);
dataSource.endEdits();
}
testBindingListDataSourceShiftInGroupSorted() {
var logger = new LoggingNotificationHandler(true);
var list = listGroupedByOddAndEven();
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
dataSource.beginEdits();
list.push(1, 2, 3, 4, 5, 8, 7, 10, 9);
dataSource.endEdits();
logger.setExpected([
"beginNotifications",
"removed"
]).
appendExpectedN("indexChanged", list.length - 1).
appendExpected(
"countChanged",
"endNotifications"
);
dataSource.beginEdits();
list.shift();
dataSource.endEdits();
logger.assertEmpty("checking correct shift in groupSorted");
}
testBindingListDataSourceUnShiftInGroupSorted() {
var logger = new LoggingNotificationHandler(true);
var list = listGroupedByOddAndEven();
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
dataSource.beginEdits();
list.push(1, 2, 3, 4, 5, 8, 7, 10, 9);
dataSource.endEdits();
logger.setExpected([
"beginNotifications",
"inserted"
]).
appendExpectedN("indexChanged", list.length).
appendExpected(
"countChanged",
"endNotifications"
);
dataSource.beginEdits();
list.unshift(11);
dataSource.endEdits();
logger.assertEmpty("checking correct unshift in groupSorted");
var numOfEvens = (function (list) {
var count = 0;
for (var i = 0; i < list.length; i++) {
if (list.getAt(i) % 2 === 0) {
count++;
}
}
return count;
})(list);
logger.setExpected([
"beginNotifications",
"inserted"
]).
appendExpectedN("indexChanged", numOfEvens).
appendExpected(
"countChanged",
"endNotifications"
);
dataSource.beginEdits();
list.unshift(6);
dataSource.endEdits();
logger.assertEmpty("checking correct unshift in groupSorted");
}
testBindingListDataSourceSpliceInGroupSortedWithSpeicalStableInsert() {
var logger = new LoggingNotificationHandler(true);
var list = listGroupedByOddAndEven();
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
dataSource.beginEdits();
list.push(1, 2, 3, 4, 5, 8, 7, 10, 9);
dataSource.endEdits();
//before splice: 1, 3, 5, 7, 9, 2, 4, 8, 10
logger.setExpected([
"beginNotifications",
"removed"
]).
appendExpectedN("indexChanged", list.length - 1).
appendExpected(
"countChanged",
"endNotifications"
);
dataSource.beginEdits();
list.splice(0, 1);
dataSource.endEdits();
logger.assertEmpty("testing splice to delete from the begining in groupSorted");
var ind = 3;
logger.setExpected([
"beginNotifications",
"inserted"
]).
appendExpectedN("indexChanged", list.length - ind).
appendExpected(
"countChanged",
"endNotifications"
);
dataSource.beginEdits();
list.splice(ind, 0, 11);
dataSource.endEdits();
//before splice: 3, 5, 7, 9, 2, 4, 8, 10
//After splice: 3, 5, 7, 11, 9, 2, 4, 8, 10
logger.assertEmpty("checking the correct adding of an element using splice");
logger.setExpected([
"beginNotifications",
"inserted"
]).
appendExpectedN("indexChanged", 3).
appendExpected(
"countChanged",
"endNotifications"
);
dataSource.beginEdits();
list.splice(0, 0, 4);
dataSource.endEdits();
//before splice: 3, 5, 7, 11, 9, 2, 4, 8, 10
//After splice: 3, 5, 7, 11, 9, 2, 4, 4, 8, 10
logger.assertEmpty("checking deleting elements using splice");
}
testBindingListDataSourceSpliceInGroupSorted() {
var logger = new LoggingNotificationHandler(true);
var list = listGroupedByOddAndEven();
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
dataSource.beginEdits();
list.push(1, 2, 3, 4, 5, 8, 7, 10, 9);
dataSource.endEdits();
//before splice: 1, 3, 5, 7, 9, 2, 4, 8, 10
logger.setExpected([
"beginNotifications",
"removed"
]).
appendExpectedN("indexChanged", list.length - 1).
appendExpected(
"countChanged",
"endNotifications"
);
dataSource.beginEdits();
list.splice(0, 1);
dataSource.endEdits();
logger.assertEmpty("testing splice to delete from the begining in groupSorted");
var ind = 3;
logger.setExpected([
"beginNotifications",
"inserted"
]).
appendExpectedN("indexChanged", list.length - ind).
appendExpected(
"countChanged",
"endNotifications"
);
dataSource.beginEdits();
list.splice(ind, 0, 11);
dataSource.endEdits();
//before splice: 3, 5, 7, 9, 2, 4, 8, 10
//After splice: 3, 5, 7, 11, 9, 2, 4, 8, 10
logger.assertEmpty("checking the correct adding of an element using splice");
}
testBindingListDataSourceSetAtInGroupSorted() {
var logger = new LoggingNotificationHandler(true);
var list = listGroupedByOddAndEven();
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
dataSource.beginEdits();
list.push(1, 2, 3, 4, 5, 8, 7, 10, 9);
dataSource.endEdits();
logger.setExpected([
"beginNotifications",
"removed",
"inserted"
]).
appendExpectedN("indexChanged", 4).
appendExpected(
"endNotifications"
);
//before setAt: 1, 3, 5, 7, 9, 2, 4, 8, 10
//After setAt: 3, 5, 7, 9, 6, 2, 4, 8, 10
dataSource.beginEdits();
list.setAt(0, 6);
dataSource.endEdits();
logger.assertEmpty("checking the correctness of setAt in GroupSorted");
}
testBindingListDataSourceFilterOfFilter() {
var options = [undefined, { proxy: true }, { binding: true }, { proxy: true, binding: true }];
for (var i = 0; i < options.length; i++) {
var logger = new LoggingNotificationHandler(true);
var list = listSortedAndFilteredToEvens(0, options[i]);
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
var sorted = (<any>list)._list;
dataSource.beginEdits();
list.push(10, 8, 7, 12, 3, 4, -1, 0, -2, 11);
dataSource.endEdits();
// sorted list :[-2, -1, 0, 3, 4, 7, 8, 10, 11, 12]
//Even sorted list: [-2, 0, 4, 8, 10, 12];
logger.setExpected([
"beginNotifications",
"inserted",
]).
appendExpectedN("indexChanged", 4).
appendExpected(
"countChanged",
"endNotifications"
);
dataSource.beginEdits();
list.push(13, 15, 7, 2, 21);
dataSource.endEdits();
logger.setExpected([
"beginNotifications",
"removed",
]).
appendExpectedN("indexChanged", list.length - 1).
appendExpected(
"countChanged",
"endNotifications"
);
dataSource.beginEdits();
list.setAt(0, 1);
dataSource.endEdits();
//After setAt Even sorted list: [0, 2, 4, 8, 10, 12];
logger.assertEmpty("checking the correctness of push in filter of filter");
logger.setExpected([
"beginNotifications",
"removed",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.pop();
dataSource.endEdits();
//After pop Even sorted list: [0, 2, 4, 8, 10];
logger.assertEmpty("checking the correctness of push in filter of filter");
LiveUnit.Assert.areEqual(5, list.length, "Checking the length after pop and setAt");
// sorted list :[-1, 1, 2, 3, 4, 7, 8, 10]
dataSource.beginEdits();
sorted.pop();
dataSource.endEdits();
logger.assertEmpty("making sure that poping an even element does not affect the filter of filter");
logger.setExpected([
"beginNotifications",
"inserted"
]).
appendExpectedN("indexChanged", list.length).
appendExpected(
"countChanged",
"endNotifications"
);
dataSource.beginEdits();
sorted.setAt(sorted.length - 1, -12);
dataSource.endEdits();
logger.assertEmpty("checking setAt from the main filter");
//After setAt Even sorted list: [-12, 0, 2, 4, 8, 10];
logger.setExpected([
"beginNotifications",
"removed",
"removed",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.length = list.length - 2;
dataSource.endEdits();
//After changing the length: Even sorted list: [-12, 0, 2, 4];
logger.assertEmpty("checking the correctness of notificatios after changing the length");
logger.setExpected([
"beginNotifications",
"removed",
]).
appendExpectedN("indexChanged", list.length - 1).
appendExpected(
"countChanged",
"endNotifications"
);
dataSource.beginEdits();
list.shift();
dataSource.endEdits();
logger.assertEmpty("checking the correctness of notificatios after shifting an element");
dataSource.beginEdits();
list.unshift(13);
dataSource.endEdits();
logger.setExpected([
"beginNotifications",
"inserted",
"inserted",
"inserted"
]).
appendExpectedN("indexChanged", list.length + 1).
appendExpected(
"countChanged",
"endNotifications"
);
dataSource.beginEdits();
list.unshift(-52);
list.unshift(52);
list.unshift(50);
dataSource.endEdits();
logger.assertEmpty("checking the correctness of notificatios after unshifting invalid number");
logger.setExpected([
"beginNotifications",
"removed",
"inserted",
"inserted"
]).
appendExpectedN("indexChanged", list.length).
appendExpected(
"countChanged",
"endNotifications"
);
dataSource.beginEdits();
list.splice(0, 1);
list.splice(0, 0, 56);
list.splice(0, 0, 43);
sorted.splice(0, 0, 54);
sorted.splice(0, 0, 53);
dataSource.endEdits();
logger.assertEmpty("checking the correctness of notificatios after splice");
}
}
testBindingListDataSourceMutationFunction(complete) {
var logger = new LoggingNotificationHandler();
var list = new WinJS.Binding.List();
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
logger.setExpected([
"beginNotifications",
"inserted",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
dataSource.insertAtEnd(null, 100);
dataSource.endEdits();
LiveUnit.Assert.isTrue(verifyListContent(list, [100]));
logger.assertEmpty();
dataSource.beginEdits();
dataSource.insertAtEnd(null, 90);
LiveUnit.Assert.isTrue(verifyListContent(list, [100, 90]));
dataSource.insertAtStart(null, 80);
LiveUnit.Assert.isTrue(verifyListContent(list, [80, 100, 90]));
list.pop();
list.pop();
list.pop();
dataSource.insertAtStart(null, 80);
LiveUnit.Assert.isTrue(verifyListContent(list, [80]));
dataSource.insertAtStart(null, 70);
LiveUnit.Assert.isTrue(verifyListContent(list, [70, 80]));
dataSource.beginEdits();
listBinding.next()
.then(scanFor(listBinding, 70))
.then(function (item) {
dataSource.insertBefore(null, 60, item.key);
dataSource.insertAfter(null, 75, item.key);
LiveUnit.Assert.isTrue(verifyListContent(list, [60, 70, 75, 80]), "checking the correctness of insertAfter and before");
return listBinding.next();
})
.then(function (item) {
dataSource.moveToStart(item.key);
LiveUnit.Assert.isTrue(verifyListContent(list, [75, 60, 70, 80]), "checking the correctness of moveToStart");
return listBinding.previous();
})
.then(function (item) {
dataSource.moveToEnd(item.key);
LiveUnit.Assert.isTrue(verifyListContent(list, [75, 70, 80, 60]), "checking the correctness of moveToEnd");
dataSource.change(item.key, 100);
LiveUnit.Assert.isTrue(verifyListContent(list, [75, 70, 80, 100]), "checking the correctness of change");
return listBinding.previous();
})
.then<any>(function (item) {
dataSource.remove(item.key);
LiveUnit.Assert.isTrue(verifyListContent(list, [70, 80, 100]), "checking the correctness of remove");
dataSource.insertAtStart(null, 50);
dataSource.insertAtStart(null, 40);
LiveUnit.Assert.isTrue(verifyListContent(list, [40, 50, 70, 80, 100]), "checking the correctness of insertion after multiple mutations");
return WinJS.Promise.join({
current: listBinding.current(), // 70
next: listBinding.next(), // 80
nextNext: listBinding.next() // 100
});
})
.then(function (items) {
dataSource.moveBefore(items.next.key, items.current.key);
dataSource.moveAfter(items.nextNext.key, items.next.key);
LiveUnit.Assert.isTrue(verifyListContent(list, [40, 50, 80, 100, 70]), "checking the correctness of list after multiple moves");
dataSource.moveBefore(items.current.key, items.current.key); //move before with same keys should be a noop
dataSource.moveAfter(items.next.key, items.next.key); //move after with same keys should be a noop
LiveUnit.Assert.isTrue(verifyListContent(list, [40, 50, 80, 100, 70]), "checking the correctness of list after noop moves");
return WinJS.Promise.timeout();
})
.then(null, errorHandler)
.then(complete);
}
testBindingListMoveBeforeAndAFterWithSameKey(complete) {
var logger = new LoggingNotificationHandler();
var list = new WinJS.Binding.List();
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
logger.setExpected([
"beginNotifications",
"inserted",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
dataSource.insertAtEnd(null, 100);
dataSource.endEdits();
LiveUnit.Assert.isTrue(verifyListContent(list, [100]));
logger.assertEmpty();
dataSource.beginEdits();
dataSource.insertAtEnd(null, 90);
LiveUnit.Assert.isTrue(verifyListContent(list, [100, 90]));
dataSource.insertAtStart(null, 80);
LiveUnit.Assert.isTrue(verifyListContent(list, [80, 100, 90]));
dataSource.insertAtEnd(null, 110);
LiveUnit.Assert.isTrue(verifyListContent(list, [80, 100, 90, 110]));
listBinding.next()
.then(scanFor(listBinding, 100))
.then(function (item) {
dataSource.moveBefore(item.key, item.key);
LiveUnit.Assert.isTrue(verifyListContent(list, [80, 100, 90, 110]), "checking the correctness of moveBefore");
return listBinding.next();
})
.then(function (item) {
dataSource.moveAfter(item.key, item.key);
LiveUnit.Assert.isTrue(verifyListContent(list, [80, 100, 90, 110]), "checking the correctness of moveAfter");
})
.then(null, errorHandler)
.then(complete);
}
testBindingFilteredListDataSourceMutationFunction(complete) {
var logger = new LoggingNotificationHandler(true);
var list = oddListFilter();
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
dataSource.beginEdits();
dataSource.insertAtEnd(null, 100);
dataSource.endEdits();
LiveUnit.Assert.isTrue(verifyListContent(list, []));
logger.setExpected([
"beginNotifications",
"inserted",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
dataSource.insertAtEnd(null, 101);
dataSource.endEdits();
LiveUnit.Assert.isTrue(verifyListContent(list, [101]));
logger.assertEmpty();
dataSource.insertAtEnd(null, 91);
LiveUnit.Assert.isTrue(verifyListContent(list, [101, 91]));
dataSource.insertAtStart(null, 80);
LiveUnit.Assert.isTrue(verifyListContent(list, [101, 91]));
dataSource.insertAtStart(null, 81);
LiveUnit.Assert.isTrue(verifyListContent(list, [81, 101, 91]));
list.pop();
list.pop();
list.pop();
dataSource.insertAtStart(null, 80);
LiveUnit.Assert.isTrue(verifyListContent(list, []));
dataSource.insertAtStart(null, 81);
dataSource.insertAtStart(null, 71);
LiveUnit.Assert.isTrue(verifyListContent(list, [71, 81]));
listBinding.next()
.then(scanFor(listBinding, 71))
.then(function (item) {
var key = item.key;
dataSource.insertBefore(null, 60, key);
dataSource.insertBefore(null, 61, key);
dataSource.insertAfter(null, 75, key);
dataSource.insertAfter(null, 70, key);
LiveUnit.Assert.isTrue(verifyListContent(list, [61, 71, 75, 81]), "checking the correctness of insertAfter and before");
return listBinding.next();
})
.then(function (item) {
dataSource.moveToStart(item.key);
LiveUnit.Assert.isTrue(verifyListContent(list, [75, 61, 71, 81]), "checking the correctness of moveToStart");
return listBinding.previous();
})
.then(function (item) {
dataSource.moveToEnd(item.key);
LiveUnit.Assert.isTrue(verifyListContent(list, [75, 71, 81, 61]), "checking the correctness of moveToEnd");
dataSource.change(item.key, 100);
LiveUnit.Assert.isTrue(verifyListContent(list, [75, 71, 81]), "checking the correctness of change");
dataSource.insertAtEnd(item.key, 101);
return listBinding.previous();
})
.then<any>(function (item) {
dataSource.remove(item.key);
LiveUnit.Assert.isTrue(verifyListContent(list, [71, 81, 101]), "checking the correctness of remove");
dataSource.insertAtStart(null, 51);
dataSource.insertAtStart(null, 41);
LiveUnit.Assert.isTrue(verifyListContent(list, [41, 51, 71, 81, 101]), "checking the correctness of insertion after multiple mutations");
return WinJS.Promise.join({
current: listBinding.current(), // 71
next: listBinding.next(), // 81
nextNext: listBinding.next() // 101
});
})
.then(function (items) {
dataSource.moveBefore(items.next.key, items.current.key);
dataSource.moveAfter(items.nextNext.key, items.next.key);
LiveUnit.Assert.isTrue(verifyListContent(list, [41, 51, 81, 101, 71]), "checking the correctness of list after multiple moves");
return WinJS.Promise.timeout();
})
.then(null, errorHandler)
.then(complete);
}
testBindingSortedListDataSourceMutationFunction(complete) {
var logger = new LoggingNotificationHandler(true);
var list = sortedList();
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
logger.setExpected([
"beginNotifications",
"inserted",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
dataSource.insertAtEnd(null, 101);
dataSource.endEdits();
LiveUnit.Assert.isTrue(verifyListContent(list, [101]));
logger.assertEmpty();
dataSource.insertAtEnd(null, 91);
LiveUnit.Assert.isTrue(verifyListContent(list, [91, 101]));
dataSource.insertAtStart(null, 80);
LiveUnit.Assert.isTrue(verifyListContent(list, [80, 91, 101]));
dataSource.insertAtStart(null, 81);
LiveUnit.Assert.isTrue(verifyListContent(list, [80, 81, 91, 101]));
listBinding.next()
.then(scanFor(listBinding, 80))
.then(function (item) {
var key = item.key;
dataSource.insertBefore(null, 60, key);
dataSource.insertAfter(null, 75, key);
LiveUnit.Assert.isTrue(verifyListContent(list, [60, 75, 80, 81, 91, 101]), "checking the correctness of insertAfter and before");
return listBinding.next();
})
.then(function (item) {
dataSource.moveToStart(item.key);
LiveUnit.Assert.isTrue(verifyListContent(list, [60, 75, 80, 81, 91, 101]), "checking the correctness of moveToStart");
return listBinding.previous();
})
.then(function (item) {
dataSource.moveToEnd(item.key);
LiveUnit.Assert.isTrue(verifyListContent(list, [60, 75, 80, 81, 91, 101]), "checking the correctness of moveToEnd");
dataSource.change(item.key, -100);
LiveUnit.Assert.isTrue(verifyListContent(list, [-100, 60, 75, 81, 91, 101]), "checking the correctness of change");
return listBinding.previous();
})
.then(function (item) {
dataSource.remove(item.key);
LiveUnit.Assert.isTrue(verifyListContent(list, [-100, 60, 81, 91, 101]), "checking the correctness of remove");
dataSource.insertAtStart(null, 50);
dataSource.insertAtStart(null, 40);
LiveUnit.Assert.isTrue(verifyListContent(list, [-100, 40, 50, 60, 81, 91, 101]), "checking the correctness of insertion after multiple mutations");
return WinJS.Promise.join({
current: listBinding.current(),
next: listBinding.next(),
nextNext: listBinding.next()
});
})
.then(function (items) {
dataSource.moveBefore(items.next.key, items.current.key);
dataSource.moveAfter(items.nextNext.key, items.next.key);
LiveUnit.Assert.isTrue(verifyListContent(list, [-100, 40, 50, 60, 81, 91, 101]), "checking the correctness of list after multiple moves");
dataSource.moveBefore(items.current.key, items.current.key); //move before with same keys should be a noop
dataSource.moveAfter(items.next.key, items.next.key); //move after with same keys should be a noop
LiveUnit.Assert.isTrue(verifyListContent(list, [-100, 40, 50, 60, 81, 91, 101]), "checking the correctness of list after noop moves");
return WinJS.Promise.timeout();
})
.then(null, errorHandler)
.then(complete);
}
testBindingListInGroupSorted() {
var logger = new LoggingNotificationHandler(true);
var list = listGroupedByOddAndEven();
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
dataSource.beginEdits();
list.push(1, 2, 3, 4);
dataSource.endEdits();
//1, 3, 2, 4
logger.setExpected([
"beginNotifications",
"inserted",
"inserted",
"indexChanged",
"indexChanged",
"indexChanged",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
list.push(0);
list.push(5);
dataSource.endEdits();
//1, 3, 5, 2, 4, 0
LiveUnit.Assert.isTrue(verifyListContent(list, [1, 3, 5, 2, 4, 0]));
logger.assertEmpty();
logger.setExpected([
"beginNotifications",
"removed",
"removed"
])
.appendExpectedN("indexChanged", list.length - 2)
.appendExpected(
"countChanged",
"endNotifications"
);
dataSource.beginEdits();
list.splice(0, 2);
dataSource.endEdits();
//5, 2, 4, 0
LiveUnit.Assert.isTrue(verifyListContent(list, [5, 2, 4, 0]));
logger.assertEmpty();
dataSource.beginEdits();
list.pop();
list.pop();
list.pop();
list.pop();
list.push(1, 2, 3, 4, 5, 6);
dataSource.endEdits();
//1, 3, 5, 2, 4, 6
LiveUnit.Assert.isTrue(verifyListContent(list, [1, 3, 5, 2, 4, 6]));
logger.setExpected([
"beginNotifications",
"indexChanged",
"indexChanged",
"moved",
"endNotifications"
]);
dataSource.beginEdits();
list.move(0, 1);
dataSource.endEdits();
logger.assertEmpty();
}
testBindingGroupSortedListDataSourceMutationFunction() {
var logger = new LoggingNotificationHandler(true);
var list = listGroupedByOddAndEven();
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
logger.setExpected([
"beginNotifications",
"inserted",
"countChanged",
"endNotifications"
]);
dataSource.beginEdits();
dataSource.insertAtEnd(null, 101);
dataSource.endEdits();
LiveUnit.Assert.isTrue(verifyListContent(list, [101]));
logger.assertEmpty();
dataSource.insertAtEnd(null, 90);
LiveUnit.Assert.isTrue(verifyListContent(list, [101, 90]));
LiveUnit.Assert.areEqual("odd", list.groups.getAt(0), "checking the group content");
LiveUnit.Assert.areEqual("even", list.groups.getAt(1), "checking the group content");
dataSource.insertAtStart(null, 80);
LiveUnit.Assert.isTrue(verifyListContent(list, [101, 80, 90]));
dataSource.insertAtStart(null, 81);
LiveUnit.Assert.isTrue(verifyListContent(list, [81, 101, 80, 90]));
}
testBindingGroupSortedListDataSourceMutationFunction2(complete) {
var logger = new LoggingNotificationHandler(true);
var list = listGroupedByOddAndEven(5);
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
dataSource.insertAtEnd(null, 101);
LiveUnit.Assert.isTrue(verifyListContent(list, [1, 3, 101, 0, 2, 4]));
dataSource.insertAtEnd(null, 90);
LiveUnit.Assert.isTrue(verifyListContent(list, [1, 3, 101, 0, 2, 4, 90]));
LiveUnit.Assert.areEqual("odd", list.groups.getAt(0), "checking the group content");
LiveUnit.Assert.areEqual("even", list.groups.getAt(1), "checking the group content");
listBinding.next()
.then(scanFor(listBinding, 3))
.then(function (item) {
var key = item.key;
dataSource.insertBefore(null, 60, key);
dataSource.insertAfter(null, 75, key);
LiveUnit.Assert.isTrue(verifyListContent(list, [1, 3, 75, 101, 0, 2, 60, 4, 90]), "checking the correctness of insertAfter and before");
return listBinding.next();
})
.then(function (item) {
dataSource.moveToStart(item.key);
LiveUnit.Assert.isTrue(verifyListContent(list, [75, 1, 3, 101, 0, 2, 60, 4, 90]), "checking the correctness of moveToStart");
return listBinding.previous();
})
.then(function (item) {
dataSource.moveToEnd(item.key);
LiveUnit.Assert.isTrue(verifyListContent(list, [75, 3, 101, 1, 0, 2, 60, 4, 90]), "checking the correctness of moveToEnd");
return listBinding.current();
})
.then(function (item) {
dataSource.change(item.key, 100);
LiveUnit.Assert.isTrue(verifyListContent(list, [75, 101, 1, 0, 2, 60, 100, 4, 90]), "checking the correctness of change");
})
.then(null, errorHandler)
.then(complete);
}
testBindingGroupSortedListDataSourceMutationFunction3(complete) {
var logger = new LoggingNotificationHandler(true);
var list = listGroupedByOddAndEven(5);
var dataSource = list.dataSource;
var listBinding = dataSource.createListBinding(logger);
dataSource.insertAtEnd(null, 101);
LiveUnit.Assert.isTrue(verifyListContent(list, [1, 3, 101, 0, 2, 4]));
dataSource.insertAtEnd(null, 90);
LiveUnit.Assert.isTrue(verifyListContent(list, [1, 3, 101, 0, 2, 4, 90]));
LiveUnit.Assert.areEqual("odd", list.groups.getAt(0), "checking the group content");
LiveUnit.Assert.areEqual("even", list.groups.getAt(1), "checking the group content");
listBinding.next()
.then(scanFor(listBinding, 3))
.then(function (item) {
var key = item.key;
dataSource.insertBefore(null, 60, key);
dataSource.insertAfter(null, 75, key);
LiveUnit.Assert.isTrue(verifyListContent(list, [1, 3, 75, 101, 0, 2, 60, 4, 90]), "checking the correctness of insertAfter and before");
return listBinding.next();
})
.then(function (item) {
dataSource.moveToStart(item.key);
LiveUnit.Assert.isTrue(verifyListContent(list, [75, 1, 3, 101, 0, 2, 60, 4, 90]), "checking the correctness of moveToStart");
return listBinding.previous();
})
.then<any>(function (item) {
dataSource.moveToEnd(item.key);
LiveUnit.Assert.isTrue(verifyListContent(list, [75, 3, 101, 1, 0, 2, 60, 4, 90]), "checking the correctness of moveToEnd");
return WinJS.Promise.join({
current: listBinding.next(),
next: listBinding.next(),
nextNext: listBinding.next()
});
})
.then(function (items) {
dataSource.moveBefore(items.next.key, items.current.key);
dataSource.moveAfter(items.nextNext.key, items.next.key);
LiveUnit.Assert.isTrue(verifyListContent(list, [75, 3, 1, 101, 2, 60, 4, 0, 90]), "checking the correctness of list after multiple moves");
dataSource.moveBefore(items.current.key, items.current.key); //move before with same keys should be a noop
dataSource.moveAfter(items.next.key, items.next.key); //move after with same keys should be a noop
LiveUnit.Assert.isTrue(verifyListContent(list, [75, 3, 1, 101, 2, 60, 4, 0, 90]), "checking the correctness of list after noop moves");
dataSource.insertAtStart(null, 50);
dataSource.insertAtStart(null, 40);
LiveUnit.Assert.isTrue(verifyListContent(list, [75, 3, 1, 101, 50, 40, 2, 60, 4, 0, 90]), "checking the correctness of insertion after multiple mutations");
})
.then(null, errorHandler)
.then(complete);
}
testBindingGroupSortedListMutatingGroup(complete) {
function groupKeySelector(item) {
return item.group.key;
}
function groupDataSelector(item) {
return {
title: item.group.key,
}
}
var list = new WinJS.Binding.List<{ group: { key: string }; title: string }>();
var groupedItems = list.createGrouped(groupKeySelector, groupDataSelector);
var logger = new LoggingNotificationHandler(true);
var dataSource = groupedItems.dataSource;
var listBinding = dataSource.createListBinding(logger);
var groupsListBinding = groupedItems.groups.dataSource.createListBinding();
dataSource.beginEdits();
list.push({ group: { key: "1" }, title: "Banana" });
list.push({ group: { key: "2" }, title: "Peach" });
list.push({ group: { key: "1" }, title: "Blueberry" });
list.push({ group: { key: "2" }, title: "Plum" });
dataSource.endEdits();
LiveUnit.Assert.areEqual("Banana,Blueberry,Peach,Plum", groupedItems.map(function (item) { return item.title; }).join());
groupedItems.getAt(0).group.key = "2";
logger.setExpected([
"beginNotifications",
"removed",
"inserted",
"indexChanged",
"endNotifications"
]);
dataSource.beginEdits();
groupedItems.notifyMutated(0);
dataSource.endEdits();
logger.assertEmpty();
LiveUnit.Assert.areEqual("Blueberry,Banana,Peach,Plum", groupedItems.map(function (item) { return item.title; }).join());
var assertItems = listBinding.next()
.then(function (item) {
LiveUnit.Assert.areEqual("Blueberry", item.data.title);
LiveUnit.Assert.areEqual("1", item.groupKey);
return listBinding.next();
})
.then(function (item) {
LiveUnit.Assert.areEqual("Banana", item.data.title);
LiveUnit.Assert.areEqual("2", item.groupKey);
return listBinding.next();
})
.then(function (item) {
LiveUnit.Assert.areEqual("Peach", item.data.title);
LiveUnit.Assert.areEqual("2", item.groupKey);
return listBinding.next();
})
.then(function (item) {
LiveUnit.Assert.areEqual("Plum", item.data.title);
LiveUnit.Assert.areEqual("2", item.groupKey);
});
var assertGroups = groupsListBinding.next()
.then(function (group: any) {
LiveUnit.Assert.areEqual("1", group.data.title);
LiveUnit.Assert.areEqual(1, group.groupSize);
LiveUnit.Assert.areEqual(0, group.firstItemIndexHint);
LiveUnit.Assert.areEqual(list.getItem(2).key, group.firstItemKey);
return groupsListBinding.next();
})
.then(function (group: any) {
LiveUnit.Assert.areEqual("2", group.data.title);
LiveUnit.Assert.areEqual(3, group.groupSize);
LiveUnit.Assert.areEqual(1, group.firstItemIndexHint);
LiveUnit.Assert.areEqual(list.getItem(0).key, group.firstItemKey);
});
WinJS.Promise.join([assertItems, assertGroups])
.then(null, errorHandler)
.then(complete);
}
testBindingListDirectAccess(complete) {
var testArray = [10, 20, 30, 40, 50],
testIndex = 2;
var list = new WinJS.Binding.List(testArray),
dataSource = list.dataSource;
dataSource.itemFromIndex(testIndex)
.then(function (item) {
LiveUnit.Assert.areEqual(testIndex, item.index);
LiveUnit.Assert.areEqual(testArray[testIndex], item.data);
return dataSource.itemFromKey(item.key);
})
.then(function (item) {
LiveUnit.Assert.areEqual(testIndex, item.index);
LiveUnit.Assert.areEqual(testArray[testIndex], item.data);
})
.then(complete);
}
}
function parent(element) {
document.body.appendChild(element);
return function () { document.body.removeChild(element); };
}
export class BindingListWithListViewTests {
testListViewInstantiation(complete) {
var div = document.createElement("DIV");
var cleanup = parent(div);
var list = new WinJS.Binding.List([1, 2, 3]);
var lv = new WinJS.UI.ListView(div);
lv.itemDataSource = list.dataSource;
Helper.ListView.waitForReady(lv)()
.then(function () {
LiveUnit.Assert.areEqual(3, div.querySelectorAll(".win-container").length);
})
.then(null, errorHandler)
.then(cleanup)
.done(complete);
}
};
// Register the object as a test class by passing in the name
LiveUnit.registerTestClass("WinJSTests.BindingListTests");
LiveUnit.registerTestClass("WinJSTests.BindingListFilteredProjectionTests");
LiveUnit.registerTestClass("WinJSTests.BindingListWithListViewTests");
} | the_stack |
import {
MessagePanelView,
PlainMessageView,
LineMessageView,
} from 'atom-message-panel'
import { InformationView } from './views/information-view'
import { HolesView } from './views/holes-view'
import Logger from './utils/Logger'
import { IdrisModel } from './idris-model'
import * as Ipkg from './utils/ipkg'
import * as Symbol from './utils/symbol'
import { getWordUnderCursor, moveToNextEmptyLine } from './utils/editor'
import * as highlighter from './utils/highlighter'
import {
TextEditor,
RangeCompatible,
DisplayMarker,
Pane,
WorkspaceOpenOptions,
} from 'atom'
export class IdrisController {
errorMarkers: Array<DisplayMarker> = []
model: IdrisModel = new IdrisModel()
messages: MessagePanelView = new MessagePanelView({
title: 'Idris Messages',
})
constructor() {
this.prefixLiterateClause = this.prefixLiterateClause.bind(this)
this.clearMessagePanel = this.clearMessagePanel.bind(this)
this.hideAndClearMessagePanel = this.hideAndClearMessagePanel.bind(this)
this.stopCompiler = this.stopCompiler.bind(this)
this.runCommand = this.runCommand.bind(this)
this.provideReplCompletions = this.provideReplCompletions.bind(this)
this.typecheckFile = this.typecheckFile.bind(this)
this.getDocsForWord = this.getDocsForWord.bind(this)
this.getTypeForWord = this.getTypeForWord.bind(this)
this.doCaseSplit = this.doCaseSplit.bind(this)
this.doAddClause = this.doAddClause.bind(this)
this.doAddProofClause = this.doAddProofClause.bind(this)
this.doMakeWith = this.doMakeWith.bind(this)
this.doMakeLemma = this.doMakeLemma.bind(this)
this.doMakeCase = this.doMakeCase.bind(this)
this.showHoles = this.showHoles.bind(this)
this.doProofSearch = this.doProofSearch.bind(this)
this.doBrowseNamespace = this.doBrowseNamespace.bind(this)
this.printDefinition = this.printDefinition.bind(this)
this.openREPL = this.openREPL.bind(this)
this.apropos = this.apropos.bind(this)
this.displayErrors = this.displayErrors.bind(this)
}
getCommands() {
return {
'language-idris:type-of': this.runCommand(this.getTypeForWord),
'language-idris:docs-for': this.runCommand(this.getDocsForWord),
'language-idris:case-split': this.runCommand(this.doCaseSplit),
'language-idris:add-clause': this.runCommand(this.doAddClause),
'language-idris:make-with': this.runCommand(this.doMakeWith),
'language-idris:make-lemma': this.runCommand(this.doMakeLemma),
'language-idris:make-case': this.runCommand(this.doMakeCase),
'language-idris:holes': this.runCommand(this.showHoles),
'language-idris:proof-search': this.runCommand(this.doProofSearch),
'language-idris:typecheck': this.runCommand(this.typecheckFile),
'language-idris:print-definition': this.runCommand(
this.printDefinition,
),
// 'language-idris:stop-compiler': this.stopCompiler,
'language-idris:open-repl': this.runCommand(this.openREPL),
'language-idris:apropos': this.runCommand(this.apropos),
'language-idris:add-proof-clause': this.runCommand(
this.doAddProofClause,
),
'language-idris:browse-namespace': this.runCommand(
this.doBrowseNamespace,
),
'language-idris:close-information-view': this
.hideAndClearMessagePanel,
}
}
// check if this is a literate idris file
isLiterateGrammar(): boolean {
return (
this.getEditor()?.getGrammar().scopeName === 'source.idris.literate'
)
}
// prefix code lines with "> " if we are in the literate grammar
prefixLiterateClause(clause: Array<string>): Array<string> {
const birdPattern = new RegExp(`^\
>\
(\\s)+\
`)
if (this.isLiterateGrammar()) {
return Array.from(clause).map((line: string) =>
line.match(birdPattern) ? line : '> ' + line,
)
} else {
return clause
}
}
createMarker(
editor: TextEditor,
range: RangeCompatible,
type:
| 'line'
| 'line-number'
| 'text'
| 'highlight'
| 'overlay'
| 'gutter'
| 'block'
| 'cursor',
): DisplayMarker {
const marker = editor.markBufferRange(range, { invalidate: 'never' })
editor.decorateMarker(marker, {
type,
class: 'highlight-idris-error',
})
return marker
}
destroyMarkers(): void {
Array.from(this.errorMarkers).map((marker) => marker.destroy())
}
destroy(): void {
if (this.model) {
Logger.logText('Idris: Shutting down!')
this.model.stop()
}
}
// clear the message panel and optionally display a new title
clearMessagePanel(title?: string): void {
if (this.messages) {
this.messages.attach()
this.messages.show()
this.messages.clear()
if (title) {
this.messages.setTitle(title, true)
}
}
}
// hide the message panel
hideAndClearMessagePanel(): void {
if (this.messages) {
this.clearMessagePanel()
this.messages.hide()
}
}
// add raw information to the message panel
rawMessage(text: string): void {
this.messages.add(
new PlainMessageView({
raw: true,
message: '<pre>' + text + '</pre>',
className: 'preview',
}),
)
}
initialize(compilerOptions: Ipkg.CompilerOptions): void {
this.destroyMarkers()
this.messages.attach()
this.messages.hide()
this.model.setCompilerOptions(compilerOptions)
}
/**
* Get the currently active text editor.
*/
getEditor(): TextEditor | undefined {
return atom.workspace.getActiveTextEditor()
}
getPane(): Pane {
return atom.workspace.getActivePane()
}
stopCompiler(): boolean | undefined {
return this.model != null ? this.model.stop() : undefined
}
runCommand(command: (args: any) => void) {
return (args: any) => {
const compilerOptions = Ipkg.compilerOptions(atom.project)
return compilerOptions.subscribe((options: any) => {
Logger.logObject('Compiler Options:', options)
this.initialize(options)
return command(args)
})
}
}
// see https://github.com/atom/autocomplete-plus/wiki/Provider-API
provideReplCompletions() {
return {
selector: '.source.idris',
inclusionPriority: 1,
excludeLowerPriority: false,
// Get suggestions from the Idris REPL. You can always ask for suggestions <Ctrl+Space>
// or type at least 3 characters to get suggestions based on your autocomplete-plus
// settings.
getSuggestions: ({ prefix, activatedManually }: any) => {
const trimmedPrefix = prefix.trim()
if (trimmedPrefix.length > 2 || activatedManually) {
return Ipkg.compilerOptions(atom.project)
.flatMap((options: any) => {
this.initialize(options)
return this.model.replCompletions(trimmedPrefix)
})
.toPromise()
.then(({ msg }: any) =>
Array.from(msg[0][0]).map((sug) => ({
type: 'function',
text: sug,
})),
)
} else {
return null
}
},
}
}
saveFile(editor: TextEditor | undefined): Promise<string> {
if (editor) {
const path = editor.getPath()
if (path) {
return editor.save().then(() => path)
} else {
const pane = this.getPane()
const savePromise = pane.saveActiveItemAs()
if (savePromise) {
const newPath = editor.getPath()
if (newPath) {
return savePromise.then(() => newPath)
} else {
return Promise.reject()
}
} else {
return Promise.reject()
}
}
} else {
return Promise.reject()
}
}
typecheckFile() {
const editor = this.getEditor()
if (editor) {
return this.saveFile(editor).then((uri) => {
this.clearMessagePanel('Idris: Typechecking...')
const successHandler = () => {
return this.clearMessagePanel(
'Idris: File loaded successfully',
)
}
return this.model
.load(uri)
.filter(
({ responseType }: any) => responseType === 'return',
)
.subscribe(successHandler, this.displayErrors)
})
}
}
getDocsForWord() {
const editor = this.getEditor()
if (editor) {
return this.saveFile(editor).then((uri) => {
const word = Symbol.serializeWord(getWordUnderCursor(editor))
this.clearMessagePanel(
'Idris: Searching docs for <tt>' + word + '</tt> ...',
)
const successHandler = ({ msg }: any) => {
const [type, highlightingInfo] = Array.from(msg)
this.clearMessagePanel(
'Idris: Docs for <tt>' + word + '</tt>',
)
const informationView = new InformationView()
informationView.initialize({
obligation: type,
highlightingInfo,
})
return this.messages.add(informationView)
}
return this.model
.load(uri)
.filter(
({ responseType }: any) => responseType === 'return',
)
.flatMap(() => this.model.docsFor(word))
.catch(() => this.model.docsFor(word))
.subscribe(successHandler, this.displayErrors)
})
}
}
getTypeForWord() {
const editor = this.getEditor()
if (editor) {
return this.saveFile(editor).then((uri) => {
const word = Symbol.serializeWord(getWordUnderCursor(editor))
this.clearMessagePanel(
'Idris: Searching type of <tt>' + word + '</tt> ...',
)
const successHandler = ({ msg }: any): void => {
const [type, highlightingInfo] = msg
this.clearMessagePanel(
'Idris: Type of <tt>' + word + '</tt>',
)
const informationView = new InformationView()
informationView.initialize({
obligation: type,
highlightingInfo,
})
this.messages.add(informationView)
}
return this.model
.load(uri)
.filter((response: any) => {
return response.responseType === 'return'
})
.flatMap(() => this.model.getType(word))
.subscribe(successHandler, this.displayErrors)
})
}
}
doCaseSplit() {
const editor = this.getEditor()
if (editor) {
return this.saveFile(editor).then((uri) => {
const cursor = editor.getLastCursor()
const line = cursor.getBufferRow()
const word = getWordUnderCursor(editor)
this.clearMessagePanel('Idris: Do case split ...')
const successHandler = ({ msg }: any) => {
const [split] = msg
if (split === '') {
// split returned nothing - cannot split
return this.clearMessagePanel(
'Idris: Cannot split ' + word,
)
} else {
this.hideAndClearMessagePanel()
const lineRange = cursor.getCurrentLineBufferRange({
includeNewline: true,
})
return editor.setTextInBufferRange(lineRange, split)
}
}
return this.model
.load(uri)
.filter(
({ responseType }: any) => responseType === 'return',
)
.flatMap(() => this.model.caseSplit(line + 1, word))
.subscribe(successHandler, this.displayErrors)
})
}
}
/**
* Add a new clause to a function.
*/
doAddClause() {
const editor = this.getEditor()
if (editor) {
return this.saveFile(editor).then((uri) => {
const line = editor.getLastCursor().getBufferRow()
// by adding a clause we make sure that the word is
// not treated as a symbol
const word = getWordUnderCursor(editor)
this.clearMessagePanel('Idris: Add clause ...')
const successHandler = ({ msg }: any) => {
const [clause] = this.prefixLiterateClause(msg)
this.hideAndClearMessagePanel()
editor.transact(() => {
moveToNextEmptyLine(editor)
// Insert the new clause
editor.insertText(clause)
// And move the cursor to the beginning of
// the new line and add an empty line below it
editor.insertNewlineBelow()
editor.moveUp()
editor.moveToBeginningOfLine()
})
}
return this.model
.load(uri)
.filter(
({ responseType }: any) => responseType === 'return',
)
.flatMap(() => this.model.addClause(line + 1, word))
.subscribe(successHandler, this.displayErrors)
})
}
}
/**
* Use special syntax for proof obligation clauses.
*/
doAddProofClause() {
const editor = this.getEditor()
if (editor) {
return this.saveFile(editor).then((uri) => {
const line = editor.getLastCursor().getBufferRow()
const word = getWordUnderCursor(editor)
this.clearMessagePanel('Idris: Add proof clause ...')
const successHandler = ({ msg }: any) => {
const [clause] = this.prefixLiterateClause(msg)
this.hideAndClearMessagePanel()
editor.transact(() => {
moveToNextEmptyLine(editor)
// Insert the new clause
editor.insertText(clause)
// And move the cursor to the beginning of
// the new line and add an empty line below it
editor.insertNewlineBelow()
editor.moveUp()
editor.moveToBeginningOfLine()
})
}
return this.model
.load(uri)
.filter(
({ responseType }: any) => responseType === 'return',
)
.flatMap(() => this.model.addProofClause(line + 1, word))
.subscribe(successHandler, this.displayErrors)
})
}
}
// add a with view
doMakeWith() {
const editor = this.getEditor()
if (editor) {
return this.saveFile(editor).then((uri) => {
const line = editor.getLastCursor().getBufferRow()
const word = getWordUnderCursor(editor)
this.clearMessagePanel('Idris: Make with view ...')
const successHandler = ({ msg }: any) => {
const [clause] = Array.from(this.prefixLiterateClause(msg))
this.hideAndClearMessagePanel()
return editor.transact(function () {
// Delete old line, insert the new with block
editor.deleteLine()
editor.insertText(clause)
// And move the cursor to the beginning of
// the new line
editor.moveToBeginningOfLine()
return editor.moveUp()
})
}
if (word != null ? word.length : undefined) {
return this.model
.load(uri)
.filter(
({ responseType }: any) =>
responseType === 'return',
)
.flatMap(() => this.model.makeWith(line + 1, word))
.subscribe(successHandler, this.displayErrors)
} else {
return this.clearMessagePanel(
'Idris: Illegal position to make a with view',
)
}
})
}
}
// construct a lemma from a hole
doMakeLemma() {
const editor = this.getEditor()
if (editor) {
return this.saveFile(editor).then((uri) => {
let line = editor.getLastCursor().getBufferRow()
const word = getWordUnderCursor(editor)
this.clearMessagePanel('Idris: Make lemma ...')
const successHandler = ({ msg }: any) => {
// param1 contains the code which replaces the hole
// param2 contains the code for the lemma function
let [lemty, param1, param2] = msg
param2 = this.prefixLiterateClause(param2)
this.hideAndClearMessagePanel()
return editor.transact(function () {
if (lemty === ':metavariable-lemma') {
// Move the cursor to the beginning of the word
editor.moveToBeginningOfWord()
// Because the ? in the Holes isn't part of
// the word, we move left once, and then select two
// words
editor.moveLeft()
editor.selectToEndOfWord()
editor.selectToEndOfWord()
// And then replace the replacement with the lemma call..
editor.insertText(param1[1])
// Now move to the previous blank line and insert the type
// of the lemma
editor.moveToBeginningOfLine()
line = editor.getLastCursor().getBufferRow()
// I tried to make this a function but failed to find out how
// to call it and gave up...
while (line > 0) {
editor.moveToBeginningOfLine()
editor.selectToEndOfLine()
const contents = editor.getSelectedText()
if (contents === '') {
break
}
editor.moveUp()
line--
}
editor.insertNewlineBelow()
editor.insertText(param2[1])
return editor.insertNewlineBelow()
}
})
}
return this.model
.load(uri)
.filter(
({ responseType }: any) => responseType === 'return',
)
.flatMap(() => this.model.makeLemma(line + 1, word))
.subscribe(successHandler, this.displayErrors)
})
}
}
// create a case statement
doMakeCase() {
const editor = this.getEditor()
if (editor) {
return this.saveFile(editor).then((uri) => {
const line = editor.getLastCursor().getBufferRow()
const word = getWordUnderCursor(editor)
this.clearMessagePanel('Idris: Make case ...')
const successHandler = ({ msg }: any) => {
const [clause] = Array.from(this.prefixLiterateClause(msg))
this.hideAndClearMessagePanel()
return editor.transact(function () {
// Delete old line, insert the new case block
editor.moveToBeginningOfLine()
editor.deleteLine()
editor.insertText(clause)
// And move the cursor to the beginning of
// the new line
editor.moveToBeginningOfLine()
return editor.moveUp()
})
}
return this.model
.load(uri)
.filter(
({ responseType }: any) => responseType === 'return',
)
.flatMap(() => this.model.makeCase(line + 1, word))
.subscribe(successHandler, this.displayErrors)
})
}
}
// show all holes in the current file
showHoles() {
const editor = this.getEditor()
if (editor) {
return this.saveFile(editor).then((uri) => {
this.clearMessagePanel('Idris: Searching holes ...')
const successHandler = ({ msg }: any) => {
const [holes] = msg
this.clearMessagePanel('Idris: Holes')
const holesView = new HolesView()
holesView.initialize(holes)
this.messages.add(holesView)
}
return this.model
.load(uri)
.filter(
({ responseType }: any) => responseType === 'return',
)
.flatMap(() => this.model.holes(80))
.subscribe(successHandler, this.displayErrors)
})
}
}
/**
* Replace a hole with a proof.
*/
doProofSearch() {
const editor = this.getEditor()
if (editor) {
return this.saveFile(editor).then((uri) => {
const line = editor.getLastCursor().getBufferRow()
const word = getWordUnderCursor(editor)
this.clearMessagePanel('Idris: Searching proof ...')
const successHandler = ({ msg }: any) => {
const [res] = msg
this.hideAndClearMessagePanel()
if (res.startsWith('?')) {
// proof search returned a new hole
this.clearMessagePanel(
'Idris: Searching proof was not successful.',
)
} else {
editor.transact(() => {
// Move the cursor to the beginning of the word
editor.moveToBeginningOfWord()
// Because the ? in the Holes isn't part of
// the word, we move left once, and then select two
// words
editor.moveLeft()
editor.selectToEndOfWord()
editor.selectToEndOfWord()
// And then replace the replacement with the guess..
editor.insertText(res)
})
}
}
return this.model
.load(uri)
.filter(
({ responseType }: any) => responseType === 'return',
)
.flatMap(() => this.model.proofSearch(line + 1, word))
.subscribe(successHandler, this.displayErrors)
})
}
}
doBrowseNamespace() {
const editor = this.getEditor()
if (editor) {
return this.saveFile(editor).then((uri) => {
let nameSpace = editor.getSelectedText()
this.clearMessagePanel(
'Idris: Browsing namespace <tt>' + nameSpace + '</tt>',
)
const successHandler = ({ msg }: any) => {
// the information is in a two dimensional array
// one array contains the namespaces contained in the namespace
// and the seconds all the methods
const namesSpaceInformation = msg[0][0]
for (nameSpace of namesSpaceInformation) {
this.rawMessage(nameSpace)
}
const methodInformation = msg[0][1]
return (() => {
const result = []
for (let [
line,
highlightInformation,
] of methodInformation) {
const highlighting = highlighter.highlight(
line,
highlightInformation,
)
const info = highlighter.highlightToString(
highlighting,
)
result.push(this.rawMessage(info))
}
return result
})()
}
return this.model
.load(uri)
.filter(
({ responseType }: any) => responseType === 'return',
)
.flatMap(() => this.model.browseNamespace(nameSpace))
.subscribe(successHandler, this.displayErrors)
})
}
}
/**
* get the definition of a function or type
*/
printDefinition() {
const editor = this.getEditor()
if (editor) {
return this.saveFile(editor).then((uri) => {
const word = Symbol.serializeWord(getWordUnderCursor(editor))
this.clearMessagePanel(
'Idris: Searching definition of <tt>' + word + '</tt> ...',
)
const successHandler = ({ msg }: any) => {
const [type, highlightingInfo] = Array.from(msg)
this.clearMessagePanel(
'Idris: Definition of <tt>' + word + '</tt>',
)
const informationView = new InformationView()
informationView.initialize({
obligation: type,
highlightingInfo,
})
return this.messages.add(informationView)
}
return this.model
.load(uri)
.filter(
({ responseType }: any) => responseType === 'return',
)
.flatMap(() => this.model.printDefinition(word))
.catch(() => this.model.printDefinition(word))
.subscribe(successHandler, this.displayErrors)
})
}
}
/**
* open the repl window
*/
openREPL() {
const editor = this.getEditor()
if (editor) {
const uri = editor.getPath() as any
this.clearMessagePanel('Idris: opening REPL ...')
const successHandler = () => {
this.hideAndClearMessagePanel()
const options: WorkspaceOpenOptions = {
split: 'right',
searchAllPanes: true,
}
atom.workspace.open('idris://repl', options)
}
return this.model
.load(uri)
.filter(({ responseType }: any) => responseType === 'return')
.subscribe(successHandler, this.displayErrors)
}
}
/**
* open the apropos window
*/
apropos() {
const editor = this.getEditor()
if (editor) {
const uri = editor.getPath() as any
this.clearMessagePanel('Idris: opening apropos view ...')
const successHandler = () => {
this.hideAndClearMessagePanel()
const options: WorkspaceOpenOptions = {
split: 'right',
searchAllPanes: true,
}
return atom.workspace.open('idris://apropos', options)
}
return this.model
.load(uri)
.filter(({ responseType }: any) => responseType === 'return')
.subscribe(successHandler, this.displayErrors)
}
}
// generic function to display errors in the status bar
displayErrors(err: any) {
this.clearMessagePanel('<i class="icon-bug"></i> Idris Errors')
// display the general error message
if (err.message != null) {
this.rawMessage(err.message)
}
return (() => {
const result = []
for (let warning of err.warnings) {
const type = warning[3]
const highlightingInfo = warning[4]
const highlighting = highlighter.highlight(
type,
highlightingInfo,
)
const info = highlighter.highlightToString(highlighting)
const line = warning[1][0]
const character = warning[1][1]
const uri = warning[0].replace('./', err.cwd + '/')
// this provides information about the line and column of the error
this.messages.add(
new LineMessageView({
line,
character,
file: uri,
}),
)
// this provides a highlighted version of the error message
// returned by idris
this.rawMessage(info)
const editor = atom.workspace.getActiveTextEditor()
if (editor && line > 0 && uri === editor.getPath()) {
const startPoint = warning[1]
startPoint[0] = startPoint[0] - 1
const endPoint = warning[2]
endPoint[0] = endPoint[0] - 1
const gutterMarker = this.createMarker(
editor,
[startPoint, endPoint],
'line-number',
)
const lineMarker = this.createMarker(
editor,
[
[line - 1, character - 1],
[line, 0],
],
'line',
)
this.errorMarkers.push(gutterMarker)
result.push(this.errorMarkers.push(lineMarker))
} else {
result.push(undefined)
}
}
return result
})()
}
} | the_stack |
import { getRawHelpers } from "../helpers/index";
const {
and,
arrArgMatch,
arrLen,
arrTypeMatch,
arrIncl,
btw,
btwe,
deep,
Email,
entry,
extant,
falsey,
gt,
gte,
Lc,
lt,
lte,
LUc,
Nc,
not,
obj,
or,
prim,
regx,
strLen,
truthy,
Uc,
val,
validation,
wildcard,
Xc
} = getRawHelpers();
// In order of global greedy token parsing
export const tokens = {
TRUE: "true",
FALSE: "false",
EMAIL_REGX: "Email",
EXTENDED_CHARS_REGX: "Xc",
NUM_CHARS_REGX: "Nc",
LOW_CHARS_REGX: "Lc",
UP_CHARS_REGX: "Uc",
LOW_UP_CHARS_REGX: "LUc",
VALIDATION_MSG: `<-\\s*\\"((?:\\\\\\"|[^\\"])*)\\"`,
EMPTY_OBJ: "\\{\\}",
EMPTY_ARRAY: "\\[\\]",
EMPTY_STRING_DOUBLE: `\\"\\"`,
EMPTY_STRING_SINGLE: "\\'\\'",
STRING_LENGTH: "string\\[",
ARRAY_LENGTH: "array\\[",
PRIM_NUMBER: "Number",
PRIM_OBJECT: "Object",
ARRAY_TYPED: "Array<",
PRIM_ARRAY: "Array",
NULL: "null",
UNDEFINED: "undefined",
PRIM_NUMBER_VAL: "number",
PRIM_BOOLEAN_VAL: "boolean",
PRIM_SYMBOL_VAL: "symbol",
PRIM_STRING_VAL: "string",
PRIM_ARRAY_VAL: "array",
PRIM_BOOLEAN: "Boolean",
PRIM_STRING: "String",
PRIM_SYMBOL: "Symbol",
PRIM_FUNCTION: "Function",
WILDCARD_PREDICATE: "\\*",
TRUTHY: "\\!\\!",
FALSY_KEYWORD: "falsey", // Using literal falsey as if we use "\\!" it will be picked up all the not operators
IDENTIFIER: "[a-zA-Z_]+[a-zA-Z0-9_-]*",
EXTANT_PREDICATE: "_",
REST_SYMBOL: "\\.\\.\\.",
NUMBER: "-?\\d+(\\.\\d+)?",
STRING_DOUBLE: `\\"[^\\"]*\\"`,
STRING_SINGLE: `\\'[^\\']*\\'`,
PREDICATE_LOOKUP: "@{LINK:(\\d+)}",
OBJ_EXACT: "\\{\\|",
OBJ_EXACT_CLOSE: "\\|\\}",
NOT: "\\!",
AND: "\\&\\&",
AND_SHORT: "\\&",
OR: "\\|\\|",
OR_SHORT: "\\|",
BTW: "\\<\\s\\<",
BTWE: "\\.\\.",
GTE: "\\>\\=",
LTE: "\\<\\=",
GT: "\\>(?=(?:\\s*)?[\\.\\d])", // disambiguation checks if followed by a number
LT: "\\<",
ENTRY: "\\:",
OBJ: "\\{",
OBJ_CLOSE: "\\}",
ARRAY_INCLUDES: "\\[\\?",
ARRAY: "\\[",
ARRAY_CLOSE: "\\]",
ARG: "\\,",
PRECEDENCE: "\\(",
PRECEDENCE_CLOSE: "\\)"
};
export const types = {
BooleanLiteral: "BooleanLiteral",
PredicateLiteral: "PredicateLiteral",
SymbolLiteral: "SymbolLiteral",
NumericLiteral: "NumericLiteral",
StringLiteral: "StringLiteral",
PredicateLookup: "PredicateLookup",
Operator: "Operator",
VariableArityOperator: "VariableArityOperator",
VariableArityOperatorClose: "VariableArityOperatorClose",
ArgumentSeparator: "ArgumentSeparator",
PrecidenceOperator: "PrecidenceOperator",
PrecidenceOperatorClose: "PrecidenceOperatorClose"
};
export const grammar = {
// LITERALS
[tokens.TRUE]: token => ({
type: types.BooleanLiteral,
token,
runtime: () => true,
runtimeIdentifier: undefined,
toString() {
return token;
}
}),
[tokens.FALSE]: token => ({
type: types.BooleanLiteral,
token,
runtime: () => false,
runtimeIdentifier: undefined,
toString() {
return token;
}
}),
[tokens.EMAIL_REGX]: token => ({
type: types.PredicateLiteral,
token,
runtime: ctx => regx(ctx)(Email),
runtimeIdentifier: "regx",
toString() {
return "Email";
}
}),
[tokens.EXTENDED_CHARS_REGX]: token => ({
type: types.PredicateLiteral,
token,
runtime: ctx => regx(ctx)(Xc),
runtimeIdentifier: "regx",
toString() {
return "Xc";
}
}),
[tokens.NUM_CHARS_REGX]: token => ({
type: types.PredicateLiteral,
token,
runtime: ctx => regx(ctx)(Nc),
runtimeIdentifier: "regx",
toString() {
return "Nc";
}
}),
[tokens.LOW_CHARS_REGX]: token => ({
type: types.PredicateLiteral,
token,
runtime: ctx => regx(ctx)(Lc),
runtimeIdentifier: "regx",
toString() {
return "Lc";
}
}),
[tokens.UP_CHARS_REGX]: token => ({
type: types.PredicateLiteral,
token,
runtime: ctx => regx(ctx)(Uc),
runtimeIdentifier: "regx",
toString() {
return "Uc";
}
}),
[tokens.LOW_UP_CHARS_REGX]: token => ({
type: types.PredicateLiteral,
token,
runtime: ctx => regx(ctx)(LUc),
runtimeIdentifier: "regx",
toString() {
return "LUc";
}
}),
[tokens.EMPTY_OBJ]: token => ({
type: types.PredicateLiteral,
token,
runtime: ctx => deep(ctx)({}),
runtimeIdentifier: "deep",
toString() {
return "{}";
}
}),
[tokens.EMPTY_ARRAY]: token => ({
type: types.PredicateLiteral,
token,
runtime: ctx => deep(ctx)([]),
runtimeIdentifier: "deep",
toString() {
return "[]";
}
}),
[tokens.EMPTY_STRING_DOUBLE]: token => ({
type: types.PredicateLiteral,
token,
runtime: ctx => deep(ctx)(""),
runtimeIdentifier: "deep",
toString() {
return `""`;
}
}),
[tokens.EMPTY_STRING_SINGLE]: token => ({
type: types.PredicateLiteral,
token,
runtime: ctx => deep(ctx)(""),
runtimeIdentifier: "deep",
toString() {
return `""`;
}
}),
[tokens.PRIM_NUMBER]: token => ({
type: types.PredicateLiteral,
token,
runtime: ctx => prim(ctx)(Number),
runtimeIdentifier: "prim",
toString() {
return "Number";
}
}),
[tokens.PRIM_OBJECT]: token => ({
type: types.PredicateLiteral,
token,
runtime: ctx => prim(ctx)(Object),
runtimeIdentifier: "prim",
toString() {
return "Object";
}
}),
[tokens.PRIM_ARRAY]: token => ({
type: types.PredicateLiteral,
token,
runtime: ctx => prim(ctx)(Array),
runtimeIdentifier: "prim",
toString() {
return "Array";
}
}),
[tokens.NULL]: token => ({
type: types.PredicateLiteral,
token,
runtime: ctx => val(ctx)(null),
runtimeIdentifier: "val",
toString() {
return "null";
}
}),
[tokens.UNDEFINED]: token => ({
type: types.PredicateLiteral,
token,
runtime: ctx => val(ctx)(undefined),
runtimeIdentifier: "val",
toString() {
return "undefined";
}
}),
[tokens.PRIM_NUMBER_VAL]: token => ({
type: types.PredicateLiteral,
token,
runtime: ctx => prim(ctx)(Number),
runtimeIdentifier: "prim",
toString() {
return "number";
}
}),
[tokens.PRIM_BOOLEAN_VAL]: token => ({
type: types.PredicateLiteral,
token,
runtime: ctx => prim(ctx)(Boolean),
runtimeIdentifier: "prim",
toString() {
return "boolean";
}
}),
[tokens.PRIM_SYMBOL_VAL]: token => ({
type: types.PredicateLiteral,
token,
runtime: ctx => prim(ctx)(Symbol),
runtimeIdentifier: "prim",
toString() {
return "symbol";
}
}),
[tokens.PRIM_STRING_VAL]: token => ({
type: types.PredicateLiteral,
token,
runtime: ctx => prim(ctx)(String),
runtimeIdentifier: "prim",
toString() {
return "string";
}
}),
[tokens.PRIM_ARRAY_VAL]: token => ({
type: types.PredicateLiteral,
token,
runtime: /* istanbul ignore next */ ctx => prim(ctx)(Array),
runtimeIdentifier: "prim",
toString() {
return "array";
}
}),
[tokens.PRIM_BOOLEAN]: token => ({
type: types.PredicateLiteral,
token,
runtime: ctx => prim(ctx)(Boolean),
runtimeIdentifier: "prim",
toString() {
return "Boolean";
}
}),
[tokens.PRIM_STRING]: token => ({
type: types.PredicateLiteral,
token,
runtime: ctx => prim(ctx)(String),
runtimeIdentifier: "prim",
toString() {
return "String";
}
}),
[tokens.PRIM_SYMBOL]: token => ({
type: types.PredicateLiteral,
token,
runtime: ctx => prim(ctx)(Symbol),
runtimeIdentifier: "prim",
toString() {
return "Symbol";
}
}),
[tokens.PRIM_FUNCTION]: token => ({
type: types.PredicateLiteral,
token,
runtime: ctx => prim(ctx)(Function),
runtimeIdentifier: "prim",
toString() {
return "Function";
}
}),
[tokens.EXTANT_PREDICATE]: token => ({
type: types.PredicateLiteral,
token,
runtime: ctx => extant(ctx),
runtimeIdentifier: "extant",
toString() {
return "_";
}
}),
[tokens.WILDCARD_PREDICATE]: token => ({
type: types.PredicateLiteral,
token,
runtime: ctx => wildcard(),
runtimeIdentifier: "wildcard",
toString() {
return "*";
}
}),
[tokens.TRUTHY]: token => {
return {
type: types.PredicateLiteral,
token,
runtime: ctx => truthy(ctx),
runtimeIdentifier: "truthy",
toString() {
return "!!";
}
};
},
[tokens.FALSY_KEYWORD]: token => {
return {
type: types.PredicateLiteral,
token,
runtime: ctx => falsey(ctx),
runtimeIdentifier: "falsey",
toString() {
return "!";
}
};
},
[tokens.IDENTIFIER]: token => ({
type: types.SymbolLiteral,
token,
runtime: () => token,
runtimeIdentifier: undefined,
toString() {
return token;
}
}),
[tokens.REST_SYMBOL]: token => ({
type: types.SymbolLiteral,
token,
runtime: () => token,
runtimeIdentifier: undefined,
toString() {
return token;
}
}),
[tokens.NUMBER]: token => ({
type: types.NumericLiteral,
token,
runtime: () => Number(token),
runtimeIdentifier: undefined,
toString() {
return token;
}
}),
[tokens.STRING_DOUBLE]: token => {
const t = token.match(/\"(.*)\"/);
/* istanbul ignore next because __deafult never matches in tests */
const value = t ? t[1] : "__default";
return {
type: types.StringLiteral,
token: value,
runtime: ctx => val(ctx)(value),
runtimeIdentifier: "val",
toString() {
return token;
}
};
},
[tokens.STRING_SINGLE]: token => {
const t = token.match(/\'(.*)\'/);
/* istanbul ignore next because __deafult never matches in tests */
const value = t ? t[1] : "__default";
return {
type: types.StringLiteral,
token: value,
runtime: ctx => val(ctx)(value),
runtimeIdentifier: "val",
toString() {
return token;
}
};
},
[tokens.PREDICATE_LOOKUP]: token => {
const t = token.match(/@{LINK:(\d+)}/);
/* istanbul ignore next because __deafult never matches in tests */
const val = t ? t[1] : "__default";
return {
type: types.PredicateLookup,
token: val,
runtime: /* istanbul ignore next as not used */ () => val,
runtimeIdentifier: undefined,
toString() {
return token;
}
};
},
// OPERATORS
[tokens.NOT]: token => ({
type: types.Operator,
token,
arity: 1,
runtime: ctx => not(ctx),
runtimeIdentifier: "not",
toString() {
return token + this.arity;
},
prec: 10
}),
[tokens.AND]: token => ({
type: types.Operator,
token,
arity: 2,
runtime: ctx => and(ctx),
runtimeIdentifier: "and",
prec: 60,
toString() {
return token;
}
}),
[tokens.AND_SHORT]: token => ({
type: types.Operator,
token,
arity: 2,
runtime: ctx => and(ctx),
runtimeIdentifier: "and",
prec: 60,
toString() {
return token;
}
}),
[tokens.OR]: token => ({
type: types.Operator,
token,
arity: 2,
runtime: ctx => or(ctx),
runtimeIdentifier: "or",
prec: 60,
toString() {
return token;
}
}),
[tokens.OR_SHORT]: token => ({
type: types.Operator,
token,
arity: 2,
runtime: ctx => or(ctx),
runtimeIdentifier: "or",
prec: 60,
toString() {
return token;
}
}),
[tokens.BTW]: token => ({
type: types.Operator,
token,
arity: 2,
runtime: ctx => btw(ctx),
runtimeIdentifier: "btw",
prec: 50,
toString() {
return token;
}
}),
[tokens.BTWE]: token => ({
type: types.Operator,
token,
arity: 2,
runtime: ctx => btwe(ctx),
runtimeIdentifier: "btwe",
prec: 50,
toString() {
return token;
}
}),
[tokens.GTE]: token => ({
type: types.Operator,
token,
arity: 1,
runtime: ctx => gte(ctx),
runtimeIdentifier: "gte",
prec: 50,
toString() {
return token;
}
}),
[tokens.LTE]: token => ({
type: types.Operator,
token,
arity: 1,
runtime: ctx => lte(ctx),
runtimeIdentifier: "lte",
prec: 50,
toString() {
return token;
}
}),
[tokens.GT]: token => ({
type: types.Operator,
token,
arity: 1,
runtime: ctx => gt(ctx),
runtimeIdentifier: "gt",
prec: 50,
toString() {
return token;
}
}),
[tokens.LT]: token => ({
type: types.Operator,
token,
arity: 1,
runtime: ctx => lt(ctx),
runtimeIdentifier: "lt",
prec: 50,
toString() {
return token;
}
}),
[tokens.VALIDATION_MSG]: token => {
const [, msg] = token.match(
/<-\s*\"((?:\\\"|[^\"])*)\"/
) || /* istanbul ignore next because it is tested in babel plugin */ [, ""];
return {
type: types.Operator,
token: ":e:",
arity: 1,
prec: 55, //??
runtime: ctx => validation(ctx)(msg.trim()),
runtimeIdentifier: "validation",
toString() {
return ":e:" + msg.slice(0, 3) + ":";
}
};
},
// functions have highest precidence
[tokens.ENTRY]: token => ({
type: types.Operator,
token,
arity: 2,
runtime: ctx => entry(ctx),
runtimeIdentifier: "entry",
prec: 100,
toString() {
return token;
}
}),
[tokens.OBJ_EXACT]: token => ({
type: types.VariableArityOperator,
token,
arity: 0,
runtime: ctx => obj(ctx, true),
runtimeIdentifier: "obj",
prec: 100,
closingToken: "|}",
toString() {
return token + this.arity;
}
}),
[tokens.OBJ_EXACT_CLOSE]: token => ({
type: types.VariableArityOperatorClose,
token,
toString() {
return token;
}
}),
[tokens.OBJ]: token => ({
type: types.VariableArityOperator,
token,
arity: 0,
runtime: ctx => obj(ctx),
runtimeIdentifier: "obj",
prec: 100,
closingToken: "}",
toString() {
return token + this.arity;
}
}),
[tokens.OBJ_CLOSE]: token => ({
type: types.VariableArityOperatorClose,
token,
toString() {
return token;
}
}),
[tokens.ARRAY_INCLUDES]: token => ({
type: types.VariableArityOperator,
token,
arity: 0,
runtime: ctx => arrIncl(ctx),
runtimeIdentifier: "arrIncl",
prec: 100,
closingToken: "]",
toString() {
return token + this.arity;
}
}),
[tokens.ARRAY]: token => ({
type: types.VariableArityOperator,
token,
arity: 0,
runtime: ctx => arrArgMatch(ctx),
runtimeIdentifier: "arrArgMatch",
prec: 100,
closingToken: "]",
toString() {
return token + this.arity;
}
}),
[tokens.ARRAY_CLOSE]: token => ({
type: types.VariableArityOperatorClose,
token,
toString() {
return token;
}
}),
[tokens.ARG]: token => ({
type: types.ArgumentSeparator,
token,
toString() {
return token;
}
}),
[tokens.PRECEDENCE]: token => ({
type: types.PrecidenceOperator,
token,
toString() {
return token;
}
}),
[tokens.PRECEDENCE_CLOSE]: token => ({
type: types.PrecidenceOperatorClose,
token,
toString() {
return token;
}
}),
[tokens.ARRAY_TYPED]: token => ({
type: types.Operator,
token,
arity: 1,
prec: 50,
runtime: ctx => arrTypeMatch(ctx),
runtimeIdentifier: "arrTypeMatch",
toString() {
return "Array<";
}
}),
[tokens.STRING_LENGTH]: token => ({
type: types.Operator,
token,
arity: 1,
prec: 50,
runtime: strLen,
runtimeIdentifier: "strLen",
toString() {
return "string[";
}
}),
[tokens.ARRAY_LENGTH]: token => ({
type: types.Operator,
token,
arity: 1,
prec: 50,
runtime: ctx => arrLen(ctx),
runtimeIdentifier: "arrLen",
toString() {
return "array[";
}
})
};
export function isOperator(node) {
if (!node) return false;
return node.type === types.Operator;
}
export function isLiteral(node) {
if (!node) return false;
return (
{
NumericLiteral: 1,
StringLiteral: 1,
SymbolLiteral: 1,
BooleanLiteral: 1,
PredicateLiteral: 1
}[node.type] || false
);
}
export function isPredicateLookup(node) {
if (!node) return false;
return node.type === types.PredicateLookup;
}
export function isVaradicFunctionClose(node) {
if (!node) return false;
return node.type === types.VariableArityOperatorClose;
}
export function isVaradicFunction(node, closingNode?) {
if (!node) return false;
const isVaradicStart = node.type === types.VariableArityOperator;
if (!closingNode) return isVaradicStart;
return isVaradicStart && node.closingToken === closingNode.token;
}
export function isBooleanable(node) {
return (
isLiteral(node) ||
isPredicateLookup(node) ||
isVaradicFunction(node) ||
isPrecidenceOperator(node)
);
}
export function isArgumentSeparator(node) {
if (!node) return false;
return node.type === types.ArgumentSeparator;
}
export function isPrecidenceOperator(node) {
if (!node) return false;
return node.type === types.PrecidenceOperator;
}
export function isPrecidenceOperatorClose(node) {
if (!node) return false;
return node.type === types.PrecidenceOperatorClose;
}
export function hasToken(node, token) {
return node && node.token === token;
} | the_stack |
import {spawn} from 'child_process'
import readline from 'readline'
import ClientBase from '../client-base'
import {formatAPIObjectOutput, formatAPIObjectInput} from '../utils'
import * as chat1 from '../types/chat1'
/** A function to call when a message is received. */
export type OnMessage = (message: chat1.MsgSummary) => void | Promise<void>
/** A function to call when an error occurs. */
export type OnError = (error: Error) => void | Promise<void>
/** A function to call when the bot is added to a new conversation. */
export type OnConv = (channel: chat1.ConvSummary) => void | Promise<void>
/**
* Options for the `list` method of the chat module.
*/
export interface ChatListOptions {
failOffline?: boolean
showErrors?: boolean
topicType?: chat1.TopicType
unreadOnly?: boolean
}
/**
* Options for the `listChannels` method of the chat module.
*/
export interface ChatListChannelsOptions {
topicType?: chat1.TopicType
membersType?: chat1.ConversationMembersType
}
/**
* Options for the `read` method of the chat module.
*/
export interface ChatReadOptions {
failOffline?: boolean
pagination?: chat1.Pagination
peek?: boolean
unreadOnly?: boolean
}
/**
* Options for the `send` method of the chat module.
*/
export interface ChatSendOptions {
nonblock?: boolean
membersType?: chat1.ConversationMembersType
confirmLumenSend?: boolean
replyTo?: chat1.MessageID
explodingLifetime?: number
}
/**
* Options for the `attach` method of the chat module.
*/
export interface ChatAttachOptions {
title?: string
preview?: string
explodingLifetime?: number
}
/**
* Options for the `download` method of the chat module.
*/
export interface ChatDownloadOptions {
preview?: string
noStream?: boolean
}
/**
* Options for the methods in the chat module that listen for new messages.
* Local messages are ones sent by your device. Including them in the output is
* useful for applications such as logging conversations, monitoring own flips
* and building tools that seamlessly integrate with a running client used by
* the user. If onNewConvo is set, it will be called when the bot is added to a new conversation.
*/
export interface ListenOptions {
hideExploding: boolean
showLocal: boolean
}
export interface Advertisement {
alias?: string
advertisements: chat1.AdvertiseCommandAPIParam[]
}
export interface AdvertisementsLookup {
channel: chat1.ChatChannel
conversationID?: string
}
export interface ReadResult {
messages: chat1.MsgSummary[]
pagination: chat1.Pagination
}
/** The chat module of your Keybase bot. For more info about the API this module uses, you may want to check out `keybase chat api`. */
class Chat extends ClientBase {
/**
* Lists your chats, with info on which ones have unread messages.
* @memberof Chat
* @param options - An object of options that can be passed to the method.
* @returns - An array of chat conversations. If there are no conversations, the array is empty.
* @example
* const chatConversations = await bot.chat.list({unreadOnly: true})
* console.log(chatConversations)
*/
public async list(options?: ChatListOptions): Promise<chat1.ConvSummary[]> {
await this._guardInitialized()
const res = await this._runApiCommand({apiName: 'chat', method: 'list', options})
if (!res) {
throw new Error('Keybase chat list returned nothing.')
}
return res.conversations || []
}
/**
* Lists conversation channels in a team
* @memberof Chat
* @param name - Name of the team
* @param options - An object of options that can be passed to the method.
* @returns - An array of chat conversations. If there are no conversations, the array is empty.
* @example
* bot.chat.listChannels('team_name').then(chatConversations => console.log(chatConversations))
*/
public async listChannels(name: string, options?: ChatListChannelsOptions): Promise<chat1.ConvSummary[]> {
await this._guardInitialized()
const optionsWithDefaults = {
...options,
name,
membersType: options && options.membersType ? options.membersType : 'team',
}
const res = await this._runApiCommand({
apiName: 'chat',
method: 'listconvsonname',
options: optionsWithDefaults,
})
if (!res) {
throw new Error('Keybase chat list convs on name returned nothing.')
}
return res.conversations || []
}
private getChannelOrConversationId(
channelOrConversationId: chat1.ChatChannel | chat1.ConvIDStr
): {
channel?: chat1.ChatChannel
conversationId?: chat1.ConvIDStr
} {
return {
...(typeof channelOrConversationId === 'string' ? {conversationId: channelOrConversationId} : {}),
...(typeof channelOrConversationId === 'string' ? {} : {channel: channelOrConversationId}),
}
}
/**
* Reads the messages in a channel. You can read with or without marking as read.
* @memberof Chat
* @param channel - The chat channel to read messages in.
* @param options - An object of options that can be passed to the method.
* @returns - A summary of data about a message, including who send it, when, the content of the message, etc. If there are no messages in your channel, then an error is thrown.
* @example
* alice.chat.read(channel).then(messages => console.log(messages))
*/
public async read(channelOrConversationId: chat1.ChatChannel | chat1.ConvIDStr, options?: ChatReadOptions): Promise<ReadResult> {
await this._guardInitialized()
const conv = this.getChannelOrConversationId(channelOrConversationId)
const optionsWithDefaults = {
...options,
...conv,
peek: options && options.peek ? options.peek : false,
unreadOnly: options && options.unreadOnly !== undefined ? options.unreadOnly : false,
}
const res = await this._runApiCommand({apiName: 'chat', method: 'read', options: optionsWithDefaults})
if (!res) {
throw new Error('Keybase chat read returned nothing.')
}
// Pagination gets passed as-is, while the messages get cleaned up
return {
pagination: res.pagination,
messages: res.messages.map((message: chat1.MsgNotification): chat1.MsgSummary => message.msg!),
}
}
/**
* Joins a team conversation.
* @param channel - The team chat channel to join.
* @example
* bot.chat.listConvsOnName('team_name').then(async teamConversations => {
* for (const conversation of teamConversations) {
* if (conversation.memberStatus !== 'active') {
* await bot.chat.join(conversation.channel)
* console.log('Joined team channel', conversation.channel)
* }
* }
* })
*/
public async joinChannel(channel: chat1.ChatChannel): Promise<void> {
await this._guardInitialized()
const res = await this._runApiCommand({
apiName: 'chat',
method: 'join',
options: {
channel,
},
})
if (!res) {
throw new Error('Keybase chat join returned nothing')
}
}
/**
* Leaves a team conversation.
* @param channel - The team chat channel to leave.
* @example
* bot.chat.listConvsOnName('team_name').then(async teamConversations => {
* for (const conversation of teamConversations) {
* if (conversation.memberStatus === 'active') {
* await bot.chat.leave(conversation.channel)
* console.log('Left team channel', conversation.channel)
* }
* }
* })
*/
public async leaveChannel(channel: chat1.ChatChannel): Promise<void> {
await this._guardInitialized()
const res = await this._runApiCommand({
apiName: 'chat',
method: 'leave',
options: {
channel,
},
})
if (!res) {
throw new Error('Keybase chat leave returned nothing')
}
}
/**
* Send a message to a certain channel.
* @memberof Chat
* @param channel - The chat channel to send the message in.
* @param message - The chat message to send.
* @example
* const channel = {name: 'kbot,' + bot.myInfo().username, public: false, topicType: 'chat'}
* const message = {body: 'Hello kbot!'}
* bot.chat.send(channel, message).then(() => console.log('message sent!'))
*/
public async send(
channelOrConversationId: chat1.ChatChannel | chat1.ConvIDStr,
message: chat1.ChatMessage,
options?: ChatSendOptions
): Promise<chat1.SendRes> {
await this._guardInitialized()
const conv = this.getChannelOrConversationId(channelOrConversationId)
const args = {
...options,
explodingLifetime: options?.explodingLifetime ? `${options?.explodingLifetime}ms` : undefined,
...conv,
message,
}
this._adminDebugLogger.info(`sending message "${message.body}" in conversation ${JSON.stringify(conv)}`)
const res = await this._runApiCommand({
apiName: 'chat',
method: 'send',
options: args,
})
if (!res) {
throw new Error('Keybase chat send returned nothing')
}
this._adminDebugLogger.info(`message sent with id ${res.id}`)
return res
}
/**
* Creates a new blank conversation.
* @memberof Chat
* @param channel - The chat channel to create.
* @example
* bot.chat.createChannel(channel).then(() => console.log('conversation created'))
*/
public async createChannel(channel: chat1.ChatChannel): Promise<void> {
await this._guardInitialized()
const args = {
channel,
}
const res = await this._runApiCommand({
apiName: 'chat',
method: 'newconv',
options: args,
})
if (!res) {
throw new Error('Keybase chat newconv returned nothing')
}
}
/**
* Send a file to a channel.
* @memberof Chat
* @param channel - The chat channel to send the message in.
* @param filename - The absolute path of the file to send.
* @param options - An object of options that can be passed to the method.
* @example
* bot.chat.attach(channel, '/Users/nathan/my_picture.png').then(() => console.log('Sent a picture!'))
*/
public async attach(
channelOrConversationId: chat1.ChatChannel | chat1.ConvIDStr,
filename: string,
options?: ChatAttachOptions
): Promise<chat1.SendRes> {
await this._guardInitialized()
const conv = this.getChannelOrConversationId(channelOrConversationId)
const args = {
...options,
explodingLifetime: options?.explodingLifetime ? `${options?.explodingLifetime}ms` : undefined,
...conv,
filename,
}
const res = await this._runApiCommand({apiName: 'chat', method: 'attach', options: args})
if (!res) {
throw new Error('Keybase chat attach returned nothing')
}
return res
}
/**
* Download a file send via Keybase chat.
* @memberof Chat
* @param channel - The chat channel that the desired attacment to download is in.
* @param messageId - The message id of the attached file.
* @param output - The absolute path of where the file should be downloaded to.
* @param options - An object of options that can be passed to the method
* @example
* bot.chat.download(channel, 325, '/Users/nathan/Downloads/file.png')
*/
public async download(
channelOrConversationId: chat1.ChatChannel | chat1.ConvIDStr,
messageId: number,
output: string,
options?: ChatDownloadOptions
): Promise<void> {
await this._guardInitialized()
const conv = this.getChannelOrConversationId(channelOrConversationId)
const args = {...options, ...conv, messageId, output}
const res = await this._runApiCommand({apiName: 'chat', method: 'download', options: args})
if (!res) {
throw new Error('Keybase chat download returned nothing')
}
}
/**
* Reacts to a given message in a channel. Messages have messageId's associated with
* them, which you can learn in `bot.chat.read`.
* @memberof Chat
* @param channel - The chat channel to send the message in.
* @param messageId - The id of the message to react to.
* @param reaction - The reaction emoji, in colon form.
* @param options - An object of options that can be passed to the method.
* @example
* bot.chat.react(channel, 314, ':+1:').then(() => console.log('Thumbs up!'))
*/
public async react(
channelOrConversationId: chat1.ChatChannel | chat1.ConvIDStr,
messageId: number,
reaction: string
): Promise<chat1.SendRes> {
await this._guardInitialized()
const conv = this.getChannelOrConversationId(channelOrConversationId)
const args = {
...conv,
messageId,
message: {body: reaction},
}
const res = await this._runApiCommand({apiName: 'chat', method: 'reaction', options: args})
if (!res) {
throw new Error('Keybase chat react returned nothing.')
}
return res
}
/**
* Deletes a message in a channel. Messages have messageId's associated with
* them, which you can learn in `bot.chat.read`. Known bug: the GUI has a cache,
* and deleting from the CLI may not become apparent immediately.
* @memberof Chat
* @param channel - The chat channel to send the message in.
* @param messageId - The id of the message to delete.
* @param options - An object of options that can be passed to the method.
* @example
* bot.chat.delete(channel, 314).then(() => console.log('message deleted!'))
*/
public async delete(channelOrConversationId: chat1.ChatChannel | chat1.ConvIDStr, messageId: number): Promise<void> {
await this._guardInitialized()
const conv = this.getChannelOrConversationId(channelOrConversationId)
const args = {
...conv,
messageId,
}
const res = await this._runApiCommand({apiName: 'chat', method: 'delete', options: args})
if (!res) {
throw new Error('Keybase chat delete returned nothing.')
}
}
/**
* Gets current unfurling settings
* @example
* bot.chat.getUnfurlSettings().then((mode) => console.log(mode))
*/
public async getUnfurlSettings(): Promise<chat1.UnfurlSettings> {
await this._guardInitialized()
const res = await this._runApiCommand({apiName: 'chat', method: 'getunfurlsettings', options: {}})
if (!res) {
throw new Error('Keybase chat get unfurl mode returned nothing.')
}
return res
}
/**
* Sets the unfurling mode
* In Keybase, unfurling means generating previews for links that you're sending
* in chat messages. If the mode is set to always or the domain in the URL is
* present on the whitelist, the Keybase service will automatically send a preview
* to the message recipient in a background chat channel.
* @param mode - the new unfurl mode
* @example
* bot.chat.setUnfurlMode({
* "mode": "always",
* }).then((mode) => console.log('mode updated!'))
*/
public async setUnfurlSettings(mode: chat1.UnfurlSettings): Promise<void> {
await this._guardInitialized()
const res = await this._runApiCommand({apiName: 'chat', method: 'setunfurlsettings', options: mode})
if (!res) {
throw new Error('Keybase chat set unfurl mode returned nothing.')
}
}
/**
* Gets device information for a given username.
* This method allows you to see device name, description, type (desktop
* or mobile), and creation time for all active devices of a given username.
* @param username - the Keybase username to get devices for
* @example
* bot.chat.getDeviceInfo(username).then((devices) => console.log(devices))
*/
public async getDeviceInfo(username: string): Promise<chat1.GetDeviceInfoRes> {
await this._guardInitialized()
const res = await this._runApiCommand({apiName: 'chat', method: 'getdeviceinfo', options: {username}})
if (!res) {
throw new Error('Keybase chat get device info returned nothing.')
}
return res
}
/**
* Loads a flip's details
* @param conversationID - conversation ID received in API listen.
* @param flipConversationID - flipConvID from the message summary.
* @param messageID - ID of the message in the conversation.
* @param gameID - gameID from the flip message contents.
* @example
* // check demos/es7/poker-hands.js
*/
public async loadFlip(
conversationID: string,
flipConversationID: string,
messageID: number,
gameID: string
): Promise<chat1.UICoinFlipStatus> {
await this._guardInitialized()
const res = await this._runApiCommand({
apiName: 'chat',
method: 'loadflip',
// The flip method uses `msg_id` as a parameter instead of `message_id`, like other chat methods
// eslint-disable-next-line @typescript-eslint/camelcase
options: formatAPIObjectInput({conversationID, flipConversationID, msg_id: messageID, gameID}, 'chat'),
timeout: 2000,
})
if (!res) {
throw new Error('Keybase chat load flip returned nothing.')
}
return res.status
}
/**
* Publishes a commands advertisement which is shown in the "!" chat autocomplete.
* @param advertisement - details of the advertisement
* @example
* await bot.chat.advertiseCommands({
* advertisements: [
* {
* type: 'public',
* commands: [
* {
* name: '!echo',
* description: 'Sends out your message to the current channel.',
* usage: '[your text]',
* },
* ]
* }
* ],
* })
*/
public async advertiseCommands(advertisement: Advertisement): Promise<void> {
await this._guardInitialized()
const res = await this._runApiCommand({apiName: 'chat', method: 'advertisecommands', options: advertisement})
if (!res) {
throw new Error('Keybase chat advertise commands returned nothing.')
}
}
/**
* Clears all published commands advertisements.
* @param advertisement - advertisement parameters
* @example
* await bot.chat.clearCommands()
*/
public async clearCommands(): Promise<void> {
await this._guardInitialized()
const res = await this._runApiCommand({apiName: 'chat', method: 'clearcommands'})
if (!res) {
throw new Error('Keybase chat clear commands returned nothing.')
}
}
/**
* Let's a conversation partner back in after they've reset their account. You can
* get a list of such candidates with getResetConvMembers()
* @param username - the username of the user who has reset
* @param conversationId
* @example
* await bot.chat.addResetConvMember({username: "chris", conversationId: "abc1234567"})
*/
public async addResetConvMember(param: chat1.ResetConvMemberAPI): Promise<chat1.GetResetConvMembersRes> {
await this._guardInitialized()
const res = await this._runApiCommand({apiName: 'chat', method: 'addresetconvmember', options: param})
if (!res) {
throw new Error('addResetConvMember returned nothing.')
}
return res
}
/**
* Lists all the direct (non-team) conversations your bot has, in
* which their partner has "reset" their account and needs to be let back in
* @example
* await bot.chat.getResetConvMembers()
*/
public async getResetConvMembers(): Promise<chat1.GetResetConvMembersRes> {
await this._guardInitialized()
const res = await this._runApiCommand({apiName: 'chat', method: 'getresetconvmembers'})
if (!res) {
throw new Error('getResetConvMembers returned nothing.')
}
return res
}
/**
* Lists all commands advertised in a channel.
* @param lookup - either conversation id or channel
* @example
* const commandsList = await bot.chat.listCommands({
* channel: channel,
* })
* console.log(commandsList)
* // prints out something like:
* // {
* // commands: [
* // {
* // name: '!helloworld',
* // description: 'sample description',
* // usage: '[command arguments]',
* // username: 'userwhopublished',
* // }
* // ]
* // }
*/
public async listCommands(lookup: AdvertisementsLookup): Promise<{commands: chat1.UserBotCommandOutput[]}> {
await this._guardInitialized()
const res = await this._runApiCommand({apiName: 'chat', method: 'listcommands', options: lookup})
if (!res) {
throw new Error('Keybase chat list commands returned nothing.')
}
return {commands: res.commands || []}
}
/**
* Listens for new chat messages on a specified channel. The `onMessage` function is called for every message your bot receives. This is pretty similar to `watchAllChannelsForNewMessages`, except it specifically checks one channel. Note that it receives messages your own bot posts, but from other devices. You can filter out your own messages by looking at a message's sender object.
* Hides exploding messages by default.
* @memberof Chat
* @param channel - The chat channel to watch.
* @param onMessage - A callback that is triggered on every message your bot receives.
* @param onError - A callback that is triggered on any error that occurs while the method is executing.
* @param options - Options for the listen method.
* @example
* // Reply to all messages between you and `kbot` with 'thanks!'
* const channel = {name: 'kbot,' + bot.myInfo().username, public: false, topicType: 'chat'}
* const onMessage = message => {
* const channel = message.channel
* bot.chat.send(channel, {body: 'thanks!!!'})
* }
* bot.chat.watchChannelForNewMessages(channel, onMessage)
*/
public async watchChannelForNewMessages(
channel: chat1.ChatChannel,
onMessage: OnMessage,
onError?: OnError,
options?: ListenOptions
): Promise<void> {
await this._guardInitialized()
return this._chatListenMessage(onMessage, onError, channel, options)
}
/**
* This function will put your bot into full-read mode, where it reads
* everything it can and every new message it finds it will pass to you, so
* you can do what you want with it. For example, if you want to write a
* Keybase bot that talks shit at anyone who dares approach it, this is the
* function to use. Note that it receives messages your own bot posts, but from other devices.
* You can filter out your own messages by looking at a message's sender object.
* Hides exploding messages by default.
* @memberof Chat
* @param onMessage - A callback that is triggered on every message your bot receives.
* @param onError - A callback that is triggered on any error that occurs while the method is executing.
* @param options - Options for the listen method.
* @example
* // Reply to incoming traffic on all channels with 'thanks!'
* const onMessage = message => {
* const channel = message.channel
* bot.chat.send(channel, {body: 'thanks!!!'})
* }
* bot.chat.watchAllChannelsForNewMessages(onMessage)
*
*/
public async watchAllChannelsForNewMessages(onMessage: OnMessage, onError?: OnError, options?: ListenOptions): Promise<void> {
await this._guardInitialized()
return this._chatListenMessage(onMessage, onError, undefined, options)
}
/**
* This function watches for new conversations your bot is added into. This gives your bot a chance to say hi when it's added/installed into a conversation.
* @param onConv - A callback that is triggered when the bot is added into a conversation.
* @param onError - A callback that is triggered on any error that occurs while the method is executing.
* @example
* // Say hi
* const onConv = conv => {
* const channel = conv.channel
* bot.chat.send(channel, {body: 'Hi!'})
* }
* bot.chat.watchForNewConversation(onConv)
*
*/
public async watchForNewConversation(onConv: OnConv, onError?: OnError): Promise<void> {
await this._guardInitialized()
return this._chatListenConvs(onConv, onError)
}
private _spawnChatListenChild(args: Array<string>, onLine: (line: string) => void): Promise<void> {
return new Promise((resolve, reject): void => {
const child = spawn(this._pathToKeybaseBinary(), args)
this._spawnedProcesses.push(child)
const cmdSample = this._pathToKeybaseBinary() + ' ' + args.join(' ')
this._adminDebugLogger.info(`beginning listen using ${cmdSample}`)
const lineReaderStderr = readline.createInterface({input: child.stderr})
const stdErrBuffer: string[] = []
child.on('error', (err: Error): void => {
this._adminDebugLogger.error(`got listen error ${err.message}`)
})
child.on('exit', (): void => {
this._adminDebugLogger.info(`got listen exit`)
})
child.on('close', (code: number): void => {
this._adminDebugLogger.info(`got listen close, code ${code}`)
if (code) {
return this._deinitializing ? resolve() : reject(new Error(stdErrBuffer.join('\n')))
}
resolve()
})
child.on('disconnect', (): void => {
this._adminDebugLogger.info(`got listen disconnect`)
})
lineReaderStderr.on('line', (line: string): void => {
stdErrBuffer.push(line)
this._adminDebugLogger.error(`stderr from listener: ${line}`)
})
const lineReaderStdout = readline.createInterface({input: child.stdout})
lineReaderStdout.on('line', onLine)
})
}
private _getChatListenArgs(channel?: chat1.ChatChannel, options?: ListenOptions): Array<string> {
const args = ['chat', 'api-listen']
if (this.homeDir) {
args.unshift('--home', this.homeDir)
}
if (!options || (options && options.hideExploding !== false)) {
args.push('--hide-exploding')
}
if (options && options.showLocal === true) {
args.push('--local')
}
if (channel) {
args.push('--filter-channel', JSON.stringify(formatAPIObjectInput(channel, 'chat')))
}
return args
}
/**
* Spawns the chat listen process and handles the calling of onMessage, onError, and filtering for a specific channel.
* @memberof Chat
* @ignore
* @param onMessage - A callback that is triggered on every message your bot receives.
* @param onError - A callback that is triggered on any error that occurs while the method is executing.
* @param channel - The chat channel to watch.
* @param options - Options for the listen method.
* @example
* this._chatListenMessage(onMessage, onError)
*/
private _chatListenMessage(onMessage: OnMessage, onError?: OnError, channel?: chat1.ChatChannel, options?: ListenOptions): Promise<void> {
const args = this._getChatListenArgs(channel, options)
const onLine = (line: string): void => {
this._adminDebugLogger.info(`stdout from listener: ${line}`)
try {
const messageObject = formatAPIObjectOutput(JSON.parse(line), null)
if (messageObject.hasOwnProperty('error')) {
throw new Error(messageObject.error)
}
if (messageObject.type !== 'chat' || !messageObject.msg) {
return
}
const msgNotification: chat1.MsgNotification = messageObject
if (msgNotification.msg) {
if (
// fire onMessage if it was from a different sender or at least a different device
// from this sender. Bots can filter out their own messages from other devices.
(options && options.showLocal) ||
(this.username &&
this.devicename &&
(msgNotification.msg.sender.username !== this.username.toLowerCase() ||
msgNotification.msg.sender.deviceName !== this.devicename))
) {
onMessage(msgNotification.msg)
}
}
} catch (error) {
if (onError) {
onError(error)
}
}
}
this._adminDebugLogger.info(`spawningChatListenChild on channel=${JSON.stringify(channel || 'ALL')}`)
return this._spawnChatListenChild(args, onLine)
}
/**
* Spawns the chat listen process for new channels and handles the calling of onConv, and onError.
* @memberof Chat
* @ignore
* @param onConv - A callback that is triggered on every new channel your bot is added to.
* @param onError - A callback that is triggered on any error that occurs while the method is executing.
* @example
* this._chatListenConvs(onConv, onError)
*/
private _chatListenConvs(onConv: OnConv, onError?: OnError): Promise<void> {
const args = this._getChatListenArgs()
args.push('--convs')
this._adminDebugLogger.info(`spawningChatListenChild for convs`)
return this._spawnChatListenChild(args, (line: string) => {
this._adminDebugLogger.info(`stdout from listener: ${line}`)
try {
const messageObject = formatAPIObjectOutput(JSON.parse(line), null)
if (messageObject.hasOwnProperty('error')) {
throw new Error(messageObject.error)
}
if (messageObject.type !== 'chat_conv' || !messageObject.conv) {
return
}
const convNotification: chat1.ConvNotification = messageObject
convNotification.conv && onConv(convNotification.conv)
} catch (error) {
if (onError) {
onError(error)
}
}
})
}
}
export default Chat | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/filesystemOperationsMappers";
import * as Parameters from "../models/parameters";
import { DataLakeStorageClientContext } from "../dataLakeStorageClientContext";
/** Class representing a FilesystemOperations. */
export class FilesystemOperations {
private readonly client: DataLakeStorageClientContext;
/**
* Create a FilesystemOperations.
* @param client - Reference to the service client.
*/
constructor(client: DataLakeStorageClientContext) {
this.client = client;
}
/**
* List filesystems and their properties in given account.
* @summary List Filesystems
* @param options - The optional parameters
* @returns Promise<Models.FilesystemListResponse>
*/
list(options?: Models.FilesystemListOptionalParams): Promise<Models.FilesystemListResponse>;
/**
* @param callback - The callback
*/
list(callback: msRest.ServiceCallback<Models.FilesystemList>): void;
/**
* @param options - The optional parameters
* @param callback - The callback
*/
list(
options: Models.FilesystemListOptionalParams,
callback: msRest.ServiceCallback<Models.FilesystemList>
): void;
list(
options?: Models.FilesystemListOptionalParams | msRest.ServiceCallback<Models.FilesystemList>,
callback?: msRest.ServiceCallback<Models.FilesystemList>
): Promise<Models.FilesystemListResponse> {
return this.client.sendOperationRequest(
{
options
},
listOperationSpec,
callback
) as Promise<Models.FilesystemListResponse>;
}
/**
* Create a filesystem rooted at the specified location. If the filesystem already exists, the
* operation fails. This operation does not support conditional HTTP requests.
* @summary Create Filesystem
* @param filesystem - The filesystem identifier. The value must start and end with a letter or
* number and must contain only letters, numbers, and the dash (-) character. Consecutive dashes
* are not permitted. All letters must be lowercase. The value must have between 3 and 63
* characters.
* @param options - The optional parameters
* @returns Promise<Models.FilesystemCreateResponse>
*/
create(
filesystem: string,
options?: Models.FilesystemCreateOptionalParams
): Promise<Models.FilesystemCreateResponse>;
/**
* @param filesystem - The filesystem identifier. The value must start and end with a letter or
* number and must contain only letters, numbers, and the dash (-) character. Consecutive dashes
* are not permitted. All letters must be lowercase. The value must have between 3 and 63
* characters.
* @param callback - The callback
*/
create(filesystem: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param filesystem - The filesystem identifier. The value must start and end with a letter or
* number and must contain only letters, numbers, and the dash (-) character. Consecutive dashes
* are not permitted. All letters must be lowercase. The value must have between 3 and 63
* characters.
* @param options - The optional parameters
* @param callback - The callback
*/
create(
filesystem: string,
options: Models.FilesystemCreateOptionalParams,
callback: msRest.ServiceCallback<void>
): void;
create(
filesystem: string,
options?: Models.FilesystemCreateOptionalParams | msRest.ServiceCallback<void>,
callback?: msRest.ServiceCallback<void>
): Promise<Models.FilesystemCreateResponse> {
return this.client.sendOperationRequest(
{
filesystem,
options
},
createOperationSpec,
callback
) as Promise<Models.FilesystemCreateResponse>;
}
/**
* Set properties for the filesystem. This operation supports conditional HTTP requests. For more
* information, see [Specifying Conditional Headers for Blob Service
* Operations](https://docs.microsoft.com/en-us/rest/api/storageservices/specifying-conditional-headers-for-blob-service-operations).
* @summary Set Filesystem Properties
* @param filesystem - The filesystem identifier. The value must start and end with a letter or
* number and must contain only letters, numbers, and the dash (-) character. Consecutive dashes
* are not permitted. All letters must be lowercase. The value must have between 3 and 63
* characters.
* @param options - The optional parameters
* @returns Promise<Models.FilesystemSetPropertiesResponse>
*/
setProperties(
filesystem: string,
options?: Models.FilesystemSetPropertiesOptionalParams
): Promise<Models.FilesystemSetPropertiesResponse>;
/**
* @param filesystem - The filesystem identifier. The value must start and end with a letter or
* number and must contain only letters, numbers, and the dash (-) character. Consecutive dashes
* are not permitted. All letters must be lowercase. The value must have between 3 and 63
* characters.
* @param callback - The callback
*/
setProperties(filesystem: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param filesystem - The filesystem identifier. The value must start and end with a letter or
* number and must contain only letters, numbers, and the dash (-) character. Consecutive dashes
* are not permitted. All letters must be lowercase. The value must have between 3 and 63
* characters.
* @param options - The optional parameters
* @param callback - The callback
*/
setProperties(
filesystem: string,
options: Models.FilesystemSetPropertiesOptionalParams,
callback: msRest.ServiceCallback<void>
): void;
setProperties(
filesystem: string,
options?: Models.FilesystemSetPropertiesOptionalParams | msRest.ServiceCallback<void>,
callback?: msRest.ServiceCallback<void>
): Promise<Models.FilesystemSetPropertiesResponse> {
return this.client.sendOperationRequest(
{
filesystem,
options
},
setPropertiesOperationSpec,
callback
) as Promise<Models.FilesystemSetPropertiesResponse>;
}
/**
* All system and user-defined filesystem properties are specified in the response headers.
* @summary Get Filesystem Properties.
* @param filesystem - The filesystem identifier. The value must start and end with a letter or
* number and must contain only letters, numbers, and the dash (-) character. Consecutive dashes
* are not permitted. All letters must be lowercase. The value must have between 3 and 63
* characters.
* @param options - The optional parameters
* @returns Promise<Models.FilesystemGetPropertiesResponse>
*/
getProperties(
filesystem: string,
options?: Models.FilesystemGetPropertiesOptionalParams
): Promise<Models.FilesystemGetPropertiesResponse>;
/**
* @param filesystem - The filesystem identifier. The value must start and end with a letter or
* number and must contain only letters, numbers, and the dash (-) character. Consecutive dashes
* are not permitted. All letters must be lowercase. The value must have between 3 and 63
* characters.
* @param callback - The callback
*/
getProperties(filesystem: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param filesystem - The filesystem identifier. The value must start and end with a letter or
* number and must contain only letters, numbers, and the dash (-) character. Consecutive dashes
* are not permitted. All letters must be lowercase. The value must have between 3 and 63
* characters.
* @param options - The optional parameters
* @param callback - The callback
*/
getProperties(
filesystem: string,
options: Models.FilesystemGetPropertiesOptionalParams,
callback: msRest.ServiceCallback<void>
): void;
getProperties(
filesystem: string,
options?: Models.FilesystemGetPropertiesOptionalParams | msRest.ServiceCallback<void>,
callback?: msRest.ServiceCallback<void>
): Promise<Models.FilesystemGetPropertiesResponse> {
return this.client.sendOperationRequest(
{
filesystem,
options
},
getPropertiesOperationSpec,
callback
) as Promise<Models.FilesystemGetPropertiesResponse>;
}
/**
* Marks the filesystem for deletion. When a filesystem is deleted, a filesystem with the same
* identifier cannot be created for at least 30 seconds. While the filesystem is being deleted,
* attempts to create a filesystem with the same identifier will fail with status code 409
* (Conflict), with the service returning additional error information indicating that the
* filesystem is being deleted. All other operations, including operations on any files or
* directories within the filesystem, will fail with status code 404 (Not Found) while the
* filesystem is being deleted. This operation supports conditional HTTP requests. For more
* information, see [Specifying Conditional Headers for Blob Service
* Operations](https://docs.microsoft.com/en-us/rest/api/storageservices/specifying-conditional-headers-for-blob-service-operations).
* @summary Delete Filesystem
* @param filesystem - The filesystem identifier. The value must start and end with a letter or
* number and must contain only letters, numbers, and the dash (-) character. Consecutive dashes
* are not permitted. All letters must be lowercase. The value must have between 3 and 63
* characters.
* @param options - The optional parameters
* @returns Promise<Models.FilesystemDeleteResponse>
*/
deleteMethod(
filesystem: string,
options?: Models.FilesystemDeleteMethodOptionalParams
): Promise<Models.FilesystemDeleteResponse>;
/**
* @param filesystem - The filesystem identifier. The value must start and end with a letter or
* number and must contain only letters, numbers, and the dash (-) character. Consecutive dashes
* are not permitted. All letters must be lowercase. The value must have between 3 and 63
* characters.
* @param callback - The callback
*/
deleteMethod(filesystem: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param filesystem - The filesystem identifier. The value must start and end with a letter or
* number and must contain only letters, numbers, and the dash (-) character. Consecutive dashes
* are not permitted. All letters must be lowercase. The value must have between 3 and 63
* characters.
* @param options - The optional parameters
* @param callback - The callback
*/
deleteMethod(
filesystem: string,
options: Models.FilesystemDeleteMethodOptionalParams,
callback: msRest.ServiceCallback<void>
): void;
deleteMethod(
filesystem: string,
options?: Models.FilesystemDeleteMethodOptionalParams | msRest.ServiceCallback<void>,
callback?: msRest.ServiceCallback<void>
): Promise<Models.FilesystemDeleteResponse> {
return this.client.sendOperationRequest(
{
filesystem,
options
},
deleteMethodOperationSpec,
callback
) as Promise<Models.FilesystemDeleteResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
urlParameters: [Parameters.accountName, Parameters.dnsSuffix],
queryParameters: [
Parameters.resource0,
Parameters.prefix,
Parameters.continuation,
Parameters.maxResults,
Parameters.timeout
],
headerParameters: [
Parameters.xMsClientRequestId,
Parameters.xMsDate,
Parameters.xMsVersion,
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.FilesystemList,
headersMapper: Mappers.FilesystemListHeaders
},
default: {
bodyMapper: Mappers.DataLakeStorageError
}
},
serializer
};
const createOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "{filesystem}",
urlParameters: [Parameters.accountName, Parameters.dnsSuffix, Parameters.filesystem],
queryParameters: [Parameters.resource1, Parameters.timeout],
headerParameters: [
Parameters.xMsProperties,
Parameters.xMsClientRequestId,
Parameters.xMsDate,
Parameters.xMsVersion,
Parameters.acceptLanguage
],
responses: {
201: {
headersMapper: Mappers.FilesystemCreateHeaders
},
default: {
bodyMapper: Mappers.DataLakeStorageError
}
},
serializer
};
const setPropertiesOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "{filesystem}",
urlParameters: [Parameters.accountName, Parameters.dnsSuffix, Parameters.filesystem],
queryParameters: [Parameters.resource1, Parameters.timeout],
headerParameters: [
Parameters.xMsProperties,
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.xMsClientRequestId,
Parameters.xMsDate,
Parameters.xMsVersion,
Parameters.acceptLanguage
],
responses: {
200: {
headersMapper: Mappers.FilesystemSetPropertiesHeaders
},
default: {
bodyMapper: Mappers.DataLakeStorageError
}
},
serializer
};
const getPropertiesOperationSpec: msRest.OperationSpec = {
httpMethod: "HEAD",
path: "{filesystem}",
urlParameters: [Parameters.accountName, Parameters.dnsSuffix, Parameters.filesystem],
queryParameters: [Parameters.resource1, Parameters.timeout],
headerParameters: [
Parameters.xMsClientRequestId,
Parameters.xMsDate,
Parameters.xMsVersion,
Parameters.acceptLanguage
],
responses: {
200: {
headersMapper: Mappers.FilesystemGetPropertiesHeaders
},
default: {
bodyMapper: Mappers.DataLakeStorageError
}
},
serializer
};
const deleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "{filesystem}",
urlParameters: [Parameters.accountName, Parameters.dnsSuffix, Parameters.filesystem],
queryParameters: [Parameters.resource1, Parameters.timeout],
headerParameters: [
Parameters.ifModifiedSince,
Parameters.ifUnmodifiedSince,
Parameters.xMsClientRequestId,
Parameters.xMsDate,
Parameters.xMsVersion,
Parameters.acceptLanguage
],
responses: {
202: {
headersMapper: Mappers.FilesystemDeleteHeaders
},
default: {
bodyMapper: Mappers.DataLakeStorageError
}
},
serializer
}; | the_stack |
import { ITelemetryLoggerPropertyBag } from '@fluidframework/telemetry-utils';
import { ITelemetryBaseEvent } from '@fluidframework/common-definitions';
import { IFluidHandle } from '@fluidframework/core-interfaces';
import { Payload } from './generic';
const defaultFailMessage = 'Assertion failed';
/**
* Assertion failures in SharedTree will throw an exception containing this value as an `errorType`. The Fluid runtime propagates this field
* in its handlings of errors thrown by containers. See
* https://github.com/microsoft/FluidFramework/blob/main/packages/loader/container-utils/src/error.ts
*
* Exporting this enables users to safely filter telemetry handling of errors based on their type.
*
* @public
*/
export const sharedTreeAssertionErrorType = 'SharedTreeAssertion';
/**
* Telemetry properties decorated on all SharedTree events.
*/
export interface SharedTreeTelemetryProperties extends ITelemetryLoggerPropertyBag {
isSharedTreeEvent: true;
}
/**
* Returns if the supplied event is a SharedTree telemetry event.
*/
export function isSharedTreeEvent(event: ITelemetryBaseEvent): boolean {
return (event as unknown as SharedTreeTelemetryProperties).isSharedTreeEvent === true;
}
/**
* Error object thrown by assertion failures in `SharedTree`.
*/
class SharedTreeAssertionError extends Error {
public readonly errorType = sharedTreeAssertionErrorType;
public constructor(message: string) {
super(message);
this.name = 'Assertion error';
Error.captureStackTrace?.(this);
}
}
/**
* @returns true if two `Payloads` are identical.
* May return false for equivalent payloads encoded differently.
*
* Object field order and object identity are not considered significant, and are ignored by this function.
* (This is because they may not be preserved through roundtrip).
*
* For other information which Fluid would lose on serialization round trip,
* behavior is unspecified other than this this function is reflective (all payloads are equal to themselves)
* and commutative (argument order does not matter).
*
* This means that any Payload is equal to itself and a deep clone of itself.
*
* Payloads might not be equal to a version of themselves that has been serialized then deserialized.
* If they are serialized then deserialized again, the two deserialized objects will compare equal,
* however the serialized strings may be unequal (due to field order for objects being unspecified).
*
* Fluid will cause lossy operations due to use of JSON.stringify().
* This includes:
* - Loss of object identity
* - Loss of field order (may be ordered arbitrarily)
* - -0 becomes +0
* - NaN, Infinity, -Infinity all become null
* - custom toJSON functions may cause arbitrary behavior
* - functions become undefined or null
* - non enumerable properties (including prototype) are lost
* - more (this is not a complete list)
*
* Inputs must not contain cyclic references other than fields set to their immediate parent (for the JavaScript feature detection pattern).
*
* IFluidHandle instances (detected via JavaScript feature detection pattern) are only compared by absolutePath.
*
* TODO:#54095: Is there a better way to do this comparison?
* @public
*/
export function comparePayloads(a: Payload, b: Payload): boolean {
// === is not reflective because of how NaN is handled, so use Object.is instead.
// This treats -0 and +0 as different.
// Since -0 is not preserved in serialization round trips,
// it can be handed in any way that is reflective and commutative, so this is fine.
if (Object.is(a, b)) {
return true;
}
// Primitives which are equal would have early returned above, so now if the values are not both objects, they are unequal.
if (typeof a !== 'object' || typeof b !== 'object') {
return false;
}
// null is of type object, and needs to be treated as distinct from the empty object.
// Handling it early also avoids type errors trying to access its keys.
// Rationale: 'undefined' payloads are reserved for future use (see 'SetValue' interface).
// eslint-disable-next-line no-null/no-null
if (a === null || b === null) {
return false;
}
// Special case IFluidHandles, comparing them only by their absolutePath
// Detect them using JavaScript feature detection pattern: they have a `IFluidHandle` field that is set to the parent object.
{
const aHandle = a as IFluidHandle;
const bHandle = b as IFluidHandle;
if (aHandle.IFluidHandle === a) {
if (bHandle.IFluidHandle !== b) {
return false;
}
return a.absolutePath === b.absolutePath;
}
}
// Fluid Serialization (like Json) only keeps enumerable properties, so we can ignore non-enumerable ones.
const aKeys = Object.keys(a);
const bKeys = Object.keys(b);
if (aKeys.length !== bKeys.length) {
return false;
}
// make sure objects with numeric keys (or no keys) compare unequal to arrays.
if (Array.isArray(a) !== Array.isArray(b)) {
return false;
}
// Fluid Serialization (like Json) orders object fields arbitrarily, so reordering fields is not considered considered a change.
// Therefor the keys arrays must be sorted here.
if (!Array.isArray(a)) {
aKeys.sort();
bKeys.sort();
}
// First check keys are equal.
// This will often early exit, and thus is worth doing as a separate pass than recursive check.
if (!compareArrays(aKeys, bKeys)) {
return false;
}
for (let i = 0; i < aKeys.length; i++) {
const aItem: Payload = a[aKeys[i]];
const bItem: Payload = b[bKeys[i]];
// The JavaScript feature detection pattern, used for IFluidHandle, uses a field that is set to the parent object.
// Detect this pattern and special case it to avoid infinite recursion.
const aSelf = Object.is(aItem, a);
const bSelf = Object.is(bItem, b);
if (aSelf !== bSelf) {
return false;
}
if (!aSelf) {
if (!comparePayloads(aItem, bItem)) {
return false;
}
}
}
return true;
}
/**
* Asserts against a boolean condition. Throws an Error if the assertion failed. Will run and throw in release builds.
* Use when violations are logic errors in the program.
* @param condition - A condition to assert is truthy
* @param message - Message to be printed if assertion fails. Will print "Assertion failed" by default
* @param containsPII - boolean flag for whether the message passed in contains personally identifying information (PII).
*/
export function assert(condition: unknown, message?: string, containsPII = false): asserts condition {
// Rationale: Assert condition is permitted to be truthy.
// eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
if (!condition) {
fail(message, containsPII);
}
}
/**
* Fails an assertion. Throws an Error that the assertion failed.
* Use when violations are logic errors in the program.
* @param message - Message to be printed if assertion fails. Will print "Assertion failed" by default
* @param containsPII - boolean flag for whether the message passed in contains personally identifying information (PII).
*/
export function fail(message: string = defaultFailMessage, containsPII = false): never {
if (process.env.NODE_ENV !== 'production') {
debugger;
console.error(message);
}
throw new SharedTreeAssertionError(containsPII ? 'Assertion failed' : message);
}
/**
* Asserts a value is not undefined, and returns the value.
* Use when violations are logic errors in the program.
* @param value - Value to assert against is non undefined.
* @param message - Message to be printed if assertion fails.
*/
export function assertNotUndefined<T>(value: T | undefined, message = 'value must not be undefined'): T {
assert(value !== undefined, message);
return value;
}
/**
* Asserts an array contains a single value and returns the value.
* @param array - array to assert contains a single value.
* @param message - Message to be printed if assertion fails.
*/
export function assertArrayOfOne<T>(array: readonly T[], message = 'array value must contain exactly one item'): T {
assert(array.length === 1, message);
return array[0];
}
/**
* Redefine a property to have the given value. This is simply a type-safe wrapper around
* `Object.defineProperty`, but it is useful for caching public getters on first read.
* @example
* ```
* // `randomOnce()` will return a random number, but always the same random number.
* {
* get randomOnce(): number {
* return memoizeGetter(this, 'randomOnce', random(100))
* }
* }
* ```
* @param object - the object containing the property
* @param propName - the name of the property on the object
* @param value - the value of the property
*/
export function memoizeGetter<T, K extends keyof T>(object: T, propName: K, value: T[K]): T[K] {
Object.defineProperty(object, propName, {
value,
enumerable: true,
configurable: true,
});
return value;
}
/**
* Iterate through two iterables and return true if they yield equivalent elements in the same order.
* @param iterableA - the first iterable to compare
* @param iterableB - the second iterable to compare
* @param elementComparator - the function used to check if two `T`s are equivalent.
* Defaults to `Object.is()` equality (a shallow compare)
*/
export function compareIterables<T>(
iterableA: Iterable<T>,
iterableB: Iterable<T>,
elementComparator: (a: T, b: T) => boolean = Object.is
): boolean {
return compareIterators<T>(iterableA[Symbol.iterator](), iterableB[Symbol.iterator](), elementComparator);
}
/**
* Iterate through two iterators and return true if they yield equivalent elements in the same order.
* @param iteratorA - the first iterator to compare
* @param iteratorB - the second iterator to compare
* @param elementComparator - the function used to check if two `T`s are equivalent.
* Defaults to `Object.is()` equality (a shallow compare)
*/
function compareIterators<T, TReturn extends T = T>(
iteratorA: Iterator<T, TReturn>,
iteratorB: Iterator<T, TReturn>,
elementComparator: (a: T, b: T) => boolean = Object.is
): boolean {
let a: IteratorResult<T, TReturn>;
let b: IteratorResult<T, TReturn>;
for (
a = iteratorA.next(), b = iteratorB.next(); // Given two iterators...
a.done !== true && b.done !== true; // ...while both have elements remaining...
a = iteratorA.next(), b = iteratorB.next() // ...take one element at a time from each...
) {
// ...and ensure that their elements are equivalent
if (!elementComparator(a.value, b.value)) {
return false;
}
}
// If one iterator is done, but not the other, then they are not equivalent
return a.done === b.done;
}
/**
* Compare two arrays and return true if their elements are equivalent and in the same order.
* @param arrayA - the first array to compare
* @param arrayB - the second array to compare
* @param elementComparator - the function used to check if two `T`s are equivalent.
* Defaults to `Object.is()` equality (a shallow compare)
*/
export function compareArrays<T>(
arrayA: readonly T[],
arrayB: readonly T[],
elementComparator: (a: T, b: T) => boolean = Object.is
): boolean {
if (arrayA.length !== arrayB.length) {
return false;
}
for (let i = 0; i < arrayA.length; i++) {
if (!elementComparator(arrayA[i], arrayB[i])) {
return false;
}
}
return true;
}
/**
* Function which does nothing (no-ops).
*/
export function noop(): void {
// noop
}
/**
* Copies a property in such a way that it is only set on `destination` if it is present on `source`.
* This avoids having explicit undefined values under properties that would cause `Object.hasOwnProperty` to return true.
*/
export function copyPropertyIfDefined<TSrc, TDst>(source: TSrc, destination: TDst, property: keyof TSrc): void {
const value = source[property];
if (value !== undefined) {
(destination as any)[property] = value;
}
}
/**
* A developer facing (non-localized) error message.
* TODO: better error system.
*/
export type ErrorString = string; | the_stack |
import {
Range,
Point,
Emitter,
CompositeDisposable,
TextBuffer,
Directory,
TextEditor,
} from 'atom'
import * as Util from '../util'
import { extname, isAbsolute } from 'path'
import Queue = require('promise-queue')
import { unlit } from 'atom-haskell-utils'
import * as CompletionBackend from 'atom-haskell-upi/completion-backend'
import * as UPI from 'atom-haskell-upi'
import {
GhcModiProcessReal,
GHCModCaps,
RunArgs,
IErrorCallbackArgs,
} from './ghc-modi-process-real'
import { createGhcModiProcessReal } from './ghc-modi-process-real-factory'
import { getSettings } from './settings'
export { IErrorCallbackArgs, RunArgs, GHCModCaps }
type Commands =
| 'checklint'
| 'browse'
| 'typeinfo'
| 'find'
| 'init'
| 'list'
| 'lowmem'
export interface SymbolDesc {
name: string
symbolType: CompletionBackend.SymbolType
typeSignature?: string
parent?: string
}
export class GhcModiProcess {
private backend: Map<string, Promise<GhcModiProcessReal>>
private disposables: CompositeDisposable
private emitter: Emitter<
{
'did-destroy': undefined
'backend-active': undefined
'backend-idle': undefined
},
{
warning: string
error: IErrorCallbackArgs
'queue-idle': { queue: Commands }
}
>
private bufferDirMap: WeakMap<TextBuffer, Directory>
private commandQueues: { [K in Commands]: Queue }
constructor(private upiPromise: Promise<UPI.IUPIInstance>) {
this.disposables = new CompositeDisposable()
this.emitter = new Emitter()
this.disposables.add(this.emitter)
this.bufferDirMap = new WeakMap()
this.backend = new Map()
if (
process.env.GHC_PACKAGE_PATH &&
!atom.config.get('haskell-ghc-mod.suppressGhcPackagePathWarning')
) {
Util.warnGHCPackagePath()
}
this.commandQueues = {
checklint: new Queue(2),
browse: new Queue(atom.config.get('haskell-ghc-mod.maxBrowseProcesses')),
typeinfo: new Queue(1),
find: new Queue(1),
init: new Queue(4),
list: new Queue(1),
lowmem: new Queue(1),
}
this.disposables.add(
atom.config.onDidChange(
'haskell-ghc-mod.maxBrowseProcesses',
({ newValue }) =>
(this.commandQueues.browse = new Queue(newValue as number)),
),
)
}
public async getRootDir(buffer: TextBuffer): Promise<Directory> {
let dir
dir = this.bufferDirMap.get(buffer)
if (dir) {
return dir
}
dir = await Util.getRootDir(buffer)
this.bufferDirMap.set(buffer, dir)
return dir
}
public killProcess() {
for (const bp of this.backend.values()) {
bp.then((b) => b.killProcess()).catch((e: Error) => {
atom.notifications.addError('Error killing ghc-mod process', {
detail: e.toString(),
stack: e.stack,
dismissable: true,
})
})
}
this.backend.clear()
}
public destroy() {
for (const bp of this.backend.values()) {
bp.then((b) => b.destroy()).catch((e: Error) => {
atom.notifications.addError('Error killing ghc-mod process', {
detail: e.toString(),
stack: e.stack,
dismissable: true,
})
})
}
this.backend.clear()
this.emitter.emit('did-destroy')
this.disposables.dispose()
}
public onDidDestroy(callback: () => void) {
return this.emitter.on('did-destroy', callback)
}
public onWarning(callback: (warning: string) => void) {
return this.emitter.on('warning', callback)
}
public onError(callback: (error: IErrorCallbackArgs) => void) {
return this.emitter.on('error', callback)
}
public onBackendActive(callback: () => void) {
return this.emitter.on('backend-active', callback)
}
public onBackendIdle(callback: () => void) {
return this.emitter.on('backend-idle', callback)
}
public onQueueIdle(callback: () => void) {
return this.emitter.on('queue-idle', callback)
}
public async runList(buffer: TextBuffer) {
return this.queueCmd('list', await this.getRootDir(buffer), () => ({
command: 'list',
}))
}
public async runLang(dir: Directory) {
return this.queueCmd('init', dir, () => ({ command: 'lang' }))
}
public async runFlag(dir: Directory) {
return this.queueCmd('init', dir, () => ({ command: 'flag' }))
}
public async runBrowse(
rootDir: Directory,
modules: string[],
): Promise<SymbolDesc[]> {
const lines = await this.queueCmd('browse', rootDir, (caps) => {
const args = caps.browseMain
? modules
: modules.filter((v) => v !== 'Main')
if (args.length === 0) return undefined
return {
command: 'browse',
dashArgs: caps.browseParents ? ['-d', '-o', '-p'] : ['-d', '-o'],
args,
}
})
return lines.map((s) => {
// enumFrom :: Enum a => a -> [a] -- from:Enum
const pattern = /^(.*?) :: (.*?)(?: -- from:(.*))?$/
const match = s.match(pattern)
let name: string
let typeSignature: string | undefined
let parent: string | undefined
if (match) {
name = match[1]
typeSignature = match[2]
parent = match[3]
} else {
name = s
}
let symbolType: CompletionBackend.SymbolType
if (typeSignature && /^(?:type|data|newtype)/.test(typeSignature)) {
symbolType = 'type'
} else if (typeSignature && /^(?:class)/.test(typeSignature)) {
symbolType = 'class'
} else if (/^\(.*\)$/.test(name)) {
symbolType = 'operator'
name = name.slice(1, -1)
} else if (Util.isUpperCase(name[0])) {
symbolType = 'tag'
} else {
symbolType = 'function'
}
return { name, typeSignature, symbolType, parent }
})
}
public async getTypeInBuffer(buffer: TextBuffer, crange: Range) {
if (!buffer.getUri()) {
throw new Error('No URI for buffer')
}
crange = Util.tabShiftForRange(buffer, crange)
const rootDir = await this.getRootDir(buffer)
const lines = await this.queueCmd('typeinfo', rootDir, (caps) => ({
interactive: true,
command: 'type',
uri: buffer.getUri(),
text: buffer.isModified() ? buffer.getText() : undefined,
dashArgs: caps.typeConstraints ? ['-c'] : [],
args: [crange.start.row + 1, crange.start.column + 1].map((v) =>
v.toString(),
),
}))
const rx = /^(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+"([^]*)"$/ // [^] basically means "anything", incl. newlines
for (const line of lines) {
const match = line.match(rx)
if (!match) {
continue
}
const [rowstart, colstart, rowend, colend, type] = match.slice(1)
const range = Range.fromObject([
[parseInt(rowstart, 10) - 1, parseInt(colstart, 10) - 1],
[parseInt(rowend, 10) - 1, parseInt(colend, 10) - 1],
])
if (range.isEmpty()) {
continue
}
if (!range.containsRange(crange)) {
continue
}
return {
range: Util.tabUnshiftForRange(buffer, range),
type: type.replace(/\\"/g, '"'),
}
}
throw new Error('No type')
}
public async doCaseSplit(buffer: TextBuffer, crange: Range) {
if (!buffer.getUri()) {
throw new Error('No URI for buffer')
}
crange = Util.tabShiftForRange(buffer, crange)
const rootDir = await this.getRootDir(buffer)
const lines = await this.queueCmd('typeinfo', rootDir, (caps) => ({
interactive: caps.interactiveCaseSplit,
command: 'split',
uri: buffer.getUri(),
text: buffer.isModified() ? buffer.getText() : undefined,
args: [crange.start.row + 1, crange.start.column + 1].map((v) =>
v.toString(),
),
}))
const rx = /^(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+"([^]*)"$/ // [^] basically means "anything", incl. newlines
const res = []
for (const line of lines) {
const match = line.match(rx)
if (!match) {
Util.warn(`ghc-mod says: ${line}`)
continue
}
const [rowstart, colstart, rowend, colend, text] = match.slice(1)
res.push({
range: Range.fromObject([
[parseInt(rowstart, 10) - 1, parseInt(colstart, 10) - 1],
[parseInt(rowend, 10) - 1, parseInt(colend, 10) - 1],
]),
replacement: text,
})
}
return res
}
public async doSigFill(buffer: TextBuffer, crange: Range) {
if (!buffer.getUri()) {
throw new Error('No URI for buffer')
}
crange = Util.tabShiftForRange(buffer, crange)
const rootDir = await this.getRootDir(buffer)
const lines = await this.queueCmd('typeinfo', rootDir, (caps) => ({
interactive: caps.interactiveCaseSplit,
command: 'sig',
uri: buffer.getUri(),
text: buffer.isModified() ? buffer.getText() : undefined,
args: [crange.start.row + 1, crange.start.column + 1].map((v) =>
v.toString(),
),
}))
if (lines.length < 2) {
throw new Error(`Could not understand response: ${lines.join('\n')}`)
}
const rx = /^(\d+)\s+(\d+)\s+(\d+)\s+(\d+)$/ // position rx
const match = lines[1].match(rx)
if (!match) {
throw new Error(`Could not understand response: ${lines.join('\n')}`)
}
const [rowstart, colstart, rowend, colend] = match.slice(1)
const range = Range.fromObject([
[parseInt(rowstart, 10) - 1, parseInt(colstart, 10) - 1],
[parseInt(rowend, 10) - 1, parseInt(colend, 10) - 1],
])
return {
type: lines[0],
range,
body: lines.slice(2).join('\n'),
}
}
public async getInfoInBuffer(editor: TextEditor, crange: Range) {
const buffer = editor.getBuffer()
if (!buffer.getUri()) {
throw new Error('No URI for buffer')
}
const symInfo = Util.getSymbolInRange(editor, crange)
if (!symInfo) {
throw new Error("Couldn't get symbol for info")
}
const { symbol, range } = symInfo
const lines = await this.queueCmd(
'typeinfo',
await this.getRootDir(buffer),
() => ({
interactive: true,
command: 'info',
uri: buffer.getUri(),
text: buffer.isModified() ? buffer.getText() : undefined,
args: [symbol],
}),
)
const info = lines.join('\n')
if (info === 'Cannot show info' || !info) {
throw new Error('No info')
} else {
return { range, info }
}
}
public async findSymbolProvidersInBuffer(editor: TextEditor, crange: Range) {
const buffer = editor.getBuffer()
const symInfo = Util.getSymbolInRange(editor, crange)
if (!symInfo) {
throw new Error("Couldn't get symbol for import")
}
const { symbol } = symInfo
return this.queueCmd('find', await this.getRootDir(buffer), () => ({
interactive: true,
command: 'find',
args: [symbol],
}))
}
public async doCheckBuffer(buffer: TextBuffer, fast: boolean) {
return this.doCheckOrLintBuffer('check', buffer, fast)
}
public async doLintBuffer(buffer: TextBuffer) {
return this.doCheckOrLintBuffer('lint', buffer, false)
}
private async getUPI() {
return Promise.race([this.upiPromise, Promise.resolve(undefined)])
}
private async initBackend(rootDir: Directory): Promise<GhcModiProcessReal> {
const rootPath = rootDir.getPath()
const cached = this.backend.get(rootPath)
if (cached) {
return cached
}
const backend = this.createBackend(rootDir)
this.backend.set(rootPath, backend)
return backend
}
private async createBackend(rootDir: Directory): Promise<GhcModiProcessReal> {
const newBackend = createGhcModiProcessReal(rootDir, await this.getUPI())
const backend = await newBackend
this.disposables.add(
backend.onError((arg) => this.emitter.emit('error', arg)),
backend.onWarning((arg) => this.emitter.emit('warning', arg)),
)
return backend
}
private async queueCmd(
queueName: Commands,
dir: Directory,
runArgsFunc: (
caps: GHCModCaps,
) =>
| {
command: string
text?: string
uri?: string
interactive?: boolean
dashArgs?: string[]
args?: string[]
}
| undefined,
): Promise<string[]> {
if (atom.config.get('haskell-ghc-mod.lowMemorySystem')) {
queueName = 'lowmem'
}
const backend = await this.initBackend(dir)
const promise = this.commandQueues[queueName].add(async () => {
this.emitter.emit('backend-active')
try {
const settings = await getSettings(dir)
if (settings.disable) {
throw new Error('Ghc-mod disabled in settings')
}
const runArgs = runArgsFunc(backend.getCaps())
if (runArgs === undefined) return []
const upi = await this.getUPI()
let builder: string | undefined
if (upi && atom.config.get('haskell-ghc-mod.builderManagement')) {
// TODO: this is used twice, the second time in ghc-mod-process-real-factory.ts, should probably fix that
const b = await upi.getOthersConfigParam<{ name: string }>(
'ide-haskell-cabal',
'builder',
)
if (b) builder = b.name
}
return backend.run({
...runArgs,
builder,
suppressErrors: settings.suppressErrors,
ghcOptions: settings.ghcOptions,
ghcModOptions: settings.ghcModOptions,
})
} catch (err) {
Util.warn(err)
throw err
}
})
promise
.then(() => {
const qe = (qn: Commands) => {
const q = this.commandQueues[qn]
return q.getQueueLength() + q.getPendingLength() === 0
}
if (qe(queueName)) {
this.emitter.emit('queue-idle', { queue: queueName })
if (Object.keys(this.commandQueues).every(qe)) {
this.emitter.emit('backend-idle')
}
}
})
.catch((e: Error) => {
atom.notifications.addError('Error in GHCMod command queue', {
detail: e.toString(),
stack: e.stack,
dismissable: true,
})
})
return promise
}
private async doCheckOrLintBuffer(
cmd: 'check' | 'lint',
buffer: TextBuffer,
fast: boolean,
) {
let dashArgs
if (buffer.isEmpty()) {
return []
}
if (!buffer.getUri()) {
return []
}
// A dirty hack to make lint work with lhs
let uri = buffer.getUri()
const olduri = buffer.getUri()
let text: string | undefined
try {
if (cmd === 'lint' && extname(uri) === '.lhs') {
uri = uri.slice(0, -1)
text = await unlit(olduri, buffer.getText())
} else if (buffer.isModified()) {
text = buffer.getText()
}
} catch (error) {
// TODO: Reject
const m = (error as Error).message.match(/^(.*?):([0-9]+): *(.*) *$/)
if (!m) {
throw error
}
const [uri2, line, mess] = m.slice(1)
return [
{
uri: uri2,
position: new Point(parseInt(line, 10) - 1, 0),
message: mess,
severity: 'lint',
},
]
}
// end of dirty hack
// tslint:disable-next-line: totality-check
if (cmd === 'lint') {
const opts: string[] = atom.config.get('haskell-ghc-mod.hlintOptions')
dashArgs = []
for (const opt of opts) {
dashArgs.push('--hlintOpt', opt)
}
}
const rootDir = await this.getRootDir(buffer)
const textB = text
const dashArgsB = dashArgs
const lines = await this.queueCmd('checklint', rootDir, () => ({
interactive: fast,
command: cmd,
uri,
text: textB,
dashArgs: dashArgsB,
}))
const rx = /^(.*?):([0-9\s]+):([0-9\s]+): *(?:(Warning|Error): *)?([^]*)/
const res = []
for (const line of lines) {
const match = line.match(rx)
if (!match) {
if (line.trim().length) {
Util.warn(`ghc-mod says: ${line}`)
}
continue
}
const [file2, row, col, warning, message] = match.slice(1)
if (file2 === 'Dummy' && row === '0' && col === '0') {
if (warning === 'Error') {
this.emitter.emit('error', {
err: Util.mkError('GHCModStdoutError', message),
caps: (await this.initBackend(rootDir)).getCaps(), // TODO: This is not pretty
})
continue
} else if (warning === 'Warning') {
this.emitter.emit('warning', message)
continue
}
}
const file = uri.endsWith(file2) ? olduri : file2
const severity =
cmd === 'lint' ? 'lint' : warning === 'Warning' ? 'warning' : 'error'
const messPos = new Point(parseInt(row, 10) - 1, parseInt(col, 10) - 1)
const position = Util.tabUnshiftForPoint(buffer, messPos)
const myuri = isAbsolute(file) ? file : rootDir.getFile(file).getPath()
res.push({
uri: myuri,
position,
message,
severity,
})
}
return res
}
} | the_stack |
"use strict";
// uuid: 9c35c260-ebf2-42d9-b60d-94b1fe127739
// ------------------------------------------------------------------------
// Copyright (c) 2018 Alexandre Bento Freire. All rights reserved.
// Licensed under the MIT License+uuid License. See License.txt for details
// ------------------------------------------------------------------------
/** @module end-user | The lines bellow convey information for the end-user */
/**
* ## Description
*
* A **scene** is a story segment and an element container.
* Each scene has an animation pipeline that contains the actions to perform in each frame.
* If a frame has no actions, it's called a still.
* To build the animation pipeline use the methods:
*
* - `addAnimations`
* - `addSerialAnimations`
* - `addStills`
*
* A scene usually is associated with a `div` in the html file.
* Scenes with `class=abeamer-class` are automatically added to story upon story creation.
* But it can also be a virtual scene.
*
* Only one scene can be active at a certain point in time,
* but if it's defined a transition it two scene can be visible during the transition process.
*
* @see transitions
*/
namespace ABeamer {
// #generate-group-section
// ------------------------------------------------------------------------
// Scene
// ------------------------------------------------------------------------
export class _Scene implements _SceneImpl {
/** Name assigned by the user, and can be used to find the scene by name. */
name?: string;
protected _frameCount: int = 0;
protected _storyFrameStart: int = 0;
protected _storySceneIndex: int = -1;
_frameInNr: uint = 0;
_story: _StoryImpl;
_sceneAdpt: _SceneAdapter;
/** Increases inside an `addAnimation`. It used to avoid multiple calls during teleporting. */
_addAnimationCallCount: uint = 0;
/** Internal list of all the scene frames. */
protected _frames: _Frame[] = [];
/** Internal position of where the render pipeline was [consumed](consuming-the-pipeline). */
protected _renderFramePos: int = 0;
/**
* Returns scene transition information.
*
* @see transitions
*/
get transition(): Transition {
return this._transitionInterpolator._transition;
}
/**
* Defines the scene transition selector (name or function)
* and duration.
*
* @see transitions
*/
set transition(transition: Transition) {
this._transitionInterpolator._set(transition,
this._frameCount, this._story._args);
// if it's teleporting, then convert into a wrapper task.
if (this._story.isTeleporting && !this._addAnimationCallCount) {
this.addAnimations([{
tasks: [
{
handler: 'scene-transition',
params: {
handler: transition.handler,
duration: transition.duration,
} as SceneTransitionTaskParams,
},
],
}]);
}
}
protected _transitionInterpolator = new _TransitionInterpolator();
/**
* `_actionRgMaps` are 'maps' between the input animations and the output action
* for every frame.
* _actionRgMaps allow for a new animation to have access to the last modified value
* of a property of an element of the previous animation.
* And in a backward motion allows to retrieve the original value.
*/
protected _actionRgMaps: _ActionRgMaps = [];
/**
* Pointer to previous scene.
* Used by scene transitions.
*/
protected _prevScene: _Scene;
/**
* Pointer to next scene.
* Used by scene transitions.
*/
protected _nextScene: _Scene;
constructor(story: _StoryImpl, sceneSelector: SceneSelector,
prevScene: _SceneImpl | undefined) {
this._story = story;
this._sceneAdpt = _isVirtualScene(sceneSelector)
? new _VirtualSceneAdapter(sceneSelector)
: new _DOMSceneAdapter(sceneSelector);
if (prevScene) {
this._prevScene = prevScene as _Scene;
(prevScene as _Scene)._nextScene = this;
}
}
/** Removes it self from the story. Used internally. */
_remove(): void {
if (this._prevScene) {
this._prevScene._nextScene = this._nextScene;
}
if (this._nextScene) {
this._nextScene._prevScene = this._prevScene;
}
}
// ------------------------------------------------------------------------
// get/set
// ------------------------------------------------------------------------
/**
* Defines the end of the scene pipeline. Usually this value is the
* same as `frameCount` but for off-sync animations `frameInNr` can have
* less value than frameCount.
*
* #end-user @readonly
*/
get frameInNr(): uint {
return this._frameInNr;
}
/**
* Total number of frames contained the scene.
*
* #end-user @readonly
*/
get frameCount(): uint {
return this._frameCount;
}
/**
* Sum of all the frames from the previous scenes.
*
* #end-user @readonly
*/
get storyFrameStart(): uint {
this._story._calcFrameCount();
return this._storyFrameStart;
}
/**
* Zero-based Index of this scene within the list of scenes.
*
* #end-user @readonly
*/
get storySceneIndex(): uint {
return this._storySceneIndex;
}
/**
* Scene id from the DOM element.
*
* #end-user @readonly
*/
get id(): string {
return this._sceneAdpt.getProp('id', this._story._args) as string;
}
// ------------------------------------------------------------------------
// Frame methods
// ------------------------------------------------------------------------
protected _containsFrame(storyFramePos: int): boolean {
this._story._calcFrameCount();
return this._internalContainsFrame(storyFramePos);
}
_internalContainsFrame(storyFramePos: int): boolean {
return (storyFramePos >= this._storyFrameStart)
&& storyFramePos < (this._storyFrameStart + this._frameCount);
}
_setStoryParams(storyFramePos: int,
storySceneIndex: int): int {
this._storyFrameStart = storyFramePos;
this._storySceneIndex = storySceneIndex;
return this._frameCount;
}
protected _gotoSceneFrame(framePos: int): void {
if (framePos < 0 || framePos >= this._frameCount) {
throwErr(`Position ${framePos} is out of scope`);
}
this._internalGotoFrame(framePos);
}
_internalGotoFrame(framePos: int): void {
if (framePos === this._renderFramePos) { return; }
const isVerbose = this._story.isVerbose;
// @WARN: Don't use story.renderDir since it can bypassing backwards
// in order to rewind and the story.renderDir be moving forward
const bypassDir: DirectionInt = framePos > this._renderFramePos ? 1 : -1;
while (framePos !== this._renderFramePos) {
this._internalRenderFrame(this._renderFramePos, bypassDir,
isVerbose, true);
}
}
// ------------------------------------------------------------------------
// Visibility
// ------------------------------------------------------------------------
_show(): void {
this._sceneAdpt.setProp('visible', 'true', this._story._args);
}
_hide(): void {
this._sceneAdpt.setProp('visible', 'false', this._story._args);
}
// ------------------------------------------------------------------------
// Transitions
// ------------------------------------------------------------------------
/**
* Prepares the transitions when the rendering process starts
*/
_setupTransition(): void {
if (this._transitionInterpolator._active) {
this._transitionInterpolator._setup(this._sceneAdpt,
this._nextScene ? this._nextScene._sceneAdpt : undefined,
this._frameCount, this._story._args);
}
}
// ------------------------------------------------------------------------
// addStills
// ------------------------------------------------------------------------
/**
* Adds a series of motionless frames defined by duration.
* This method changes the end of the pipeline (frameInNr).
*/
addStills(duration: TimeHandler): Scene {
// if it's teleporting, then convert into a wrapper task.
if (this._story.isTeleporting && !this._addAnimationCallCount) {
this.addAnimations([{
tasks: [
{
handler: 'add-stills',
params: {
duration,
} as AddStillsTaskParams,
},
],
}]);
}
const frameCount = parseTimeHandler(duration, this._story._args, 0, 0);
if (frameCount <= 0) { return this; }
const newFrameInNr = this._frameInNr + frameCount;
if (newFrameInNr > this._frames.length) {
// #debug-start
if (this._story._isVerbose) {
this._story.logFrmt('add-stills-frame-count', [
['id', this.id],
['old-frame-count', this._frames.length],
['new-frame-count', newFrameInNr]]);
}
// #debug-end
this._frames.length = newFrameInNr;
this._frameCount = newFrameInNr;
}
// #debug-start
if (this._story._isVerbose) {
this._story.logFrmt('add-stills-frame-in', [
['id', this.id],
['old-frame-in', this._frameInNr],
['new-frame-in', newFrameInNr]]);
}
// #debug-end
this._frameInNr = newFrameInNr;
return this;
}
// ------------------------------------------------------------------------
// initInterpolators
// ------------------------------------------------------------------------
/**
* Creates the interpolator animations for `Scene.addAnimations`.
*/
protected _initInterpolators(animes: Animations): _ElWorkAnimation[] {
const story = this._story;
const args = story._args;
const elAnimations: _ElWorkAnimation[] = [];
animes.forEach((anime) => {
if (anime.enabled === false) {
elAnimations.push(undefined);
return;
}
let elAnimation: _ElWorkAnimation = new _ElWorkAnimation();
elAnimation.buildElements(this._story, this._sceneAdpt, anime);
if (elAnimation.elAdapters.length) {
if (elAnimation.assignValues(anime, story, undefined,
elAnimation.elAdapters[0].getId(args), this._frameInNr)) {
anime.props.forEach(prop => {
elAnimation.propInterpolators
.push(prop.enabled !== false ? new _PropInterpolator(prop) : undefined);
});
} else {
elAnimation = undefined;
}
} else {
if (this._story._logLevel >= LL_WARN) {
this._story.logWarn(`Selector ${anime.selector} is empty`);
}
}
elAnimations.push(elAnimation);
});
return elAnimations;
}
// ------------------------------------------------------------------------
// addAnimations
// ------------------------------------------------------------------------
/**
* Adds a list of parallel animations to the render pipeline.
* The animations can start off-sync from each other via Position parameter.
*
* @see animations
*/
addAnimations(animes: Animations): Scene {
if (!animes.length) { return this; }
const story = this._story;
const args = story._args;
let maxEndFrame = this._frameInNr;
const isVerbose = this._story._isVerbose;
const prevStage = story._args.stage;
let advanceInTheEnd = true;
story._exceptIfRendering();
if (story._teleporter.active) {
_prepareAnimationsForTeleporting(animes, args);
story._teleporter._addAnimations(animes, this._storySceneIndex);
}
this._addAnimationCallCount++;
args.stage = AS_ADD_ANIMATION;
try {
if (story.curScene !== this) {
// _internalGotoScene is enough, since to add animations doesn't requires
// extra story frame values to be computed
story._internalGotoScene(this);
}
// 1st pass - process tasks
const wkAnimes: Animations = [];
const wkAnimesTasks: _WorkTask[][] = [];
animes.forEach((anime) => {
const tasks = anime.tasks;
let wkTasks: _WorkTask[];
if (tasks) {
wkTasks = [];
if (_processTasks(tasks, wkTasks, anime, args) && !anime.props) { return; }
}
wkAnimes.push(anime);
wkAnimesTasks.push(wkTasks);
});
animes = wkAnimes;
// 2st pass - preprocess interpolators
const animeInterpolators = this._initInterpolators(animes);
let animeAdvanceValue = 0;
// 3st pass - compute values
animes.forEach((anime, animeIndex) => {
const ai = animeInterpolators[animeIndex];
if (!ai) { return; } // bypass missing selectors
const propInterpolators = ai.propInterpolators;
const elementAdapters = ai.elAdapters;
_vars.elCount = elementAdapters.length;
if (animeAdvanceValue) {
ai.positionFrame += animeAdvanceValue;
}
if (animeIndex === animes.length - 1) {
advanceInTheEnd = ai.advance !== false;
}
elementAdapters.forEach((elementAdpt, elIndex) => {
_vars.elIndex = elIndex;
const wkTasks = wkAnimesTasks[animeIndex];
if (wkTasks) { _runTasks(wkTasks, anime, animeIndex, args); }
ai.nextPropStartFrame = undefined;
anime.props.forEach((inProp, propIndex) => {
const pi = propInterpolators[propIndex];
// properties can override the anime values
if (!pi || !pi.propAssignValues(inProp, story, ai, elIndex)) { return; }
let posFrame = pi.startFrame;
const endFrame = pi.endFrame;
const totalDuration = pi.totalDuration;
if (endFrame > this._frameCount) {
this._frames.length = endFrame;
this._frameCount = endFrame;
}
maxEndFrame = Math.max(maxEndFrame, endFrame);
if (ai.advance) {
animeAdvanceValue = Math.max(animeAdvanceValue, endFrame - this._frameInNr);
}
const elActRg = _findActionRg(this._actionRgMaps, elementAdpt, pi.realPropName,
posFrame, endFrame - 1, args);
pi.attachSelector(elementAdpt, elActRg, isVerbose, args);
let frameI = pi.dirPair[0] === 1 ? 0 : (pi.framesPerCycle - 1);
let v: ActionValue;
let action: _Action;
// #debug-start
if (isVerbose) {
this._story.logFrmt('action-range', [
['id', elementAdpt.getId(args)],
['prop', pi.propName],
['frame', posFrame],
['total', totalDuration]],
);
}
// #debug-end
for (let i = 0; i < totalDuration; i++) {
const t = pi.framesPerCycle > 1 ? frameI / (pi.framesPerCycle - 1) : 1;
v = pi.interpolate(t, story, isVerbose);
action = pi.toAction(v, i === 0, i === totalDuration - 1);
frameI = _computeIterationCount(i, frameI, pi.dirPair, pi.framesPerCycle);
this._setActionOnFrames(posFrame, elementAdpt, pi, action, v);
posFrame++;
}
// stores the last output value in the ActRg
const outputValue = _applyAction(action, elementAdpt, false,
args, true);
elActRg.actionRg.endValue = outputValue;
});
});
});
} catch (error) {
throw error;
} finally {
if (advanceInTheEnd) {
this._frameInNr = maxEndFrame;
} else {
// #debug-start
if (isVerbose) {
this._story.logFrmt('no-advance-in-end', [],
);
}
// #debug-end
}
this._addAnimationCallCount--;
if (!this._addAnimationCallCount) { args.stage = prevStage; }
story._setFrameCountChanged();
}
return this;
}
protected _setActionOnFrames(pos: uint,
elementAdpt: _ElementAdapter,
pi: _PropInterpolator,
action: _Action,
v: ActionValue): void {
function getIAction(): _ElActions {
return {
elementAdpt,
actions: [action],
} as _ElActions;
}
let frame: _Frame;
elementAdpt._clearComputerData();
if (this._frames[pos] === undefined) {
this._frames[pos] = {
elActions: [getIAction()],
uniqueElementAdpt: new Set([elementAdpt]),
};
} else {
frame = this._frames[pos];
frame.uniqueElementAdpt.add(elementAdpt);
const item = frame.elActions.find(it => it.elementAdpt === elementAdpt);
if (!item) {
frame.elActions.push(getIAction());
} else {
const actions = item.actions;
const oldAction = actions.find(actionI =>
actionI.realPropName === pi.propName);
if (oldAction) {
oldAction.value = v;
} else {
actions.push(action);
}
}
}
}
// ------------------------------------------------------------------------
// addSerialAnimations
// ------------------------------------------------------------------------
/**
* Adds a list of serial animations to the render pipeline.
* This is the same as: `serialAnimes.forEach(anime => addAnimations(anime))`
* Use this if you want to load all animations from an external file.
*/
addSerialAnimations(serialAnimes: Animations[]): Scene {
serialAnimes.forEach(anime => this.addAnimations(anime));
return this;
}
// ------------------------------------------------------------------------
// Render
// ------------------------------------------------------------------------
_internalRenderFrame(framePos: int, dir: DirectionInt,
isVerbose: boolean, bypassMode: boolean): void {
const args = this._story._args;
// handle transitions
if (!bypassMode) {
if (this._transitionInterpolator._active) {
this._transitionInterpolator._render(framePos, this._frameCount,
true, this._story._args);
}
const prevScene = this._prevScene;
if (prevScene && prevScene._transitionInterpolator._active) {
prevScene._transitionInterpolator._render(framePos, this._frameCount,
false, this._story._args);
}
}
const frame = this._frames[framePos];
// stills must come after transitions
if (!frame) {
// #debug-start
if (isVerbose && !bypassMode) {
this._story.logFrmt('render-still', [['frame', framePos]]);
}
// #debug-end
this._renderFramePos += dir;
return;
}
// execute each action of a frame
const itemCount = frame.elActions.length;
for (let i = 0; i < itemCount; i++) {
const item = frame.elActions[i];
const elementAdpt = item.elementAdpt;
const actionCount = item.actions.length;
for (let j = 0; j < actionCount; j++) {
const action = item.actions[j];
// handles bypassing
if (bypassMode) {
const canByPass = dir > 0 ? action.toBypassForward :
action.toBypassBackward;
if (canByPass) {
// #debug-start
if (isVerbose) {
this._story.logFrmt('bypass',
[['id', elementAdpt.getId(args)],
['prop', action.realPropName],
['frame', framePos]]);
}
// #debug-end
continue;
}
}
_applyAction(action, elementAdpt, isVerbose, args);
}
}
frame.uniqueElementAdpt.forEach(elAdapter => {
if (elAdapter.frameRendered) { elAdapter.frameRendered(args); }
});
this._renderFramePos += dir;
}
// ------------------------------------------------------------------------
// Wrappers
// ------------------------------------------------------------------------
/**
* Used only task plugin creators.
*/
getElementAdapters(selector: ElSelectorHandler): ElementAdapter[] {
return _parseInElSelector(this._story, [], this._sceneAdpt, selector);
}
/**
* Creates a pEls from the selectors.
*/
getPEls(selector: ElSelector): pEls {
return new _pEls(this, selector);
}
/**
* Adds `visible = true` to the pipeline.
*/
pElsShow(selector: ElSelector): pEls {
return this.getPEls(selector).show();
}
/**
* Adds `visible = false` to the pipeline.
*/
pElsHide(selector: ElSelector): pEls {
return this.getPEls(selector).hide();
}
/**
* Wrapper for `addAnimation` with `visible = false`,
* followed by opacity moving to 1.
*/
pElsFadeIn(selector: ElSelector, duration?: TimeHandler): pEls {
return this.getPEls(selector).fadeIn(duration);
}
/**
* Wrapper for `addAnimation` with opacity moving to 0,
* followed by `visible = false`
*/
pElsFadeOut(selector: ElSelector, duration?: TimeHandler): pEls {
return this.getPEls(selector).fadeOut(duration);
}
}
} | the_stack |
module TDev {
export class ModalDialog {
private overlay = div("modalOverlay");
private dialog = div("modalDialog");
private floating: HTMLElement;
private outerDialog: HTMLElement;
private savedKeyState = null;
private id = Random.uniqueId();
private logView: TDev.RT.AppLogView;
constructor(header = "") {
this.dialog.setAttribute("role", "dialog");
this.floating = div("modalDialogInner", this.dialog);
this.outerDialog = div("modalDialogOuter", div("modalDialogMid", this.floating));
if (header)
this.add(div("wall-dialog-header", header));
this.fullWhite();
}
public setAlert() {
this.dialog.setAttribute("role", "alertdialog");
this.applyAria();
}
private applyAria() {
var foundtitle = false;
var founddesc = false;
Util.children(this.dialog).forEach(el => {
if (!foundtitle && el.classList.contains('wall-dialog-header')) {
foundtitle = true;
if (!el.id) el.id = Util.guidGen();
this.dialog.setAttribute("aria-labelledby", el.id);
}
if (!founddesc && el.classList.contains('wall-dialog-body')) {
founddesc = true;
if (!el.id) el.id = Util.guidGen();
this.dialog.setAttribute("aria-describedby", el.id);
}
})
}
public opacity = 0.85;
public onDismiss: (m: ModalDialog) => void = null;
public visible = false;
public canDismiss = true;
static current: ModalDialog;
static dismissCurrent() {
if (ModalDialog.currentIsVisible()) {
ModalDialog.current.canDismiss = true;
ModalDialog.current.dismiss()
}
}
static currentIsVisible() {
return ModalDialog.current && ModalDialog.current.visible;
}
public show() {
this.showBare();
}
public addLog() {
if (!this.logView) {
this.logView = new TDev.RT.AppLogView();
this.logView.charts(false);
this.logView.search(false);
this.logView.reversed(true);
this.logView.attachLogEvents();
this.logView.element.style.fontSize = "0.7em";
this.add(this.logView.element);
this.setScroll();
this.stretchWide();
}
}
public addFirst(v: HTMLElement) {
if (this.dialog.firstChild)
this.dialog.insertBefore(v, this.dialog.firstChild)
else this.add(v)
}
public empty() {
this.dialog.setChildren([])
}
public addBody(v: any) {
this.add(div("wall-dialog-body", v))
}
public add(v: any) {
if (v && Array.isArray(v))
this.dialog.appendChildren(v);
else
this.dialog.appendChildren([v]);
this.applyAria();
}
public addClass(c: string) {
this.dialog.className += " " + c;
}
public addHTML(html: string): HTMLElement {
var b = div("wall-dialog-body");
Browser.setInnerHTML(b, html);
this.add(b);
return b;
}
public addOuter(v: any) {
this.outerDialog.appendChildren([v]);
}
public stretchDown(e: HTMLElement, keep = 0) {
this.outerDialog.className += " modalDialogOuterLong";
this.listheight = SizeMgr.windowHeight - e.offsetTop - (3 + keep) * SizeMgr.topFontSize;
e.style.height = this.listheight + "px";
}
public adjustlistsize() {
if (!this.list || !this.buttondiv)
return;
var howmuchover = this.dialog.scrollHeight - this.dialog.clientHeight;
if (howmuchover > 0) {
this.listheight = Math.max(10 * SizeMgr.topFontSize, this.listheight - howmuchover);
this.list.style.height = this.listheight + "px";
}
}
public stretchWide() {
this.floating.style.width = 'calc(100% - 1em)';
this.dialog.style.width = '100%';
}
public showBare(what: HTMLElement = null) {
Ticker.dbg("ModalDialog.showBare0");
if (ModalDialog.current && ModalDialog.current != this && !ModalDialog.current.canDismiss)
return;
this.overlay.style.opacity = this.opacity.toString();
this.overlay.withClick(() => { this.dismiss(); });
this.outerDialog.withClick(() => { this.dismiss() });
this.floating.withClick(() => { });
var root = elt("root");
Util.children(root).forEach(ch => ch.setAttribute("aria-hidden", "true"));
root.appendChildren([this.overlay, what || this.outerDialog]);
var btnsDiv: HTMLElement;
Util.children(this.dialog).forEach((e) => {
if (e.className == "wall-dialog-buttons")
btnsDiv = e;
if (e.withClick && !(<any>e).clickHandler && !(<any>e).onselectstart)
e.tabIndex = -1;
});
if (!what) {
Util.showPopup(this.floating);
} else {
this.outerDialog = what;
Util.showPopup(what);
}
if (ModalDialog.current && ModalDialog.current != this) {
ModalDialog.dismissCurrent();
}
if (this.canDismiss)
Screen.pushModalHash("dialog-" + this.id, () => this.dismiss());
this.savedKeyState = KeyboardMgr.instance.saveState();
KeyboardMgr.instance.register("Esc", () => { this.dismiss(); return true });
this.visible = true;
ModalDialog.current = this;
if (btnsDiv) {
var btns = Util.children(btnsDiv).filter((e) => (<any>e).clickHandler);
if (btns.length == 1)
KeyboardMgr.instance.btnShortcut(btns[0], "Enter");
}
elt("root").setFlag("modal-visible", true);
this.dialog.removeAttribute("aria-labelledby");
var h1 = this.dialog.getElementsByTagName("h1")[0];
if (h1) {
h1.id = Util.guidGen();
this.dialog.setAttribute("aria-labelledby", h1.id);
}
// add one more fake element to trap the keyboard focus and reset it to the first focusable element
var trap = div('focustrap');
trap.tabIndex = 0;
trap.setAttribute("aria-hidden", "true");
trap.onfocus = () => this.focusFirstAsync().done();
this.dialog.appendChild(trap)
this.focusFirstAsync().done();
Ticker.dbg("ModalDialog.showBare1");
}
public focusFirstAsync() {
return new Promise((onSuccess, onError, onProgress) => {
// find first input field or buttondiv
setTimeout(() => {
try {
var focus = this.dialog.getElementsByTagName("input")[0] || this.dialog.getElementsByTagName("button")[0];
if (focus) focus.focus();
} catch (e) {
}
onSuccess(undefined);
}, 10);
});
}
public dismiss() {
if (!this.canDismiss) {
Ticker.dbg("ModalDialog.dismiss - cannot");
return;
}
Ticker.dbg("ModalDialog.dismiss0");
Screen.popModalHash("dialog-" + this.id);
if (this.logView) this.logView.removeLogEvents();
this.visible = false;
elt("root").setFlag("modal-visible", false);
KeyboardMgr.instance.loadState(this.savedKeyState);
Util.hidePopup(this.outerDialog, () => {
Ticker.dbg("ModalDialog.dismiss1");
this.outerDialog.removeSelf();
Util.children(elt("root")).forEach(ch => ch.removeAttribute("aria-hidden"));
});
Util.fadeOut(this.overlay);
var f = this.onDismiss
this.onDismiss = null
if (f) f(this);
}
static ask(msg: string, confirmation: string, act: () => void, critical = false, header: string = null) {
var m = new ModalDialog();
if (header == null) header = confirmation + "?"
m.add([
div("wall-dialog-header", header),
div("wall-dialog-body", msg),
div("wall-dialog-buttons",
HTML.mkButton(lf("cancel"), () => m.dismiss()),
HTML.mkButton(confirmation, () => { act(); m.dismiss(); }))
]);
m.setAlert();
if (critical)
m.critical();
m.show();
return m;
}
static askAsync(msg: string, confirmation: string, critical = false, header: string = null)
// the promise never finishes when not confirmed
{
var ret = new PromiseInv()
var m = ModalDialog.ask(msg, confirmation, () => { ret.success(null) }, critical, header)
return ret
}
static askMany(header: string, msg: string, options: any) {
var m = new ModalDialog();
m.add([
div("wall-dialog-header", header),
div("wall-dialog-body", msg),
div("wall-dialog-buttons",
Object.keys(options).map((k: string) =>
HTML.mkButton(k, () => { m.dismiss(); options[k](); })))
]);
m.setAlert();
m.show();
return m;
}
static askManyWithAdditionalElts(header: string, helpLink: any, msg: any, subHeader: string, subMsg: any, options: any, ...elts: any[]) {
var m = new ModalDialog();
m.add([
div("wall-dialog-header", header, helpLink),
div("wall-dialog-body", msg),
div("wall-dialog-header", subHeader),
div("wall-dialog-body", subMsg),
div("wall-dialog-buttons",
Object.keys(options).map((k: string) =>
HTML.mkButton(k, () => { m.dismiss(); options[k](); }))),
elts
]);
m.show();
return m;
}
static buttons(header: string, msg: string, subheader: string, submsg: string, ...buttons: any[]) {
var m = new ModalDialog();
m.add([
div("wall-dialog-header", header),
div("wall-dialog-body", msg),
subheader && div("wall-dialog-header", subheader),
submsg && div("wall-dialog-body", submsg),
div("wall-dialog-buttons", buttons)
]);
m.setAlert();
m.show();
return m;
}
static info(title: string, msg: string, btn: string = "ok") {
var m = new ModalDialog();
m.add([
div("wall-dialog-header", title),
div("wall-dialog-body", msg)])
if (btn)
m.addOk(btn)
m.setAlert();
m.show();
return m;
}
static infoAsync(title: string, msg: string, btn: string = "ok") {
var r = new PromiseInv()
var m = ModalDialog.info(title, msg, btn)
m.onDismiss = () => r.success(null)
return r
}
public addButtons(btns: any) {
this.add(div("wall-dialog-buttons", Object.keys(btns).map(b => HTML.mkButton(b, btns[b]))))
}
public addOk(btn = lf("ok"), f: () => void = null, cls = "", btns: any = []) {
var b = HTML.mkButton(btn, () => {
if (f) f();
else this.dismiss();
});
if (cls) b.className += " " + cls;
this.add(div("wall-dialog-buttons", [b, btns]))
return b;
}
static showAsync(msg: any, options: { title?: string; cancel?: boolean } = {}): Promise {
return new Promise(function(onSuccess, onError, onProgress) {
var m = new ModalDialog();
var ok = false;
if (options.title) m.add(div('wall-dialog-header', options.title));
if (msg) m.add(div('wall-dialog-body', msg))
m.addOk(lf("ok"), () => {
ok = true;
m.dismiss();
}, "", options.cancel ? HTML.mkButton(lf("cancel"), () => m.dismiss()) : undefined);
m.onDismiss = () => onSuccess(ok);
m.setAlert();
m.show();
})
}
static showText(s: string, title: string = null, msg: string = null, done: () => void = null): ModalDialog {
var m = new ModalDialog();
if (title != null)
m.add(div('wall-dialog-header', title));
if (msg != null)
m.add(div('wall-dialog-body', msg));
var elt = HTML.mkTextArea("scriptText");
elt.value = s;
m.dialog.appendChild(elt);
(<any>m).textArea = elt;
m.onDismiss = done;
m.setAlert();
m.show();
m.stretchDown(elt);
m.stretchWide();
try {
elt.setSelectionRange(0, s.length);
} catch (e) { }
return m;
}
static showTable(headers: string[], values: string[][], ondblclick: (md: ModalDialog, idx: number) => any): ModalDialog {
var m = new ModalDialog();
var table = <HTMLTableElement>document.createElement("table");
table.className = "traces";
var hdrRow = <HTMLTableRowElement>document.createElement("tr");
for (var i = 0; i < headers.length; i++) {
var hdr = <HTMLTableHeaderCellElement>document.createElement("th");
hdr.textContent = headers[i];
hdrRow.appendChild(hdr);
}
table.appendChild(hdrRow);
for (var i = 0; i < values.length; i++) {
var row = <HTMLTableRowElement>document.createElement("tr");
row.classList.add("hover");
var rowValues = values[i];
for (var j = 0; j < rowValues.length; j++) {
var v = <HTMLTableCellElement>document.createElement("td");
v.textContent = rowValues[j];
v.ondblclick = function(ev) {
var target: any = ev.target || ev.srcElement;
return ondblclick(m, target.parentElement.sectionRowIndex - 1);
}
row.appendChild(v);
}
table.appendChild(row);
}
m.dialog.appendChild(table);
m.stretchDown(table);
m.setAlert();
m.show();
return m;
}
static editText(lbl: string, text: string, updateAsync: (s: string) => Promise) {
var m = new ModalDialog();
var btns = div("wall-dialog-buttons",
HTML.mkButton(lf("update"), () => {
btns.removeSelf()
updateAsync(inp.value)
.done(() => m.dismiss())
}),
HTML.mkButton(lf("cancel"), () => m.dismiss()))
var inp = HTML.mkTextInput("text", "")
inp.value = text
m.add(div("wall-dialog-header", lbl))
m.add(div(null, inp))
m.add(btns)
m.setAlert();
m.show()
return m
}
public noChrome() {
this.outerDialog.className += " modalNoChrome";
}
public fullScreen(iMeanIt = false) {
this.outerDialog.className += " modalNoChrome " + (iMeanIt ? "reallyFullScreen" : "modalFullScreen");
this.outerDialog.setChildren(this.dialog);
}
public fullBlack() {
this.outerDialog.classList.add("modalFullBlack");
this.outerDialog.classList.remove("modalFullWhite");
this.outerDialog.classList.remove("modalFullYellow");
}
public fullWhite() {
this.outerDialog.classList.remove("modalFullBlack");
this.outerDialog.classList.add("modalFullWhite");
this.outerDialog.classList.remove("modalFullYellow");
}
public fullYellow() {
this.outerDialog.classList.remove("modalFullBlack");
this.outerDialog.classList.remove("modalFullWhite");
this.outerDialog.classList.add("modalFullYellow");
}
public critical() {
this.outerDialog.classList.remove("modalFullBlack");
this.outerDialog.classList.remove("modalFullWhite");
this.outerDialog.classList.remove("modalFullYellow");
this.floating.classList.add('bg-critical');
this.setAlert();
}
public setScroll() {
this.dialog.style.maxHeight = (SizeMgr.windowHeight * 0.85) / SizeMgr.topFontSize + "em";
Util.setupDragToScroll(this.dialog);
}
private list: HTMLElement;
private listheight: number;
private buttondiv: HTMLElement;
private searchbox: HTMLElement;
public showorhidelist(show: boolean) {
var d = show ? "" : "none";
if (this.searchbox)
this.searchbox.style.display = d;
if (this.list)
this.list.style.display = d;
}
// queryAsync returns a promise that returns HTMLElement[]
public choose(boxes: HTMLElement[], options: ModalChooseOptions = {}) {
var progressBar = HTML.mkProgressBar();
var list = this.list = HTML.mkModalList([]);
var search = HTML.mkTextInput("text", lf("choose..."));
search.id = "chooseSearch"
search.setAttribute("role", "search");
search.placeholder = options.searchHint || (options.queryAsync ? lf("Type to search online...") : lf("Type to search..."));
var autoKeyboard = KeyboardAutoUpdate.mkInput(search, Util.catchErrors("chooseSearch", () => refresh(true)));
autoKeyboard.attach()
var limitedMode = !!options.mkSeeMore;
if (limitedMode && boxes.every((b) => !(<any>b).initiallyHidden))
limitedMode = false;
var needKbd = false;
function selectedItem(): HTMLElement { return Util.children(list).filter(el => el == document.activeElement)[0]; }
function refresh(onlineOK: boolean, focus?: boolean) {
var allTerms = search.value;
var terms = allTerms.split(/\s+/).map((s: string) => s.toLowerCase()).filter((s) => s != "");
var res = []
var ids = {}
if (terms.length > 0) limitedMode = false;
var skipCnt = 0;
boxes.forEach((b: HTMLElement) => {
var miss = false;
if (limitedMode && (<any>b).initiallyHidden) {
skipCnt++;
return;
}
var cont = b.textContent.toLowerCase();
terms.forEach((term) => {
if (!miss && cont.indexOf(term) < 0) miss = true;
})
if (!miss) {
ids[cont] = 1;
res.push(b);
Util.highlightWords(b, terms, true);
}
});
if (limitedMode) {
var b = options.mkSeeMore(needKbd ? lf("you can also search") : lf("more option{0:s}", skipCnt))
HTML.setTickCallback(b, Ticks.sideMoreOptions, () => {
limitedMode = false;
refresh(options.initialEmptyQuery);
});
res.push(b);
}
list.setChildren(res);
if (onlineOK && !!options.queryAsync && Cloud.isOnline()) {
progressBar.start();
options.queryAsync(allTerms).then((bxs: HTMLElement[]) => {
progressBar.stop();
if (!autoKeyboard.resultsCurrent(allTerms)) {
return;
}
if (!!bxs) {
bxs.forEach((bx) => {
var bkey = bx.textContent.toLowerCase();
if (!ids[bkey]) {
ids[bkey] = 1;
list.appendChild(bx);
Util.highlightWords(bx, terms, true);
}
});
}
}).done();
}
if (focus && !!list.firstElementChild) {
var fe = <HTMLElement>list.firstElementChild;
Util.setTimeout(10, () => fe.focus());
}
if (options.afterRefresh)
options.afterRefresh();
}
if (!options.noBackground)
this.outerDialog.className += " modalChooser";
if (options.header) {
this.add(div("modalSearchHeader", options.header));
}
if (options.includeSearch !== undefined)
needKbd = !!options.includeSearch;
else
needKbd = (!!options.queryAsync || boxes.length > 5)
if (needKbd)
this.add(this.searchbox = div("modalSearch", [<HTMLElement>progressBar, search]));
this.add(list);
this.buttondiv = div('wall-dialog-buttons modalChooseBtns');
if (options.custombuttons !== undefined)
this.buttondiv.appendChildren(options.custombuttons);
else
this.buttondiv.appendChild(HTML.mkButtonTick(lf("cancel"), Ticks.chooseCancel, () => this.dismiss()));
this.add(this.buttondiv);
this.show();
function keyDown() {
var selected = selectedItem();
if (!selected && list.firstElementChild) {
(<HTMLElement>list.firstElementChild).focus();
}
else if (selected && selected.nextElementSibling) {
(<HTMLElement>selected.nextElementSibling).focus();
(<HTMLElement>selected.nextElementSibling).scrollIntoView(false);
}
return true;
}
function keyUp() {
var selected = selectedItem();
if (!selected && list.lastElementChild) {
(<HTMLElement>list.lastElementChild).focus();
}
else if (selected && selected.previousElementSibling) {
(<HTMLElement>selected.previousElementSibling).focus();
(<HTMLElement>selected.previousElementSibling).scrollIntoView(false);
}
return true;
}
// this has to happen after show() - show() saves the keyboard state so later this handler is removed
// always capture keyboard in modal dialog
KeyboardMgr.instance.register("Down", keyDown);
KeyboardMgr.instance.register("Up", keyUp);
KeyboardMgr.instance.register("Enter", e => {
var selected = selectedItem();
if (selected && (<any>selected).clickHandler) {
(<any>selected).clickHandler.fireClick(e);
} else if (list.firstElementChild) {
(<HTMLElement>list.firstElementChild).focus();
}
return true;
});
KeyboardMgr.instance.register("***", (e: KeyboardEvent) => {
if (e.fromTextBox) return false;
var s = Util.keyEventString(e);
if (s) {
search.value += s;
Util.setKeyboardFocus(search);
return true;
}
return false;
});
if (!options.dontStretchDown)
this.stretchDown(list, 2.8);
if (options.adjustListSize)
this.adjustlistsize();
var needFocus = true;
if (options.initialQuery !== undefined) {
options.initialEmptyQuery = true
search.value = options.initialQuery
if (needKbd) {
Util.setKeyboardFocus(search, true)
needFocus = false;
}
}
refresh(options.initialEmptyQuery, needFocus);
}
}
export interface ModalChooseOptions {
queryAsync?: (terms: string) => Promise;
searchHint?: string;
initialQuery?: string;
initialEmptyQuery?: boolean;
header?: any;
mkSeeMore?: (lbl: string) => HTMLElement;
afterRefresh?: () => void;
includeSearch?: boolean; // overrides default of 6+ items
dontStretchDown?: boolean;
adjustListSize?: boolean;
noBackground?: boolean;
custombuttons?: HTMLElement[];
}
export module ProgressOverlay {
var overlay: HTMLElement;
var msgDiv: HTMLElement;
var addInfo: HTMLElement;
var progress: HTMLElement;
var visible = 0;
var unblockedKeyboard = false;
var logView: TDev.RT.AppLogView;
export var lock: PromiseInv = PromiseInv.as();
export function lockAndShow(msg = lf("working hard"), f?: () => void, splashUrl?: string) {
lock.done(() => show(msg, f, splashUrl))
}
export function lockAndShowAsync(msg: string) {
var r = new PromiseInv()
lockAndShow(msg, () => r.success(null));
return r
}
export function bumpShow() {
Util.assert(isActive())
visible++;
}
export function show(msg = lf("working hard"), f?: () => void, splashUrl?: string) {
visible++;
Ticker.dbg("ProgressOverlay.show " + visible + " " + msg);
if (visible > 1) {
setMessage(msg);
return;
}
if (!overlay) {
overlay =
div("modalOverlay", div("modalMessage",
msgDiv = div("modalMessageHeader"),
addInfo = div("modalMessagePleaseWait"),
progress = div("modalMessagePleaseWait")
));
overlay.withClick(() => { });
overlay.style.backgroundColor = "white";
overlay.style.opacity = "0.95";
overlay.style.backgroundSize = "cover";
overlay.style.backgroundRepeat = "no-repeat";
}
lock = new PromiseInv();
setMessage(msg);
setSplashArtId(splashUrl);
addInfo.setChildren([lf("please wait...")]);
closeLog();
//Util.cancelAnim(overlay);
overlay.removeSelf();
elt("root").appendChildren([overlay]);
if (f)
// webkit seems to optimize the thing away if we don't give it enough time
Util.setTimeout(Browser.isWebkit ? 100 : 1, f);
}
export function setAddInfo(info: any[]) {
addInfo.setChildren(info);
}
export function hide() {
if (visible == 0) {
// certain code path call setMessage but don't actually display the overlay
// thus this check fails in the compiled apps
// Util.check(false, "too many hides()");
return;
}
visible--;
Ticker.dbg("ProgressOverlay.hide " + visible);
if (visible == 0) {
lock.success(null);
progress.setChildren([]);
overlay.removeSelf();
unblockedKeyboard = false
closeLog();
}
}
function closeLog() {
if (logView) {
logView.element.removeSelf();
logView.removeLogEvents();
logView = undefined;
}
}
export function setProgress(msg: string) {
if (progress)
progress.setChildren(msg);
}
export function setMessage(msg: string) {
if (msgDiv)
msgDiv.setChildren(msg);
}
export function setSplashArtId(url: string) {
if (overlay) overlay.style.backgroundImage = HTML.cssImage(url, 0.3);
}
export function unblockKeyboard() { unblockedKeyboard = true }
export function isKeyboardBlocked() { return isActive() && !unblockedKeyboard; }
export function showLog() {
if (!logView) {
logView = new TDev.RT.AppLogView();
logView.charts(false);
logView.search(false);
logView.reversed(true);
logView.attachLogEvents();
logView.element.style.fontSize = "0.7em";
progress.parentElement.appendChild(logView.element);
}
}
export function isActive() { return visible > 0; }
}
} | the_stack |
import { TypedRule, excludeDeclarationFiles } from '@fimbul/ymir';
import * as ts from 'typescript';
import {
isBinaryExpression,
isPrefixUnaryExpression,
unionTypeParts,
isFalsyType,
isTypeOfExpression,
isTextualLiteral,
isIdentifier,
isEmptyObjectType,
isIntersectionType,
isStrictCompilerOptionEnabled,
isPropertyAccessExpression,
isElementAccessExpression,
isParenthesizedExpression,
isLiteralType,
unwrapParentheses,
getLateBoundPropertyNames,
getPropertyOfType,
intersectionTypeParts,
formatPseudoBigInt,
} from 'tsutils';
import { tryGetBaseConstraintType } from '../utils';
interface TypePredicate {
nullable: boolean;
check(type: ts.Type): boolean | undefined;
}
interface Equals {
negated: boolean;
strict: boolean;
}
const primitiveFlags = ts.TypeFlags.BigIntLike | ts.TypeFlags.BooleanLike | ts.TypeFlags.NumberLike | ts.TypeFlags.StringLike |
ts.TypeFlags.ESSymbolLike | ts.TypeFlags.Undefined | ts.TypeFlags.Void;
const predicates: Record<string, TypePredicate> = {
object: {
nullable: true,
check(type) {
return isEmptyObjectType(type) ? undefined : (type.flags & primitiveFlags) === 0 && !isTypeofFunction(type);
},
},
number: {
nullable: false,
check: checkFlags(ts.TypeFlags.NumberLike),
},
bigint: {
nullable: false,
check: checkFlags(ts.TypeFlags.BigIntLike),
},
string: {
nullable: false,
check: checkFlags(ts.TypeFlags.StringLike),
},
boolean: {
nullable: false,
check: checkFlags(ts.TypeFlags.BooleanLike),
},
symbol: {
nullable: false,
check: checkFlags(ts.TypeFlags.ESSymbolLike),
},
function: {
nullable: false,
check: isTypeofFunction,
},
null: {
nullable: true,
check: checkFlags(ts.TypeFlags.Null),
},
undefined: {
nullable: true,
check: checkFlags(ts.TypeFlags.Undefined | ts.TypeFlags.Void),
},
nullOrUndefined: {
nullable: true,
check: checkFlags(ts.TypeFlags.Null | ts.TypeFlags.Undefined | ts.TypeFlags.Void),
},
};
@excludeDeclarationFiles
export class Rule extends TypedRule {
private strictNullChecks = isStrictCompilerOptionEnabled(this.context.compilerOptions, 'strictNullChecks');
public apply() {
for (const node of this.context.getFlatAst()) {
switch (node.kind) {
case ts.SyntaxKind.IfStatement:
this.checkCondition((<ts.IfStatement>node).expression);
break;
case ts.SyntaxKind.ConditionalExpression:
this.checkCondition((<ts.ConditionalExpression>node).condition);
break;
case ts.SyntaxKind.WhileStatement:
case ts.SyntaxKind.DoStatement:
if ((<ts.WhileStatement | ts.DoStatement>node).expression.kind !== ts.SyntaxKind.TrueKeyword)
this.checkCondition((<ts.WhileStatement | ts.DoStatement>node).expression);
break;
case ts.SyntaxKind.ForStatement: {
const {condition} = <ts.ForStatement>node;
if (condition !== undefined && condition.kind !== ts.SyntaxKind.TrueKeyword)
this.checkCondition(condition);
break;
}
case ts.SyntaxKind.SwitchStatement:
this.checkSwitch(<ts.SwitchStatement>node);
break;
case ts.SyntaxKind.BinaryExpression:
if (isLogicalOperator((<ts.BinaryExpression>node).operatorToken.kind)) {
this.checkCondition((<ts.BinaryExpression>node).left);
} else if (isEqualityOrInOperator((<ts.BinaryExpression>node).operatorToken.kind)) {
this.checkNode(<ts.BinaryExpression>node);
}
break;
case ts.SyntaxKind.PrefixUnaryExpression:
if ((<ts.PrefixUnaryExpression>node).operator === ts.SyntaxKind.ExclamationToken)
this.checkCondition((<ts.PrefixUnaryExpression>node).operand);
}
}
}
private checkSwitch(node: ts.SwitchStatement) {
for (const clause of node.caseBlock.clauses) {
if (clause.kind === ts.SyntaxKind.DefaultClause)
continue;
this.maybeFail(clause, this.isConstantComparison(node.expression, clause.expression, ts.SyntaxKind.EqualsEqualsEqualsToken));
}
}
private checkCondition(node: ts.Expression) {
return this.maybeFail(node, this.isTruthyFalsy(node, true));
}
private checkNode(node: ts.Expression) {
return this.maybeFail(node, this.isTruthyFalsy(node, false));
}
private maybeFail(node: ts.Node, result: boolean | undefined) {
if (result !== undefined)
return this.addFindingAtNode(node, result ? 'Expression is always truthy.' : 'Expression is always falsy.');
}
private isTruthyFalsy(node: ts.Expression, nested: boolean): boolean | undefined {
if (isBinaryExpression(node)) {
if (isEqualityOperator(node.operatorToken.kind)) // TODO check <, >, <=, >= with literal types
return nested ? undefined : this.isConstantComparison(node.left, node.right, node.operatorToken.kind);
if (node.operatorToken.kind === ts.SyntaxKind.InKeyword)
return nested ? undefined : this.isPropertyPresent(node.right, node.left);
} else if (isPrefixUnaryExpression(node) && node.operator === ts.SyntaxKind.ExclamationToken) {
return;
} else if (isParenthesizedExpression(node)) {
return this.isTruthyFalsy(node.expression, true);
}
// in non-strictNullChecks mode we can only detect if a type is definitely falsy
return this.executePredicate(this.getTypeOfExpression(node), this.strictNullChecks ? truthyFalsy : falsy);
}
private isConstantComparison(left: ts.Expression, right: ts.Expression, operator: ts.EqualityOperator) {
left = unwrapParentheses(left);
right = unwrapParentheses(right);
const equals: Equals = {
negated: operator === ts.SyntaxKind.ExclamationEqualsEqualsToken || operator === ts.SyntaxKind.ExclamationEqualsToken,
strict: operator === ts.SyntaxKind.ExclamationEqualsEqualsToken || operator === ts.SyntaxKind.EqualsEqualsEqualsToken,
};
let result = this.checkEquals(left, right, equals);
if (result === undefined)
result = this.checkEquals(right, left, equals);
return result;
}
private checkEquals(left: ts.Expression, right: ts.Expression, equals: Equals): boolean | undefined {
let predicate: TypePredicate;
if (isTypeOfExpression(left)) {
left = unwrapParentheses(left.expression);
if (right.kind === ts.SyntaxKind.NullKeyword || isUndefined(right))
return equals.negated;
let literal: string;
if (isTextualLiteral(right)) {
literal = right.text;
} else {
const type = tryGetBaseConstraintType(this.getTypeOfExpression(right), this.checker);
if ((type.flags & ts.TypeFlags.StringLiteral) === 0)
return;
literal = (<ts.StringLiteralType>type).value;
}
switch (literal) {
default:
return equals.negated;
case 'number':
case 'string':
case 'boolean':
case 'symbol':
case 'object':
case 'function':
case 'undefined':
case 'bigint':
predicate = predicates[literal];
}
} else if (right.kind === ts.SyntaxKind.NullKeyword) {
predicate = equals.strict ? predicates.null : predicates.nullOrUndefined;
} else if (isUndefined(right)) {
predicate = equals.strict ? predicates.undefined : predicates.nullOrUndefined;
} else if (this.strictNullChecks) {
const leftLiteral = this.getPrimitiveLiteral(left);
return leftLiteral !== undefined && leftLiteral === this.getPrimitiveLiteral(right) ? !equals.negated : undefined;
} else {
return;
}
return this.nullAwarePredicate(this.getTypeOfExpression(left), predicate);
}
private getPrimitiveLiteral(node: ts.Expression) {
// TODO reuse some logic from 'no-duplicate-case' to compute prefix unary expressions
const type = tryGetBaseConstraintType(this.getTypeOfExpression(node), this.checker);
for (const t of intersectionTypeParts(type)) {
if (isLiteralType(t))
return typeof t.value === 'object' ? formatPseudoBigInt(t.value) : String(t.value);
if (t.flags & ts.TypeFlags.BooleanLiteral)
return (<{intrinsicName: string}><{}>t).intrinsicName;
if (t.flags & ts.TypeFlags.Undefined)
return 'undefined';
if (t.flags & ts.TypeFlags.Null)
return 'null';
// TODO unique symbol
}
return;
}
private nullAwarePredicate(type: ts.Type, predicate: TypePredicate): boolean | undefined {
if (!this.strictNullChecks && predicate.nullable)
return;
const result = this.executePredicate(
type,
// empty object type can contain anything but `null | undefined`
// TODO use assignability check to avoid false positives
predicate.nullable ? predicate.check : (t) => isEmptyObjectType(t) ? undefined : predicate.check(t),
);
return result && !this.strictNullChecks
? undefined
: result;
}
private executePredicate(type: ts.Type, predicate: (type: ts.Type) => boolean | undefined) {
let result: boolean | undefined;
for (let t of unionTypeParts(type)) {
if (t.flags & (ts.TypeFlags.TypeVariable | ts.TypeFlags.Instantiable)) {
const constraint = this.checker.getBaseConstraintOfType(t);
if (constraint === undefined)
return;
t = constraint;
}
if (t.flags & (ts.TypeFlags.Any | ts.TypeFlags.Never | ts.TypeFlags.Unknown))
return;
switch (isIntersectionType(t) ? this.matchIntersectionType(t, predicate) : predicate(t)) {
case true:
if (result === false)
return;
result = true;
break;
case false:
if (result === true)
return;
result = false;
break;
default:
return;
}
}
return result;
}
/**
* If one of the types in the intersection matches the precicate, this function returns true.
* Otherwise if any of the types results in undefined, this function returns undefined.
* If every type results in false, it returns false.
*/
private matchIntersectionType(type: ts.IntersectionType, predicate: (type: ts.Type) => boolean | undefined) {
let result: boolean | undefined = false;
for (const t of type.types) {
switch (this.executePredicate(t, predicate)) {
case true:
return true;
case undefined:
result = undefined;
}
}
return result;
}
private getTypeOfExpression(node: ts.Expression): ts.Type {
const type = this.checker.getTypeAtLocation(node);
if (!this.strictNullChecks)
return type;
if (unionTypeParts(type).some((t) => (t.flags & ts.TypeFlags.Undefined) !== 0))
return type;
if ((!isPropertyAccessExpression(node) || node.name.kind === ts.SyntaxKind.PrivateIdentifier) && !isElementAccessExpression(node))
return type;
const objectType = this.checker.getApparentType(this.checker.getTypeAtLocation(node.expression));
if (objectType.getStringIndexType() === undefined && objectType.getNumberIndexType() === undefined)
return type;
if (isPropertyAccessExpression(node)) {
if (objectType.getProperty(node.name.text) !== undefined)
return type;
} else {
const names = getLateBoundPropertyNames(node.argumentExpression, this.checker);
if (names.known && names.names.every(({symbolName}) => getPropertyOfType(objectType, symbolName) !== undefined))
return type;
}
return this.checker.getNullableType(type, ts.TypeFlags.Undefined);
}
private isPropertyPresent(node: ts.Expression, name: ts.Expression): true | undefined {
if (!this.strictNullChecks)
return;
const names = getLateBoundPropertyNames(name, this.checker);
if (!names.known)
return;
const types = unionTypeParts(this.checker.getApparentType(this.getTypeOfExpression(unwrapParentheses(node))));
for (const {symbolName} of names.names) {
// we check every union type member separately because symbols lose optionality when accessed through union types
for (const type of types) {
const symbol = getPropertyOfType(type, symbolName);
if (symbol === undefined || symbol.flags & ts.SymbolFlags.Optional)
return; // it might be present at runtime, so we don't return false
}
}
return true;
}
}
function isUndefined(node: ts.Expression): node is ts.Identifier {
return isIdentifier(node) && node.originalKeywordKind === ts.SyntaxKind.UndefinedKeyword;
}
function falsy(type: ts.Type): false | undefined {
return isFalsyType(type) ? false : undefined;
}
function truthyFalsy(type: ts.Type) {
if (type.flags & ts.TypeFlags.PossiblyFalsy) {
if (isFalsyType(type))
return false;
return type.flags & ts.TypeFlags.Literal ? true : undefined;
}
// TODO use assignability check
return isEmptyObjectType(type) ? undefined : true;
}
function isLogicalOperator(kind: ts.BinaryOperator) {
return kind === ts.SyntaxKind.AmpersandAmpersandToken || kind === ts.SyntaxKind.BarBarToken;
}
function isEqualityOrInOperator(kind: ts.BinaryOperator): kind is ts.EqualityOperator | ts.SyntaxKind.InKeyword {
return isEqualityOperator(kind) || kind === ts.SyntaxKind.InKeyword;
}
function isEqualityOperator(kind: ts.BinaryOperator): kind is ts.EqualityOperator {
switch (kind) {
case ts.SyntaxKind.ExclamationEqualsEqualsToken:
case ts.SyntaxKind.ExclamationEqualsToken:
case ts.SyntaxKind.EqualsEqualsEqualsToken:
case ts.SyntaxKind.EqualsEqualsToken:
return true;
default:
return false;
}
}
function checkFlags(flags: ts.TypeFlags) {
return (type: ts.Type) => (type.flags & flags) !== 0;
}
function isTypeofFunction(type: ts.Type) {
if (type.getCallSignatures().length !== 0 || type.getConstructSignatures().length !== 0)
return true;
// check if this could be the global `Function` type
return type.symbol !== undefined && type.symbol.escapedName === 'Function' &&
hasPropertyOfKind(type, 'apply', ts.SymbolFlags.Method) &&
hasPropertyOfKind(type, 'arguments', ts.SymbolFlags.Property) &&
hasPropertyOfKind(type, 'bind', ts.SymbolFlags.Method) &&
hasPropertyOfKind(type, 'call', ts.SymbolFlags.Method) &&
hasPropertyOfKind(type, 'caller', ts.SymbolFlags.Property) &&
hasPropertyOfKind(type, 'length', ts.SymbolFlags.Property) &&
hasPropertyOfKind(type, 'prototype', ts.SymbolFlags.Property);
}
function hasPropertyOfKind(type: ts.Type, name: string, flag: ts.SymbolFlags) {
const property = type.getProperty(name);
return property !== undefined && (property.flags & flag) !== 0;
} | the_stack |
declare module Babylon {
export class AbstractMesh { }
export interface IGetSetVerticesData { }
export interface Observable<Mesh> { }
export class Engine {
meshes(): Array<Mesh>;
}
export class Mesh extends AbstractMesh implements IGetSetVerticesData {
/**
* Mesh side orientation : usually the external or front surface
*/
static readonly FRONTSIDE: number;
/**
* Mesh side orientation : usually the internal or back surface
*/
static readonly BACKSIDE: number;
/**
* Mesh side orientation : both internal and external or front and back surfaces
*/
static readonly DOUBLESIDE: number;
/**
* Mesh side orientation : by default, `FRONTSIDE`
*/
static readonly DEFAULTSIDE: number;
/**
* Mesh cap setting : no cap
*/
static readonly NO_CAP: number;
/**
* Mesh cap setting : one cap at the beginning of the mesh
*/
static readonly CAP_START: number;
/**
* Mesh cap setting : one cap at the end of the mesh
*/
static readonly CAP_END: number;
/**
* Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
*/
static readonly CAP_ALL: number;
/**
* Mesh pattern setting : no flip or rotate
*/
static readonly NO_FLIP: number;
/**
* Mesh pattern setting : flip (reflect in y axis) alternate tiles on each row or column
*/
static readonly FLIP_TILE: number;
/**
* Mesh pattern setting : rotate (180degs) alternate tiles on each row or column
*/
static readonly ROTATE_TILE: number;
/**
* Mesh pattern setting : flip (reflect in y axis) all tiles on alternate rows
*/
static readonly FLIP_ROW: number;
/**
* Mesh pattern setting : rotate (180degs) all tiles on alternate rows
*/
static readonly ROTATE_ROW: number;
/**
* Mesh pattern setting : flip and rotate alternate tiles on each row or column
*/
static readonly FLIP_N_ROTATE_TILE: number;
/**
* Mesh pattern setting : rotate pattern and rotate
*/
static readonly FLIP_N_ROTATE_ROW: number;
/**
* Mesh tile positioning : part tiles same on left/right or top/bottom
*/
static readonly CENTER: number;
/**
* Mesh tile positioning : part tiles on left
*/
static readonly LEFT: number;
/**
* Mesh tile positioning : part tiles on right
*/
static readonly RIGHT: number;
/**
* Mesh tile positioning : part tiles on top
*/
static readonly TOP: number;
/**
* Mesh tile positioning : part tiles on bottom
*/
static readonly BOTTOM: number;
/**
* Gets the default side orientation.
* @param orientation the orientation to value to attempt to get
* @returns the default orientation
* @hidden
*/
static _GetDefaultSideOrientation(orientation?: number): number;
private _internalMeshDataInfo;
/**
* An event triggered before rendering the mesh
*/
get onBeforeRenderObservable(): Observable<Mesh>;
/**
* An event triggered before binding the mesh
*/
get onBeforeBindObservable(): Observable<Mesh>;
/**
* An event triggered after rendering the mesh
*/
get onAfterRenderObservable(): Observable<Mesh>;
/**
* An event triggered before drawing the mesh
*/
get onBeforeDrawObservable(): Observable<Mesh>;
private _onBeforeDrawObserver;
/**
* Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
*/
set onBeforeDraw(callback: () => void);
get hasInstances(): boolean;
/**
* Gets the delay loading state of the mesh (when delay loading is turned on)
* @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
*/
delayLoadState: number;
/**
* Gets the list of instances created from this mesh
* it is not supposed to be modified manually.
* Note also that the order of the InstancedMesh wihin the array is not significant and might change.
* @see http://doc.babylonjs.com/how_to/how_to_use_instances
*/
instances: InstancedMesh[];
/**
* Gets the file containing delay loading data for this mesh
*/
delayLoadingFile: string;
/** @hidden */
_binaryInfo: any;
/**
* User defined function used to change how LOD level selection is done
* @see http://doc.babylonjs.com/how_to/how_to_use_lod
*/
onLODLevelSelection: (distance: number, mesh: Mesh, selectedLevel: Nullable<Mesh>) => void;
/**
* Gets or sets the morph target manager
* @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
*/
get morphTargetManager(): Nullable<MorphTargetManager>;
set morphTargetManager(value: Nullable<MorphTargetManager>);
/** @hidden */
_creationDataStorage: Nullable<_CreationDataStorage>;
/** @hidden */
_geometry: Nullable<Geometry>;
/** @hidden */
_delayInfo: Array<string>;
/** @hidden */
_delayLoadingFunction: (any: any, mesh: Mesh) => void;
/** @hidden */
_instanceDataStorage: _InstanceDataStorage;
private _effectiveMaterial;
/** @hidden */
_shouldGenerateFlatShading: boolean;
/** @hidden */
_originalBuilderSideOrientation: number;
/**
* Use this property to change the original side orientation defined at construction time
*/
overrideMaterialSideOrientation: Nullable<number>;
/**
* Gets the source mesh (the one used to clone this one from)
*/
get source(): Nullable<Mesh>;
/**
* Gets or sets a boolean indicating that this mesh does not use index buffer
*/
get isUnIndexed(): boolean;
set isUnIndexed(value: boolean);
/** Gets the array buffer used to store the instanced buffer used for instances' world matrices */
get worldMatrixInstancedBuffer(): Float32Array;
/** Gets or sets a boolean indicating that the update of the instance buffer of the world matrices is manual */
get manualUpdateOfWorldMatrixInstancedBuffer(): boolean;
set manualUpdateOfWorldMatrixInstancedBuffer(value: boolean);
/**
* @constructor
* @param name The value used by scene.getMeshByName() to do a lookup.
* @param scene The scene to add this mesh to.
* @param parent The parent of this mesh, if it has one
* @param source An optional Mesh from which geometry is shared, cloned.
* @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
* When false, achieved by calling a clone(), also passing False.
* This will make creation of children, recursive.
* @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
*/
constructor(name: string, scene?: Nullable<Scene>, parent?: Nullable<Node>, source?: Nullable<Mesh>, doNotCloneChildren?: boolean, clonePhysicsImpostor?: boolean);
instantiateHierarchy(newParent?: Nullable<TransformNode>, options?: {
doNotInstantiate: boolean;
}, onNewNodeCreated?: (source: TransformNode, clone: TransformNode) => void): Nullable<TransformNode>;
/**
* Gets the class name
* @returns the string "Mesh".
*/
getClassName(): string;
/** @hidden */
get _isMesh(): boolean;
/**
* Returns a description of this mesh
* @param fullDetails define if full details about this mesh must be used
* @returns a descriptive string representing this mesh
*/
toString(fullDetails?: boolean): string;
/** @hidden */
_unBindEffect(): void;
/**
* Gets a boolean indicating if this mesh has LOD
*/
get hasLODLevels(): boolean;
/**
* Gets the list of MeshLODLevel associated with the current mesh
* @returns an array of MeshLODLevel
*/
getLODLevels(): MeshLODLevel[];
private _sortLODLevels;
/**
* Add a mesh as LOD level triggered at the given distance.
* @see https://doc.babylonjs.com/how_to/how_to_use_lod
* @param distance The distance from the center of the object to show this level
* @param mesh The mesh to be added as LOD level (can be null)
* @return This mesh (for chaining)
*/
addLODLevel(distance: number, mesh: Nullable<Mesh>): Mesh;
/**
* Returns the LOD level mesh at the passed distance or null if not found.
* @see https://doc.babylonjs.com/how_to/how_to_use_lod
* @param distance The distance from the center of the object to show this level
* @returns a Mesh or `null`
*/
getLODLevelAtDistance(distance: number): Nullable<Mesh>;
/**
* Remove a mesh from the LOD array
* @see https://doc.babylonjs.com/how_to/how_to_use_lod
* @param mesh defines the mesh to be removed
* @return This mesh (for chaining)
*/
removeLODLevel(mesh: Mesh): Mesh;
/**
* Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
* @see https://doc.babylonjs.com/how_to/how_to_use_lod
* @param camera defines the camera to use to compute distance
* @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
* @return This mesh (for chaining)
*/
getLOD(camera: Camera, boundingSphere?: BoundingSphere): Nullable<AbstractMesh>;
/**
* Gets the mesh internal Geometry object
*/
get geometry(): Nullable<Geometry>;
/**
* Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
* @returns the total number of vertices
*/
getTotalVertices(): number;
/**
* Returns the content of an associated vertex buffer
* @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
* - VertexBuffer.PositionKind
* - VertexBuffer.UVKind
* - VertexBuffer.UV2Kind
* - VertexBuffer.UV3Kind
* - VertexBuffer.UV4Kind
* - VertexBuffer.UV5Kind
* - VertexBuffer.UV6Kind
* - VertexBuffer.ColorKind
* - VertexBuffer.MatricesIndicesKind
* - VertexBuffer.MatricesIndicesExtraKind
* - VertexBuffer.MatricesWeightsKind
* - VertexBuffer.MatricesWeightsExtraKind
* @param copyWhenShared defines a boolean indicating that if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one
* @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
* @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
*/
getVerticesData(kind: string, copyWhenShared?: boolean, forceCopy?: boolean): Nullable<FloatArray>;
/**
* Returns the mesh VertexBuffer object from the requested `kind`
* @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
* - VertexBuffer.PositionKind
* - VertexBuffer.NormalKind
* - VertexBuffer.UVKind
* - VertexBuffer.UV2Kind
* - VertexBuffer.UV3Kind
* - VertexBuffer.UV4Kind
* - VertexBuffer.UV5Kind
* - VertexBuffer.UV6Kind
* - VertexBuffer.ColorKind
* - VertexBuffer.MatricesIndicesKind
* - VertexBuffer.MatricesIndicesExtraKind
* - VertexBuffer.MatricesWeightsKind
* - VertexBuffer.MatricesWeightsExtraKind
* @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
*/
getVertexBuffer(kind: string): Nullable<VertexBuffer>;
/**
* Tests if a specific vertex buffer is associated with this mesh
* @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
* - VertexBuffer.PositionKind
* - VertexBuffer.NormalKind
* - VertexBuffer.UVKind
* - VertexBuffer.UV2Kind
* - VertexBuffer.UV3Kind
* - VertexBuffer.UV4Kind
* - VertexBuffer.UV5Kind
* - VertexBuffer.UV6Kind
* - VertexBuffer.ColorKind
* - VertexBuffer.MatricesIndicesKind
* - VertexBuffer.MatricesIndicesExtraKind
* - VertexBuffer.MatricesWeightsKind
* - VertexBuffer.MatricesWeightsExtraKind
* @returns a boolean
*/
isVerticesDataPresent(kind: string): boolean;
/**
* Returns a boolean defining if the vertex data for the requested `kind` is updatable.
* @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
* - VertexBuffer.PositionKind
* - VertexBuffer.UVKind
* - VertexBuffer.UV2Kind
* - VertexBuffer.UV3Kind
* - VertexBuffer.UV4Kind
* - VertexBuffer.UV5Kind
* - VertexBuffer.UV6Kind
* - VertexBuffer.ColorKind
* - VertexBuffer.MatricesIndicesKind
* - VertexBuffer.MatricesIndicesExtraKind
* - VertexBuffer.MatricesWeightsKind
* - VertexBuffer.MatricesWeightsExtraKind
* @returns a boolean
*/
isVertexBufferUpdatable(kind: string): boolean;
/**
* Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
* @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
* - VertexBuffer.PositionKind
* - VertexBuffer.NormalKind
* - VertexBuffer.UVKind
* - VertexBuffer.UV2Kind
* - VertexBuffer.UV3Kind
* - VertexBuffer.UV4Kind
* - VertexBuffer.UV5Kind
* - VertexBuffer.UV6Kind
* - VertexBuffer.ColorKind
* - VertexBuffer.MatricesIndicesKind
* - VertexBuffer.MatricesIndicesExtraKind
* - VertexBuffer.MatricesWeightsKind
* - VertexBuffer.MatricesWeightsExtraKind
* @returns an array of strings
*/
getVerticesDataKinds(): string[];
/**
* Returns a positive integer : the total number of indices in this mesh geometry.
* @returns the numner of indices or zero if the mesh has no geometry.
*/
getTotalIndices(): number;
/**
* Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
* @param copyWhenShared If true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
* @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
* @returns the indices array or an empty array if the mesh has no geometry
*/
getIndices(copyWhenShared?: boolean, forceCopy?: boolean): Nullable<IndicesArray>;
get isBlocked(): boolean;
/**
* Determine if the current mesh is ready to be rendered
* @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
* @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
* @returns true if all associated assets are ready (material, textures, shaders)
*/
isReady(completeCheck?: boolean, forceInstanceSupport?: boolean): boolean;
/**
* Gets a boolean indicating if the normals aren't to be recomputed on next mesh `positions` array update. This property is pertinent only for updatable parametric shapes.
*/
get areNormalsFrozen(): boolean;
/**
* This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It prevents the mesh normals from being recomputed on next `positions` array update.
* @returns the current mesh
*/
freezeNormals(): Mesh;
/**
* This function affects parametric shapes on vertex position update only : ribbons, tubes, etc. It has no effect at all on other shapes. It reactivates the mesh normals computation if it was previously frozen
* @returns the current mesh
*/
unfreezeNormals(): Mesh;
/**
* Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
*/
set overridenInstanceCount(count: number);
/** @hidden */
_preActivate(): Mesh;
/** @hidden */
_preActivateForIntermediateRendering(renderId: number): Mesh;
/** @hidden */
_registerInstanceForRenderId(instance: InstancedMesh, renderId: number): Mesh;
/**
* This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
* This means the mesh underlying bounding box and sphere are recomputed.
* @param applySkeleton defines whether to apply the skeleton before computing the bounding info
* @returns the current mesh
*/
refreshBoundingInfo(applySkeleton?: boolean): Mesh;
/** @hidden */
_createGlobalSubMesh(force: boolean): Nullable<SubMesh>;
/**
* This function will subdivide the mesh into multiple submeshes
* @param count defines the expected number of submeshes
*/
subdivide(count: number): void;
/**
* Copy a FloatArray into a specific associated vertex buffer
* @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
* - VertexBuffer.PositionKind
* - VertexBuffer.UVKind
* - VertexBuffer.UV2Kind
* - VertexBuffer.UV3Kind
* - VertexBuffer.UV4Kind
* - VertexBuffer.UV5Kind
* - VertexBuffer.UV6Kind
* - VertexBuffer.ColorKind
* - VertexBuffer.MatricesIndicesKind
* - VertexBuffer.MatricesIndicesExtraKind
* - VertexBuffer.MatricesWeightsKind
* - VertexBuffer.MatricesWeightsExtraKind
* @param data defines the data source
* @param updatable defines if the updated vertex buffer must be flagged as updatable
* @param stride defines the data stride size (can be null)
* @returns the current mesh
*/
setVerticesData(kind: string, data: FloatArray, updatable?: boolean, stride?: number): AbstractMesh;
/**
* Delete a vertex buffer associated with this mesh
* @param kind defines which buffer to delete (positions, indices, normals, etc). Possible `kind` values :
* - VertexBuffer.PositionKind
* - VertexBuffer.UVKind
* - VertexBuffer.UV2Kind
* - VertexBuffer.UV3Kind
* - VertexBuffer.UV4Kind
* - VertexBuffer.UV5Kind
* - VertexBuffer.UV6Kind
* - VertexBuffer.ColorKind
* - VertexBuffer.MatricesIndicesKind
* - VertexBuffer.MatricesIndicesExtraKind
* - VertexBuffer.MatricesWeightsKind
* - VertexBuffer.MatricesWeightsExtraKind
*/
removeVerticesData(kind: string): void;
/**
* Flags an associated vertex buffer as updatable
* @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
* - VertexBuffer.PositionKind
* - VertexBuffer.UVKind
* - VertexBuffer.UV2Kind
* - VertexBuffer.UV3Kind
* - VertexBuffer.UV4Kind
* - VertexBuffer.UV5Kind
* - VertexBuffer.UV6Kind
* - VertexBuffer.ColorKind
* - VertexBuffer.MatricesIndicesKind
* - VertexBuffer.MatricesIndicesExtraKind
* - VertexBuffer.MatricesWeightsKind
* - VertexBuffer.MatricesWeightsExtraKind
* @param updatable defines if the updated vertex buffer must be flagged as updatable
*/
markVerticesDataAsUpdatable(kind: string, updatable?: boolean): void;
/**
* Sets the mesh global Vertex Buffer
* @param buffer defines the buffer to use
* @returns the current mesh
*/
setVerticesBuffer(buffer: VertexBuffer): Mesh;
/**
* Update a specific associated vertex buffer
* @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
* - VertexBuffer.PositionKind
* - VertexBuffer.UVKind
* - VertexBuffer.UV2Kind
* - VertexBuffer.UV3Kind
* - VertexBuffer.UV4Kind
* - VertexBuffer.UV5Kind
* - VertexBuffer.UV6Kind
* - VertexBuffer.ColorKind
* - VertexBuffer.MatricesIndicesKind
* - VertexBuffer.MatricesIndicesExtraKind
* - VertexBuffer.MatricesWeightsKind
* - VertexBuffer.MatricesWeightsExtraKind
* @param data defines the data source
* @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
* @param makeItUnique defines if the geometry associated with the mesh must be cloned to make the change only for this mesh (and not all meshes associated with the same geometry)
* @returns the current mesh
*/
updateVerticesData(kind: string, data: FloatArray, updateExtends?: boolean, makeItUnique?: boolean): AbstractMesh;
/**
* This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
* @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
* @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
* @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
* @returns the current mesh
*/
updateMeshPositions(positionFunction: (data: FloatArray) => void, computeNormals?: boolean): Mesh;
/**
* Creates a un-shared specific occurence of the geometry for the mesh.
* @returns the current mesh
*/
makeGeometryUnique(): Mesh;
/**
* Set the index buffer of this mesh
* @param indices defines the source data
* @param totalVertices defines the total number of vertices referenced by this index data (can be null)
* @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
* @returns the current mesh
*/
setIndices(indices: IndicesArray, totalVertices?: Nullable<number>, updatable?: boolean): AbstractMesh;
/**
* Update the current index buffer
* @param indices defines the source data
* @param offset defines the offset in the index buffer where to store the new data (can be null)
* @param gpuMemoryOnly defines a boolean indicating that only the GPU memory must be updated leaving the CPU version of the indices unchanged (false by default)
* @returns the current mesh
*/
updateIndices(indices: IndicesArray, offset?: number, gpuMemoryOnly?: boolean): AbstractMesh;
/**
* Invert the geometry to move from a right handed system to a left handed one.
* @returns the current mesh
*/
toLeftHanded(): Mesh;
/** @hidden */
_bind(subMesh: SubMesh, effect: Effect, fillMode: number): Mesh;
/** @hidden */
_draw(subMesh: SubMesh, fillMode: number, instancesCount?: number): Mesh;
/**
* Registers for this mesh a javascript function called just before the rendering process
* @param func defines the function to call before rendering this mesh
* @returns the current mesh
*/
registerBeforeRender(func: (mesh: AbstractMesh) => void): Mesh;
/**
* Disposes a previously registered javascript function called before the rendering
* @param func defines the function to remove
* @returns the current mesh
*/
unregisterBeforeRender(func: (mesh: AbstractMesh) => void): Mesh;
/**
* Registers for this mesh a javascript function called just after the rendering is complete
* @param func defines the function to call after rendering this mesh
* @returns the current mesh
*/
registerAfterRender(func: (mesh: AbstractMesh) => void): Mesh;
/**
* Disposes a previously registered javascript function called after the rendering.
* @param func defines the function to remove
* @returns the current mesh
*/
unregisterAfterRender(func: (mesh: AbstractMesh) => void): Mesh;
/** @hidden */
_getInstancesRenderList(subMeshId: number, isReplacementMode?: boolean): _InstancesBatch;
/** @hidden */
_renderWithInstances(subMesh: SubMesh, fillMode: number, batch: _InstancesBatch, effect: Effect, engine: Engine): Mesh;
/** @hidden */
_processInstancedBuffers(visibleInstances: InstancedMesh[], renderSelf: boolean): void;
/** @hidden */
_processRendering(subMesh: SubMesh, effect: Effect, fillMode: number, batch: _InstancesBatch, hardwareInstancedRendering: boolean, onBeforeDraw: (isInstance: boolean, world: Matrix, effectiveMaterial?: Material) => void, effectiveMaterial?: Material): Mesh;
/** @hidden */
_rebuild(): void;
/** @hidden */
_freeze(): void;
/** @hidden */
_unFreeze(): void;
/**
* Triggers the draw call for the mesh. Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager
* @param subMesh defines the subMesh to render
* @param enableAlphaMode defines if alpha mode can be changed
* @param effectiveMeshReplacement defines an optional mesh used to provide info for the rendering
* @returns the current mesh
*/
render(subMesh: SubMesh, enableAlphaMode: boolean, effectiveMeshReplacement?: AbstractMesh): Mesh;
private _onBeforeDraw;
/**
* Renormalize the mesh and patch it up if there are no weights
* Similar to normalization by adding the weights compute the reciprocal and multiply all elements, this wil ensure that everything adds to 1.
* However in the case of zero weights then we set just a single influence to 1.
* We check in the function for extra's present and if so we use the normalizeSkinWeightsWithExtras rather than the FourWeights version.
*/
cleanMatrixWeights(): void;
private normalizeSkinFourWeights;
private normalizeSkinWeightsAndExtra;
/**
* ValidateSkinning is used to determine that a mesh has valid skinning data along with skin metrics, if missing weights,
* or not normalized it is returned as invalid mesh the string can be used for console logs, or on screen messages to let
* the user know there was an issue with importing the mesh
* @returns a validation object with skinned, valid and report string
*/
validateSkinning(): {
skinned: boolean;
valid: boolean;
report: string;
};
/** @hidden */
_checkDelayState(): Mesh;
private _queueLoad;
/**
* Returns `true` if the mesh is within the frustum defined by the passed array of planes.
* A mesh is in the frustum if its bounding box intersects the frustum
* @param frustumPlanes defines the frustum to test
* @returns true if the mesh is in the frustum planes
*/
isInFrustum(frustumPlanes: Plane[]): boolean;
/**
* Sets the mesh material by the material or multiMaterial `id` property
* @param id is a string identifying the material or the multiMaterial
* @returns the current mesh
*/
setMaterialByID(id: string): Mesh;
/**
* Returns as a new array populated with the mesh material and/or skeleton, if any.
* @returns an array of IAnimatable
*/
getAnimatables(): IAnimatable[];
/**
* Modifies the mesh geometry according to the passed transformation matrix.
* This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
* The mesh normals are modified using the same transformation.
* Note that, under the hood, this method sets a new VertexBuffer each call.
* @param transform defines the transform matrix to use
* @see http://doc.babylonjs.com/resources/baking_transformations
* @returns the current mesh
*/
bakeTransformIntoVertices(transform: Matrix): Mesh;
/**
* Modifies the mesh geometry according to its own current World Matrix.
* The mesh World Matrix is then reset.
* This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
* Note that, under the hood, this method sets a new VertexBuffer each call.
* @see http://doc.babylonjs.com/resources/baking_transformations
* @param bakeIndependenlyOfChildren indicates whether to preserve all child nodes' World Matrix during baking
* @returns the current mesh
*/
bakeCurrentTransformIntoVertices(bakeIndependenlyOfChildren?: boolean): Mesh;
/** @hidden */
get _positions(): Nullable<Vector3[]>;
/** @hidden */
_resetPointsArrayCache(): Mesh;
/** @hidden */
_generatePointsArray(): boolean;
/**
* Returns a new Mesh object generated from the current mesh properties.
* This method must not get confused with createInstance()
* @param name is a string, the name given to the new mesh
* @param newParent can be any Node object (default `null`)
* @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
* @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
* @returns a new mesh
*/
clone(name?: string, newParent?: Nullable<Node>, doNotCloneChildren?: boolean, clonePhysicsImpostor?: boolean): Mesh;
/**
* Releases resources associated with this mesh.
* @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
* @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
*/
dispose(doNotRecurse?: boolean, disposeMaterialAndTextures?: boolean): void;
/** @hidden */
_disposeInstanceSpecificData(): void;
/**
* Modifies the mesh geometry according to a displacement map.
* A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
* The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
* @param url is a string, the URL from the image file is to be downloaded.
* @param minHeight is the lower limit of the displacement.
* @param maxHeight is the upper limit of the displacement.
* @param onSuccess is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
* @param uvOffset is an optional vector2 used to offset UV.
* @param uvScale is an optional vector2 used to scale UV.
* @param forceUpdate defines whether or not to force an update of the generated buffers. This is useful to apply on a deserialized model for instance.
* @returns the Mesh.
*/
applyDisplacementMap(url: string, minHeight: number, maxHeight: number, onSuccess?: (mesh: Mesh) => void, uvOffset?: Vector2, uvScale?: Vector2, forceUpdate?: boolean): Mesh;
/**
* Modifies the mesh geometry according to a displacementMap buffer.
* A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
* The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
* @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
* @param heightMapWidth is the width of the buffer image.
* @param heightMapHeight is the height of the buffer image.
* @param minHeight is the lower limit of the displacement.
* @param maxHeight is the upper limit of the displacement.
* @param onSuccess is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
* @param uvOffset is an optional vector2 used to offset UV.
* @param uvScale is an optional vector2 used to scale UV.
* @param forceUpdate defines whether or not to force an update of the generated buffers. This is useful to apply on a deserialized model for instance.
* @returns the Mesh.
*/
applyDisplacementMapFromBuffer(buffer: Uint8Array, heightMapWidth: number, heightMapHeight: number, minHeight: number, maxHeight: number, uvOffset?: Vector2, uvScale?: Vector2, forceUpdate?: boolean): Mesh;
/**
* Modify the mesh to get a flat shading rendering.
* This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
* Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
* @returns current mesh
*/
convertToFlatShadedMesh(): Mesh;
/**
* This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
* In other words, more vertices, no more indices and a single bigger VBO.
* The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
* @returns current mesh
*/
convertToUnIndexedMesh(): Mesh;
/**
* Inverses facet orientations.
* Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
* @param flipNormals will also inverts the normals
* @returns current mesh
*/
flipFaces(flipNormals?: boolean): Mesh;
/**
* Increase the number of facets and hence vertices in a mesh
* Vertex normals are interpolated from existing vertex normals
* Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
* @param numberPerEdge the number of new vertices to add to each edge of a facet, optional default 1
*/
increaseVertices(numberPerEdge: number): void;
/**
* Force adjacent facets to share vertices and remove any facets that have all vertices in a line
* This will undo any application of covertToFlatShadedMesh
* Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
*/
forceSharedVertices(): void;
/** @hidden */
static _instancedMeshFactory(name: string, mesh: Mesh): InstancedMesh;
/** @hidden */
static _PhysicsImpostorParser(scene: Scene, physicObject: IPhysicsEnabledObject, jsonObject: any): PhysicsImpostor;
/**
* Creates a new InstancedMesh object from the mesh model.
* @see http://doc.babylonjs.com/how_to/how_to_use_instances
* @param name defines the name of the new instance
* @returns a new InstancedMesh
*/
createInstance(name: string): InstancedMesh;
/**
* Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
* After this call, all the mesh instances have the same submeshes than the current mesh.
* @returns the current mesh
*/
synchronizeInstances(): Mesh;
/**
* Optimization of the mesh's indices, in case a mesh has duplicated vertices.
* The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
* This should be used together with the simplification to avoid disappearing triangles.
* @param successCallback an optional success callback to be called after the optimization finished.
* @returns the current mesh
*/
optimizeIndices(successCallback?: (mesh?: Mesh) => void): Mesh;
/**
* Serialize current mesh
* @param serializationObject defines the object which will receive the serialization data
*/
serialize(serializationObject: any): void;
/** @hidden */
_syncGeometryWithMorphTargetManager(): void;
/** @hidden */
static _GroundMeshParser: (parsedMesh: any, scene: Scene) => Mesh;
/**
* Returns a new Mesh object parsed from the source provided.
* @param parsedMesh is the source
* @param scene defines the hosting scene
* @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
* @returns a new Mesh
*/
static Parse(parsedMesh: any, scene: Scene, rootUrl: string): Mesh;
/**
* Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
* @see http://doc.babylonjs.com/how_to/parametric_shapes
* @param name defines the name of the mesh to create
* @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
* @param closeArray creates a seam between the first and the last paths of the path array (default is false)
* @param closePath creates a seam between the first and the last points of each path of the path array
* @param offset is taken in account only if the `pathArray` is containing a single path
* @param scene defines the hosting scene
* @param updatable defines if the mesh must be flagged as updatable
* @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
* @param instance defines an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#ribbon)
* @returns a new Mesh
*/
static CreateRibbon(name: string, pathArray: Vector3[][], closeArray: boolean, closePath: boolean, offset: number, scene?: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh;
/**
* Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
* @param name defines the name of the mesh to create
* @param radius sets the radius size (float) of the polygon (default 0.5)
* @param tessellation sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc
* @param scene defines the hosting scene
* @param updatable defines if the mesh must be flagged as updatable
* @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
* @returns a new Mesh
*/
static CreateDisc(name: string, radius: number, tessellation: number, scene?: Nullable<Scene>, updatable?: boolean, sideOrientation?: number): Mesh;
/**
* Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
* @param name defines the name of the mesh to create
* @param size sets the size (float) of each box side (default 1)
* @param scene defines the hosting scene
* @param updatable defines if the mesh must be flagged as updatable
* @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
* @returns a new Mesh
*/
static CreateBox(name: string, size: number, scene?: Nullable<Scene>, updatable?: boolean, sideOrientation?: number): Mesh;
/**
* Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
* @param name defines the name of the mesh to create
* @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
* @param diameter sets the diameter size (float) of the sphere (default 1)
* @param scene defines the hosting scene
* @param updatable defines if the mesh must be flagged as updatable
* @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
* @returns a new Mesh
*/
static CreateSphere(name: string, segments: number, diameter: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh;
/**
* Creates a hemisphere mesh. Please consider using the same method from the MeshBuilder class instead
* @param name defines the name of the mesh to create
* @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
* @param diameter sets the diameter size (float) of the sphere (default 1)
* @param scene defines the hosting scene
* @returns a new Mesh
*/
static CreateHemisphere(name: string, segments: number, diameter: number, scene?: Scene): Mesh;
/**
* Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
* @param name defines the name of the mesh to create
* @param height sets the height size (float) of the cylinder/cone (float, default 2)
* @param diameterTop set the top cap diameter (floats, default 1)
* @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
* @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
* @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
* @param scene defines the hosting scene
* @param updatable defines if the mesh must be flagged as updatable
* @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
* @returns a new Mesh
*/
static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: any, scene?: Scene, updatable?: any, sideOrientation?: number): Mesh;
/**
* Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
* @param name defines the name of the mesh to create
* @param diameter sets the diameter size (float) of the torus (default 1)
* @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
* @param tessellation sets the number of torus sides (postive integer, default 16)
* @param scene defines the hosting scene
* @param updatable defines if the mesh must be flagged as updatable
* @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
* @returns a new Mesh
*/
static CreateTorus(name: string, diameter: number, thickness: number, tessellation: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh;
/**
* Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
* @param name defines the name of the mesh to create
* @param radius sets the global radius size (float) of the torus knot (default 2)
* @param tube sets the diameter size of the tube of the torus (float, default 0.5)
* @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
* @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
* @param p the number of windings on X axis (positive integers, default 2)
* @param q the number of windings on Y axis (positive integers, default 3)
* @param scene defines the hosting scene
* @param updatable defines if the mesh must be flagged as updatable
* @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
* @returns a new Mesh
*/
static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene?: Scene, updatable?: boolean, sideOrientation?: number): Mesh;
/**
* Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
* @param name defines the name of the mesh to create
* @param points is an array successive Vector3
* @param scene defines the hosting scene
* @param updatable defines if the mesh must be flagged as updatable
* @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines).
* @returns a new Mesh
*/
static CreateLines(name: string, points: Vector3[], scene?: Nullable<Scene>, updatable?: boolean, instance?: Nullable<LinesMesh>): LinesMesh;
/**
* Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
* @param name defines the name of the mesh to create
* @param points is an array successive Vector3
* @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
* @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
* @param dashNb is the intended total number of dashes (positive integer, default 200)
* @param scene defines the hosting scene
* @param updatable defines if the mesh must be flagged as updatable
* @param instance is an instance of an existing LineMesh object to be updated with the passed `points` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#lines-and-dashedlines)
* @returns a new Mesh
*/
static CreateDashedLines(name: string, points: Vector3[], dashSize: number, gapSize: number, dashNb: number, scene?: Nullable<Scene>, updatable?: boolean, instance?: LinesMesh): LinesMesh;
/**
* Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
* The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
* The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors.
* You can set the mesh side orientation with the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE
* The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
* Remember you can only change the shape positions, not their number when updating a polygon.
* @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
* @param name defines the name of the mesh to create
* @param shape is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors
* @param scene defines the hosting scene
* @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
* @param updatable defines if the mesh must be flagged as updatable
* @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
* @param earcutInjection can be used to inject your own earcut reference
* @returns a new Mesh
*/
static CreatePolygon(name: string, shape: Vector3[], scene: Scene, holes?: Vector3[][], updatable?: boolean, sideOrientation?: number, earcutInjection?: any): Mesh;
/**
* Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
* @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
* @param name defines the name of the mesh to create
* @param shape is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors
* @param depth defines the height of extrusion
* @param scene defines the hosting scene
* @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
* @param updatable defines if the mesh must be flagged as updatable
* @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
* @param earcutInjection can be used to inject your own earcut reference
* @returns a new Mesh
*/
static ExtrudePolygon(name: string, shape: Vector3[], depth: number, scene: Scene, holes?: Vector3[][], updatable?: boolean, sideOrientation?: number, earcutInjection?: any): Mesh;
/**
* Creates an extruded shape mesh.
* The extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters. Please consider using the same method from the MeshBuilder class instead
* @see http://doc.babylonjs.com/how_to/parametric_shapes
* @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
* @param name defines the name of the mesh to create
* @param shape is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis
* @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
* @param scale is the value to scale the shape
* @param rotation is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve
* @param cap sets the way the extruded shape is capped. Possible values : Mesh.NO_CAP (default), Mesh.CAP_START, Mesh.CAP_END, Mesh.CAP_ALL
* @param scene defines the hosting scene
* @param updatable defines if the mesh must be flagged as updatable
* @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
* @param instance is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#extruded-shape)
* @returns a new Mesh
*/
static ExtrudeShape(name: string, shape: Vector3[], path: Vector3[], scale: number, rotation: number, cap: number, scene?: Nullable<Scene>, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh;
/**
* Creates an custom extruded shape mesh.
* The custom extrusion is a parametric shape.
* It has no predefined shape. Its final shape will depend on the input parameters.
* Please consider using the same method from the MeshBuilder class instead
* @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
* @param name defines the name of the mesh to create
* @param shape is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be extruded along the Z axis
* @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
* @param scaleFunction is a custom Javascript function called on each path point
* @param rotationFunction is a custom Javascript function called on each path point
* @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
* @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
* @param cap sets the way the extruded shape is capped. Possible values : Mesh.NO_CAP (default), Mesh.CAP_START, Mesh.CAP_END, Mesh.CAP_ALL
* @param scene defines the hosting scene
* @param updatable defines if the mesh must be flagged as updatable
* @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
* @param instance is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters (http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#extruded-shape)
* @returns a new Mesh
*/
static ExtrudeShapeCustom(name: string, shape: Vector3[], path: Vector3[], scaleFunction: Function, rotationFunction: Function, ribbonCloseArray: boolean, ribbonClosePath: boolean, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh;
/**
* Creates lathe mesh.
* The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
* Please consider using the same method from the MeshBuilder class instead
* @param name defines the name of the mesh to create
* @param shape is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero
* @param radius is the radius value of the lathe
* @param tessellation is the side number of the lathe.
* @param scene defines the hosting scene
* @param updatable defines if the mesh must be flagged as updatable
* @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
* @returns a new Mesh
*/
static CreateLathe(name: string, shape: Vector3[], radius: number, tessellation: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh;
/**
* Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
* @param name defines the name of the mesh to create
* @param size sets the size (float) of both sides of the plane at once (default 1)
* @param scene defines the hosting scene
* @param updatable defines if the mesh must be flagged as updatable
* @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
* @returns a new Mesh
*/
static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean, sideOrientation?: number): Mesh;
/**
* Creates a ground mesh.
* Please consider using the same method from the MeshBuilder class instead
* @param name defines the name of the mesh to create
* @param width set the width of the ground
* @param height set the height of the ground
* @param subdivisions sets the number of subdivisions per side
* @param scene defines the hosting scene
* @param updatable defines if the mesh must be flagged as updatable
* @returns a new Mesh
*/
static CreateGround(name: string, width: number, height: number, subdivisions: number, scene?: Scene, updatable?: boolean): Mesh;
/**
* Creates a tiled ground mesh.
* Please consider using the same method from the MeshBuilder class instead
* @param name defines the name of the mesh to create
* @param xmin set the ground minimum X coordinate
* @param zmin set the ground minimum Y coordinate
* @param xmax set the ground maximum X coordinate
* @param zmax set the ground maximum Z coordinate
* @param subdivisions is an object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the numbers of subdivisions on the ground width and height. Each subdivision is called a tile
* @param precision is an object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the numbers of subdivisions on the ground width and height of each tile
* @param scene defines the hosting scene
* @param updatable defines if the mesh must be flagged as updatable
* @returns a new Mesh
*/
static CreateTiledGround(name: string, xmin: number, zmin: number, xmax: number, zmax: number, subdivisions: {
w: number;
h: number;
}, precision: {
w: number;
h: number;
}, scene: Scene, updatable?: boolean): Mesh;
/**
* Creates a ground mesh from a height map.
* Please consider using the same method from the MeshBuilder class instead
* @see http://doc.babylonjs.com/babylon101/height_map
* @param name defines the name of the mesh to create
* @param url sets the URL of the height map image resource
* @param width set the ground width size
* @param height set the ground height size
* @param subdivisions sets the number of subdivision per side
* @param minHeight is the minimum altitude on the ground
* @param maxHeight is the maximum altitude on the ground
* @param scene defines the hosting scene
* @param updatable defines if the mesh must be flagged as updatable
* @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
* @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
* @returns a new Mesh
*/
static CreateGroundFromHeightMap(name: string, url: string, width: number, height: number, subdivisions: number, minHeight: number, maxHeight: number, scene: Scene, updatable?: boolean, onReady?: (mesh: GroundMesh) => void, alphaFilter?: number): GroundMesh;
/**
* Creates a tube mesh.
* The tube is a parametric shape.
* It has no predefined shape. Its final shape will depend on the input parameters.
* Please consider using the same method from the MeshBuilder class instead
* @see http://doc.babylonjs.com/how_to/parametric_shapes
* @param name defines the name of the mesh to create
* @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
* @param radius sets the tube radius size
* @param tessellation is the number of sides on the tubular surface
* @param radiusFunction is a custom function. If it is not null, it overwrittes the parameter `radius`. This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path
* @param cap sets the way the extruded shape is capped. Possible values : Mesh.NO_CAP (default), Mesh.CAP_START, Mesh.CAP_END, Mesh.CAP_ALL
* @param scene defines the hosting scene
* @param updatable defines if the mesh must be flagged as updatable
* @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
* @param instance is an instance of an existing Tube object to be updated with the passed `pathArray` parameter (http://doc.babylonjs.com/how_to/How_to_dynamically_morph_a_mesh#tube)
* @returns a new Mesh
*/
static CreateTube(name: string, path: Vector3[], radius: number, tessellation: number, radiusFunction: {
(i: number, distance: number): number;
}, cap: number, scene: Scene, updatable?: boolean, sideOrientation?: number, instance?: Mesh): Mesh;
/**
* Creates a polyhedron mesh.
* Please consider using the same method from the MeshBuilder class instead.
* * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial to choose the wanted type
* * The parameter `size` (positive float, default 1) sets the polygon size
* * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
* * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`
* * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
* * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`)
* * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : https://doc.babylonjs.com/how_to/createbox_per_face_textures_and_colors
* * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored
* * You can also set the mesh side orientation with the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE
* * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
* * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
* @param name defines the name of the mesh to create
* @param options defines the options used to create the mesh
* @param scene defines the hosting scene
* @returns a new Mesh
*/
static CreatePolyhedron(name: string, options: {
type?: number;
size?: number;
sizeX?: number;
sizeY?: number;
sizeZ?: number;
custom?: any;
faceUV?: Vector4[];
faceColors?: Color4[];
updatable?: boolean;
sideOrientation?: number;
}, scene: Scene): Mesh;
/**
* Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
* * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
* * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`)
* * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
* * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface
* * You can also set the mesh side orientation with the values : Mesh.FRONTSIDE (default), Mesh.BACKSIDE or Mesh.DOUBLESIDE
* * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
* * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
* @param name defines the name of the mesh
* @param options defines the options used to create the mesh
* @param scene defines the hosting scene
* @returns a new Mesh
* @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
*/
static CreateIcoSphere(name: string, options: {
radius?: number;
flat?: boolean;
subdivisions?: number;
sideOrientation?: number;
updatable?: boolean;
}, scene: Scene): Mesh;
/**
* Creates a decal mesh.
* Please consider using the same method from the MeshBuilder class instead.
* A decal is a mesh usually applied as a model onto the surface of another mesh
* @param name defines the name of the mesh
* @param sourceMesh defines the mesh receiving the decal
* @param position sets the position of the decal in world coordinates
* @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
* @param size sets the decal scaling
* @param angle sets the angle to rotate the decal
* @returns a new Mesh
*/
static CreateDecal(name: string, sourceMesh: AbstractMesh, position: Vector3, normal: Vector3, size: Vector3, angle: number): Mesh;
/**
* Prepare internal position array for software CPU skinning
* @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
*/
setPositionsForCPUSkinning(): Float32Array;
/**
* Prepare internal normal array for software CPU skinning
* @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
*/
setNormalsForCPUSkinning(): Float32Array;
/**
* Updates the vertex buffer by applying transformation from the bones
* @param skeleton defines the skeleton to apply to current mesh
* @returns the current mesh
*/
applySkeleton(skeleton: Skeleton): Mesh;
/**
* Returns an object containing a min and max Vector3 which are the minimum and maximum vectors of each mesh bounding box from the passed array, in the world coordinates
* @param meshes defines the list of meshes to scan
* @returns an object `{min:` Vector3`, max:` Vector3`}`
*/
static MinMax(meshes: AbstractMesh[]): {
min: Vector3;
max: Vector3;
};
/**
* Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
* @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
* @returns a vector3
*/
static Center(meshesOrMinMaxVector: {
min: Vector3;
max: Vector3;
} | AbstractMesh[]): Vector3;
/**
* Merge the array of meshes into a single mesh for performance reasons.
* @param meshes defines he vertices source. They should all be of the same material. Entries can empty
* @param disposeSource when true (default), dispose of the vertices from the source meshes
* @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
* @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
* @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
* @param multiMultiMaterials when true (false default), subdivide mesh and accept multiple multi materials, ignores subdivideWithSubMeshes.
* @returns a new mesh
*/
static MergeMeshes(meshes: Array<Mesh>, disposeSource?: boolean, allow32BitsIndices?: boolean, meshSubclass?: Mesh, subdivideWithSubMeshes?: boolean, multiMultiMaterials?: boolean): Nullable<Mesh>;
/** @hidden */
addInstance(instance: InstancedMesh): void;
/** @hidden */
removeInstance(instance: InstancedMesh): void;
}
export class Vector3 {
/**
* Defines the first coordinates (on X axis)
*/
x: number;
/**
* Defines the second coordinates (on Y axis)
*/
y: number;
/**
* Defines the third coordinates (on Z axis)
*/
z: number;
private static _UpReadOnly;
private static _ZeroReadOnly;
/**
* Creates a new Vector3 object from the given x, y, z (floats) coordinates.
* @param x defines the first coordinates (on X axis)
* @param y defines the second coordinates (on Y axis)
* @param z defines the third coordinates (on Z axis)
*/
constructor(
/**
* Defines the first coordinates (on X axis)
*/
x?: number,
/**
* Defines the second coordinates (on Y axis)
*/
y?: number,
/**
* Defines the third coordinates (on Z axis)
*/
z?: number);
/**
* Creates a string representation of the Vector3
* @returns a string with the Vector3 coordinates.
*/
toString(): string;
/**
* Gets the class name
* @returns the string "Vector3"
*/
getClassName(): string;
/**
* Creates the Vector3 hash code
* @returns a number which tends to be unique between Vector3 instances
*/
getHashCode(): number;
/**
* Creates an array containing three elements : the coordinates of the Vector3
* @returns a new array of numbers
*/
asArray(): number[];
/**
* Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
* @param array defines the destination array
* @param index defines the offset in the destination array
* @returns the current Vector3
*/
toArray(array: FloatArray, index?: number): Vector3;
/**
* Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
* @returns a new Quaternion object, computed from the Vector3 coordinates
*/
toQuaternion(): Quaternion;
/**
* Adds the given vector to the current Vector3
* @param otherVector defines the second operand
* @returns the current updated Vector3
*/
addInPlace(otherVector: DeepImmutable<Vector3>): Vector3;
/**
* Adds the given coordinates to the current Vector3
* @param x defines the x coordinate of the operand
* @param y defines the y coordinate of the operand
* @param z defines the z coordinate of the operand
* @returns the current updated Vector3
*/
addInPlaceFromFloats(x: number, y: number, z: number): Vector3;
/**
* Gets a new Vector3, result of the addition the current Vector3 and the given vector
* @param otherVector defines the second operand
* @returns the resulting Vector3
*/
add(otherVector: DeepImmutable<Vector3>): Vector3;
/**
* Adds the current Vector3 to the given one and stores the result in the vector "result"
* @param otherVector defines the second operand
* @param result defines the Vector3 object where to store the result
* @returns the current Vector3
*/
addToRef(otherVector: DeepImmutable<Vector3>, result: Vector3): Vector3;
/**
* Subtract the given vector from the current Vector3
* @param otherVector defines the second operand
* @returns the current updated Vector3
*/
subtractInPlace(otherVector: DeepImmutable<Vector3>): Vector3;
/**
* Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
* @param otherVector defines the second operand
* @returns the resulting Vector3
*/
subtract(otherVector: DeepImmutable<Vector3>): Vector3;
/**
* Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
* @param otherVector defines the second operand
* @param result defines the Vector3 object where to store the result
* @returns the current Vector3
*/
subtractToRef(otherVector: DeepImmutable<Vector3>, result: Vector3): Vector3;
/**
* Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
* @param x defines the x coordinate of the operand
* @param y defines the y coordinate of the operand
* @param z defines the z coordinate of the operand
* @returns the resulting Vector3
*/
subtractFromFloats(x: number, y: number, z: number): Vector3;
/**
* Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
* @param x defines the x coordinate of the operand
* @param y defines the y coordinate of the operand
* @param z defines the z coordinate of the operand
* @param result defines the Vector3 object where to store the result
* @returns the current Vector3
*/
subtractFromFloatsToRef(x: number, y: number, z: number, result: Vector3): Vector3;
/**
* Gets a new Vector3 set with the current Vector3 negated coordinates
* @returns a new Vector3
*/
negate(): Vector3;
/**
* Negate this vector in place
* @returns this
*/
negateInPlace(): Vector3;
/**
* Negate the current Vector3 and stores the result in the given vector "result" coordinates
* @param result defines the Vector3 object where to store the result
* @returns the current Vector3
*/
negateToRef(result: Vector3): Vector3;
/**
* Multiplies the Vector3 coordinates by the float "scale"
* @param scale defines the multiplier factor
* @returns the current updated Vector3
*/
scaleInPlace(scale: number): Vector3;
/**
* Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
* @param scale defines the multiplier factor
* @returns a new Vector3
*/
scale(scale: number): Vector3;
/**
* Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
* @param scale defines the multiplier factor
* @param result defines the Vector3 object where to store the result
* @returns the current Vector3
*/
scaleToRef(scale: number, result: Vector3): Vector3;
/**
* Scale the current Vector3 values by a factor and add the result to a given Vector3
* @param scale defines the scale factor
* @param result defines the Vector3 object where to store the result
* @returns the unmodified current Vector3
*/
scaleAndAddToRef(scale: number, result: Vector3): Vector3;
/**
* Returns true if the current Vector3 and the given vector coordinates are strictly equal
* @param otherVector defines the second operand
* @returns true if both vectors are equals
*/
equals(otherVector: DeepImmutable<Vector3>): boolean;
/**
* Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
* @param otherVector defines the second operand
* @param epsilon defines the minimal distance to define values as equals
* @returns true if both vectors are distant less than epsilon
*/
equalsWithEpsilon(otherVector: DeepImmutable<Vector3>, epsilon?: number): boolean;
/**
* Returns true if the current Vector3 coordinates equals the given floats
* @param x defines the x coordinate of the operand
* @param y defines the y coordinate of the operand
* @param z defines the z coordinate of the operand
* @returns true if both vectors are equals
*/
equalsToFloats(x: number, y: number, z: number): boolean;
/**
* Multiplies the current Vector3 coordinates by the given ones
* @param otherVector defines the second operand
* @returns the current updated Vector3
*/
multiplyInPlace(otherVector: DeepImmutable<Vector3>): Vector3;
/**
* Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
* @param otherVector defines the second operand
* @returns the new Vector3
*/
multiply(otherVector: DeepImmutable<Vector3>): Vector3;
/**
* Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
* @param otherVector defines the second operand
* @param result defines the Vector3 object where to store the result
* @returns the current Vector3
*/
multiplyToRef(otherVector: DeepImmutable<Vector3>, result: Vector3): Vector3;
/**
* Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
* @param x defines the x coordinate of the operand
* @param y defines the y coordinate of the operand
* @param z defines the z coordinate of the operand
* @returns the new Vector3
*/
multiplyByFloats(x: number, y: number, z: number): Vector3;
/**
* Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
* @param otherVector defines the second operand
* @returns the new Vector3
*/
divide(otherVector: DeepImmutable<Vector3>): Vector3;
/**
* Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
* @param otherVector defines the second operand
* @param result defines the Vector3 object where to store the result
* @returns the current Vector3
*/
divideToRef(otherVector: DeepImmutable<Vector3>, result: Vector3): Vector3;
/**
* Divides the current Vector3 coordinates by the given ones.
* @param otherVector defines the second operand
* @returns the current updated Vector3
*/
divideInPlace(otherVector: Vector3): Vector3;
/**
* Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
* @param other defines the second operand
* @returns the current updated Vector3
*/
minimizeInPlace(other: DeepImmutable<Vector3>): Vector3;
/**
* Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
* @param other defines the second operand
* @returns the current updated Vector3
*/
maximizeInPlace(other: DeepImmutable<Vector3>): Vector3;
/**
* Updates the current Vector3 with the minimal coordinate values between its and the given coordinates
* @param x defines the x coordinate of the operand
* @param y defines the y coordinate of the operand
* @param z defines the z coordinate of the operand
* @returns the current updated Vector3
*/
minimizeInPlaceFromFloats(x: number, y: number, z: number): Vector3;
/**
* Updates the current Vector3 with the maximal coordinate values between its and the given coordinates.
* @param x defines the x coordinate of the operand
* @param y defines the y coordinate of the operand
* @param z defines the z coordinate of the operand
* @returns the current updated Vector3
*/
maximizeInPlaceFromFloats(x: number, y: number, z: number): Vector3;
/**
* Due to float precision, scale of a mesh could be uniform but float values are off by a small fraction
* Check if is non uniform within a certain amount of decimal places to account for this
* @param epsilon the amount the values can differ
* @returns if the the vector is non uniform to a certain number of decimal places
*/
isNonUniformWithinEpsilon(epsilon: number): boolean;
/**
* Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
*/
get isNonUniform(): boolean;
/**
* Gets a new Vector3 from current Vector3 floored values
* @returns a new Vector3
*/
floor(): Vector3;
/**
* Gets a new Vector3 from current Vector3 floored values
* @returns a new Vector3
*/
fract(): Vector3;
/**
* Gets the length of the Vector3
* @returns the length of the Vector3
*/
length(): number;
/**
* Gets the squared length of the Vector3
* @returns squared length of the Vector3
*/
lengthSquared(): number;
/**
* Normalize the current Vector3.
* Please note that this is an in place operation.
* @returns the current updated Vector3
*/
normalize(): Vector3;
/**
* Reorders the x y z properties of the vector in place
* @param order new ordering of the properties (eg. for vector 1,2,3 with "ZYX" will produce 3,2,1)
* @returns the current updated vector
*/
reorderInPlace(order: string): this;
/**
* Rotates the vector around 0,0,0 by a quaternion
* @param quaternion the rotation quaternion
* @param result vector to store the result
* @returns the resulting vector
*/
rotateByQuaternionToRef(quaternion: Quaternion, result: Vector3): Vector3;
/**
* Rotates a vector around a given point
* @param quaternion the rotation quaternion
* @param point the point to rotate around
* @param result vector to store the result
* @returns the resulting vector
*/
rotateByQuaternionAroundPointToRef(quaternion: Quaternion, point: Vector3, result: Vector3): Vector3;
/**
* Returns a new Vector3 as the cross product of the current vector and the "other" one
* The cross product is then orthogonal to both current and "other"
* @param other defines the right operand
* @returns the cross product
*/
cross(other: Vector3): Vector3;
/**
* Normalize the current Vector3 with the given input length.
* Please note that this is an in place operation.
* @param len the length of the vector
* @returns the current updated Vector3
*/
normalizeFromLength(len: number): Vector3;
/**
* Normalize the current Vector3 to a new vector
* @returns the new Vector3
*/
normalizeToNew(): Vector3;
/**
* Normalize the current Vector3 to the reference
* @param reference define the Vector3 to update
* @returns the updated Vector3
*/
normalizeToRef(reference: DeepImmutable<Vector3>): Vector3;
/**
* Creates a new Vector3 copied from the current Vector3
* @returns the new Vector3
*/
clone(): Vector3;
/**
* Copies the given vector coordinates to the current Vector3 ones
* @param source defines the source Vector3
* @returns the current updated Vector3
*/
copyFrom(source: DeepImmutable<Vector3>): Vector3;
/**
* Copies the given floats to the current Vector3 coordinates
* @param x defines the x coordinate of the operand
* @param y defines the y coordinate of the operand
* @param z defines the z coordinate of the operand
* @returns the current updated Vector3
*/
copyFromFloats(x: number, y: number, z: number): Vector3;
/**
* Copies the given floats to the current Vector3 coordinates
* @param x defines the x coordinate of the operand
* @param y defines the y coordinate of the operand
* @param z defines the z coordinate of the operand
* @returns the current updated Vector3
*/
set(x: number, y: number, z: number): Vector3;
/**
* Copies the given float to the current Vector3 coordinates
* @param v defines the x, y and z coordinates of the operand
* @returns the current updated Vector3
*/
setAll(v: number): Vector3;
/**
* Get the clip factor between two vectors
* @param vector0 defines the first operand
* @param vector1 defines the second operand
* @param axis defines the axis to use
* @param size defines the size along the axis
* @returns the clip factor
*/
static GetClipFactor(vector0: DeepImmutable<Vector3>, vector1: DeepImmutable<Vector3>, axis: DeepImmutable<Vector3>, size: number): number;
/**
* Get angle between two vectors
* @param vector0 angle between vector0 and vector1
* @param vector1 angle between vector0 and vector1
* @param normal direction of the normal
* @return the angle between vector0 and vector1
*/
static GetAngleBetweenVectors(vector0: DeepImmutable<Vector3>, vector1: DeepImmutable<Vector3>, normal: DeepImmutable<Vector3>): number;
/**
* Returns a new Vector3 set from the index "offset" of the given array
* @param array defines the source array
* @param offset defines the offset in the source array
* @returns the new Vector3
*/
static FromArray(array: DeepImmutable<ArrayLike<number>>, offset?: number): Vector3;
/**
* Returns a new Vector3 set from the index "offset" of the given Float32Array
* @param array defines the source array
* @param offset defines the offset in the source array
* @returns the new Vector3
* @deprecated Please use FromArray instead.
*/
static FromFloatArray(array: DeepImmutable<Float32Array>, offset?: number): Vector3;
/**
* Sets the given vector "result" with the element values from the index "offset" of the given array
* @param array defines the source array
* @param offset defines the offset in the source array
* @param result defines the Vector3 where to store the result
*/
static FromArrayToRef(array: DeepImmutable<ArrayLike<number>>, offset: number, result: Vector3): void;
/**
* Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
* @param array defines the source array
* @param offset defines the offset in the source array
* @param result defines the Vector3 where to store the result
* @deprecated Please use FromArrayToRef instead.
*/
static FromFloatArrayToRef(array: DeepImmutable<Float32Array>, offset: number, result: Vector3): void;
/**
* Sets the given vector "result" with the given floats.
* @param x defines the x coordinate of the source
* @param y defines the y coordinate of the source
* @param z defines the z coordinate of the source
* @param result defines the Vector3 where to store the result
*/
static FromFloatsToRef(x: number, y: number, z: number, result: Vector3): void;
/**
* Returns a new Vector3 set to (0.0, 0.0, 0.0)
* @returns a new empty Vector3
*/
static Zero(): Vector3;
/**
* Returns a new Vector3 set to (1.0, 1.0, 1.0)
* @returns a new unit Vector3
*/
static One(): Vector3;
/**
* Returns a new Vector3 set to (0.0, 1.0, 0.0)
* @returns a new up Vector3
*/
static Up(): Vector3;
/**
* Gets a up Vector3 that must not be updated
*/
static get UpReadOnly(): DeepImmutable<Vector3>;
/**
* Gets a zero Vector3 that must not be updated
*/
static get ZeroReadOnly(): DeepImmutable<Vector3>;
/**
* Returns a new Vector3 set to (0.0, -1.0, 0.0)
* @returns a new down Vector3
*/
static Down(): Vector3;
/**
* Returns a new Vector3 set to (0.0, 0.0, 1.0)
* @returns a new forward Vector3
*/
static Forward(): Vector3;
/**
* Returns a new Vector3 set to (0.0, 0.0, -1.0)
* @returns a new forward Vector3
*/
static Backward(): Vector3;
/**
* Returns a new Vector3 set to (1.0, 0.0, 0.0)
* @returns a new right Vector3
*/
static Right(): Vector3;
/**
* Returns a new Vector3 set to (-1.0, 0.0, 0.0)
* @returns a new left Vector3
*/
static Left(): Vector3;
/**
* Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
* This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
* @param vector defines the Vector3 to transform
* @param transformation defines the transformation matrix
* @returns the transformed Vector3
*/
static TransformCoordinates(vector: DeepImmutable<Vector3>, transformation: DeepImmutable<Matrix>): Vector3;
/**
* Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
* This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
* @param vector defines the Vector3 to transform
* @param transformation defines the transformation matrix
* @param result defines the Vector3 where to store the result
*/
static TransformCoordinatesToRef(vector: DeepImmutable<Vector3>, transformation: DeepImmutable<Matrix>, result: Vector3): void;
/**
* Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
* This method computes tranformed coordinates only, not transformed direction vectors
* @param x define the x coordinate of the source vector
* @param y define the y coordinate of the source vector
* @param z define the z coordinate of the source vector
* @param transformation defines the transformation matrix
* @param result defines the Vector3 where to store the result
*/
static TransformCoordinatesFromFloatsToRef(x: number, y: number, z: number, transformation: DeepImmutable<Matrix>, result: Vector3): void;
/**
* Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
* This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
* @param vector defines the Vector3 to transform
* @param transformation defines the transformation matrix
* @returns the new Vector3
*/
static TransformNormal(vector: DeepImmutable<Vector3>, transformation: DeepImmutable<Matrix>): Vector3;
/**
* Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
* This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
* @param vector defines the Vector3 to transform
* @param transformation defines the transformation matrix
* @param result defines the Vector3 where to store the result
*/
static TransformNormalToRef(vector: DeepImmutable<Vector3>, transformation: DeepImmutable<Matrix>, result: Vector3): void;
/**
* Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
* This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
* @param x define the x coordinate of the source vector
* @param y define the y coordinate of the source vector
* @param z define the z coordinate of the source vector
* @param transformation defines the transformation matrix
* @param result defines the Vector3 where to store the result
*/
static TransformNormalFromFloatsToRef(x: number, y: number, z: number, transformation: DeepImmutable<Matrix>, result: Vector3): void;
/**
* Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
* @param value1 defines the first control point
* @param value2 defines the second control point
* @param value3 defines the third control point
* @param value4 defines the fourth control point
* @param amount defines the amount on the spline to use
* @returns the new Vector3
*/
static CatmullRom(value1: DeepImmutable<Vector3>, value2: DeepImmutable<Vector3>, value3: DeepImmutable<Vector3>, value4: DeepImmutable<Vector3>, amount: number): Vector3;
/**
* Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
* If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
* If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
* @param value defines the current value
* @param min defines the lower range value
* @param max defines the upper range value
* @returns the new Vector3
*/
static Clamp(value: DeepImmutable<Vector3>, min: DeepImmutable<Vector3>, max: DeepImmutable<Vector3>): Vector3;
/**
* Sets the given vector "result" with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max"
* If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
* If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
* @param value defines the current value
* @param min defines the lower range value
* @param max defines the upper range value
* @param result defines the Vector3 where to store the result
*/
static ClampToRef(value: DeepImmutable<Vector3>, min: DeepImmutable<Vector3>, max: DeepImmutable<Vector3>, result: Vector3): void;
/**
* Checks if a given vector is inside a specific range
* @param v defines the vector to test
* @param min defines the minimum range
* @param max defines the maximum range
*/
static CheckExtends(v: Vector3, min: Vector3, max: Vector3): void;
/**
* Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
* @param value1 defines the first control point
* @param tangent1 defines the first tangent vector
* @param value2 defines the second control point
* @param tangent2 defines the second tangent vector
* @param amount defines the amount on the interpolation spline (between 0 and 1)
* @returns the new Vector3
*/
static Hermite(value1: DeepImmutable<Vector3>, tangent1: DeepImmutable<Vector3>, value2: DeepImmutable<Vector3>, tangent2: DeepImmutable<Vector3>, amount: number): Vector3;
/**
* Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
* @param start defines the start value
* @param end defines the end value
* @param amount max defines amount between both (between 0 and 1)
* @returns the new Vector3
*/
static Lerp(start: DeepImmutable<Vector3>, end: DeepImmutable<Vector3>, amount: number): Vector3;
/**
* Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
* @param start defines the start value
* @param end defines the end value
* @param amount max defines amount between both (between 0 and 1)
* @param result defines the Vector3 where to store the result
*/
static LerpToRef(start: DeepImmutable<Vector3>, end: DeepImmutable<Vector3>, amount: number, result: Vector3): void;
/**
* Returns the dot product (float) between the vectors "left" and "right"
* @param left defines the left operand
* @param right defines the right operand
* @returns the dot product
*/
static Dot(left: DeepImmutable<Vector3>, right: DeepImmutable<Vector3>): number;
/**
* Returns a new Vector3 as the cross product of the vectors "left" and "right"
* The cross product is then orthogonal to both "left" and "right"
* @param left defines the left operand
* @param right defines the right operand
* @returns the cross product
*/
static Cross(left: DeepImmutable<Vector3>, right: DeepImmutable<Vector3>): Vector3;
/**
* Sets the given vector "result" with the cross product of "left" and "right"
* The cross product is then orthogonal to both "left" and "right"
* @param left defines the left operand
* @param right defines the right operand
* @param result defines the Vector3 where to store the result
*/
static CrossToRef(left: Vector3, right: Vector3, result: Vector3): void;
/**
* Returns a new Vector3 as the normalization of the given vector
* @param vector defines the Vector3 to normalize
* @returns the new Vector3
*/
static Normalize(vector: DeepImmutable<Vector3>): Vector3;
/**
* Sets the given vector "result" with the normalization of the given first vector
* @param vector defines the Vector3 to normalize
* @param result defines the Vector3 where to store the result
*/
static NormalizeToRef(vector: DeepImmutable<Vector3>, result: Vector3): void;
/**
* Project a Vector3 onto screen space
* @param vector defines the Vector3 to project
* @param world defines the world matrix to use
* @param transform defines the transform (view x projection) matrix to use
* @param viewport defines the screen viewport to use
* @returns the new Vector3
*/
static Project(vector: DeepImmutable<Vector3>, world: DeepImmutable<Matrix>, transform: DeepImmutable<Matrix>, viewport: DeepImmutable<Viewport>): Vector3;
/** @hidden */
static _UnprojectFromInvertedMatrixToRef(source: DeepImmutable<Vector3>, matrix: DeepImmutable<Matrix>, result: Vector3): void;
/**
* Unproject from screen space to object space
* @param source defines the screen space Vector3 to use
* @param viewportWidth defines the current width of the viewport
* @param viewportHeight defines the current height of the viewport
* @param world defines the world matrix to use (can be set to Identity to go to world space)
* @param transform defines the transform (view x projection) matrix to use
* @returns the new Vector3
*/
static UnprojectFromTransform(source: Vector3, viewportWidth: number, viewportHeight: number, world: DeepImmutable<Matrix>, transform: DeepImmutable<Matrix>): Vector3;
/**
* Unproject from screen space to object space
* @param source defines the screen space Vector3 to use
* @param viewportWidth defines the current width of the viewport
* @param viewportHeight defines the current height of the viewport
* @param world defines the world matrix to use (can be set to Identity to go to world space)
* @param view defines the view matrix to use
* @param projection defines the projection matrix to use
* @returns the new Vector3
*/
static Unproject(source: DeepImmutable<Vector3>, viewportWidth: number, viewportHeight: number, world: DeepImmutable<Matrix>, view: DeepImmutable<Matrix>, projection: DeepImmutable<Matrix>): Vector3;
/**
* Unproject from screen space to object space
* @param source defines the screen space Vector3 to use
* @param viewportWidth defines the current width of the viewport
* @param viewportHeight defines the current height of the viewport
* @param world defines the world matrix to use (can be set to Identity to go to world space)
* @param view defines the view matrix to use
* @param projection defines the projection matrix to use
* @param result defines the Vector3 where to store the result
*/
static UnprojectToRef(source: DeepImmutable<Vector3>, viewportWidth: number, viewportHeight: number, world: DeepImmutable<Matrix>, view: DeepImmutable<Matrix>, projection: DeepImmutable<Matrix>, result: Vector3): void;
/**
* Unproject from screen space to object space
* @param sourceX defines the screen space x coordinate to use
* @param sourceY defines the screen space y coordinate to use
* @param sourceZ defines the screen space z coordinate to use
* @param viewportWidth defines the current width of the viewport
* @param viewportHeight defines the current height of the viewport
* @param world defines the world matrix to use (can be set to Identity to go to world space)
* @param view defines the view matrix to use
* @param projection defines the projection matrix to use
* @param result defines the Vector3 where to store the result
*/
static UnprojectFloatsToRef(sourceX: float, sourceY: float, sourceZ: float, viewportWidth: number, viewportHeight: number, world: DeepImmutable<Matrix>, view: DeepImmutable<Matrix>, projection: DeepImmutable<Matrix>, result: Vector3): void;
/**
* Gets the minimal coordinate values between two Vector3
* @param left defines the first operand
* @param right defines the second operand
* @returns the new Vector3
*/
static Minimize(left: DeepImmutable<Vector3>, right: DeepImmutable<Vector3>): Vector3;
/**
* Gets the maximal coordinate values between two Vector3
* @param left defines the first operand
* @param right defines the second operand
* @returns the new Vector3
*/
static Maximize(left: DeepImmutable<Vector3>, right: DeepImmutable<Vector3>): Vector3;
/**
* Returns the distance between the vectors "value1" and "value2"
* @param value1 defines the first operand
* @param value2 defines the second operand
* @returns the distance
*/
static Distance(value1: DeepImmutable<Vector3>, value2: DeepImmutable<Vector3>): number;
/**
* Returns the squared distance between the vectors "value1" and "value2"
* @param value1 defines the first operand
* @param value2 defines the second operand
* @returns the squared distance
*/
static DistanceSquared(value1: DeepImmutable<Vector3>, value2: DeepImmutable<Vector3>): number;
/**
* Returns a new Vector3 located at the center between "value1" and "value2"
* @param value1 defines the first operand
* @param value2 defines the second operand
* @returns the new Vector3
*/
static Center(value1: DeepImmutable<Vector3>, value2: DeepImmutable<Vector3>): Vector3;
/**
* Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
* RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
* to something in order to rotate it from its local system to the given target system
* Note: axis1, axis2 and axis3 are normalized during this operation
* @param axis1 defines the first axis
* @param axis2 defines the second axis
* @param axis3 defines the third axis
* @returns a new Vector3
*/
static RotationFromAxis(axis1: DeepImmutable<Vector3>, axis2: DeepImmutable<Vector3>, axis3: DeepImmutable<Vector3>): Vector3;
/**
* The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
* @param axis1 defines the first axis
* @param axis2 defines the second axis
* @param axis3 defines the third axis
* @param ref defines the Vector3 where to store the result
*/
static RotationFromAxisToRef(axis1: DeepImmutable<Vector3>, axis2: DeepImmutable<Vector3>, axis3: DeepImmutable<Vector3>, ref: Vector3): void;
}
} | the_stack |
import {IInputTsccSpecJSON, ITsccSpecJSON, closureCompilerFlags, TsccSpec, TsccSpecError} from '@tscc/tscc-spec';
import * as ts from 'typescript';
import ITsccSpecWithTS from './ITsccSpecWithTS';
import path = require('path');
export class TsError extends Error {
constructor(
public diagnostics: ReadonlyArray<ts.Diagnostic>
) {
super(ts.formatDiagnostics(diagnostics, ts.createCompilerHost({})));
}
}
type TWarningCallback = (msg: string) => void;
export default class TsccSpecWithTS extends TsccSpec implements ITsccSpecWithTS {
static loadTsConfigFromArgs(tsArgs: string[], specRoot: string, onWarning: TWarningCallback) {
const {options, fileNames, errors} = ts.parseCommandLine(tsArgs);
if (errors.length) {
throw new TsError(errors);
}
if (fileNames.length) {
onWarning(`Files provided via TS args are ignored.`);
}
// If "--project" argument is supplied - load tsconfig from there, merge things with this.
// Otherwise, we lookup from tsccSpecPath - this is what is different to "tsc" (which looks up
// the current working directory).
// I think this is a more reasonable behavior, since many users will just put spec.json and
// tsconfig.json at the same directory, they will otherwise have to provide the same information
// twice, once for tscc and once for tsc.
const configFileName = TsccSpecWithTS.findConfigFileAndThrow(options.project, specRoot);
return TsccSpecWithTS.loadTsConfigFromResolvedPath(configFileName, options);
}
// compilerOptions is a JSON object in the form of tsconfig.json's compilerOption value.
// Its value will override compiler options.
static loadTsConfigFromPath(tsConfigPath?: string, specRoot?: string, compilerOptions?: object) {
const configFileName = TsccSpecWithTS.findConfigFileAndThrow(tsConfigPath, specRoot);
let options: ts.CompilerOptions = {}, errors: ts.Diagnostic[];
if (compilerOptions) {
({options, errors} = ts.convertCompilerOptionsFromJson(
compilerOptions, path.dirname(configFileName)
));
if (errors.length) {
throw new TsError(errors);
}
}
return TsccSpecWithTS.loadTsConfigFromResolvedPath(configFileName, options);
}
// At least one among searchPath and defaultLocation must be non-null.
private static findConfigFileAndThrow(searchPath?: string, defaultLocation?: string) {
const configFileName =
TsccSpecWithTS.resolveSpecFile(searchPath, 'tsconfig.json', defaultLocation);
if (configFileName === undefined) {
throw new TsccSpecError(
`Cannot find tsconfig at ${TsccSpecWithTS.toDisplayedPath(searchPath ?? defaultLocation!)}.`
)
}
return configFileName;
}
private static loadTsConfigFromResolvedPath(configFileName: string, options: ts.CompilerOptions) {
const compilerHost: ts.ParseConfigFileHost = Object.create(ts.sys);
compilerHost.onUnRecoverableConfigFileDiagnostic = (diagnostic) => {throw new TsError([diagnostic]);}
const parsedConfig = ts.getParsedCommandLineOfConfigFile(configFileName, options, compilerHost)!;
if (parsedConfig.errors.length) {
throw new TsError(parsedConfig!.errors);
}
const projectRoot = path.dirname(configFileName);
return {projectRoot, parsedConfig};
}
static loadSpecWithTS(
tsccSpecJSONOrItsPath: string | IInputTsccSpecJSON,
tsConfigPathOrTsArgs?: string | string[],
compilerOptionsOverride?: object,
onTsccWarning: (msg: string) => void = noop
) {
// When TS project root is not provided, it will be assumed to be the location of tscc spec file.
let {tsccSpecJSON, tsccSpecJSONPath} = TsccSpecWithTS.loadSpecRaw(tsccSpecJSONOrItsPath);
let specRoot = path.dirname(tsccSpecJSONPath);
let {projectRoot, parsedConfig} = Array.isArray(tsConfigPathOrTsArgs) ?
TsccSpecWithTS.loadTsConfigFromArgs(tsConfigPathOrTsArgs, specRoot, onTsccWarning) :
TsccSpecWithTS.loadTsConfigFromPath(tsConfigPathOrTsArgs, specRoot, compilerOptionsOverride);
TsccSpecWithTS.pruneCompilerOptions(parsedConfig.options, onTsccWarning);
return new TsccSpecWithTS(tsccSpecJSON, tsccSpecJSONPath, parsedConfig, projectRoot);
}
/**
* Prune compiler options
* - "module" to "commonjs"
* - Get values of outDir, strip it, and pass it to closure compiler
* - Warn when rootDir is used - it is of no use.
*/
private static pruneCompilerOptions(options: ts.CompilerOptions, onWarning: TWarningCallback) {
if (options.module !== ts.ModuleKind.CommonJS) {
onWarning(`tsickle converts TypeScript modules to Closure modules via CommonJS internally.`
+ `"module" flag is overridden to "commonjs".`);
options.module = ts.ModuleKind.CommonJS;
}
if (options.outDir) {
onWarning(`--outDir option is ignored. Use prefix option in the spec file.`);
options.outDir = undefined;
}
/**
* {@link https://github.com/angular/tsickle/commit/2050e902ea0fa59aa36f414cab192155167a9b06}
* tsickle throws if `rootDir` is not provided, for presumably "internal" reasons. In tscc,
* it normalizes paths to absolute paths, so the presence of `rootDir` does not have any
* visible effect. If it is not supplied, we provide a default value of the config file's
* containing root directory. Note that ts.CompilerOptions.configFilePath is an internal
* property.
*/
const {configFilePath} = options;
const rootDir = configFilePath ? path.parse(configFilePath as string).root : '/';
if (options.rootDir) {
onWarning(`--rootDir option is ignored. It will internally set to ${rootDir}.`);
}
options.rootDir = rootDir;
if (!options.importHelpers) {
onWarning(`tsickle uses a custom tslib optimized for closure compiler. importHelpers flag is set.`);
options.importHelpers = true;
}
if (options.removeComments) {
onWarning(`Closure compiler relies on type annotations, removeComments flag is unset.`);
options.removeComments = false;
}
if (options.inlineSourceMap) {
onWarning(`Inlining sourcemap is not supported. inlineSourceMap flag is unset.`);
options.inlineSourceMap = false;
// inlineSource option depends on sourceMap or inlineSourceMap being enabled
// so enabling sourceMap in order not to break tsc.
options.sourceMap = true;
}
if (options.incremental) {
// Incremental compilation produces an additional .tsbuildinfo file. This triggers
// unrecognized file extension error, so we disable it.
// Currently I'm not sure that among typescript and closure compiler, which impacts the
// compilation time more. If it is closure compiler, there would not be much sense to
// support incremental compilation, for closure compiler does not support it. Otherwise,
// I may try to attempt implementing it. To do so, we have to write intermediate output
// like what we do with --debug.persistArtifacts.
onWarning(`Incremental compilation is not supported. incremental flag is unset.`);
options.incremental = false;
}
if (options.declaration) {
// silently unset declaration flag
options.declaration = false;
}
}
private tsCompilerHost: ts.CompilerHost = ts.createCompilerHost(this.parsedConfig.options);
constructor(
tsccSpec: ITsccSpecJSON,
basePath: string,
private parsedConfig: ts.ParsedCommandLine,
private projectRoot: string
) {
super(tsccSpec, basePath);
this.validateSpec();
}
protected validateSpec() {
// Checks that each of entry files is provided in tsConfig.
const fileNames = this.getAbsoluteFileNamesSet();
const modules = this.getOrderedModuleSpecs();
for (let module of modules) {
if (!fileNames.has(module.entry)) {
throw new TsccSpecError(
`An entry file ${module.entry} is not provided ` +
`in a typescript project ${this.projectRoot}.`
)
}
}
}
getTSRoot() {
return this.projectRoot;
}
getCompilerOptions() {
return this.parsedConfig.options;
}
getCompilerHost() {
return this.tsCompilerHost;
}
private static readonly tsTargetToCcTarget = {
[ts.ScriptTarget.ES3]: "ECMASCRIPT3",
[ts.ScriptTarget.ES5]: "ECMASCRIPT5_STRICT",
[ts.ScriptTarget.ES2015]: "ECMASCRIPT_2015",
[ts.ScriptTarget.ES2016]: "ECMASCRIPT_2016",
[ts.ScriptTarget.ES2017]: "ECMASCRIPT_2017",
[ts.ScriptTarget.ES2018]: "ECMASCRIPT_2018",
[ts.ScriptTarget.ES2019]: "ECMASCRIPT_2019",
[ts.ScriptTarget.ES2020]: "ECMASCRIPT_2020",
[ts.ScriptTarget.ES2021]: "ECMASCRIPT_2021",
[ts.ScriptTarget.ESNext]: "ECMASCRIPT_NEXT"
}
getOutputFileNames(): string[] {
return this.getOrderedModuleSpecs()
.map(moduleSpec => {
const {moduleName} = moduleSpec;
return this.absolute(this.getOutputPrefix('cc')) + moduleName + '.js';
});
}
private getDefaultFlags(): closureCompilerFlags {
// Typescript accepts an undocumented compilation target "json".
type DocumentedCompilerOptions = ts.CompilerOptions & {
target: Exclude<ts.ScriptTarget, ts.ScriptTarget.JSON>
}
let {target, sourceMap, inlineSources} = this.parsedConfig.options as DocumentedCompilerOptions;
const defaultFlags: closureCompilerFlags = {};
defaultFlags["language_in"] = TsccSpecWithTS.tsTargetToCcTarget[
typeof target === 'undefined' ? ts.ScriptTarget.ES3 : target
]; // ts default value is ES3.
defaultFlags["language_out"] = "ECMASCRIPT5";
defaultFlags["compilation_level"] = "ADVANCED";
if (this.getOrderedModuleSpecs().length > 1) {
// Multi-chunk build uses --chunk and --chunk_output_path_prefix.
// This path will appear in a sourcemap that closure compiler generates - need to use
// relative path in order not to leak global directory structure.
defaultFlags["chunk_output_path_prefix"] = this.relativeFromCwd(this.getOutputPrefix('cc'));
} else {
// Single-chunk build uses --js_output_file.
defaultFlags["js_output_file"] =
this.relativeFromCwd(this.getOutputPrefix('cc')) +
this.getOrderedModuleSpecs()[0].moduleName + '.js';
}
defaultFlags["generate_exports"] = true;
defaultFlags["export_local_property_definitions"] = true;
if (sourceMap) {
defaultFlags["create_source_map"] = "%outname%.map";
defaultFlags["apply_input_source_maps"] = true;
}
if (inlineSources) {
defaultFlags["source_map_include_content"] = true;
}
return defaultFlags;
}
getBaseCompilerFlags() {
const baseFlags = this.tsccSpec.compilerFlags || {};
const defaultFlags = this.getDefaultFlags();
const flagsMap = Object.assign(defaultFlags, baseFlags);
const outFlags: string[] = [];
const pushFlag = (key: string, value: string | number | boolean) => {
if (typeof value === 'boolean') {
if (value === true) outFlags.push('--' + key);
} else {
outFlags.push('--' + key, String(value));
}
}
for (let [key, value] of Object.entries(flagsMap)) {
if (Array.isArray(value)) {
for (let val of value) {
pushFlag(key, val);
}
} else {
pushFlag(key, value);
}
}
return outFlags;
}
getAbsoluteFileNamesSet() {
return new Set(
this.parsedConfig.fileNames
.map(fileName => path.resolve(this.projectRoot, fileName))
);
}
resolveExternalModuleTypeReference(moduleName: string) {
const resolved = ts.resolveTypeReferenceDirective(
moduleName,
// Following convention of Typescript source code
path.join(this.projectRoot, '__inferred type names__.ts'),
this.getCompilerOptions(),
this.getCompilerHost()
);
if (resolved && resolved.resolvedTypeReferenceDirective &&
resolved.resolvedTypeReferenceDirective.isExternalLibraryImport) {
return resolved.resolvedTypeReferenceDirective.resolvedFileName ?? null;
}
return null;
}
getProjectHash(): string {
return require('crypto').createHash('sha256')
.update(
this.basePath + JSON.stringify(this.tsccSpec) +
this.projectRoot + JSON.stringify(this.parsedConfig.options)
)
.digest('hex');
}
}
function noop() {} | the_stack |
import type {Mutable, ObserverType} from "@swim/util";
import type {FastenerOwner} from "@swim/component";
import type {Trait, TraitRef} from "@swim/model";
import type {Controller} from "../controller/Controller";
import {ControllerSetInit, ControllerSetClass, ControllerSet} from "../controller/ControllerSet";
/** @internal */
export type TraitControllerSetType<F extends TraitControllerSet<any, any, any>> =
F extends TraitControllerSet<any, any, infer C> ? C : never;
/** @public */
export interface TraitControllerSetInit<T extends Trait = Trait, C extends Controller = Controller> extends ControllerSetInit<C> {
extends?: {prototype: TraitControllerSet<any, any, any>} | string | boolean | null;
getTraitRef?(controller: C): TraitRef<any, T>;
willAttachControllerTrait?(controller: C, trait: T, targetTrait: Trait | null): void;
didAttachControllerTrait?(controller: C, trait: T, targetTrait: Trait | null): void;
willDetachControllerTrait?(controller: C, trait: T): void;
didDetachControllerTrait?(controller: C, trait: T): void;
createController?(trait?: T): C;
}
/** @public */
export type TraitControllerSetDescriptor<O = unknown, T extends Trait = Trait, C extends Controller = Controller, I = {}> = ThisType<TraitControllerSet<O, T, C> & I> & TraitControllerSetInit<T, C> & Partial<I>;
/** @public */
export interface TraitControllerSetClass<F extends TraitControllerSet<any, any, any> = TraitControllerSet<any, any, any>> extends ControllerSetClass<F> {
}
/** @public */
export interface TraitControllerSetFactory<F extends TraitControllerSet<any, any, any> = TraitControllerSet<any, any, any>> extends TraitControllerSetClass<F> {
extend<I = {}>(className: string, classMembers?: Partial<I> | null): TraitControllerSetFactory<F> & I;
define<O, T extends Trait = Trait, C extends Controller = Controller>(className: string, descriptor: TraitControllerSetDescriptor<O, T, C>): TraitControllerSetFactory<TraitControllerSet<any, T, C>>;
define<O, T extends Trait = Trait, C extends Controller = Controller>(className: string, descriptor: {observes: boolean} & TraitControllerSetDescriptor<O, T, C, ObserverType<C>>): TraitControllerSetFactory<TraitControllerSet<any, T, C>>;
define<O, T extends Trait = Trait, C extends Controller = Controller, I = {}>(className: string, descriptor: {implements: unknown} & TraitControllerSetDescriptor<O, T, C, I>): TraitControllerSetFactory<TraitControllerSet<any, T, C> & I>;
define<O, T extends Trait = Trait, C extends Controller = Controller, I = {}>(className: string, descriptor: {implements: unknown; observes: boolean} & TraitControllerSetDescriptor<O, T, C, I & ObserverType<C>>): TraitControllerSetFactory<TraitControllerSet<any, T, C> & I>;
<O, T extends Trait = Trait, C extends Controller = Controller>(descriptor: TraitControllerSetDescriptor<O, T, C>): PropertyDecorator;
<O, T extends Trait = Trait, C extends Controller = Controller>(descriptor: {observes: boolean} & TraitControllerSetDescriptor<O, T, C, ObserverType<C>>): PropertyDecorator;
<O, T extends Trait = Trait, C extends Controller = Controller, I = {}>(descriptor: {implements: unknown} & TraitControllerSetDescriptor<O, T, C, I>): PropertyDecorator;
<O, T extends Trait = Trait, C extends Controller = Controller, I = {}>(descriptor: {implements: unknown; observes: boolean} & TraitControllerSetDescriptor<O, T, C, I & ObserverType<C>>): PropertyDecorator;
}
/** @public */
export interface TraitControllerSet<O = unknown, T extends Trait = Trait, C extends Controller = Controller> extends ControllerSet<O, C> {
/** @internal */
readonly traitControllers: {readonly [traitId: number]: C | undefined};
/** @internal */
getTraitRef(controller: C): TraitRef<unknown, T>;
hasTraitController(trait: Trait): boolean;
addTraitController(trait: T, targetTrait?: Trait | null, key?: string): C;
removeTraitController(trait: T): C | null;
deleteTraitController(trait: T): C | null;
attachControllerTrait(controller: C, trait: T, targetTrait?: Trait | null): C;
/** @protected */
initControllerTrait(controller: C, trait: T): void;
/** @protected */
willAttachControllerTrait(controller: C, trait: T, targetTrait: Trait | null): void;
/** @protected */
onAttachControllerTrait(controller: C, trait: T, targetTrait: Trait | null): void;
/** @protected */
didAttachControllerTrait(controller: C, trait: T, targetTrait: Trait | null): void;
detachControllerTrait(controller: C, trait: T): C | null;
/** @protected */
deinitControllerTrait(controller: C, trait: T): void;
/** @protected */
willDetachControllerTrait(controller: C, trait: T): void;
/** @protected */
onDetachControllerTrait(controller: C, trait: T): void;
/** @protected */
didDetachControllerTrait(controller: C, trait: T): void;
/** @protected @override */
onAttachController(controller: C, targetController: Controller | null): void;
/** @protected @override */
onDetachController(controller: C): void;
createController(trait?: T): C;
}
/** @public */
export const TraitControllerSet = (function (_super: typeof ControllerSet) {
const TraitControllerSet: TraitControllerSetFactory = _super.extend("TraitControllerSet");
TraitControllerSet.prototype.getTraitRef = function <T extends Trait, C extends Controller>(controller: C): TraitRef<unknown, T> {
throw new Error("missing implementation");
};
TraitControllerSet.prototype.hasTraitController = function (this: TraitControllerSet, trait: Trait): boolean {
return this.traitControllers[trait.uid] !== void 0;
};
TraitControllerSet.prototype.addTraitController = function <T extends Trait, C extends Controller>(this: TraitControllerSet<unknown, T, C>, trait: T, targetTrait?: Trait | null, key?: string): C {
const traitControllers = this.traitControllers as {[traitId: number]: C | undefined};
let controller = traitControllers[trait.uid];
if (controller === void 0) {
controller = this.createController(trait);
const traitRef = this.getTraitRef(controller);
traitRef.setTrait(trait, targetTrait, key);
const targetController = targetTrait !== void 0 && targetTrait !== null ? traitControllers[targetTrait.uid] : void 0;
this.addController(controller, targetController, key);
}
return controller;
};
TraitControllerSet.prototype.removeTraitController = function <T extends Trait, C extends Controller>(this: TraitControllerSet<unknown, T, C>, trait: T): C | null {
const controllers = this.controllers;
for (const controllerId in controllers) {
const controller = controllers[controllerId]!;
const traitRef = this.getTraitRef(controller);
if (traitRef.trait === trait) {
this.removeController(controller);
return controller;
}
}
return null;
};
TraitControllerSet.prototype.deleteTraitController = function <T extends Trait, C extends Controller>(this: TraitControllerSet<unknown, T, C>, trait: T): C | null {
const controllers = this.controllers;
for (const controllerId in controllers) {
const controller = controllers[controllerId]!;
const traitRef = this.getTraitRef(controller);
if (traitRef.trait === trait) {
this.deleteController(controller);
return controller;
}
}
return null;
};
TraitControllerSet.prototype.attachControllerTrait = function <T extends Trait, C extends Controller>(this: TraitControllerSet<unknown, T, C>, controller: C, trait: T, targetTrait?: Trait | null): C {
const traitControllers = this.traitControllers as {[traitId: number]: C | undefined};
let traitController = traitControllers[trait.uid];
if (traitController === void 0) {
traitController = controller;
if (targetTrait === void 0) {
targetTrait = null;
}
this.willAttachControllerTrait(traitController, trait, targetTrait);
traitControllers[trait.uid] = traitController;
(this as Mutable<typeof this>).controllerCount += 1;
this.onAttachControllerTrait(traitController, trait, targetTrait);
this.initControllerTrait(traitController, trait);
this.didAttachControllerTrait(traitController, trait, targetTrait);
}
return traitController;
};
TraitControllerSet.prototype.detachControllerTrait = function <T extends Trait, C extends Controller>(this: TraitControllerSet<unknown, T, C>, controller: C, trait: T): C | null {
const traitControllers = this.traitControllers as {[comtroltraitIdltraitIderId: number]: C | undefined};
const traitController = traitControllers[trait.uid];
if (traitController !== void 0) {
this.willDetachControllerTrait(traitController, trait);
(this as Mutable<typeof this>).controllerCount -= 1;
delete traitControllers[trait.uid];
this.onDetachControllerTrait(traitController, trait);
this.deinitControllerTrait(traitController, trait);
this.didDetachControllerTrait(traitController, trait);
return traitController;
}
return null;
};
TraitControllerSet.prototype.initControllerTrait = function <T extends Trait, C extends Controller>(this: TraitControllerSet<unknown, T, C>, controller: C, trait: T): void {
// hook
};
TraitControllerSet.prototype.willAttachControllerTrait = function <T extends Trait, C extends Controller>(this: TraitControllerSet<unknown, T, C>, controller: C, trait: T, targetTrait: Trait | null): void {
// hook
};
TraitControllerSet.prototype.onAttachControllerTrait = function <T extends Trait, C extends Controller>(this: TraitControllerSet<unknown, T, C>, controller: C, trait: T, targetTrait: Trait | null): void {
// hook
};
TraitControllerSet.prototype.didAttachControllerTrait = function <T extends Trait, C extends Controller>(this: TraitControllerSet<unknown, T, C>, controller: C, trait: T, targetTrait: Trait | null): void {
// hook
};
TraitControllerSet.prototype.deinitControllerTrait = function <T extends Trait, C extends Controller>(this: TraitControllerSet<unknown, T, C>, controller: C, trait: T): void {
// hook
};
TraitControllerSet.prototype.willDetachControllerTrait = function <T extends Trait, C extends Controller>(this: TraitControllerSet<unknown, T, C>, controller: C, trait: T): void {
// hook
};
TraitControllerSet.prototype.onDetachControllerTrait = function <T extends Trait, C extends Controller>(this: TraitControllerSet<unknown, T, C>, controller: C, trait: T): void {
// hook
};
TraitControllerSet.prototype.didDetachControllerTrait = function <T extends Trait, C extends Controller>(this: TraitControllerSet<unknown, T, C>, controller: C, trait: T): void {
// hook
};
TraitControllerSet.prototype.onAttachController = function <T extends Trait, C extends Controller>(this: TraitControllerSet<unknown, T, C>, controller: C, targetController: Controller | null): void {
const trait = this.getTraitRef(controller).trait;
if (trait !== null) {
const targetTrait = targetController !== null && this.hasController(targetController) ? this.getTraitRef(targetController as C).trait : null;
this.attachControllerTrait(controller, trait, targetTrait);
}
ControllerSet.prototype.onAttachController.call(this, controller, targetController);
};
TraitControllerSet.prototype.onDetachController = function <T extends Trait, C extends Controller>(this: TraitControllerSet<unknown, T, C>, controller: C): void {
ControllerSet.prototype.onDetachController.call(this, controller);
const trait = this.getTraitRef(controller).trait;
if (trait !== null) {
this.detachControllerTrait(controller, trait);
}
};
TraitControllerSet.construct = function <F extends TraitControllerSet<any, any, any>>(fastenerClass: {prototype: F}, fastener: F | null, owner: FastenerOwner<F>): F {
fastener = _super.construct(fastenerClass, fastener, owner) as F;
(fastener as Mutable<typeof fastener>).traitControllers = {};
return fastener;
};
TraitControllerSet.define = function <O, T extends Trait, C extends Controller>(className: string, descriptor: TraitControllerSetDescriptor<O, T, C>): TraitControllerSetFactory<TraitControllerSet<any, T, C>> {
let superClass = descriptor.extends as TraitControllerSetFactory | null | undefined;
const affinity = descriptor.affinity;
const inherits = descriptor.inherits;
const sorted = descriptor.sorted;
delete descriptor.extends;
delete descriptor.implements;
delete descriptor.affinity;
delete descriptor.inherits;
delete descriptor.sorted;
if (superClass === void 0 || superClass === null) {
superClass = this;
}
const fastenerClass = superClass.extend(className, descriptor);
fastenerClass.construct = function (fastenerClass: {prototype: TraitControllerSet<any, any, any>}, fastener: TraitControllerSet<O, T, C> | null, owner: O): TraitControllerSet<O, T, C> {
fastener = superClass!.construct(fastenerClass, fastener, owner);
if (affinity !== void 0) {
fastener.initAffinity(affinity);
}
if (inherits !== void 0) {
fastener.initInherits(inherits);
}
if (sorted !== void 0) {
fastener.initSorted(sorted);
}
return fastener;
};
return fastenerClass;
};
return TraitControllerSet;
})(ControllerSet); | the_stack |
import React, { useEffect, useCallback } from 'react'
import cn from 'classnames'
import { connect } from 'react-redux'
import { animated } from 'react-spring'
import { Transition } from 'react-spring/renderprops'
import { Dispatch } from 'redux'
import { ID } from 'common/models/Identifiers'
import { User } from 'common/models/User'
import { InstagramProfile } from 'common/store/account/reducer'
import MobilePageContainer from 'components/general/MobilePageContainer'
import * as settingPageActions from 'containers/settings-page/store/actions'
import { PushNotificationSetting } from 'containers/settings-page/store/types'
import FollowPage, {
BottomSection as FollowPageBottom
} from 'containers/sign-on/components/mobile/FollowPage'
import Header from 'containers/sign-on/components/mobile/Header'
import InitialPage from 'containers/sign-on/components/mobile/InitialPage'
import NotificationPermissionsPage from 'containers/sign-on/components/mobile/NotificationPermissionsPage'
import PasswordPage from 'containers/sign-on/components/mobile/PasswordPage'
import ProfilePage from 'containers/sign-on/components/mobile/ProfilePage'
import { Pages, FollowArtistsCategory } from 'containers/sign-on/store/types'
import { PromptPushNotificationPermissions } from 'services/native-mobile-interface/notifications'
import { BASE_URL, SIGN_UP_PAGE } from 'utils/route'
import LoadingPage from './LoadingPage'
import styles from './SignOnPage.module.css'
const NATIVE_MOBILE = process.env.REACT_APP_NATIVE_MOBILE
export type SignOnProps = {
title: string
description: string
page: MobilePages
signIn: boolean
hasAccount: boolean
initialPage: boolean
showMetaMaskOption: boolean
metaMaskModalOpen: boolean
hasOpened: boolean
fields: any
onSignIn: (email: string, password: string) => void
onMetaMaskSignIn: () => void
onViewSignUp: () => void
onViewSignIn: () => void
onEmailChange: (email: string, validate?: boolean) => void
onEmailSubmitted: (email: string) => void
onPasswordChange: (password: string) => void
onHandleChange: (handle: string) => void
onNameChange: (name: string) => void
onSetProfileImage: (img: any) => void
setTwitterProfile: (
uuid: string,
profile: any,
profileImg?: { url: string; file: any },
coverBannerImg?: { url: string; file: any },
skipEdit?: boolean
) => void
setInstagramProfile: (
uuid: string,
profile: InstagramProfile,
profileImg?: { url: string; file: any },
skipEdit?: boolean
) => void
recordInstagramStart: () => void
recordTwitterStart: () => void
validateHandle: (
handle: string,
isOauthVerified: boolean,
onValidate?: (error: boolean) => void
) => void
onAddFollows: (followIds: ID[]) => void
onRemoveFollows: (followIds: ID[]) => void
onAutoSelect: () => void
onSelectArtistCategory: (category: FollowArtistsCategory) => void
onNextPage: () => void
suggestedFollows: User[]
}
export type MobilePages =
| Pages.SIGNIN
| Pages.EMAIL
| Pages.PASSWORD
| Pages.PROFILE
| Pages.NOTIFICATION_SETTINGS
| Pages.FOLLOW
| Pages.LOADING
/**
* TODO: When the user selects the metamask option, set the localStorage key 'useMetaMask' to true
* Reference the setup function in Audius backend. A new instance of Audiusbackend will have to be created
*/
const SignOnPage = ({
title,
description,
page,
hasAccount,
hasOpened,
fields,
onSignIn,
onViewSignUp,
onViewSignIn,
onEmailChange,
onEmailSubmitted,
onPasswordChange,
onHandleChange,
onNameChange,
onSetProfileImage,
setTwitterProfile,
setInstagramProfile,
recordTwitterStart,
recordInstagramStart,
validateHandle,
onAddFollows,
onRemoveFollows,
onAutoSelect,
onSelectArtistCategory,
onNextPage,
suggestedFollows: suggestedFollowEntries,
togglePushNotificationSetting
}: SignOnProps & ReturnType<typeof mapDispatchToProps>) => {
const {
email,
name,
password,
handle,
twitterId,
verified,
profileImage,
status,
accountReady,
followArtists: { selectedCategory, selectedUserIds }
} = fields
useEffect(() => {
if (accountReady && page === Pages.LOADING) {
onNextPage()
}
}, [accountReady, onNextPage, page])
const onAllowNotifications = useCallback(() => {
if (NATIVE_MOBILE) {
if (page === Pages.SIGNIN) {
// Trigger enable push notifs drawer
new PromptPushNotificationPermissions().send()
} else {
// Sign up flow
// Enable push notifications (will trigger device popup)
togglePushNotificationSetting(PushNotificationSetting.MobilePush, true)
onNextPage()
}
}
}, [togglePushNotificationSetting, onNextPage, page])
const pages = {
// Captures Pages.EMAIL and Pages.SIGNIN
init: (style: object) => (
<animated.div
style={{
...style,
width: '100%',
height: '100%',
position: 'absolute',
top: 0,
left: 0
}}
>
<InitialPage
hasAccount={hasAccount}
isLoading={status === 'loading'}
didSucceed={status === 'success'}
isSignIn={page === Pages.SIGNIN}
email={email}
password={password}
onViewSignIn={onViewSignIn}
onSubmitSignIn={onSignIn}
onViewSignUp={onViewSignUp}
onPasswordChange={onPasswordChange}
onEmailChange={onEmailChange}
onAllowNotifications={onAllowNotifications}
onEmailSubmitted={onEmailSubmitted}
/>
</animated.div>
),
[Pages.PASSWORD]: (style: object) => (
<animated.div
style={{
...style,
width: '100%',
height: '100%',
position: 'absolute',
top: 0,
left: 0
}}
>
<Header />
<PasswordPage
email={email}
password={password}
inputStatus={''}
onPasswordChange={onPasswordChange}
onNextPage={onNextPage}
onTermsOfServiceClick={() => {}}
onPrivacyPolicyClick={() => {}}
/>
</animated.div>
),
[Pages.PROFILE]: (style: object) => (
<animated.div
style={{
...style,
width: '100%',
height: '100%',
position: 'absolute',
top: 0,
left: 0
}}
>
<Header />
<ProfilePage
name={name}
handle={handle}
isVerified={verified}
twitterId={twitterId}
onHandleChange={onHandleChange}
onNameChange={onNameChange}
profileImage={profileImage}
setProfileImage={onSetProfileImage}
setTwitterProfile={setTwitterProfile}
setInstagramProfile={setInstagramProfile}
recordTwitterStart={recordTwitterStart}
recordInstagramStart={recordInstagramStart}
validateHandle={validateHandle}
onNextPage={onNextPage}
/>
</animated.div>
),
[Pages.NOTIFICATION_SETTINGS]: (style: object) => (
<animated.div
style={{
...style,
width: '100%',
height: '100%',
position: 'absolute',
top: 0,
left: 0
}}
>
<Header />
<NotificationPermissionsPage
onAllowNotifications={onAllowNotifications}
onSkip={onNextPage}
/>
</animated.div>
),
[Pages.FOLLOW]: (style: object) =>
// Note that the bottom section is not contained in the full page wrapper because it is
// position fixed and the full page wrapper prevents it from sicking the bottom
[
<animated.div
style={style}
className={styles.followPageWrapper}
key='follow'
>
<Header />
<FollowPage
users={suggestedFollowEntries}
followedArtists={selectedUserIds}
selectedCategory={selectedCategory}
onSelectArtistCategory={onSelectArtistCategory}
onAddFollows={onAddFollows}
onRemoveFollows={onRemoveFollows}
onAutoSelect={onAutoSelect}
/>
</animated.div>,
<animated.div style={{ opacity: (style as any).opacity }} key='bottom'>
<FollowPageBottom
followedArtists={selectedUserIds}
onNextPage={onNextPage}
/>
</animated.div>
],
[Pages.LOADING]: (style: object) => (
<animated.div style={style} className={styles.fullPageWrapper}>
<LoadingPage />
</animated.div>
)
}
const isInitPage = page === Pages.EMAIL || page === Pages.SIGNIN
const transitionPage = isInitPage ? 'init' : page
return (
<MobilePageContainer
title={title}
description={description}
canonicalUrl={`${BASE_URL}${SIGN_UP_PAGE}`}
fullHeight
backgroundClassName={styles.background}
containerClassName={cn(styles.container, {
[styles.followPage]: transitionPage === Pages.FOLLOW
})}
>
<form
className={styles.form}
method='post'
onSubmit={e => {
e.preventDefault()
}}
autoComplete='off'
>
<div>
<Transition
items={transitionPage as any}
unique
from={{
...{ opacity: !hasOpened || isInitPage ? 1 : 0 },
transform:
page !== Pages.EMAIL && page !== Pages.SIGNIN && hasOpened
? 'translate3d(100%,0,0)'
: 'translate3d(0,0,0)'
}}
enter={{
...{ opacity: 1 },
transform:
!isInitPage && hasOpened
? 'translate3d(0%,0,0)'
: 'translate3d(0,0,0)'
}}
leave={{
...{ opacity: isInitPage ? 1 : 0 },
transform: !isInitPage
? 'translate3d(-50%,0,0)'
: 'translate3d(0,0,0)'
}}
config={
page !== Pages.SIGNIN && page !== Pages.EMAIL
? { duration: 75 }
: { duration: 400 }
}
>
{(item: any) => (pages as any)[item]}
</Transition>
</div>
</form>
</MobilePageContainer>
)
}
function mapDispatchToProps(dispatch: Dispatch) {
return {
togglePushNotificationSetting: (
notificationType: PushNotificationSetting,
isOn: boolean
) =>
dispatch(
settingPageActions.togglePushNotificationSetting(notificationType, isOn)
)
}
}
export default connect(null, mapDispatchToProps)(SignOnPage) | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { ScheduledQueryRules } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { MonitorClient } from "../monitorClient";
import {
LogSearchRuleResource,
ScheduledQueryRulesListBySubscriptionOptionalParams,
ScheduledQueryRulesListByResourceGroupOptionalParams,
ScheduledQueryRulesCreateOrUpdateOptionalParams,
ScheduledQueryRulesCreateOrUpdateResponse,
ScheduledQueryRulesGetOptionalParams,
ScheduledQueryRulesGetResponse,
LogSearchRuleResourcePatch,
ScheduledQueryRulesUpdateOptionalParams,
ScheduledQueryRulesUpdateResponse,
ScheduledQueryRulesDeleteOptionalParams,
ScheduledQueryRulesListBySubscriptionResponse,
ScheduledQueryRulesListByResourceGroupResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing ScheduledQueryRules operations. */
export class ScheduledQueryRulesImpl implements ScheduledQueryRules {
private readonly client: MonitorClient;
/**
* Initialize a new instance of the class ScheduledQueryRules class.
* @param client Reference to the service client
*/
constructor(client: MonitorClient) {
this.client = client;
}
/**
* List the Log Search rules within a subscription group.
* @param options The options parameters.
*/
public listBySubscription(
options?: ScheduledQueryRulesListBySubscriptionOptionalParams
): PagedAsyncIterableIterator<LogSearchRuleResource> {
const iter = this.listBySubscriptionPagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listBySubscriptionPagingPage(options);
}
};
}
private async *listBySubscriptionPagingPage(
options?: ScheduledQueryRulesListBySubscriptionOptionalParams
): AsyncIterableIterator<LogSearchRuleResource[]> {
let result = await this._listBySubscription(options);
yield result.value || [];
}
private async *listBySubscriptionPagingAll(
options?: ScheduledQueryRulesListBySubscriptionOptionalParams
): AsyncIterableIterator<LogSearchRuleResource> {
for await (const page of this.listBySubscriptionPagingPage(options)) {
yield* page;
}
}
/**
* List the Log Search rules within a resource group.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param options The options parameters.
*/
public listByResourceGroup(
resourceGroupName: string,
options?: ScheduledQueryRulesListByResourceGroupOptionalParams
): PagedAsyncIterableIterator<LogSearchRuleResource> {
const iter = this.listByResourceGroupPagingAll(resourceGroupName, options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByResourceGroupPagingPage(resourceGroupName, options);
}
};
}
private async *listByResourceGroupPagingPage(
resourceGroupName: string,
options?: ScheduledQueryRulesListByResourceGroupOptionalParams
): AsyncIterableIterator<LogSearchRuleResource[]> {
let result = await this._listByResourceGroup(resourceGroupName, options);
yield result.value || [];
}
private async *listByResourceGroupPagingAll(
resourceGroupName: string,
options?: ScheduledQueryRulesListByResourceGroupOptionalParams
): AsyncIterableIterator<LogSearchRuleResource> {
for await (const page of this.listByResourceGroupPagingPage(
resourceGroupName,
options
)) {
yield* page;
}
}
/**
* Creates or updates an log search rule.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param ruleName The name of the rule.
* @param parameters The parameters of the rule to create or update.
* @param options The options parameters.
*/
createOrUpdate(
resourceGroupName: string,
ruleName: string,
parameters: LogSearchRuleResource,
options?: ScheduledQueryRulesCreateOrUpdateOptionalParams
): Promise<ScheduledQueryRulesCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, ruleName, parameters, options },
createOrUpdateOperationSpec
);
}
/**
* Gets an Log Search rule
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param ruleName The name of the rule.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
ruleName: string,
options?: ScheduledQueryRulesGetOptionalParams
): Promise<ScheduledQueryRulesGetResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, ruleName, options },
getOperationSpec
);
}
/**
* Update log search Rule.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param ruleName The name of the rule.
* @param parameters The parameters of the rule to update.
* @param options The options parameters.
*/
update(
resourceGroupName: string,
ruleName: string,
parameters: LogSearchRuleResourcePatch,
options?: ScheduledQueryRulesUpdateOptionalParams
): Promise<ScheduledQueryRulesUpdateResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, ruleName, parameters, options },
updateOperationSpec
);
}
/**
* Deletes a Log Search rule
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param ruleName The name of the rule.
* @param options The options parameters.
*/
delete(
resourceGroupName: string,
ruleName: string,
options?: ScheduledQueryRulesDeleteOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ resourceGroupName, ruleName, options },
deleteOperationSpec
);
}
/**
* List the Log Search rules within a subscription group.
* @param options The options parameters.
*/
private _listBySubscription(
options?: ScheduledQueryRulesListBySubscriptionOptionalParams
): Promise<ScheduledQueryRulesListBySubscriptionResponse> {
return this.client.sendOperationRequest(
{ options },
listBySubscriptionOperationSpec
);
}
/**
* List the Log Search rules within a resource group.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param options The options parameters.
*/
private _listByResourceGroup(
resourceGroupName: string,
options?: ScheduledQueryRulesListByResourceGroupOptionalParams
): Promise<ScheduledQueryRulesListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, options },
listByResourceGroupOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const createOrUpdateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/scheduledQueryRules/{ruleName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.LogSearchRuleResource
},
201: {
bodyMapper: Mappers.LogSearchRuleResource
},
default: {
bodyMapper: Mappers.ErrorContract
}
},
requestBody: Parameters.parameters6,
queryParameters: [Parameters.apiVersion7],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.ruleName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const getOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/scheduledQueryRules/{ruleName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.LogSearchRuleResource
},
default: {
bodyMapper: Mappers.ErrorContract
}
},
queryParameters: [Parameters.apiVersion7],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.ruleName
],
headerParameters: [Parameters.accept],
serializer
};
const updateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/scheduledQueryRules/{ruleName}",
httpMethod: "PATCH",
responses: {
200: {
bodyMapper: Mappers.LogSearchRuleResource
},
default: {
bodyMapper: Mappers.ErrorContract
}
},
requestBody: Parameters.parameters7,
queryParameters: [Parameters.apiVersion7],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.ruleName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/scheduledQueryRules/{ruleName}",
httpMethod: "DELETE",
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.ErrorContract
}
},
queryParameters: [Parameters.apiVersion7],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.ruleName
],
headerParameters: [Parameters.accept],
serializer
};
const listBySubscriptionOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/Microsoft.Insights/scheduledQueryRules",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.LogSearchRuleResourceCollection
},
default: {
bodyMapper: Mappers.ErrorContract
}
},
queryParameters: [Parameters.filter1, Parameters.apiVersion7],
urlParameters: [Parameters.$host, Parameters.subscriptionId],
headerParameters: [Parameters.accept],
serializer
};
const listByResourceGroupOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Insights/scheduledQueryRules",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.LogSearchRuleResourceCollection
},
default: {
bodyMapper: Mappers.ErrorContract
}
},
queryParameters: [Parameters.filter1, Parameters.apiVersion7],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.subscriptionId
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import { ServiceType } from "@protobuf-ts/runtime-rpc";
import type { BinaryWriteOptions } from "@protobuf-ts/runtime";
import type { IBinaryWriter } from "@protobuf-ts/runtime";
import { WireType } from "@protobuf-ts/runtime";
import type { BinaryReadOptions } from "@protobuf-ts/runtime";
import type { IBinaryReader } from "@protobuf-ts/runtime";
import { UnknownFieldHandler } from "@protobuf-ts/runtime";
import type { PartialMessage } from "@protobuf-ts/runtime";
import { reflectionMergePartial } from "@protobuf-ts/runtime";
import { MESSAGE_TYPE } from "@protobuf-ts/runtime";
import { MessageType } from "@protobuf-ts/runtime";
import { Duration } from "../../../google/protobuf/duration";
import { Timestamp } from "../../../google/protobuf/timestamp";
import { LabelSet } from "../../profilestore/v1alpha1/profilestore";
/**
* TargetsRequest contains the parameters for the set of targets to return
*
* @generated from protobuf message parca.scrape.v1alpha1.TargetsRequest
*/
export interface TargetsRequest {
/**
* state is the state of targets to returns
*
* @generated from protobuf field: parca.scrape.v1alpha1.TargetsRequest.State state = 1;
*/
state: TargetsRequest_State;
}
/**
* State represents the current state of a target
*
* @generated from protobuf enum parca.scrape.v1alpha1.TargetsRequest.State
*/
export enum TargetsRequest_State {
/**
* STATE_ANY_UNSPECIFIED unspecified
*
* @generated from protobuf enum value: STATE_ANY_UNSPECIFIED = 0;
*/
ANY_UNSPECIFIED = 0,
/**
* STATE_ACTIVE target active state
*
* @generated from protobuf enum value: STATE_ACTIVE = 1;
*/
ACTIVE = 1,
/**
* STATE_DROPPED target dropped state
*
* @generated from protobuf enum value: STATE_DROPPED = 2;
*/
DROPPED = 2
}
/**
* TargetsResponse is the set of targets for the given requested state
*
* @generated from protobuf message parca.scrape.v1alpha1.TargetsResponse
*/
export interface TargetsResponse {
/**
* targets is the mapping of targets
*
* @generated from protobuf field: map<string, parca.scrape.v1alpha1.Targets> targets = 1;
*/
targets: {
[key: string]: Targets;
};
}
/**
* Targets is a list of targets
*
* @generated from protobuf message parca.scrape.v1alpha1.Targets
*/
export interface Targets {
/**
* targets is a list of targets
*
* @generated from protobuf field: repeated parca.scrape.v1alpha1.Target targets = 1;
*/
targets: Target[];
}
/**
* Target is the scrape target representation
*
* @generated from protobuf message parca.scrape.v1alpha1.Target
*/
export interface Target {
/**
* discovered_labels are the set of labels for the target that have been discovered
*
* @generated from protobuf field: parca.profilestore.v1alpha1.LabelSet discovered_labels = 1;
*/
discoveredLabels?: LabelSet;
/**
* labels are the set of labels given for the target
*
* @generated from protobuf field: parca.profilestore.v1alpha1.LabelSet labels = 2;
*/
labels?: LabelSet;
/**
* lase_error is the error message most recently received from a scrape attempt
*
* @generated from protobuf field: string last_error = 3;
*/
lastError: string;
/**
* last_scrape is the time stamp the last scrape request was performed
*
* @generated from protobuf field: google.protobuf.Timestamp last_scrape = 4;
*/
lastScrape?: Timestamp;
/**
* last_scrape_duration is the duration of the last scrape request
*
* @generated from protobuf field: google.protobuf.Duration last_scrape_duration = 5;
*/
lastScrapeDuration?: Duration;
/**
* url is the url of the target
*
* @generated from protobuf field: string url = 6;
*/
url: string;
/**
* health indicates the current health of the target
*
* @generated from protobuf field: parca.scrape.v1alpha1.Target.Health health = 7;
*/
health: Target_Health;
}
/**
* Health are the possible health values of a target
*
* @generated from protobuf enum parca.scrape.v1alpha1.Target.Health
*/
export enum Target_Health {
/**
* HEALTH_UNKNOWN_UNSPECIFIED unspecified
*
* @generated from protobuf enum value: HEALTH_UNKNOWN_UNSPECIFIED = 0;
*/
UNKNOWN_UNSPECIFIED = 0,
/**
* HEALTH_GOOD healthy target
*
* @generated from protobuf enum value: HEALTH_GOOD = 1;
*/
GOOD = 1,
/**
* HEALTH_BAD unhealthy target
*
* @generated from protobuf enum value: HEALTH_BAD = 2;
*/
BAD = 2
}
// @generated message type with reflection information, may provide speed optimized methods
class TargetsRequest$Type extends MessageType<TargetsRequest> {
constructor() {
super("parca.scrape.v1alpha1.TargetsRequest", [
{ no: 1, name: "state", kind: "enum", T: () => ["parca.scrape.v1alpha1.TargetsRequest.State", TargetsRequest_State, "STATE_"] }
]);
}
create(value?: PartialMessage<TargetsRequest>): TargetsRequest {
const message = { state: 0 };
globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this });
if (value !== undefined)
reflectionMergePartial<TargetsRequest>(this, message, value);
return message;
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: TargetsRequest): TargetsRequest {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* parca.scrape.v1alpha1.TargetsRequest.State state */ 1:
message.state = reader.int32();
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message: TargetsRequest, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* parca.scrape.v1alpha1.TargetsRequest.State state = 1; */
if (message.state !== 0)
writer.tag(1, WireType.Varint).int32(message.state);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message parca.scrape.v1alpha1.TargetsRequest
*/
export const TargetsRequest = new TargetsRequest$Type();
// @generated message type with reflection information, may provide speed optimized methods
class TargetsResponse$Type extends MessageType<TargetsResponse> {
constructor() {
super("parca.scrape.v1alpha1.TargetsResponse", [
{ no: 1, name: "targets", kind: "map", K: 9 /*ScalarType.STRING*/, V: { kind: "message", T: () => Targets } }
]);
}
create(value?: PartialMessage<TargetsResponse>): TargetsResponse {
const message = { targets: {} };
globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this });
if (value !== undefined)
reflectionMergePartial<TargetsResponse>(this, message, value);
return message;
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: TargetsResponse): TargetsResponse {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* map<string, parca.scrape.v1alpha1.Targets> targets */ 1:
this.binaryReadMap1(message.targets, reader, options);
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
private binaryReadMap1(map: TargetsResponse["targets"], reader: IBinaryReader, options: BinaryReadOptions): void {
let len = reader.uint32(), end = reader.pos + len, key: keyof TargetsResponse["targets"] | undefined, val: TargetsResponse["targets"][any] | undefined;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case 1:
key = reader.string();
break;
case 2:
val = Targets.internalBinaryRead(reader, reader.uint32(), options);
break;
default: throw new globalThis.Error("unknown map entry field for field parca.scrape.v1alpha1.TargetsResponse.targets");
}
}
map[key ?? ""] = val ?? Targets.create();
}
internalBinaryWrite(message: TargetsResponse, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* map<string, parca.scrape.v1alpha1.Targets> targets = 1; */
for (let k of Object.keys(message.targets)) {
writer.tag(1, WireType.LengthDelimited).fork().tag(1, WireType.LengthDelimited).string(k);
writer.tag(2, WireType.LengthDelimited).fork();
Targets.internalBinaryWrite(message.targets[k], writer, options);
writer.join().join();
}
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message parca.scrape.v1alpha1.TargetsResponse
*/
export const TargetsResponse = new TargetsResponse$Type();
// @generated message type with reflection information, may provide speed optimized methods
class Targets$Type extends MessageType<Targets> {
constructor() {
super("parca.scrape.v1alpha1.Targets", [
{ no: 1, name: "targets", kind: "message", repeat: 1 /*RepeatType.PACKED*/, T: () => Target }
]);
}
create(value?: PartialMessage<Targets>): Targets {
const message = { targets: [] };
globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this });
if (value !== undefined)
reflectionMergePartial<Targets>(this, message, value);
return message;
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: Targets): Targets {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* repeated parca.scrape.v1alpha1.Target targets */ 1:
message.targets.push(Target.internalBinaryRead(reader, reader.uint32(), options));
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message: Targets, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* repeated parca.scrape.v1alpha1.Target targets = 1; */
for (let i = 0; i < message.targets.length; i++)
Target.internalBinaryWrite(message.targets[i], writer.tag(1, WireType.LengthDelimited).fork(), options).join();
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message parca.scrape.v1alpha1.Targets
*/
export const Targets = new Targets$Type();
// @generated message type with reflection information, may provide speed optimized methods
class Target$Type extends MessageType<Target> {
constructor() {
super("parca.scrape.v1alpha1.Target", [
{ no: 1, name: "discovered_labels", kind: "message", T: () => LabelSet },
{ no: 2, name: "labels", kind: "message", T: () => LabelSet },
{ no: 3, name: "last_error", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
{ no: 4, name: "last_scrape", kind: "message", T: () => Timestamp },
{ no: 5, name: "last_scrape_duration", kind: "message", T: () => Duration },
{ no: 6, name: "url", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
{ no: 7, name: "health", kind: "enum", T: () => ["parca.scrape.v1alpha1.Target.Health", Target_Health, "HEALTH_"] }
]);
}
create(value?: PartialMessage<Target>): Target {
const message = { lastError: "", url: "", health: 0 };
globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this });
if (value !== undefined)
reflectionMergePartial<Target>(this, message, value);
return message;
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: Target): Target {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* parca.profilestore.v1alpha1.LabelSet discovered_labels */ 1:
message.discoveredLabels = LabelSet.internalBinaryRead(reader, reader.uint32(), options, message.discoveredLabels);
break;
case /* parca.profilestore.v1alpha1.LabelSet labels */ 2:
message.labels = LabelSet.internalBinaryRead(reader, reader.uint32(), options, message.labels);
break;
case /* string last_error */ 3:
message.lastError = reader.string();
break;
case /* google.protobuf.Timestamp last_scrape */ 4:
message.lastScrape = Timestamp.internalBinaryRead(reader, reader.uint32(), options, message.lastScrape);
break;
case /* google.protobuf.Duration last_scrape_duration */ 5:
message.lastScrapeDuration = Duration.internalBinaryRead(reader, reader.uint32(), options, message.lastScrapeDuration);
break;
case /* string url */ 6:
message.url = reader.string();
break;
case /* parca.scrape.v1alpha1.Target.Health health */ 7:
message.health = reader.int32();
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message: Target, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* parca.profilestore.v1alpha1.LabelSet discovered_labels = 1; */
if (message.discoveredLabels)
LabelSet.internalBinaryWrite(message.discoveredLabels, writer.tag(1, WireType.LengthDelimited).fork(), options).join();
/* parca.profilestore.v1alpha1.LabelSet labels = 2; */
if (message.labels)
LabelSet.internalBinaryWrite(message.labels, writer.tag(2, WireType.LengthDelimited).fork(), options).join();
/* string last_error = 3; */
if (message.lastError !== "")
writer.tag(3, WireType.LengthDelimited).string(message.lastError);
/* google.protobuf.Timestamp last_scrape = 4; */
if (message.lastScrape)
Timestamp.internalBinaryWrite(message.lastScrape, writer.tag(4, WireType.LengthDelimited).fork(), options).join();
/* google.protobuf.Duration last_scrape_duration = 5; */
if (message.lastScrapeDuration)
Duration.internalBinaryWrite(message.lastScrapeDuration, writer.tag(5, WireType.LengthDelimited).fork(), options).join();
/* string url = 6; */
if (message.url !== "")
writer.tag(6, WireType.LengthDelimited).string(message.url);
/* parca.scrape.v1alpha1.Target.Health health = 7; */
if (message.health !== 0)
writer.tag(7, WireType.Varint).int32(message.health);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message parca.scrape.v1alpha1.Target
*/
export const Target = new Target$Type();
/**
* @generated ServiceType for protobuf service parca.scrape.v1alpha1.ScrapeService
*/
export const ScrapeService = new ServiceType("parca.scrape.v1alpha1.ScrapeService", [
{ name: "Targets", options: { "google.api.http": { get: "/targets" } }, I: TargetsRequest, O: TargetsResponse }
]); | the_stack |
import {
INodeProperties,
} from 'n8n-workflow';
export const changeOperations: INodeProperties[] = [
{
displayName: 'Operation',
name: 'operation',
type: 'options',
displayOptions: {
show: {
resource: [
'change',
],
},
},
options: [
{
name: 'Create',
value: 'create',
description: 'Create a change',
},
{
name: 'Delete',
value: 'delete',
description: 'Delete a change',
},
{
name: 'Get',
value: 'get',
description: 'Retrieve a change',
},
{
name: 'Get All',
value: 'getAll',
description: 'Retrieve all changes',
},
{
name: 'Update',
value: 'update',
description: 'Update a change',
},
],
default: 'create',
},
];
export const changeFields: INodeProperties[] = [
// ----------------------------------------
// change: create
// ----------------------------------------
{
displayName: 'Requester Name/ID',
name: 'requesterId',
description: 'ID of the requester of the change. Choose from the list or specify an ID. You can also specify the ID using an <a href="https://docs.n8n.io/nodes/expressions.html#expressions">expression</a>.',
type: 'options',
required: true,
default: '',
typeOptions: {
loadOptionsMethod: 'getRequesters',
},
displayOptions: {
show: {
resource: [
'change',
],
operation: [
'create',
],
},
},
},
{
displayName: 'Subject',
name: 'subject',
type: 'string',
required: true,
default: '',
displayOptions: {
show: {
resource: [
'change',
],
operation: [
'create',
],
},
},
},
{
displayName: 'Planned Start Date',
name: 'plannedStartDate',
type: 'dateTime',
required: true,
default: '',
displayOptions: {
show: {
resource: [
'change',
],
operation: [
'create',
],
},
},
},
{
displayName: 'Planned End Date',
name: 'plannedEndDate',
type: 'dateTime',
required: true,
default: '',
displayOptions: {
show: {
resource: [
'change',
],
operation: [
'create',
],
},
},
},
{
displayName: 'Additional Fields',
name: 'additionalFields',
type: 'collection',
placeholder: 'Add Field',
default: {},
displayOptions: {
show: {
resource: [
'change',
],
operation: [
'create',
],
},
},
options: [
{
displayName: 'Agent Name/ID',
name: 'agent_id',
type: 'options',
default: '',
description: 'ID of the agent to whom the change is assigned. Choose from the list or specify an ID. You can also specify the ID using an <a href="https://docs.n8n.io/nodes/expressions.html#expressions">expression</a>.',
typeOptions: {
loadOptionsMethod: 'getAgents',
},
},
{
displayName: 'Change Type',
name: 'change_type',
type: 'options',
default: 1,
options: [
{
name: 'Minor',
value: 1,
},
{
name: 'Standard',
value: 2,
},
{
name: 'Major',
value: 3,
},
{
name: 'Emergency',
value: 4,
},
],
},
{
displayName: 'Department Name/ID',
name: 'department_id',
type: 'options',
default: '',
description: 'ID of the department requesting the change. Choose from the list or specify an ID. You can also specify the ID using an <a href="https://docs.n8n.io/nodes/expressions.html#expressions">expression</a>.',
typeOptions: {
loadOptionsMethod: 'getDepartments',
},
},
{
displayName: 'Description',
name: 'description',
type: 'string',
default: '',
description: 'HTML supported',
},
{
displayName: 'Group Name/ID',
name: 'group_id',
type: 'options',
default: '',
description: 'ID of the agent group to which the change is assigned. Choose from the list or specify an ID. You can also specify the ID using an <a href="https://docs.n8n.io/nodes/expressions.html#expressions">expression</a>.',
typeOptions: {
loadOptionsMethod: 'getAgentGroups',
},
},
{
displayName: 'Impact',
name: 'impact',
type: 'options',
default: 1,
options: [
{
name: 'Low',
value: 1,
},
{
name: 'Medium',
value: 2,
},
{
name: 'High',
value: 3,
},
],
},
{
displayName: 'Priority',
name: 'priority',
type: 'options',
default: 1,
options: [
{
name: 'Low',
value: 1,
},
{
name: 'Medium',
value: 2,
},
{
name: 'High',
value: 3,
},
{
name: 'Urgent',
value: 4,
},
],
},
{
displayName: 'Risk',
name: 'risk',
type: 'options',
default: 1,
options: [
{
name: 'Low',
value: 1,
},
{
name: 'Medium',
value: 2,
},
{
name: 'High',
value: 3,
},
{
name: 'Very High',
value: 4,
},
],
},
{
displayName: 'Status',
name: 'status',
type: 'options',
default: 1,
options: [
{
name: 'Open',
value: 1,
},
{
name: 'Planning',
value: 2,
},
{
name: 'Approval',
value: 3,
},
{
name: 'Pending Release',
value: 4,
},
{
name: 'Pending Review',
value: 5,
},
{
name: 'Closed',
value: 6,
},
],
},
{
displayName: 'Subject',
name: 'subject',
type: 'string',
default: '',
},
],
},
// ----------------------------------------
// change: delete
// ----------------------------------------
{
displayName: 'Change ID',
name: 'changeId',
description: 'ID of the change to delete',
type: 'string',
required: true,
default: '',
displayOptions: {
show: {
resource: [
'change',
],
operation: [
'delete',
],
},
},
},
// ----------------------------------------
// change: get
// ----------------------------------------
{
displayName: 'Change ID',
name: 'changeId',
description: 'ID of the change to retrieve',
type: 'string',
required: true,
default: '',
displayOptions: {
show: {
resource: [
'change',
],
operation: [
'get',
],
},
},
},
// ----------------------------------------
// change: getAll
// ----------------------------------------
{
displayName: 'Return All',
name: 'returnAll',
type: 'boolean',
default: false,
description: 'Whether to return all results or only up to a given limit',
displayOptions: {
show: {
resource: [
'change',
],
operation: [
'getAll',
],
},
},
},
{
displayName: 'Limit',
name: 'limit',
type: 'number',
default: 50,
description: 'How many results to return',
typeOptions: {
minValue: 1,
},
displayOptions: {
show: {
resource: [
'change',
],
operation: [
'getAll',
],
returnAll: [
false,
],
},
},
},
{
displayName: 'Filters',
name: 'filters',
type: 'collection',
placeholder: 'Add Filter',
default: {},
displayOptions: {
show: {
resource: [
'change',
],
operation: [
'getAll',
],
},
},
options: [
{
displayName: 'Predefined Filters',
name: 'filter',
type: 'options',
default: 'my_open',
options: [
{
name: 'Closed',
value: 'closed',
},
{
name: 'My Open',
value: 'my_open',
},
{
name: 'Release Requested',
value: 'release_requested',
},
{
name: 'Requester ID',
value: 'requester_id',
},
{
name: 'Unassigned',
value: 'unassigned',
},
],
},
{
displayName: 'Sort Order',
name: 'sort_by',
type: 'options',
options: [
{
name: 'Ascending',
value: 'asc',
},
{
name: 'Descending',
value: 'desc',
},
],
default: 'asc',
},
{
displayName: 'Updated Since',
name: 'updated_since',
type: 'dateTime',
default: '',
},
],
},
// ----------------------------------------
// change: update
// ----------------------------------------
{
displayName: 'Change ID',
name: 'changeId',
description: 'ID of the change to update',
type: 'string',
required: true,
default: '',
displayOptions: {
show: {
resource: [
'change',
],
operation: [
'update',
],
},
},
},
{
displayName: 'Update Fields',
name: 'updateFields',
type: 'collection',
placeholder: 'Add Field',
default: {},
displayOptions: {
show: {
resource: [
'change',
],
operation: [
'update',
],
},
},
options: [
{
displayName: 'Agent Name/ID',
name: 'agent_id',
type: 'options',
default: '',
description: 'ID of the agent to whom the change is assigned. Choose from the list or specify an ID. You can also specify the ID using an <a href="https://docs.n8n.io/nodes/expressions.html#expressions">expression</a>.',
typeOptions: {
loadOptionsMethod: 'getAgents',
},
},
{
displayName: 'Change Type',
name: 'change_type',
type: 'options',
default: 1,
options: [
{
name: 'Minor',
value: 1,
},
{
name: 'Standard',
value: 2,
},
{
name: 'Major',
value: 3,
},
{
name: 'Emergency',
value: 4,
},
],
},
{
displayName: 'Department Name/ID',
name: 'department_id',
type: 'options',
default: '',
description: 'ID of the department requesting the change. Choose from the list or specify an ID. You can also specify the ID using an <a href="https://docs.n8n.io/nodes/expressions.html#expressions">expression</a>.',
typeOptions: {
loadOptionsMethod: 'getDepartments',
},
},
{
displayName: 'Description',
name: 'description',
type: 'string',
default: '',
description: 'HTML supported',
},
{
displayName: 'Group Name/ID',
name: 'group_id',
type: 'options',
default: '',
description: 'ID of the agent group to which the change is assigned. Choose from the list or specify an ID. You can also specify the ID using an <a href="https://docs.n8n.io/nodes/expressions.html#expressions">expression</a>.',
typeOptions: {
loadOptionsMethod: 'getAgentGroups',
},
},
{
displayName: 'Impact',
name: 'impact',
type: 'options',
default: 1,
description: 'Impact of the change',
options: [
{
name: 'Low',
value: 1,
},
{
name: 'Medium',
value: 2,
},
{
name: 'High',
value: 3,
},
],
},
{
displayName: 'Priority',
name: 'priority',
type: 'options',
default: 1,
options: [
{
name: 'Low',
value: 1,
},
{
name: 'Medium',
value: 2,
},
{
name: 'High',
value: 3,
},
{
name: 'Urgent',
value: 4,
},
],
},
{
displayName: 'Requester Name/ID',
name: 'requester_id',
type: 'options',
default: '',
description: 'ID of the requester of the change. Choose from the list or specify an ID. You can also specify the ID using an <a href="https://docs.n8n.io/nodes/expressions.html#expressions">expression</a>.',
typeOptions: {
loadOptionsMethod: 'getRequesters',
},
},
{
displayName: 'Risk',
name: 'risk',
type: 'options',
default: 1,
options: [
{
name: 'Low',
value: 1,
},
{
name: 'Medium',
value: 2,
},
{
name: 'High',
value: 3,
},
{
name: 'Very High',
value: 4,
},
],
},
{
displayName: 'Status',
name: 'status',
type: 'options',
default: 1,
options: [
{
name: 'Open',
value: 1,
},
{
name: 'Planning',
value: 2,
},
{
name: 'Approval',
value: 3,
},
{
name: 'Pending Release',
value: 4,
},
{
name: 'Pending Review',
value: 5,
},
{
name: 'Closed',
value: 6,
},
],
},
{
displayName: 'Subject',
name: 'subject',
type: 'string',
default: '',
},
],
},
]; | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace Formmsdyn_fieldservicesetting_Information {
interface tab__4CC8A00D_6D79_4310_A61A_6B5A0597CAF4_Sections {
_C420A5EF_CA73_43EA_A432_4F9ECE791087: DevKit.Controls.Section;
}
interface tab_RemoteAssist_Sections {
tab_13_section_1_2: DevKit.Controls.Section;
}
interface tab_tab_10_Sections {
tab_10_section_2: DevKit.Controls.Section;
}
interface tab_tab_11_Sections {
tab_11_section_1: DevKit.Controls.Section;
}
interface tab_tab_12_Sections {
tab_12_section_1: DevKit.Controls.Section;
tab_12_section_2: DevKit.Controls.Section;
tab_12_section_3: DevKit.Controls.Section;
}
interface tab_tab_13_Sections {
tab_13_section_1: DevKit.Controls.Section;
}
interface tab_tab_14_Sections {
tab_14_section_1: DevKit.Controls.Section;
}
interface tab_tab_4_Sections {
tab_4_section_2: DevKit.Controls.Section;
}
interface tab_tab_6_Sections {
Crew_Management: DevKit.Controls.Section;
tab_3_section_1: DevKit.Controls.Section;
tab_6_section_2: DevKit.Controls.Section;
}
interface tab_tab_7_Sections {
tab_7_section_1: DevKit.Controls.Section;
}
interface tab_tab_8_Sections {
tab_8_section_1: DevKit.Controls.Section;
}
interface tab_tab_9_Sections {
tab_9_section_1: DevKit.Controls.Section;
}
interface tab_TimeEntry_Sections {
TimeEntry: DevKit.Controls.Section;
}
interface tab__4CC8A00D_6D79_4310_A61A_6B5A0597CAF4 extends DevKit.Controls.ITab {
Section: tab__4CC8A00D_6D79_4310_A61A_6B5A0597CAF4_Sections;
}
interface tab_RemoteAssist extends DevKit.Controls.ITab {
Section: tab_RemoteAssist_Sections;
}
interface tab_tab_10 extends DevKit.Controls.ITab {
Section: tab_tab_10_Sections;
}
interface tab_tab_11 extends DevKit.Controls.ITab {
Section: tab_tab_11_Sections;
}
interface tab_tab_12 extends DevKit.Controls.ITab {
Section: tab_tab_12_Sections;
}
interface tab_tab_13 extends DevKit.Controls.ITab {
Section: tab_tab_13_Sections;
}
interface tab_tab_14 extends DevKit.Controls.ITab {
Section: tab_tab_14_Sections;
}
interface tab_tab_4 extends DevKit.Controls.ITab {
Section: tab_tab_4_Sections;
}
interface tab_tab_6 extends DevKit.Controls.ITab {
Section: tab_tab_6_Sections;
}
interface tab_tab_7 extends DevKit.Controls.ITab {
Section: tab_tab_7_Sections;
}
interface tab_tab_8 extends DevKit.Controls.ITab {
Section: tab_tab_8_Sections;
}
interface tab_tab_9 extends DevKit.Controls.ITab {
Section: tab_tab_9_Sections;
}
interface tab_TimeEntry extends DevKit.Controls.ITab {
Section: tab_TimeEntry_Sections;
}
interface Tabs {
_4CC8A00D_6D79_4310_A61A_6B5A0597CAF4: tab__4CC8A00D_6D79_4310_A61A_6B5A0597CAF4;
RemoteAssist: tab_RemoteAssist;
tab_10: tab_tab_10;
tab_11: tab_tab_11;
tab_12: tab_tab_12;
tab_13: tab_tab_13;
tab_14: tab_tab_14;
tab_4: tab_tab_4;
tab_6: tab_tab_6;
tab_7: tab_tab_7;
tab_8: tab_tab_8;
tab_9: tab_tab_9;
TimeEntry: tab_TimeEntry;
}
interface Body {
Tab: Tabs;
/** For internal use only. */
msdyn_AdvancedSettings: DevKit.Controls.String;
msdyn_AgreementPrefix: DevKit.Controls.String;
/** This field defines the time of day when Work Orders and Invoices are generated by the Agreement Booking Setups and Agreement Invoice Setups where the timing was not defined on the related Agreement. */
msdyn_AgreementRecordGeneration: DevKit.Controls.DateTime;
/** This field defines the time of day when Work Orders and Invoices are generated by the Agreement Booking Setups and Agreement Invoice Setups where the timing was not defined on the related Agreement. */
msdyn_AgreementRecordGeneration_1: DevKit.Controls.DateTime;
msdyn_AgreementStartingNumber: DevKit.Controls.Integer;
msdyn_AnalyticsIngestDataInXDays: DevKit.Controls.Integer;
/** If enabled then Allocated will be automatically set when entering a Work order Product with a Line Status of Estimate. */
msdyn_AutoAllocateEstimatedProducts: DevKit.Controls.Boolean;
msdyn_AutoGenerateWOforAgreementBookings: DevKit.Controls.Boolean;
/** If set then the system will automatically geo code addresses when the address has been updated and the record is saved */
msdyn_AutoGeoCodeAddresses: DevKit.Controls.Boolean;
/** For Internal Use. If Yes the org is opted in for use of latest autonumbering implementation. If No the org is not opted in. */
msdyn_AutoNumberingOptIn: DevKit.Controls.Boolean;
/** Default Pay Type to be used for Break hours */
msdyn_BreakPayType: DevKit.Controls.Lookup;
/** Default Pay Type to be used for business closure work hours */
msdyn_BusinessClosurePayType: DevKit.Controls.Lookup;
/** On disabling, all tax related fields will be removed and no tax calculations will be performed. */
msdyn_CalculateTax: DevKit.Controls.Boolean;
/** Default Crew Strategy */
msdyn_DefaultCrewStrategy: DevKit.Controls.OptionSet;
/** Shows the warehouse associated with the field service setting. */
msdyn_DefaultWarehouse: DevKit.Controls.Lookup;
/** Select whether the default work order completed status is either "Completed" or "Posted." */
msdyn_DefaultWorkOrderCompletedStatus: DevKit.Controls.OptionSet;
/** This field turns off validation on customer asset for service account */
msdyn_disablecustomerassetvalidation: DevKit.Controls.Boolean;
/** Specifies whether users can make booking status changes in the Remote Assist application. */
msdyn_DisableRemoteAssistBookingStatusChanges: DevKit.Controls.Boolean;
/** If enabled then address suggestions will be displayed when editing the address on the account, contact, user, or work order form. */
msdyn_EnableAddressSuggestions: DevKit.Controls.Boolean;
/** Enable Incident Type Suggestion. When enabled, the system will generate suggestions to improve Incident Types based on completed Work Orders. */
msdyn_EnableIncidentTypeRecommendation: DevKit.Controls.Boolean;
msdyn_EnableLegacyScheduleAssistant: DevKit.Controls.Boolean;
/** When enabled, specific Work Order subgrid records open in a pop-up within the context of the parent (WO Service Task, WO Product, WO Service, WO Incident, Booking, and Time Entry). */
msdyn_EnableMainFormDialogForSubgrids: DevKit.Controls.Boolean;
/** Enable Suggested Duration for Incident Type. System will calculate Suggested Duration daily or on demand based on historical bookings */
msdyn_EnableSuggestedDuration: DevKit.Controls.Boolean;
/** When this option is enabled, all asynchronous Field Service background processes will be processed through Flow or asynchronous plugins instead of the historic Field Service workflows. See documentation for more details. */
msdyn_EnhancedBackgroundProcessing: DevKit.Controls.Boolean;
msdyn_EntityNumberLength: DevKit.Controls.Integer;
msdyn_GenerateAgreementInvoicesXDaysInAdvance: DevKit.Controls.Integer;
/** Specify default how many days in advance of the Agreement Booking Date the system should automatically generate a Work Order */
msdyn_GenerateAgreementWOXDaysInAdvance: DevKit.Controls.Integer;
msdyn_GenerateBookingDatesXMonthsInAdvance: DevKit.Controls.Integer;
msdyn_GenerateInvoiceDatesXMonthsInAdvance: DevKit.Controls.Integer;
/** Choose the range of date to use for suggested duration calculation */
msdyn_HistoricalDataFilter: DevKit.Controls.OptionSet;
msdyn_InspectionAnalyticsEnabled: DevKit.Controls.Boolean;
msdyn_InspectionAnalyticsFrequency: DevKit.Controls.OptionSet;
msdyn_InspectionAnalyticsRecommendedTime: DevKit.Controls.DateTime;
/** Shows the prefix to be added to the inventory adjustment numbers. */
msdyn_InventoryAdjustmentPrefix: DevKit.Controls.String;
/** Shows the number to be used as the starting number for inventory adjustments. */
msdyn_InventoryAdjustmentStartingNumber: DevKit.Controls.Integer;
/** Shows the prefix to be added to the inventory transfer numbers. */
msdyn_InventoryTransferPrefix: DevKit.Controls.String;
/** Shows the number to be used as the starting number for inventory transfers. */
msdyn_InventoryTransferStartingNumber: DevKit.Controls.Integer;
/** Shows when the last run of incident type suggestion happens. */
msdyn_LastRunOfIncidentTypeRecommendation: DevKit.Controls.DateTime;
/** Enter the name of the custom entity. */
msdyn_name: DevKit.Controls.String;
/** Default Pay Type to be used for overtime work hours */
msdyn_OvertimePayType: DevKit.Controls.Lookup;
msdyn_ProductCostOrder: DevKit.Controls.OptionSet;
/** Enable if a Purchase Order requires approval in order for the status to be changed to Submitted */
msdyn_PurchaseOrderApprovalRequired: DevKit.Controls.Boolean;
/** Shows the prefix to be added to the purchase order numbers. */
msdyn_PurchaseOrderPrefix: DevKit.Controls.String;
/** Shows the number to be used as starting number for the automatically generated purchase order number. */
msdyn_PurchaseOrderStartingNumber: DevKit.Controls.Integer;
/** Return Top X suggstion result from last run. */
msdyn_ReturnTopXRecommendations: DevKit.Controls.Integer;
msdyn_RMAPrefix: DevKit.Controls.String;
/** Shows the number to be used as the starting number for the automatically generation RMA number. */
msdyn_RMAStartingNumber: DevKit.Controls.Integer;
msdyn_RTVPrefix: DevKit.Controls.String;
/** Shows the number to be used as the starting number for the automatically generated RTV number. */
msdyn_RTVStartingNumber: DevKit.Controls.Integer;
/** Specify the run frequency of incident type suggestion. */
msdyn_RunFrequencyOfIncidentTypeRecommendation: DevKit.Controls.OptionSet;
/** On enabling provides a dialog on change on customer asset/service account of workorder to make the account of customer asset same as service account of work order */
msdyn_suggestreparentingcustomerassets: DevKit.Controls.Boolean;
/** The Field Service solution automatically generates Actuals records. Actuals with a Transaction Type of "Cost" and a Transaction Class of "Time" can be generated when the Work Order is set to Closed-Posted from the related Booking's Booking Journals (Booking Journals on Post of Work Order) or when a Work Order related Time Entry is marked as Approved (Work Order Time Entry Approval). */
msdyn_TimeCostActualsSource: DevKit.Controls.OptionSet;
/** Field Service organizations that do not intend to use Time Entry or that wish to generate them via a custom or manual process should set to 'Manual.' Otherwise, setting to "Auto-Generate from Booking Timestamps" will ensure that Time Entries are automatically created when a Booking is complete for each span of time between Booking Timestamps. */
msdyn_TimeEntryGenerationStrategy: DevKit.Controls.OptionSet;
/** The Timestamp Frequency setting controls the generation of Booking Timestamps as Bookings progress through Booking Statuses. Timestamps can either generate every time a Booking Status is changed (Per Booking Status) or when changing the Booking Status results in a new underlying Field Service Status (Per Field Service Status). */
msdyn_TimestampFrequency: DevKit.Controls.OptionSet;
/** Product to be used by the system for Travel Charges on Work Orders */
msdyn_TravelChargeItemId: DevKit.Controls.Lookup;
/** Default Pay Type to be used for Travel hours */
msdyn_TravelPayType: DevKit.Controls.Lookup;
/** Specify how the system should react when trying to use products that are out of stock. */
msdyn_UseofProductsOutofStock: DevKit.Controls.OptionSet;
/** Specify whether the system should automatically generate an invoice for work orders. */
msdyn_WorkOrderInvoiceCreation: DevKit.Controls.OptionSet;
msdyn_WorkOrderPrefix: DevKit.Controls.String;
msdyn_WorkOrderStartingNumber: DevKit.Controls.Integer;
/** Default Pay Type to be used for regular work hours */
msdyn_WorkPayType: DevKit.Controls.Lookup;
notescontrol: DevKit.Controls.Note;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
WebResource_AgreementRecordGeneration_TimeField: DevKit.Controls.WebResource;
}
interface Footer extends DevKit.Controls.IFooter {
/** Status of the Field Service Setting */
statecode: DevKit.Controls.OptionSet;
}
interface Navigation {
navProcessSessions: DevKit.Controls.NavigationItem
}
interface Grid {
IncidentTypeSuggestionResultGrid: DevKit.Controls.Grid;
fieldserviceslaconfigurationgrid: DevKit.Controls.Grid;
}
}
class Formmsdyn_fieldservicesetting_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form msdyn_fieldservicesetting_Information
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form msdyn_fieldservicesetting_Information */
Body: DevKit.Formmsdyn_fieldservicesetting_Information.Body;
/** The Footer section of form msdyn_fieldservicesetting_Information */
Footer: DevKit.Formmsdyn_fieldservicesetting_Information.Footer;
/** The Navigation of form msdyn_fieldservicesetting_Information */
Navigation: DevKit.Formmsdyn_fieldservicesetting_Information.Navigation;
/** The Grid of form msdyn_fieldservicesetting_Information */
Grid: DevKit.Formmsdyn_fieldservicesetting_Information.Grid;
}
class msdyn_fieldservicesettingApi {
/**
* DynamicsCrm.DevKit msdyn_fieldservicesettingApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Unique identifier of the user who created the record. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was created. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who created the record. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Sequence number of the import that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Unique identifier of the user who modified the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was modified. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who modified the record. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** For internal use only. */
msdyn_AdvancedSettings: DevKit.WebApi.StringValue;
msdyn_AgreementPrefix: DevKit.WebApi.StringValue;
/** This field defines the time of day when Work Orders and Invoices are generated by the Agreement Booking Setups and Agreement Invoice Setups where the timing was not defined on the related Agreement. */
msdyn_AgreementRecordGeneration_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
msdyn_AgreementStartingNumber: DevKit.WebApi.IntegerValue;
msdyn_AnalyticsIngestDataInXDays: DevKit.WebApi.IntegerValue;
msdyn_AnalyticsPostponeIngestionUntil_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
msdyn_AnalyticsSpreadOutPostponeIngestionUntil_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** If enabled then Allocated will be automatically set when entering a Work order Product with a Line Status of Estimate. */
msdyn_AutoAllocateEstimatedProducts: DevKit.WebApi.BooleanValue;
msdyn_AutoGenerateWOforAgreementBookings: DevKit.WebApi.BooleanValue;
/** If set then the system will automatically geo code addresses when the address has been updated and the record is saved */
msdyn_AutoGeoCodeAddresses: DevKit.WebApi.BooleanValue;
/** For Internal Use. If Yes the org is opted in for use of latest autonumbering implementation. If No the org is not opted in. */
msdyn_AutoNumberingOptIn: DevKit.WebApi.BooleanValue;
msdyn_BookingAlertTemplate: DevKit.WebApi.StringValue;
/** Default Pay Type to be used for Break hours */
msdyn_BreakPayType: DevKit.WebApi.LookupValue;
/** Default Pay Type to be used for business closure work hours */
msdyn_BusinessClosurePayType: DevKit.WebApi.LookupValue;
/** On disabling, all tax related fields will be removed and no tax calculations will be performed. */
msdyn_CalculateTax: DevKit.WebApi.BooleanValue;
/** Select whether, when moving open slots to the next day, to leave the old slots and change their status to "Cancel." */
msdyn_CancelCurrentSlotsWhenMoving: DevKit.WebApi.BooleanValue;
/** If enabled system will use custom entity for its source of Geo Locations for resources to be displayed on map view */
msdyn_CustomGPSData: DevKit.WebApi.BooleanValue;
/** Shows the logical name of the latitude field to be used for geolocations. */
msdyn_CustomGPSLatitudefield: DevKit.WebApi.StringValue;
/** Shows the logical name of custom entity to be used for geolocations. */
msdyn_CustomGPSLocationentity: DevKit.WebApi.StringValue;
/** Shows the logical name of the longitude field to be used for geolocations. */
msdyn_CustomGPSLongitudefield: DevKit.WebApi.StringValue;
/** Shows the logical name of the resource field to be used for geolocations. */
msdyn_CustomGPSResourcefield: DevKit.WebApi.StringValue;
/** Shows the logical name of the timestamp field to be used for geolocations. */
msdyn_CustomGPSTimestampfield: DevKit.WebApi.StringValue;
/** For Internal Use */
msdyn_DatabaseVersion: DevKit.WebApi.IntegerValue;
/** Select whether the system should deactivate the resource booking when the system status is changed to "Canceled." */
msdyn_DeactivateBookingWhenCanceled: DevKit.WebApi.BooleanValue;
/** Select whether the system should deactivate the resource booking when the system status is changed to "Completed." */
msdyn_DeactivateBookingWhenCompleted: DevKit.WebApi.BooleanValue;
/** Select whether the system should deactivate the work order when the system status is changed to "Closed - Canceled." */
msdyn_DeactivateWorkOrderWhenCanceled: DevKit.WebApi.BooleanValue;
/** Select whether the system should deactivate the work order when the system status is changed to "Closed - Posted." */
msdyn_DeactivateWorkOrderWhenPosted: DevKit.WebApi.BooleanValue;
msdyn_DefaultBookingDuration: DevKit.WebApi.IntegerValue;
msdyn_DefaultCanceledBookingStatus: DevKit.WebApi.LookupValue;
/** Default Crew Strategy */
msdyn_DefaultCrewStrategy: DevKit.WebApi.OptionSetValue;
msdyn_DefaultRadiusUnit: DevKit.WebApi.BooleanValue;
msdyn_DefaultRadiusValue: DevKit.WebApi.IntegerValue;
msdyn_DefaultScheduledBookingStatus: DevKit.WebApi.LookupValue;
/** Shows the warehouse associated with the field service setting. */
msdyn_DefaultWarehouse: DevKit.WebApi.LookupValue;
/** Select whether the default work order completed status is either "Completed" or "Posted." */
msdyn_DefaultWorkOrderCompletedStatus: DevKit.WebApi.OptionSetValue;
/** This field turns off validation on customer asset for service account */
msdyn_disablecustomerassetvalidation: DevKit.WebApi.BooleanValue;
/** Specifies whether users can make booking status changes in the Remote Assist application. */
msdyn_DisableRemoteAssistBookingStatusChanges: DevKit.WebApi.BooleanValue;
/** If enabled then address suggestions will be displayed when editing the address on the account, contact, user, or work order form. */
msdyn_EnableAddressSuggestions: DevKit.WebApi.BooleanValue;
/** Enable Incident Type Suggestion. When enabled, the system will generate suggestions to improve Incident Types based on completed Work Orders. */
msdyn_EnableIncidentTypeRecommendation: DevKit.WebApi.BooleanValue;
msdyn_EnableLegacyScheduleAssistant: DevKit.WebApi.BooleanValue;
/** When enabled, specific Work Order subgrid records open in a pop-up within the context of the parent (WO Service Task, WO Product, WO Service, WO Incident, Booking, and Time Entry). */
msdyn_EnableMainFormDialogForSubgrids: DevKit.WebApi.BooleanValue;
/** Enable Suggested Duration for Incident Type. System will calculate Suggested Duration daily or on demand based on historical bookings */
msdyn_EnableSuggestedDuration: DevKit.WebApi.BooleanValue;
/** When this option is enabled, all asynchronous Field Service background processes will be processed through Flow or asynchronous plugins instead of the historic Field Service workflows. See documentation for more details. */
msdyn_EnhancedBackgroundProcessing: DevKit.WebApi.BooleanValue;
msdyn_EntityNumberLength: DevKit.WebApi.IntegerValue;
/** Unique identifier for entity instances */
msdyn_fieldservicesettingId: DevKit.WebApi.GuidValue;
msdyn_GenerateAgreementInvoicesXDaysInAdvance: DevKit.WebApi.IntegerValue;
/** Specify default how many days in advance of the Agreement Booking Date the system should automatically generate a Work Order */
msdyn_GenerateAgreementWOXDaysInAdvance: DevKit.WebApi.IntegerValue;
msdyn_GenerateBookingDatesXMonthsInAdvance: DevKit.WebApi.IntegerValue;
msdyn_GenerateInvoiceDatesXMonthsInAdvance: DevKit.WebApi.IntegerValue;
msdyn_GPSLocationExpiresAfterXMinutes: DevKit.WebApi.IntegerValue;
/** Choose the range of date to use for suggested duration calculation */
msdyn_HistoricalDataFilter: DevKit.WebApi.OptionSetValue;
msdyn_InspectionAnalyticsEnabled: DevKit.WebApi.BooleanValue;
msdyn_InspectionAnalyticsEnabledOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
msdyn_InspectionAnalyticsFrequency: DevKit.WebApi.OptionSetValue;
msdyn_InspectionAnalyticsRecommendedTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Shows the prefix to be added to the inventory adjustment numbers. */
msdyn_InventoryAdjustmentPrefix: DevKit.WebApi.StringValue;
/** Shows the number to be used as the starting number for inventory adjustments. */
msdyn_InventoryAdjustmentStartingNumber: DevKit.WebApi.IntegerValue;
/** Shows the prefix to be added to the inventory transfer numbers. */
msdyn_InventoryTransferPrefix: DevKit.WebApi.StringValue;
/** Shows the number to be used as the starting number for inventory transfers. */
msdyn_InventoryTransferStartingNumber: DevKit.WebApi.IntegerValue;
/** Shows when the last run of incident type suggestion happens. */
msdyn_LastRunOfIncidentTypeRecommendation_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Enter the name of the custom entity. */
msdyn_name: DevKit.WebApi.StringValue;
msdyn_NotificationTimeout: DevKit.WebApi.IntegerValue;
/** Default Pay Type to be used for overtime work hours */
msdyn_OvertimePayType: DevKit.WebApi.LookupValue;
/** Shows the date when cleanup of unique numbers will occur. */
msdyn_PostponeNumberCleanupUntil_TimezoneDateAndTime: DevKit.WebApi.TimezoneDateAndTimeValue;
msdyn_ProductCostOrder: DevKit.WebApi.OptionSetValue;
/** Enable if a Purchase Order requires approval in order for the status to be changed to Submitted */
msdyn_PurchaseOrderApprovalRequired: DevKit.WebApi.BooleanValue;
/** Shows the prefix to be added to the purchase order numbers. */
msdyn_PurchaseOrderPrefix: DevKit.WebApi.StringValue;
/** Shows the number to be used as starting number for the automatically generated purchase order number. */
msdyn_PurchaseOrderStartingNumber: DevKit.WebApi.IntegerValue;
msdyn_ResourcesSynchronizationTimeout: DevKit.WebApi.IntegerValue;
/** Return Top X suggstion result from last run. */
msdyn_ReturnTopXRecommendations: DevKit.WebApi.IntegerValue;
msdyn_RMAPrefix: DevKit.WebApi.StringValue;
/** Shows the number to be used as the starting number for the automatically generation RMA number. */
msdyn_RMAStartingNumber: DevKit.WebApi.IntegerValue;
msdyn_RTVPrefix: DevKit.WebApi.StringValue;
/** Shows the number to be used as the starting number for the automatically generated RTV number. */
msdyn_RTVStartingNumber: DevKit.WebApi.IntegerValue;
/** Specify the run frequency of incident type suggestion. */
msdyn_RunFrequencyOfIncidentTypeRecommendation: DevKit.WebApi.OptionSetValue;
/** Select whether the schedule assistant should automatically filter the results based on the territory set on the work order. */
msdyn_SAAutoFilterServiceTerritory: DevKit.WebApi.BooleanValue;
msdyn_SchedulerBusinessUnitDetailsView: DevKit.WebApi.StringValue;
msdyn_SchedulerBusinessUnitTooltipView: DevKit.WebApi.StringValue;
msdyn_SchedulerCoreDetailsView: DevKit.WebApi.StringValue;
msdyn_SchedulerCoreSlotTextTemplate: DevKit.WebApi.StringValue;
msdyn_SchedulerCoreTooltipView: DevKit.WebApi.StringValue;
msdyn_SchedulerFieldServiceDetailsView: DevKit.WebApi.StringValue;
msdyn_SchedulerFieldServiceSlotTextTemplate: DevKit.WebApi.StringValue;
msdyn_SchedulerFieldServiceTooltipView: DevKit.WebApi.StringValue;
msdyn_SchedulerResourceDetailsView: DevKit.WebApi.StringValue;
msdyn_SchedulerResourceTooltipView: DevKit.WebApi.StringValue;
msdyn_SchedulerUnscheduledView: DevKit.WebApi.StringValue;
/** Api key for map */
msdyn_sdkapimapkey: DevKit.WebApi.StringValue;
/** On enabling provides a dialog on change on customer asset/service account of workorder to make the account of customer asset same as service account of work order */
msdyn_suggestreparentingcustomerassets: DevKit.WebApi.BooleanValue;
/** The Field Service solution automatically generates Actuals records. Actuals with a Transaction Type of "Cost" and a Transaction Class of "Time" can be generated when the Work Order is set to Closed-Posted from the related Booking's Booking Journals (Booking Journals on Post of Work Order) or when a Work Order related Time Entry is marked as Approved (Work Order Time Entry Approval). */
msdyn_TimeCostActualsSource: DevKit.WebApi.OptionSetValue;
/** Field Service organizations that do not intend to use Time Entry or that wish to generate them via a custom or manual process should set to 'Manual.' Otherwise, setting to "Auto-Generate from Booking Timestamps" will ensure that Time Entries are automatically created when a Booking is complete for each span of time between Booking Timestamps. */
msdyn_TimeEntryGenerationStrategy: DevKit.WebApi.OptionSetValue;
/** The Timestamp Frequency setting controls the generation of Booking Timestamps as Bookings progress through Booking Statuses. Timestamps can either generate every time a Booking Status is changed (Per Booking Status) or when changing the Booking Status results in a new underlying Field Service Status (Per Field Service Status). */
msdyn_TimestampFrequency: DevKit.WebApi.OptionSetValue;
/** Product to be used by the system for Travel Charges on Work Orders */
msdyn_TravelChargeItemId: DevKit.WebApi.LookupValue;
/** Default Pay Type to be used for Travel hours */
msdyn_TravelPayType: DevKit.WebApi.LookupValue;
msdyn_TravelTimeRescheduling: DevKit.WebApi.BooleanValue;
/** Location for schedules where geo code info has not been defined */
msdyn_UndefinedBookingLocation: DevKit.WebApi.OptionSetValue;
msdyn_UnscheduledWOTooltipsViewId: DevKit.WebApi.StringValue;
/** Specify how the system should react when trying to use products that are out of stock. */
msdyn_UseofProductsOutofStock: DevKit.WebApi.OptionSetValue;
/** Specify whether the system should automatically generate an invoice for work orders. */
msdyn_WorkOrderInvoiceCreation: DevKit.WebApi.OptionSetValue;
msdyn_WorkOrderPrefix: DevKit.WebApi.StringValue;
msdyn_WorkOrderStartingNumber: DevKit.WebApi.IntegerValue;
/** Default Pay Type to be used for regular work hours */
msdyn_WorkPayType: DevKit.WebApi.LookupValue;
/** Date and time that the record was migrated. */
OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValue;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValue;
/** Unique identifier for the business unit that owns the record */
OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the team that owns the record. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier for the user that owns the record. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** Status of the Field Service Setting */
statecode: DevKit.WebApi.OptionSetValue;
/** Reason for the status of the Field Service Setting */
statuscode: DevKit.WebApi.OptionSetValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
/** Version Number */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
}
}
declare namespace OptionSet {
namespace msdyn_fieldservicesetting {
enum msdyn_DefaultCrewStrategy {
/** 192350000 */
Cascade_and_Accept_Cascade_Completely,
/** 192350001 */
Crew_Leader_Management,
/** 192350002 */
Crew_Member_Self_Management
}
enum msdyn_DefaultWorkOrderCompletedStatus {
/** 690970005 */
Closed_Canceled,
/** 690970004 */
Closed_Posted,
/** 690970003 */
Open_Completed,
/** 690970002 */
Open_In_Progress,
/** 690970001 */
Open_Scheduled,
/** 690970000 */
Open_Unscheduled
}
enum msdyn_HistoricalDataFilter {
/** 100000003 */
All,
/** 100000002 */
Last_12_Months,
/** 100000000 */
Last_3_Months,
/** 100000001 */
Last_6_Months
}
enum msdyn_InspectionAnalyticsFrequency {
/** 100000002 */
Custom,
/** 100000000 */
Daily,
/** 100000001 */
Immediately
}
enum msdyn_ProductCostOrder {
/** 690970001 */
CurrentStandard,
/** 690970000 */
StandardCurrent
}
enum msdyn_RunFrequencyOfIncidentTypeRecommendation {
/** 192350000 */
Once_a_Week
}
enum msdyn_TimeCostActualsSource {
/** 192354000 */
Booking_Journals_on_Post_of_Work_Order,
/** 192354001 */
Work_Order_Time_Entry_Approval
}
enum msdyn_TimeEntryGenerationStrategy {
/** 192355201 */
Auto_Generate_from_Booking_Timestamps,
/** 192355200 */
Manual
}
enum msdyn_TimestampFrequency {
/** 192350000 */
Per_Booking_Status_Change,
/** 192350001 */
Per_Field_Service_Status_Change
}
enum msdyn_UndefinedBookingLocation {
/** 690970001 */
Ignore_Location,
/** 690970000 */
Previous_Known_Location
}
enum msdyn_UseofProductsOutofStock {
/** 690970000 */
Confirm,
/** 690970001 */
Restrict
}
enum msdyn_WorkOrderInvoiceCreation {
/** 690970000 */
Never,
/** 690970001 */
On_Work_Order_Posted
}
enum statecode {
/** 0 */
Active,
/** 1 */
Inactive
}
enum statuscode {
/** 1 */
Active,
/** 2 */
Inactive
}
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
* Kanban mobile spec
*/
import { Browser } from '@syncfusion/ej2-base';
import { Popup } from '@syncfusion/ej2-popups';
import { Kanban, KanbanModel, EJ2Instance } 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';
Kanban.Inject();
describe('Kanban mobile testing', () => {
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('Basic kanban in mobile device', () => {
let kanbanObj: Kanban;
const uA: string = Browser.userAgent;
const androidUserAgent: string = 'Mozilla/5.0 (Linux; Android 9; Pixel XL Build/PPP3.180510.008) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.81 Mobile Safari/537.36';
beforeAll((done: DoneFn) => {
Browser.userAgent = androidUserAgent;
const model: KanbanModel = { width: 300, height: 500 };
kanbanObj = util.createKanban(model, kanbanData, done);
});
afterAll(() => {
util.destroy(kanbanObj);
Browser.userAgent = uA;
});
it('checking adaptive rendering or not', () => {
expect(kanbanObj.isAdaptive).toEqual(true);
});
});
describe('Swimlane kanban in mobile device', () => {
let kanbanObj: Kanban;
const uA: string = Browser.userAgent;
const androidUserAgent: string = 'Mozilla/5.0 (Linux; Android 9; Pixel XL Build/PPP3.180510.008) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.81 Mobile Safari/537.36';
beforeAll((done: DoneFn) => {
Browser.userAgent = androidUserAgent;
const model: KanbanModel = {
width: 300, height: 500,
swimlaneSettings: {
keyField: 'Assignee'
}
};
kanbanObj = util.createKanban(model, kanbanData, done);
});
afterAll(() => {
util.destroy(kanbanObj);
Browser.userAgent = uA;
});
it('swimlane toolbar testing', () => {
expect(kanbanObj.element.querySelectorAll('.e-swimlane-header')).toBeTruthy();
expect(kanbanObj.element.querySelectorAll('.e-swimlane-header-toolbar').length).toEqual(1);
expect(kanbanObj.element.querySelectorAll('.e-swimlane-header-toolbar .e-toolbar-menu').length).toEqual(1);
expect(kanbanObj.element.querySelectorAll('.e-swimlane-header-toolbar .e-toolbar-level-title').length).toEqual(1);
expect(kanbanObj.element.querySelectorAll('.e-toolbar-level-title .e-toolbar-swimlane-name').length).toEqual(1);
expect(kanbanObj.element.querySelectorAll('.e-toolbar-menu .e-icon-menu').length).toEqual(1);
});
it('swimlane treeview testing', () => {
expect(kanbanObj.element.querySelectorAll('.e-swimlane-content').length).toEqual(1);
expect(kanbanObj.element.querySelectorAll('.e-swimlane-resource').length).toEqual(1);
expect(kanbanObj.element.querySelectorAll('.e-swimlane-tree').length).toEqual(1);
expect(kanbanObj.element.querySelectorAll('.e-swimlane-tree .e-list-item').length).toEqual(8);
});
it('swimlane menu click testing', () => {
const treePopup: Popup = (kanbanObj.element.querySelector('.e-swimlane-resource') as EJ2Instance).ej2_instances[0] as Popup;
treePopup.showAnimation = null;
treePopup.hideAnimation = null;
treePopup.dataBind();
const menuElement: HTMLElement = kanbanObj.element.querySelector('.e-swimlane-header-toolbar .e-icon-menu');
util.triggerMouseEvent(menuElement, 'click');
expect(kanbanObj.element.querySelector('.e-swimlane-resource').classList.contains('e-popup-close')).toEqual(false);
expect(kanbanObj.element.querySelector('.e-swimlane-resource').classList.contains('e-popup-open')).toEqual(true);
expect(kanbanObj.element.querySelector('.e-swimlane-overlay').classList.contains('e-enable')).toEqual(true);
expect(kanbanObj.element.querySelectorAll('.e-swimlane-tree .e-list-item').length).toEqual(8);
expect(kanbanObj.element.querySelectorAll('.e-swimlane-tree .e-list-item.e-active').length).toEqual(1);
util.triggerMouseEvent(menuElement, 'click');
expect(kanbanObj.element.querySelector('.e-swimlane-resource').classList.contains('e-popup-open')).toEqual(false);
expect(kanbanObj.element.querySelector('.e-swimlane-resource').classList.contains('e-popup-close')).toEqual(true);
expect(kanbanObj.element.querySelector('.e-swimlane-overlay').classList.contains('e-enable')).toEqual(false);
});
it('resource node click testing', () => {
const menuElement: HTMLElement = kanbanObj.element.querySelector('.e-swimlane-header-toolbar .e-icon-menu');
util.triggerMouseEvent(menuElement, 'click');
expect(kanbanObj.element.querySelectorAll('.e-card').length).toEqual(10);
expect(kanbanObj.element.querySelector('.e-toolbar-level-title .e-toolbar-swimlane-name').innerHTML).toEqual('Andrew Fuller');
const nodeElement: Element = kanbanObj.element.querySelector('.e-swimlane-tree .e-list-item:not(.e-has-child):not(.e-active)');
(kanbanObj.layoutModule as any).treeSwimlaneClick({ event: new MouseEvent('mouseup'), name: 'nodeClicked', node: nodeElement });
expect(kanbanObj.element.querySelectorAll('.e-card').length).toEqual(12);
expect(kanbanObj.element.querySelector('.e-toolbar-level-title .e-toolbar-swimlane-name').innerHTML).toEqual('Janet Leverling');
});
});
describe('Multi selection using mobile', () => {
let kanbanObj: Kanban;
const uA: string = Browser.userAgent;
const androidUserAgent: string = 'Mozilla/5.0 (Linux; Android 9; Pixel XL Build/PPP3.180510.008) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.81 Mobile Safari/537.36';
beforeAll((done: DoneFn) => {
Browser.userAgent = androidUserAgent;
const model: KanbanModel = {
cardSettings: {
selectionType: 'Multiple'
}
};
kanbanObj = util.createKanban(model, kanbanData, done);
});
afterAll(() => {
util.destroy(kanbanObj);
Browser.userAgent = uA;
});
it('checking adaptive rendering or not', () => {
expect(kanbanObj.isAdaptive).toEqual(true);
expect(kanbanObj.cardSettings.selectionType).toEqual('Multiple');
const appElements: HTMLElement = kanbanObj.element.querySelector('.e-card');
(kanbanObj.touchModule as any).tapHoldHandler({ originalEvent: { target: appElements, type: 'touchstart' } });
});
it('rendering the quick popup wrapper content', () => {
const appElements: HTMLElement = kanbanObj.element.querySelector('.e-card');
expect(kanbanObj.cardSettings.selectionType).toEqual('Multiple');
expect(appElements.classList.contains('e-selection')).toBe(true);
const eventPopup: HTMLElement = document.body.querySelector('.e-mobile-popup-wrapper') as HTMLElement;
expect(eventPopup).not.toBeNull();
expect(document.body.querySelector('.e-mobile-popup-wrapper').childElementCount).toEqual(2);
expect(kanbanObj.element.querySelector('.e-card').getAttribute('data-id')).toEqual(eventPopup.innerText);
});
it('checking after close click', () => {
const eventPopup: HTMLElement = document.body.querySelector('.e-mobile-popup-wrapper') as HTMLElement;
const closeElement: HTMLElement = eventPopup.querySelector('.e-close');
util.triggerMouseEvent(closeElement, 'click');
});
it('checking more than one card clicking', () => {
const element: HTMLElement = kanbanObj.element.querySelector('.e-card[data-id="25"]') as HTMLElement;
util.triggerMouseEvent(element, 'click');
});
it('checking after close click', () => {
const element: HTMLElement = kanbanObj.element.querySelector('.e-card[data-id="25"]') as HTMLElement;
expect(element.classList.contains('e-selection')).toBe(true);
const appElements: HTMLElement = kanbanObj.element.querySelector('.e-card[data-id="2"]') as HTMLElement;
(kanbanObj.touchModule as any).tapHoldHandler({ originalEvent: { target: appElements, type: 'touchstart' } });
});
it('checking the code content', () => {
const eventPopup: HTMLElement = document.body.querySelector('.e-mobile-popup-wrapper') as HTMLElement;
const closeElement: HTMLElement = eventPopup.querySelector('.e-close');
util.triggerMouseEvent(closeElement, 'click');
});
it('checking selected card == one', () => {
const element: HTMLElement = kanbanObj.element.querySelector('.e-card[data-id="25"]') as HTMLElement;
util.triggerMouseEvent(element, 'click');
});
it('checking after close click', () => {
const appElements: HTMLElement = kanbanObj.element.querySelector('.e-card[data-id="25"]') as HTMLElement;
(kanbanObj.touchModule as any).tapHoldHandler({ originalEvent: { target: appElements, type: 'touchstart' } });
});
it('checking selected card == one', () => {
const eventPopup: HTMLElement = document.body.querySelector('.e-mobile-popup-wrapper') as HTMLElement;
const closeElement: HTMLElement = eventPopup.querySelector('.e-close');
util.triggerMouseEvent(closeElement, 'click');
});
it('checking after close click', () => {
const element: HTMLElement = kanbanObj.element.querySelector('.e-card[data-id="3"]') as HTMLElement;
util.triggerMouseEvent(element, 'click');
});
it('checking after close click', () => {
expect(kanbanObj.isAdaptive).toEqual(true);
expect(kanbanObj.cardSettings.selectionType).toEqual('Multiple');
const element: HTMLElement = kanbanObj.element.querySelector('.e-card[data-id="3"]') as HTMLElement;
expect(element.classList.contains('e-selection')).toBe(true);
});
});
describe('Multi selection using mobile', () => {
let kanbanObj: Kanban;
const uA: string = Browser.userAgent;
const androidUserAgent: string = 'Mozilla/5.0 (Linux; Android 9; Pixel XL Build/PPP3.180510.008) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.81 Mobile Safari/537.36';
beforeAll((done: DoneFn) => {
Browser.userAgent = androidUserAgent;
const model: KanbanModel = {
cardSettings: {
selectionType: 'Multiple'
}
};
kanbanObj = util.createKanban(model, kanbanData, done);
});
afterAll(() => {
util.destroy(kanbanObj);
Browser.userAgent = uA;
});
it('checking after close click', () => {
expect(kanbanObj.isAdaptive).toEqual(true);
expect(kanbanObj.cardSettings.selectionType).toEqual('Multiple');
const element: HTMLElement = kanbanObj.element.querySelector('.e-card[data-id="3"]') as HTMLElement;
util.triggerMouseEvent(element, 'click');
});
it('checking after close click', () => {
const appElement: HTMLElement = kanbanObj.element.querySelector('.e-card[data-id="1"]') as HTMLElement;
(kanbanObj.touchModule as any).tapHoldHandler({ originalEvent: { target: appElement, type: 'touchstart' } });
});
it('checking after close click', () => {
const appElement: HTMLElement = kanbanObj.element.querySelector('.e-card[data-id="1"]') as HTMLElement;
expect(appElement.classList.contains('e-selection')).toBe(true);
});
it('checking after close click', () => {
const appElements: HTMLElement = kanbanObj.element.querySelector('.e-card[data-id="3"]') as HTMLElement;
util.triggerMouseEvent(appElements, 'click');
});
it('checking after close click', () => {
const appElements: HTMLElement = kanbanObj.element.querySelector('.e-card[data-id="1"]') as HTMLElement;
util.triggerMouseEvent(appElements, 'click');
});
it('checking adaptive rendering or not', () => {
expect(kanbanObj.isAdaptive).toEqual(true);
expect(kanbanObj.cardSettings.selectionType).toEqual('Multiple');
const appElements: HTMLElement = kanbanObj.element.querySelector('.e-card[data-id="1"]');
(kanbanObj.touchModule as any).tapHoldHandler({ originalEvent: { target: appElements, type: 'touchstart' } });
});
it('checking adaptive rendering or not', () => {
const appElements: HTMLElement = kanbanObj.element.querySelector('.e-card[data-id="1"]');
expect(appElements.classList.contains('e-selection')).toBe(true);
const appElement: HTMLElement = kanbanObj.element.querySelector('.e-card[data-id="2"]') as HTMLElement;
util.triggerMouseEvent(appElement, 'click');
});
it('checking adaptive rendering or not', () => {
const appElements: HTMLElement = kanbanObj.element.querySelector('.e-card[data-id="2"]');
expect(appElements.classList.contains('e-selection')).toBe(true);
const appElement: HTMLElement = kanbanObj.element.querySelector('.e-card[data-id="3"]') as HTMLElement;
util.triggerMouseEvent(appElement, 'click');
});
it('checking adaptive rendering or not', () => {
const appElements: HTMLElement = kanbanObj.element.querySelector('.e-card[data-id="3"]');
expect(appElements.classList.contains('e-selection')).toBe(true);
const appElement: HTMLElement = kanbanObj.element.querySelector('.e-card[data-id="2"]') as HTMLElement;
util.triggerMouseEvent(appElement, 'click');
});
});
describe('Multi selection using mobile', () => {
let kanbanObj: Kanban;
const uA: string = Browser.userAgent;
const androidUserAgent: string = 'Mozilla/5.0 (Linux; Android 9; Pixel XL Build/PPP3.180510.008) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.81 Mobile Safari/537.36';
beforeAll((done: DoneFn) => {
Browser.userAgent = androidUserAgent;
const model: KanbanModel = {
cardSettings: {
selectionType: 'Multiple'
}
};
kanbanObj = util.createKanban(model, kanbanData, done);
});
afterAll(() => {
util.destroy(kanbanObj);
Browser.userAgent = uA;
});
it('checking adaptive rendering or not', () => {
expect(kanbanObj.isAdaptive).toEqual(true);
expect(kanbanObj.cardSettings.selectionType).toEqual('Multiple');
const element: HTMLElement = kanbanObj.element.querySelector('.e-card[data-id="3"]') as HTMLElement;
util.triggerMouseEvent(element, 'click');
});
it('checking adaptive rendering or not', () => {
const element: HTMLElement = kanbanObj.element.querySelector('.e-card[data-id="3"]') as HTMLElement;
expect(element.classList.contains('e-selection')).toBe(true);
});
it('checking adaptive rendering or not', () => {
const appElements: HTMLElement = kanbanObj.element.querySelector('.e-card[data-id="3"]');
(kanbanObj.touchModule as any).tapHoldHandler({ originalEvent: { target: appElements, type: 'touchstart' } });
});
it('checking adaptive rendering or not', () => {
const element: HTMLElement = kanbanObj.element.querySelector('.e-card[data-id="3"]') as HTMLElement;
expect(element.classList.contains('e-selection')).toBe(true);
});
});
describe('Multi selection using mobile', () => {
let kanbanObj: Kanban;
let uA: string = Browser.userAgent;
let androidUserAgent: string = 'Mozilla/5.0 (Linux; Android 9; Pixel XL Build/PPP3.180510.008) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.81 Mobile Safari/537.36';
beforeAll((done: DoneFn) => {
Browser.userAgent = androidUserAgent;
let model: KanbanModel = {
cardSettings: {
selectionType: 'Multiple'
}
};
kanbanObj = util.createKanban(model, kanbanData, done);
});
afterAll(() => {
util.destroy(kanbanObj);
Browser.userAgent = uA;
});
it('tabHold key action', () => {
expect(kanbanObj.isAdaptive).toEqual(true);
expect(kanbanObj.cardSettings.selectionType).toEqual('Multiple');
let appElements: HTMLElement = kanbanObj.element.querySelector('.e-card');
(kanbanObj.touchModule as any).tapHoldHandler({ originalEvent: { target: appElements, type: 'touchstart' } });
});
it('closing the popup ', () => {
let appElements: HTMLElement = kanbanObj.element.querySelector('.e-card');
expect(kanbanObj.cardSettings.selectionType).toEqual('Multiple');
expect(appElements.classList.contains('e-selection')).toBe(true);
let eventPopup: HTMLElement = document.body.querySelector('.e-mobile-popup-wrapper') as HTMLElement;
expect(eventPopup).not.toBeNull();
(kanbanObj.touchModule as any).popupClose();
expect(eventPopup.classList.contains('e-popup')).toBe(false);
});
});
describe('Swimlane kanban in mobile device', () => {
let kanbanObj: Kanban;
let uA: string = Browser.userAgent;
let androidUserAgent: string = 'Mozilla/5.0 (Linux; Android 9; Pixel XL Build/PPP3.180510.008) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.81 Mobile Safari/537.36';
beforeAll((done: DoneFn) => {
Browser.userAgent = androidUserAgent;
let model: KanbanModel = {
width: 300, height: 500,
swimlaneSettings: {
keyField: 'Assignee'
}
};
kanbanObj = util.createKanban(model, kanbanData, done);
});
afterAll(() => {
util.destroy(kanbanObj);
Browser.userAgent = uA;
});
it('click menu to open popup', (done: Function) => {
expect(kanbanObj.isAdaptive).toEqual(true);
let menuElement: HTMLElement = document.querySelector('.e-icons.e-icon-menu');
let popupElement: HTMLElement = document.querySelector('.e-swimlane-resource.e-lib.e-popup.e-control');
expect(popupElement.classList.contains('e-popup-close')).toBe(true);
expect(popupElement.classList.contains('e-popup-open')).toBe(false);
util.triggerMouseEvent(menuElement, 'click');
setTimeout(() => { done(); }, 500);
});
it('popup open functionalities', () => {
let popupElement: HTMLElement = document.querySelector('.e-swimlane-resource.e-lib.e-popup.e-control');
expect(popupElement.classList.contains('e-popup-close')).toBe(false);
expect(popupElement.classList.contains('e-popup-open')).toBe(true);
kanbanObj.layoutModule.hidePopup();
});
});
it('memory leak', () => {
profile.sample();
const average: number = inMB(profile.averageChange);
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
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 chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
import chaiSubset from 'chai-subset';
import path from 'path';
import GenericLayout from '../src/layout/generic_layout';
import jsonfile from 'jsonfile';
import {slides_v1} from 'googleapis';
import {SlideDefinition} from '../src/slides';
const expect = chai.expect;
chai.use(chaiAsPromised);
chai.use(chaiSubset);
describe('GenericLayout', () => {
const fixturePath = path.join(path.dirname(__dirname), 'test', 'fixtures');
const presentation = jsonfile.readFileSync(
path.join(fixturePath, 'mock_presentation.json')
);
describe('with title slide', () => {
const requests: slides_v1.Schema$Request[] = [];
before(() => {
const input: SlideDefinition = {
objectId: 'title-slide',
title: {
rawText: 'This is a title slide',
textRuns: [],
listMarkers: [],
big: false,
},
subtitle: {
rawText: 'Your name here',
textRuns: [],
listMarkers: [],
big: false,
},
bodies: [],
tables: [],
notes: {
rawText: 'Speaker notes here.',
textRuns: [],
listMarkers: [],
big: false,
},
};
const layout = new GenericLayout('', presentation, input);
layout.appendContentRequests(requests);
});
it('should insert title text', () => {
expect(requests).to.deep.include({
insertText: {
text: 'This is a title slide',
objectId: 'centered-title-element',
},
});
});
it('should insert subtitle text', () => {
expect(requests).to.deep.include({
insertText: {
text: 'Your name here',
objectId: 'subtitle-element',
},
});
});
it('should insert speaker notes', () => {
expect(requests).to.deep.include({
insertText: {
text: 'Speaker notes here.',
objectId: 'speaker-notes-element',
},
});
});
});
describe('with title & body slide', () => {
const requests: slides_v1.Schema$Request[] = [];
before(() => {
const input: SlideDefinition = {
objectId: 'body-slide',
title: {
rawText: 'Title & body slide',
textRuns: [],
listMarkers: [],
big: false,
},
bodies: [
{
images: [],
videos: [],
text: {
rawText: 'This is the slide body.\n',
textRuns: [],
listMarkers: [],
big: false,
},
},
],
tables: [],
};
const layout = new GenericLayout('', presentation, input);
layout.appendContentRequests(requests);
});
it('should insert title text', () => {
expect(requests).to.deep.include({
insertText: {
text: 'Title & body slide',
objectId: 'title-element',
},
});
});
it('should insert body text', () => {
expect(requests).to.deep.include({
insertText: {
text: 'This is the slide body.\n',
objectId: 'body-element',
},
});
});
});
describe('with two column slide', () => {
const requests: slides_v1.Schema$Request[] = [];
before(() => {
const input: SlideDefinition = {
objectId: 'two-column-slide',
bodies: [
{
images: [],
videos: [],
text: {
big: false,
rawText: 'This is the left column\n',
textRuns: [],
listMarkers: [],
},
},
{
images: [],
videos: [],
text: {
big: false,
rawText: 'This is the right column\n',
textRuns: [],
listMarkers: [],
},
},
],
tables: [],
};
const layout = new GenericLayout('', presentation, input);
layout.appendContentRequests(requests);
});
it('should insert left column text', () => {
expect(requests).to.deep.include({
insertText: {
text: 'This is the left column\n',
objectId: 'body-element',
},
});
});
it('should insert right column text', () => {
expect(requests).to.deep.include({
insertText: {
text: 'This is the right column\n',
objectId: 'body-element-2',
},
});
});
});
describe('with background images', () => {
const requests: slides_v1.Schema$Request[] = [];
before(() => {
const input: SlideDefinition = {
objectId: 'body-slide',
backgroundImage: {
url: 'https://placekitten.com/1600/900',
width: 1600,
height: 900,
padding: 0,
offsetX: 0,
offsetY: 0,
},
bodies: [
{
images: [],
videos: [],
text: {
big: false,
rawText: '\n',
textRuns: [],
listMarkers: [],
},
},
],
tables: [],
};
const layout = new GenericLayout('', presentation, input);
layout.appendContentRequests(requests);
});
it('should set background image', () => {
expect(requests).to.deep.include({
updatePageProperties: {
objectId: 'body-slide',
fields: 'pageBackgroundFill.stretchedPictureFill.contentUrl',
pageProperties: {
pageBackgroundFill: {
stretchedPictureFill: {
contentUrl: 'https://placekitten.com/1600/900',
},
},
},
},
});
});
});
describe('with inline images', () => {
const requests: slides_v1.Schema$Request[] = [];
before(() => {
const input: SlideDefinition = {
objectId: 'body-slide',
tables: [],
bodies: [
{
videos: [],
images: [
{
url: 'https://placekitten.com/350/315',
width: 350,
height: 315,
padding: 0,
offsetX: 0,
offsetY: 0,
},
],
text: {
rawText: '',
big: false,
listMarkers: [],
textRuns: [],
},
},
],
};
const layout = new GenericLayout('', presentation, input);
layout.appendContentRequests(requests);
});
it('should create image', () => {
expect(requests).to.containSubset([
{
createImage: {
elementProperties: {
pageObjectId: 'body-slide',
},
url: 'https://placekitten.com/350/315',
},
},
]);
});
});
describe('with video', () => {
const requests: slides_v1.Schema$Request[] = [];
before(() => {
const input: SlideDefinition = {
objectId: 'body-slide',
bodies: [
{
videos: [
{
width: 1600,
height: 900,
autoPlay: true,
id: 'MG8KADiRbOU',
},
],
images: [],
text: {
rawText: '',
big: false,
listMarkers: [],
textRuns: [],
},
},
],
tables: [],
};
const layout = new GenericLayout('', presentation, input);
layout.appendContentRequests(requests);
});
it('should create video', () => {
expect(requests).to.containSubset([
{
createVideo: {
source: 'YOUTUBE',
id: 'MG8KADiRbOU',
},
},
]);
});
});
describe('with table', () => {
const requests: slides_v1.Schema$Request[] = [];
before(() => {
const input: SlideDefinition = {
objectId: 'body-slide',
bodies: [],
tables: [
{
rows: 5,
columns: 2,
cells: [
[
{
big: false,
rawText: 'Animal',
textRuns: [],
listMarkers: [],
},
{
big: false,
rawText: 'Number',
textRuns: [],
listMarkers: [],
},
],
[
{
big: false,
rawText: 'Fish',
textRuns: [],
listMarkers: [],
},
{
big: false,
rawText: '142 million',
textRuns: [],
listMarkers: [],
},
],
[
{
big: false,
rawText: 'Cats',
textRuns: [],
listMarkers: [],
},
{
big: false,
rawText: '88 million',
textRuns: [],
listMarkers: [],
},
],
[
{
big: false,
rawText: 'Dogs',
textRuns: [],
listMarkers: [],
},
{
big: false,
rawText: '75 million',
textRuns: [],
listMarkers: [],
},
],
[
{
big: false,
rawText: 'Birds',
textRuns: [],
listMarkers: [],
},
{
big: false,
rawText: '16 million',
textRuns: [],
listMarkers: [],
},
],
],
},
],
};
const layout = new GenericLayout('', presentation, input);
layout.appendContentRequests(requests);
});
it('should create table', () => {
expect(requests).to.containSubset([
{
createTable: {
elementProperties: {
pageObjectId: 'body-slide',
},
rows: 5,
columns: 2,
},
},
]);
});
it('should create table', () => {
expect(requests).to.containSubset([
{
createTable: {
elementProperties: {
pageObjectId: 'body-slide',
},
rows: 5,
columns: 2,
},
},
]);
});
it('should insert cell text', () => {
expect(requests).to.containSubset([
{
insertText: {
text: 'Animal',
cellLocation: {
rowIndex: 0,
columnIndex: 0,
},
},
},
]);
});
});
describe('with formatted text', () => {
const requests: slides_v1.Schema$Request[] = [];
before(() => {
const input: SlideDefinition = {
objectId: 'body-slide',
bodies: [
{
images: [],
videos: [],
text: {
big: false,
rawText: 'Item 1\nItem 2\n\tfoo\n\tbar\n\tbaz\nItem 3\n',
textRuns: [
{
bold: true,
start: 0,
end: 4,
},
{
italic: true,
start: 7,
end: 11,
},
{
fontFamily: 'Courier New',
start: 29,
end: 33,
},
],
listMarkers: [
{
start: 0,
end: 36,
type: 'unordered',
},
],
},
},
],
tables: [],
};
const layout = new GenericLayout('', presentation, input);
layout.appendContentRequests(requests);
});
it('should apply bold style', () => {
expect(requests).to.containSubset([
{
updateTextStyle: {
textRange: {
type: 'FIXED_RANGE',
startIndex: 0,
endIndex: 4,
},
style: {
bold: true,
},
objectId: 'body-element',
fields: 'bold',
},
},
]);
});
it('should apply italic style', () => {
expect(requests).to.containSubset([
{
updateTextStyle: {
textRange: {
type: 'FIXED_RANGE',
startIndex: 7,
endIndex: 11,
},
style: {
italic: true,
},
objectId: 'body-element',
fields: 'italic',
},
},
]);
});
it('should apply font family style', () => {
expect(requests).to.containSubset([
{
updateTextStyle: {
textRange: {
type: 'FIXED_RANGE',
startIndex: 29,
endIndex: 33,
},
style: {
fontFamily: 'Courier New',
},
objectId: 'body-element',
fields: 'fontFamily',
},
},
]);
});
it('should create bulleted list', () => {
expect(requests).to.containSubset([
{
createParagraphBullets: {
textRange: {
type: 'FIXED_RANGE',
startIndex: 0,
endIndex: 36,
},
bulletPreset: 'BULLET_DISC_CIRCLE_SQUARE',
objectId: 'body-element',
},
},
]);
});
});
}); | the_stack |
import * as treeDescription from "./tree-description";
import {TreeNode, TreeDescription, Crosslink, GraphOrientation} from "./tree-description";
import {assertNotNull} from "./loader-utils";
import {defineSymbols} from "./symbols";
// Third-party dependencies
import * as d3selection from "d3-selection";
import * as d3flextree from "d3-flextree";
import * as d3hierarchy from "d3-hierarchy";
import * as d3shape from "d3-shape";
import * as d3zoom from "d3-zoom";
import * as d3interpolate from "d3-interpolate";
import d3tip from "d3-tip";
const MAX_DISPLAY_LENGTH = 15;
const FLEX_NODE_SIZE = 220;
const FOREIGN_OBJECT_SIZE = FLEX_NODE_SIZE * 0.85;
const ALT_CLICK_TOGGLE_NODE = true;
type d3point = [number, number];
interface xyPos {
x: number;
y: number;
}
interface xyLink {
source: xyPos;
target: xyPos;
}
interface Orientation {
link: typeof d3shape.linkVertical;
x: (d: xyPos, viewSize: xyPos) => number;
y: (d: xyPos, viewSize: xyPos) => number;
textdimension: "y" | "x";
textdimensionoffset: (d: d3hierarchy.HierarchyNode<unknown>, maxLabelLength: number) => number;
textanchor: (d: d3hierarchy.HierarchyNode<unknown>) => string;
rectoffsetx: (d: d3hierarchy.HierarchyNode<unknown>, maxLabelLength: number) => number;
rectoffsety: (d: d3hierarchy.HierarchyNode<unknown>, maxLabelLength: number) => number;
foreignoffsetx: (d: d3hierarchy.HierarchyNode<unknown>, maxLabelLength: number) => number;
nudgeoffsety: number;
nodesize: (maxLabelLength: number) => d3point;
nodesep: (a: d3hierarchy.HierarchyNode<unknown>, b: d3hierarchy.HierarchyNode<unknown>) => number;
nodespacing: (a: d3hierarchy.HierarchyNode<TreeNode>, b: d3hierarchy.HierarchyNode<TreeNode>) => number;
rootx: (viewSize: xyPos, scale: number, maxLabelLength: number) => number;
rooty: (viewSize: xyPos, scale: number, maxLabelLength: number) => number;
}
interface LabelOrientation {
toggledx: (d: d3hierarchy.HierarchyPointLink<TreeNode>) => number;
toggledy: (d: d3hierarchy.HierarchyPointLink<TreeNode>) => number;
}
// Orientation mapping
const orientations: {[k in GraphOrientation]: Orientation} = {
"top-to-bottom": {
link: d3shape.linkVertical,
x: (d, _viewSize) => d.x,
y: (d, _viewSize) => d.y,
textdimension: "y",
textdimensionoffset: d => (d.children ? -13 : 13),
textanchor: d => (d.children ? "middle" : "middle"),
rectoffsetx: (d, maxLabelLength) => (-(maxLabelLength - 2) * 6) / 2,
rectoffsety: (d, _maxLabelLength) => (d.children ? -13 - 13 / 2 : 13 - 13 / 2),
foreignoffsetx: (_d, _maxLabelLength) => -FOREIGN_OBJECT_SIZE / 2,
nudgeoffsety: -0.2,
nodesize: maxLabelLength => [maxLabelLength * 6, 45] as d3point,
nodesep: (a, b) => (a.parent === b.parent ? 1 : 1),
nodespacing: (a, b) => (a.parent === b.parent ? 0 : 0),
rootx: (_viewSize, _scale, _maxLabelLength) => 0,
rooty: (viewSize, scale, _maxLabelLength) => viewSize.y / 2 / scale - 100,
},
"right-to-left": {
link: d3shape.linkHorizontal,
x: (d, viewSize) => viewSize.y - d.y,
y: (d, _viewSize) => d.x,
textdimension: "x",
textdimensionoffset: d => (d.children ? 10 : -10),
textanchor: d => (d.children ? "start" : "end"),
rectoffsetx: (d, maxLabelLength) => (d.children ? 10 - 1.5 : -(maxLabelLength - 2) * 6 - (10 - 1.5)),
rectoffsety: (_d, _maxLabelLength) => -13 / 2,
foreignoffsetx: (_d, _maxLabelLength) => -FOREIGN_OBJECT_SIZE / 2,
nudgeoffsety: -0.2,
nodesize: maxLabelLength =>
[11.2 /* table node diameter */ + 2, Math.max(90, maxLabelLength * 6 + 10 /* textdimensionoffset */)] as d3point,
nodesep: (a, b) => (a.parent === b.parent ? 1 : 1.5),
nodespacing: (a, b) => (a.parent === b.parent ? (a.data.nodeToggled && b.data.nodeToggled ? 0 : FLEX_NODE_SIZE / 3) : 0),
rootx: (viewSize, scale, _maxLabelLength) => viewSize.x / 2 / scale + FOREIGN_OBJECT_SIZE,
rooty: (_viewSize, _scale, _maxLabelLength) => 0,
},
"bottom-to-top": {
link: d3shape.linkVertical,
x: (d, _viewSize) => d.x,
y: (d, viewSize) => viewSize.y - d.y,
textdimension: "y",
textdimensionoffset: d => (d.children ? 13 : -13),
textanchor: d => (d.children ? "middle" : "middle"),
rectoffsetx: (d, maxLabelLength) => (-(maxLabelLength - 2) * 6) / 2,
rectoffsety: (d, _maxLabelLength) => (d.children ? 13 - 13 / 2 : -13 - 13 / 2),
foreignoffsetx: (_d, _maxLabelLength) => -FOREIGN_OBJECT_SIZE / 2,
nudgeoffsety: -0.2,
nodesize: maxLabelLength => [maxLabelLength * 6, 45] as d3point,
nodesep: (a, b) => (a.parent === b.parent ? 1 : 1),
nodespacing: (a, b) => (a.parent === b.parent ? 0 : 0),
rootx: (_viewSize, _scale, _maxLabelLength) => 0,
rooty: (viewSize, scale, _maxLabelLength) => viewSize.y - viewSize.y / 2 / scale + FOREIGN_OBJECT_SIZE + 10 - 1.5,
},
"left-to-right": {
link: d3shape.linkHorizontal,
x: (d, _viewSize) => d.y,
y: (d, _viewSize) => d.x,
textdimension: "x",
textdimensionoffset: d => (d.children ? -10 : 10),
textanchor: d => (d.children ? "end" : "start"),
rectoffsetx: (d, maxLabelLength) => (d.children ? -(maxLabelLength - 2) * 6 - (10 - 1.5) : 10 - 1.5),
rectoffsety: (_d, _maxLabelLength) => -13 / 2,
foreignoffsetx: (_d, _maxLabelLength) => -FOREIGN_OBJECT_SIZE / 2,
nudgeoffsety: -0.2,
nodesize: maxLabelLength =>
[11.2 /* table node diameter */ + 2, Math.max(90, maxLabelLength * 6 + 10 /* textdimensionoffset */)] as d3point,
nodesep: (a, b) => (a.parent === b.parent ? 1 : 2),
nodespacing: (a, b) => (a.parent === b.parent ? (a.data.nodeToggled && b.data.nodeToggled ? 0 : FLEX_NODE_SIZE / 3) : 0),
rootx: (viewSize, scale, _maxLabelLength) => viewSize.x / 2 / scale - FOREIGN_OBJECT_SIZE,
rooty: (_viewSize, _scale, _maxLabelLength) => 0,
},
};
//
// Abbreviate all names if they are too long
//
function abbreviateName(name: string) {
if (name && name.length > MAX_DISPLAY_LENGTH) {
return name.substring(0, MAX_DISPLAY_LENGTH) + "…";
}
return name;
}
//
// Escapes a string for HTML
//
function escapeHtml(unsafe: string) {
return String(unsafe)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
// Link cross-links against a d3 hierarchy
function linkCrossLinks(root: d3hierarchy.HierarchyNode<treeDescription.TreeNode>, crosslinks: Crosslink[]) {
const descendants = root.descendants();
const map = (d: treeDescription.TreeNode) => descendants.find(h => h.data === d);
const linked: any[] = [];
crosslinks.forEach(l => {
linked.push({source: map(l.source), target: map(l.target)});
});
return linked;
}
//
// Draw query tree
//
// Creates an `svg` element below the `target` DOM node and draws the query
// tree within it.
export function drawQueryTree(target: HTMLElement, treeData: TreeDescription) {
const root = d3hierarchy.hierarchy(treeData.root, treeDescription.allChildren);
const crosslinks = linkCrossLinks(root, treeData.crosslinks ?? []);
const graphOrientation = treeData.graphOrientation ?? "top-to-bottom";
const DEBUG = treeData.DEBUG ?? false;
const prevPos = new Map<TreeNode, xyPos>();
// Establish maxLabelLength and set ids
let nextId = 0;
const nodeIds = new Map<TreeNode, string>();
let totalNodes = 0;
let maxLabelLength = 0;
treeDescription.visitTreeNodes(
treeData.root,
d => {
nodeIds.set(d, "" + nextId++);
totalNodes++;
if (d.name) {
maxLabelLength = Math.max(d.name.length, maxLabelLength);
}
},
treeDescription.allChildren,
);
// Limit maximum label length and keep layout tight for short names
maxLabelLength = Math.min(maxLabelLength, MAX_DISPLAY_LENGTH + 2 /* include ellipsis */);
// Misc. variables
const duration = 750;
// Size of the diagram
const viewSize = {x: target.clientWidth, y: target.clientHeight};
const ooo = orientations[graphOrientation];
// Orient labels according to node expansion
const labelOrientations: {[k in GraphOrientation]: LabelOrientation} = {
"top-to-bottom": {
toggledx: d =>
d.source.data.nodeToggled && d.source.data.nodeToggled
? ooo.x(d.target, viewSize)
: (ooo.x(d.source, viewSize) + ooo.x(d.target, viewSize)) / 2,
toggledy: d =>
(ooo.y(d.source, viewSize) +
(d.source.data.nodeToggled !== undefined && d.source.data.nodeToggled
? FOREIGN_OBJECT_SIZE + (ooo.rectoffsety(d.source, maxLabelLength) + ooo.nudgeoffsety)
: 0) +
ooo.y(d.target, viewSize)) /
2,
},
"left-to-right": {
toggledx: d => (ooo.x(d.source, viewSize) + ooo.x(d.target, viewSize)) / 2,
toggledy: d => (ooo.y(d.source, viewSize) + ooo.y(d.target, viewSize)) / 2,
},
"bottom-to-top": {
toggledx: d => (ooo.x(d.source, viewSize) + ooo.x(d.target, viewSize)) / 2,
toggledy: d =>
(ooo.y(d.source, viewSize) +
(d.source.data.nodeToggled !== undefined && d.source.data.nodeToggled
? FOREIGN_OBJECT_SIZE + (ooo.rectoffsety(d.source, maxLabelLength) + ooo.nudgeoffsety)
: 0) +
ooo.y(d.target, viewSize)) /
2,
},
"right-to-left": {
toggledx: d => (ooo.x(d.source, viewSize) + ooo.x(d.target, viewSize)) / 2,
toggledy: d => (ooo.y(d.source, viewSize) + ooo.y(d.target, viewSize)) / 2,
},
};
const labelOrientation = labelOrientations[graphOrientation];
function foreignObjectToggled(d) {
return (
d.data.nodeToggled &&
!d.data.collapsedByDefault &&
(d.data.properties?.size != 0 || getTooltipProperties(d.data).size != 0)
);
}
const treelayout = d3flextree
.flextree<treeDescription.TreeNode>()
.nodeSize(d => {
if (foreignObjectToggled(d)) {
return [FLEX_NODE_SIZE, FLEX_NODE_SIZE];
} else {
return ooo.nodesize(maxLabelLength);
}
})
.spacing((a, b) => ooo.nodespacing(a, b));
// Define a d3 diagonal projection for use by the node paths later on.
const diagonal = ooo
.link<xyLink, xyPos>()
.x(d => ooo.x(d, viewSize))
.y(d => ooo.y(d, viewSize));
// Build a HTML list of properties to be displayed in a tooltip
function buildPropertyList(properties: Map<string, string>, cssClass = "qg-prop-name") {
let html = "";
for (const [key, value] of properties.entries()) {
html += "<span class='" + cssClass + "'>" + escapeHtml(key) + ": </span>";
html += "<span style='prop-value'>" + escapeHtml(value) + "</span><br />";
}
return html;
}
// Get additional properties which should be rendered in the tooltip
function getTooltipProperties(d: TreeNode) {
const properties = new Map<string, string>();
if (d.text) {
properties.set("text", d.text);
}
if (d.tag) {
properties.set("tag", d.tag);
}
if (d.class) {
properties.set("class", d.class);
}
return properties;
}
// Retrieve all properties of the node object which should be rendered in the tooltip for debugging
function getDebugProperties(d: d3hierarchy.HierarchyPointNode<TreeNode>): Map<string, string> {
const props = new Map<string, string>();
props.set("height", d.height.toString());
props.set("depth", d.depth.toString());
props.set("x", d.x.toString());
props.set("y", d.y.toString());
props.set("rectFill", d.data.rectFill ?? "undefined");
props.set("rectFillOpacity", (d.data.rectFillOpacity ?? "undefined").toString());
props.set("nodeToggled", (d.data.nodeToggled ?? "undefined").toString());
props.set("collapsedByDefault", (d.data.collapsedByDefault ?? "undefined").toString());
return props;
}
// Initialize tooltip
const tip = d3tip()
.attr("class", "qg-tooltip")
.offset([-10, 0])
.html((_e: unknown, d: d3hierarchy.HierarchyPointNode<TreeNode>) => {
let text = "<span style='text-decoration: underline'>" + escapeHtml(d.data.name ?? "") + "</span><br />";
if (DEBUG) {
text += buildPropertyList(getDebugProperties(d), "qg-prop-name2");
text += buildPropertyList(getTooltipProperties(d.data), "qg-prop-name2");
}
if (d.data.properties !== undefined) {
text += buildPropertyList(d.data.properties);
}
return text;
});
// Define the baseSvg, attaching a class for styling and the zoomBehavior
const baseSvg = d3selection
.select(target)
.append("svg")
.attr("viewBox", `0 0 ${viewSize.x} ${viewSize.y}`)
.attr("height", viewSize.y)
.attr("class", "qg-overlay");
const baseSvgElem = baseSvg.node() as SVGSVGElement;
defineSymbols(baseSvgElem);
// Append a group which holds all nodes and which the zoom Listener can act upon.
const svgGroup = baseSvg.append("g");
// Compute path for browsers not supporting Event.Path such as Safari and Firefox
function computePath(e) {
const path: SVGPathElement[] = [];
let currentElem = e.target;
while (currentElem) {
path.push(currentElem);
currentElem = currentElem.parentElement;
}
return path;
}
// Define the zoomBehavior which calls the zoom function on the "zoom" event constrained within the scaleExtents
const zoomBehavior = d3zoom
.zoom<SVGSVGElement, unknown>()
.filter(function(e) {
if (e.path) {
return !e.path.some(object => object.tagName === "foreignObject");
} else {
return !computePath(e).some(object => object.tagName === "foreignObject");
}
})
.extent([
[0, 0],
[viewSize.x, viewSize.y],
] as [d3point, d3point])
.scaleExtent([0.1, 5])
.on("zoom", e => svgGroup.attr("transform", e.transform));
baseSvg.call(zoomBehavior);
function collapseDefault(r) {
treeDescription.visitTreeNodes(
r,
n => {
if (!n.data._children) {
return;
}
const allChildren = treeDescription.allChildren(n);
if (!allChildren) {
return;
}
n._children = [];
n.children = [];
allChildren.forEach(c => {
if (n.data.children.indexOf(c.data) !== -1) {
n.children.push(c);
}
if (n.data._children.indexOf(c.data) !== -1) {
n._children.push(c);
}
});
if (!n.children.length) {
n.children = null;
}
if (!n._children.length) {
n._children = null;
}
},
treeDescription.allChildren,
);
function initializeCollapsedByDefault(d) {
d.data.collapsedByDefault = true;
for (const child of treeDescription.allChildren(d)) {
initializeCollapsedByDefault(child);
}
}
function assignCollapsedByDefault(d) {
d.data.collapsedByDefault = false;
if (d.children != null) {
for (const child of d.children) {
assignCollapsedByDefault(child);
}
}
}
initializeCollapsedByDefault(r);
assignCollapsedByDefault(r);
}
// Return true if node is collapsed
function collapsed(d) {
if (d.children && d._children) {
// Nodes will have fewer children than _children if collapsed by streamline
if (d.children.length < d._children.length) {
return true;
}
return false;
}
if (d._children) {
return true;
}
return false;
}
// Toggle children function, streamlined nodes are partially collapsed
function toggleChildren(d) {
const children = d.children ? d.children : null;
const _children = d._children ? d._children : null;
d._children = children;
d.children = _children;
}
function toggleNode(d) {
if (d.data.nodeToggled === undefined) {
d.data.nodeToggled = true;
} else {
d.data.nodeToggled = !d.data.nodeToggled;
}
}
// Dash tween to make the highlighted edges animate from start node to end node
const tweenDash = function() {
const l = this.getTotalLength();
return d3interpolate.interpolateString("0," + l, l + "," + l);
};
// Curve crosslink path appropriate for source and target node directionality
const diagonalCrosslink = (d: xyLink) => {
const crosslinkSpacing = {direction: 11.2 * 2, offset: 11.2 * 2};
let points: xyPos[] = [];
points.push({x: d.source.x, y: d.source.y});
points.push({x: d.source.x - crosslinkSpacing.offset, y: d.source.y + crosslinkSpacing.direction});
points.push({x: d.target.x + crosslinkSpacing.offset, y: d.target.y - crosslinkSpacing.direction});
points.push({x: d.target.x, y: d.target.y});
points = points.map(d => ({x: ooo.x(d, viewSize), y: ooo.y(d, viewSize)}));
let path = `M${points[0].x},${points[0].y}`;
let i: number;
for (i = 1; i < points.length - 2; i++) {
const xc = (points[i].x + points[i + 1].x) / 2;
const yc = (points[i].y + points[i + 1].y) / 2;
path += `Q${points[i].x},${points[i].y} ${xc},${yc}`;
}
path += `Q${points[i].x},${points[i].y} ${points[i + 1].x},${points[i + 1].y}`;
return path;
};
const selectCrosslink = (d: d3hierarchy.HierarchyPointNode<unknown>) => {
return svgGroup
.selectAll<SVGPathElement, d3hierarchy.HierarchyPointLink<TreeNode>>("path.qg-crosslink-highlighted")
.filter(dd => d === dd.source || d === dd.target);
};
// Transition used to highlight edges on mouseover
const edgeTransitionIn = (_e: unknown, d: d3hierarchy.HierarchyPointNode<unknown>) => {
selectCrosslink(d)
.transition()
.duration(DEBUG ? duration : 0)
.attr("opacity", 1)
.attrTween("stroke-dasharray", tweenDash);
};
// Transition to unhighlight edges on mouseout
const edgeTransitionOut = (_e: unknown, d: d3hierarchy.HierarchyPointNode<unknown>) => {
selectCrosslink(d)
.transition()
.duration(DEBUG ? duration : 0)
.attr("opacity", 0);
};
//
// Update graph at the given source location, which may be the root or a subtree
//
function update(source: TreeNode) {
// Compute the new tree layout.
const layout = treelayout(root);
const nodes = layout.descendants().reverse();
const links = layout.links();
const prevSourcePos = assertNotNull(prevPos.get(source));
const newSourcePos = assertNotNull(nodes.find(e => e.data == source));
// Update the nodes…
const node = svgGroup
.selectAll<SVGGElement, d3hierarchy.HierarchyNode<TreeNode>>("g.qg-node")
.data(nodes, d => assertNotNull(nodeIds.get(d.data)));
// Enter any new nodes at the parent's previous position.
const nodeEnter = node
.enter()
.append("g")
.attr("class", d => "qg-node " + (d.data.nodeClass ?? ""))
.attr("transform", `translate(${ooo.x(prevSourcePos, viewSize)},${ooo.y(prevSourcePos, viewSize)})`)
.on("click", (e, d) => {
// Toggle node/children/subtree on (alt/shift) click
if (ALT_CLICK_TOGGLE_NODE) {
if (e.altKey) {
if (e.shiftKey) {
toggleNodeSubtree(d);
} else {
toggleNode(d);
}
} else {
if (e.shiftKey) {
toggleChildrenSubtree(d);
} else {
toggleChildren(d);
}
}
} else {
if (e.altKey) {
if (e.shiftKey) {
toggleChildrenSubtree(d);
} else {
toggleChildren(d);
}
} else {
if (e.shiftKey) {
toggleNodeSubtree(d);
} else {
toggleNode(d);
}
}
}
update(d.data);
});
nodeEnter.append("use").attr("xlink:href", d => "#" + (d.data.symbol ?? "default-symbol"));
nodeEnter
.append("rect")
.attr("x", d => ooo.rectoffsetx(d, maxLabelLength))
.attr("y", d => ooo.rectoffsety(d, maxLabelLength))
.attr("width", (maxLabelLength - 2) * 6)
.attr("rx", maxLabelLength / 2.5)
.attr("ry", maxLabelLength / 2.5)
.attr("height", "13")
.style("fill", d => {
return d.data.rectFill ?? "hsl(104, 100%, 100%)";
})
.style("fill-opacity", 0);
nodeEnter
.append("text")
.attr(ooo.textdimension, d => ooo.textdimensionoffset(d, maxLabelLength))
.attr("dy", ".35em")
.attr("text-anchor", d => ooo.textanchor(d))
.text(d => abbreviateName(d.data.name ?? ""))
.style("fill-opacity", 0);
// Insert hidden foreign object before rect to hold node properties upon expansion
nodeEnter
.insert("foreignObject", "rect")
.attr("class", "foreign-object")
.attr("x", d => ooo.foreignoffsetx(d, maxLabelLength))
.attr("y", d => ooo.rectoffsety(d, maxLabelLength) + ooo.nudgeoffsety)
.attr("width", FOREIGN_OBJECT_SIZE)
.attr("height", FOREIGN_OBJECT_SIZE)
.html(d => {
let text = "<br />";
if (DEBUG) {
text += buildPropertyList(getDebugProperties(d), "qg-prop-name2");
}
if (d.data.properties !== undefined) {
text += buildPropertyList(d.data.properties, "qg-prop-name");
}
return text;
})
.style("visibility", "hidden")
.style("opacity", 0);
const nodeUpdate = node.merge(nodeEnter);
const nodeTransition = nodeUpdate.transition().duration(duration);
// Update the rect and text position to reflect whether node has children or not.
nodeUpdate
.select("rect")
.attr("x", d => ooo.rectoffsetx(d, maxLabelLength))
.attr("y", d => ooo.rectoffsety(d, maxLabelLength));
nodeUpdate
.select("text")
.attr(ooo.textdimension, d => ooo.textdimensionoffset(d, maxLabelLength))
.attr("text-anchor", d => ooo.textanchor(d));
// Update foreign object position
nodeUpdate
.select("foreignObject")
.attr("x", d => ooo.foreignoffsetx(d, maxLabelLength))
.attr("y", d => ooo.rectoffsety(d, maxLabelLength) + ooo.nudgeoffsety);
// Change the symbol style class depending on whether it has children and is collapsed
nodeUpdate.select("use").attr("class", d => (collapsed(d) ? "qg-collapsed" : "qg-expanded"));
// Add tooltips and crosslinks
nodeUpdate
.filter(d => d.data.properties?.size != 0 || getTooltipProperties(d.data).size != 0)
.call(tip) // invoke tooltip
.select("use")
.on("mouseover.tooltip", tip.show)
.on("mouseout.tooltip", tip.hide)
.on("mouseover.crosslinks", edgeTransitionIn)
.on("mouseout.crosslinks", edgeTransitionOut);
nodeUpdate
.filter(d => d.data.properties?.size != 0 || getTooltipProperties(d.data).size != 0)
.select("text")
.on("mouseover.crosslinks", edgeTransitionIn)
.on("mouseout.crosslinks", edgeTransitionOut);
// Transition nodes to their new position.
nodeTransition.attr("transform", d => `translate(${ooo.x(d, viewSize)},${ooo.y(d, viewSize)})`);
// Fade the rect in
nodeTransition.select("rect").style("fill-opacity", function(d) {
return d.data.rectFillOpacity ?? 0.0;
});
// Fade the text in
nodeTransition.select("text").style("fill-opacity", 1);
// Fade the visible/hidden foreign object in/out
nodeTransition
.select("foreignObject")
.filter(d => foreignObjectToggled(d))
.style("visibility", "visible")
.style("opacity", 1);
// Delay visibility hidden until opacity duration completes
nodeUpdate
.transition()
.duration(0)
.delay(duration)
.select("foreignObject")
.filter(d => !foreignObjectToggled(d))
.style("visibility", "hidden");
nodeTransition
.select("foreignObject")
.filter(d => !foreignObjectToggled(d))
.style("opacity", 0);
// Transition exiting nodes to the parent's new position.
const nodeExit = node
.exit()
.transition()
.duration(duration)
.attr("transform", `translate(${ooo.x(newSourcePos, viewSize)},${ooo.y(newSourcePos, viewSize)})`)
.remove();
nodeExit.select("circle").attr("r", 0);
nodeExit.select("rect").style("fill-opacity", 0);
nodeExit.select("text").style("fill-opacity", 0);
nodeExit.select("foreignObject").style("opacity", 0);
// Update the links…
const link = svgGroup
.selectAll<SVGPathElement, d3hierarchy.HierarchyPointLink<TreeNode>>("path.qg-link")
.data(links, d => assertNotNull(nodeIds.get(d.target.data)));
// Enter any new links at the parent's previous position.
const linkEnter = link
.enter()
.insert("path", "g")
.attr("class", d => "qg-link " + (d.target.data.edgeClass ?? ""))
.attr("d", _d => diagonal({source: prevSourcePos, target: prevSourcePos}));
// Transition links to their new position.
link.merge(linkEnter)
.transition()
.duration(duration)
.attr("d", diagonal);
// Transition exiting nodes to the parent's new position.
link.exit()
.transition()
.duration(duration)
.attr("d", _d => diagonal({source: newSourcePos, target: newSourcePos}))
.remove();
// Select the link labels
const linksWithLabels = links.filter(d => d.target.data.edgeLabel?.length);
const linkLabel = svgGroup
.selectAll<SVGTextElement, d3hierarchy.HierarchyPointLink<treeDescription.TreeNode>>("text.qg-link-label")
.data(linksWithLabels, d => assertNotNull(nodeIds.get(d.target.data)));
// Enter new link labels before node containers
const linkLabelEnter = linkLabel
.enter()
.insert("text", "g")
.attr("class", d => "qg-link-label " + (d.target.data.edgeLabelClass ?? ""))
.attr("text-anchor", "middle")
.text(d => d.target.data.edgeLabel ?? "")
.attr("x", ooo.x(prevSourcePos, viewSize))
.attr("y", ooo.y(prevSourcePos, viewSize))
.style("fill-opacity", 0);
const linkLabelUpdate = linkLabel.merge(linkLabelEnter);
const linkLabelTransition = linkLabelUpdate.transition().duration(duration);
// Update position for existing & new labels
linkLabelTransition
.style("fill-opacity", 1)
.attr("x", d => labelOrientation.toggledx(d))
.attr("y", d => labelOrientation.toggledy(d));
// Remove labels
linkLabel
.exit()
.transition()
.duration(duration)
.attr("x", ooo.x(newSourcePos, viewSize))
.attr("y", ooo.y(newSourcePos, viewSize))
.style("fill-opacity", 0)
.remove();
// Update crosslinks
const visibleCrosslinks = crosslinks.filter(d => {
return nodes.indexOf(d.source) !== -1 && nodes.indexOf(d.target) !== -1;
});
// Helper function to update crosslink paths
const updateCrosslinkPaths = (cssClass: string, opacity: number) => {
const crossLink = svgGroup
.selectAll<SVGPathElement, d3hierarchy.HierarchyNode<TreeNode>>("path." + cssClass)
.data(visibleCrosslinks, d => nodeIds.get(d.source) + ":" + nodeIds.get(d.target));
const crossLinkEnter = crossLink
.enter()
.insert("path", "g")
.attr("class", cssClass)
.attr("opacity", opacity)
.attr("d", _d => diagonalCrosslink({source: prevSourcePos, target: prevSourcePos}));
crossLink
.merge(crossLinkEnter)
.transition("crossLinkTransition") // separate transition avoids untimely update
.duration(duration)
.attr("d", d => diagonalCrosslink({source: d.source, target: d.target}));
crossLink
.exit()
.transition("crossLinkTransition") // separate transition avoids untimely update
.duration(duration)
.attr("d", _d => diagonalCrosslink({source: newSourcePos, target: newSourcePos}))
.remove();
};
updateCrosslinkPaths("qg-crosslink", 1 /* opacity */);
updateCrosslinkPaths("qg-crosslink-highlighted", 0 /* opacity */);
// Stash the old positions for transition.
nodes.forEach(d => {
prevPos.set(d.data, {x: d.x, y: d.y});
});
}
// Layout the tree initially and center on the root node.
prevPos.set(root.data, {x: 0, y: 0});
collapseDefault(root);
update(root.data);
// Place root node into quandrant appropriate to orientation
function orientRoot() {
const scale = d3zoom.zoomTransform(baseSvgElem).k;
const x = ooo.rootx(viewSize, scale, maxLabelLength);
const y = ooo.rooty(viewSize, scale, maxLabelLength);
zoomBehavior.translateTo(baseSvg, x, y);
}
// Scale the graph so that it can fit nicely on the screen
function fitGraphScale() {
// Get the bounding box of the main SVG element, we are interested in the width and height
const bounds = baseSvgElem.getBBox();
// Get the size of the container of the main SVG element
const parent = assertNotNull(baseSvgElem.parentElement);
const fullWidth = parent.clientWidth;
const fullHeight = parent.clientHeight;
// Let's find the scale factor
// Thinking of only the X dimension, we need to make the width match the fullWidth, Equation:
// width * xfactor = fullWidth
// Solving for `xfactor` we have: xfactor = fullWidth/width
const xfactor: number = fullWidth / bounds.width;
// Similarly, we would find out that: yfactor = fullHeight/height;
const yfactor: number = fullHeight / bounds.height;
// Most likely, the X and Y factor are different. We use the minimum of them to avoid cropping
let scaleFactor: number = Math.min(xfactor, yfactor);
// Add some padding so that the graph is not touching the edges
const paddingPercent = 0.9;
scaleFactor = scaleFactor * paddingPercent;
zoomBehavior.scaleBy(baseSvg, scaleFactor);
}
// Center the graph (without scaling)
function centerGraph() {
// Find the Bounding box center, then translate to it
// In other words, put the bbox center in the center of the screen
const bbox = (svgGroup.node() as SVGGElement).getBBox();
const cx = bbox.x + bbox.width / 2;
const cy = bbox.y + bbox.height / 2;
zoomBehavior.translateTo(baseSvg, cx, cy);
}
// Scale for readability by a fixed amount due to problematic .getBBox() above
zoomBehavior.scaleBy(baseSvg, 1.5);
orientRoot();
// Add help card
const helpCard = d3selection
.select(target)
.append("div")
.attr("class", "qg-help-card");
// Add help properties
const helpProps = new Map();
helpProps.set("(alt+)click", "toggle " + (ALT_CLICK_TOGGLE_NODE ? "(node)children" : "(children)node"));
helpProps.set("(alt+)shift+click", "toggle subtree");
helpProps.set("(alt+)space", "toggle tree");
const helpText = buildPropertyList(helpProps, "qg-prop-name-help");
helpCard
.append("div")
.classed("qg-tree-label", true)
.html(helpText);
const infoCard = d3selection
.select(target)
.append("div")
.attr("class", "qg-info-card");
// Add metrics card
let treeText = "";
if (treeData.properties) {
treeText += buildPropertyList(treeData.properties);
}
if (DEBUG) {
const debugProps = new Map();
debugProps.set("nodes", totalNodes.toString());
if (crosslinks !== undefined && crosslinks.length) {
debugProps.set("crosslinks", crosslinks.length.toString());
}
treeText += buildPropertyList(debugProps);
}
infoCard
.append("div")
.classed("qg-tree-label", true)
.html(treeText);
// Add toolbar
const toolbar = infoCard.append("div").classed("qg-toolbar", true);
function addToolbarButton(id: string, description: string, action: () => void) {
toolbar
.append("div")
.classed("qg-toolbar-button", true)
.on("click", action).html(`<span class="qg-toolbar-icon">
<svg viewbox='-8 -8 16 16' width='20px' height='20px'>
<use href='#${id}-symbol' class="qg-collapsed" />
</svg>
</span>
<span class="qg-toolbar-tooltip">${description}</span>`);
}
// Zoom toolbar buttons
const zoomFactor = 1.4;
addToolbarButton("zoom-in", "Zoom In", () => {
zoomBehavior.scaleBy(baseSvg.transition().duration(200), zoomFactor);
});
addToolbarButton("zoom-out", "Zoom Out", () => {
zoomBehavior.scaleBy(baseSvg.transition().duration(200), 1.0 / zoomFactor);
});
// Rotate toolbar buttons
function getNewOrientation(orientation: GraphOrientation, shift: number): GraphOrientation {
// Gets a new orientation from a given one. 1 unit = 90 degrees
// Positive number: clockwise rotation
// Negative number: counter-clockwise rotation
const orientationList: GraphOrientation[] = ["top-to-bottom", "left-to-right", "bottom-to-top", "right-to-left"];
const index: number = orientationList.indexOf(orientation);
let newIndex: number = (index + shift) % 4;
newIndex = newIndex < 0 ? newIndex + 4 : newIndex;
return orientationList[newIndex];
}
function clearQueryGraph() {
// Removes the QueryGraph elements. This function is useful if we want to call `drawQueryTree` again
// Clear the main tree
d3selection.select(".qg-overlay").remove();
d3selection.select(".qg-info-card").remove();
d3selection.select(".qg-help-card").remove();
// Clear the tooltip element (which is not under the main tree DOM)
d3selection.select(".qg-tooltip").remove();
}
addToolbarButton("rotate-left", "Rotate 90° Left", () => {
clearQueryGraph();
treeData.graphOrientation = getNewOrientation(graphOrientation, 1);
drawQueryTree(target, treeData);
});
addToolbarButton("rotate-right", "Rotate 90° Right", () => {
clearQueryGraph();
treeData.graphOrientation = getNewOrientation(graphOrientation, -1);
drawQueryTree(target, treeData);
});
// Recenter toolbar button
addToolbarButton("recenter", "Center root", () => {
orientRoot();
});
// Fit to screen toolbar button
addToolbarButton("fit-screen", "Fit to screen", () => {
fitGraphScale();
centerGraph();
});
function toggleNodeSubtree(d) {
if (!d.data.collapsedByDefault) {
toggleNode(d);
}
for (const child of treeDescription.allChildren(d)) {
toggleNodeSubtree(child);
}
}
function toggleChildrenSubtree(d) {
if (!d.data.collapsedByDefault) {
toggleChildren(d);
}
for (const child of treeDescription.allChildren(d)) {
toggleChildrenSubtree(child);
}
}
function toggleNodeTree() {
svgGroup.selectAll<SVGGElement, d3hierarchy.HierarchyNode<TreeNode>>("g.qg-node").each(d => {
if (!d.data.collapsedByDefault) {
toggleNode(d);
}
});
// Redraw rather than update to workaround issue with node expansion after graph rotation
clearQueryGraph();
drawQueryTree(target, treeData);
}
function toggleChildrenTree() {
svgGroup.selectAll<SVGGElement, d3hierarchy.HierarchyNode<TreeNode>>("g.qg-node").each(d => {
if (!d.data.collapsedByDefault) {
toggleChildren(d);
}
});
// TODO: Can't redraw here as in toggleNodeTree because children are re-collapsed during redraw
// TODO: Therefore this function is ineffective after graph rotation or toggleNodeTree
update(root.data);
orientRoot();
}
function resize(newWidth?: number, newHeight?: number) {
viewSize.x = newWidth ?? target.clientWidth;
viewSize.y = newHeight ?? target.clientHeight;
// Adjust the view box
baseSvg.attr("viewBox", `0 0 ${viewSize.x} ${viewSize.y}`);
// Adjust the height (necessary in Internet Explorer)
baseSvg.attr("height", viewSize.y);
}
return {
toggleTree: ALT_CLICK_TOGGLE_NODE ? toggleChildrenTree : toggleNodeTree,
toggleAltTree: ALT_CLICK_TOGGLE_NODE ? toggleNodeTree : toggleChildrenTree,
resize: resize,
orientRoot: orientRoot,
};
} | the_stack |
import { Constructable, FASTElementDefinition } from "@microsoft/fast-element";
import { FoundationElement } from "../foundation-element/foundation-element";
import { Container, DI, Registration } from "../di/di";
import { DesignToken } from "../design-token/design-token";
import { ComponentPresentation } from "./component-presentation";
import type {
ContextualElementDefinition,
DesignSystemRegistrationContext,
ElementDefinitionCallback,
ElementDefinitionContext,
ElementDefinitionParams,
} from "./registration-context";
/* eslint-disable @typescript-eslint/no-non-null-assertion */
/**
* Indicates what to do with an ambiguous (duplicate) element.
* @public
*/
export const ElementDisambiguation = Object.freeze({
/**
* Skip defining the element but still call the provided callback passed
* to DesignSystemRegistrationContext.tryDefineElement
*/
definitionCallbackOnly: null,
/**
* Ignore the duplicate element entirely.
*/
ignoreDuplicate: Symbol(),
});
/**
* Represents the return values expected from an ElementDisambiguationCallback.
* @public
*/
export type ElementDisambiguationResult =
| string
| typeof ElementDisambiguation.ignoreDuplicate
| typeof ElementDisambiguation.definitionCallbackOnly;
/**
* The callback type that is invoked when two elements are trying to define themselves with
* the same name.
* @remarks
* The callback should return either:
* 1. A string to provide a new name used to disambiguate the element
* 2. ElementDisambiguation.ignoreDuplicate to ignore the duplicate element entirely
* 3. ElementDisambiguation.definitionCallbackOnly to skip defining the element but still
* call the provided callback passed to DesignSystemRegistrationContext.tryDefineElement
* @public
*/
export type ElementDisambiguationCallback = (
nameAttempt: string,
typeAttempt: Constructable,
existingType: Constructable
) => ElementDisambiguationResult;
const elementTypesByTag = new Map<string, Constructable>();
const elementTagsByType = new Map<Constructable, string>();
/**
* Represents a configurable design system.
* @public
*/
export interface DesignSystem {
/**
* Registers components and services with the design system and the
* underlying dependency injection container.
* @param params - The registries to pass to the design system
* and the underlying dependency injection container.
* @public
*/
register(...params: any[]): DesignSystem;
/**
* Configures the prefix to add to each custom element name.
* @param prefix - The prefix to use for custom elements.
* @public
*/
withPrefix(prefix: string): DesignSystem;
/**
* Overrides the default Shadow DOM mode for custom elements.
* @param mode - The Shadow DOM mode to use for custom elements.
* @public
*/
withShadowRootMode(mode: ShadowRootMode): DesignSystem;
/**
* Provides a custom callback capable of resolving scenarios where
* two different elements request the same element name.
* @param callback - The disambiguation callback.
* @public
*/
withElementDisambiguation(callback: ElementDisambiguationCallback): DesignSystem;
/**
* Overrides the {@link (DesignToken:interface)} root, controlling where
* {@link (DesignToken:interface)} default value CSS custom properties
* are emitted.
*
* Providing `null` disables automatic DesignToken registration.
* @param root - the root to register
* @public
*/
withDesignTokenRoot(root: HTMLElement | Document | null): DesignSystem;
}
let rootDesignSystem: DesignSystem | null = null;
const designSystemKey = DI.createInterface<DesignSystem>(x =>
x.cachedCallback(handler => {
if (rootDesignSystem === null) {
rootDesignSystem = new DefaultDesignSystem(null, handler);
}
return rootDesignSystem;
})
);
/**
* An API gateway to design system features.
* @public
*/
export const DesignSystem = Object.freeze({
/**
* Returns the HTML element name that the type is defined as.
* @param type - The type to lookup.
* @public
*/
tagFor(type: Constructable): string {
return elementTagsByType.get(type)!;
},
/**
* Searches the DOM hierarchy for the design system that is responsible
* for the provided element.
* @param element - The element to locate the design system for.
* @returns The located design system.
* @public
*/
responsibleFor(element: HTMLElement): DesignSystem {
const owned = (element as any).$$designSystem$$ as DesignSystem;
if (owned) {
return owned;
}
const container = DI.findResponsibleContainer(element);
return container.get(designSystemKey);
},
/**
* Gets the DesignSystem if one is explicitly defined on the provided element;
* otherwise creates a design system defined directly on the element.
* @param element - The element to get or create a design system for.
* @returns The design system.
* @public
*/
getOrCreate(node?: Node): DesignSystem {
if (!node) {
if (rootDesignSystem === null) {
rootDesignSystem = DI.getOrCreateDOMContainer().get(designSystemKey);
}
return rootDesignSystem;
}
const owned = (node as any).$$designSystem$$ as DesignSystem;
if (owned) {
return owned;
}
const container = DI.getOrCreateDOMContainer(node);
if (container.has(designSystemKey, false)) {
return container.get(designSystemKey);
} else {
const system = new DefaultDesignSystem(node, container);
container.register(Registration.instance(designSystemKey, system));
return system;
}
},
});
function extractTryDefineElementParams(
params: string | ElementDefinitionParams,
elementDefinitionType?: Constructable,
elementDefinitionCallback?: ElementDefinitionCallback
): ElementDefinitionParams {
if (typeof params === "string") {
return {
name: params,
type: elementDefinitionType!,
callback: elementDefinitionCallback!,
};
} else {
return params;
}
}
class DefaultDesignSystem implements DesignSystem {
private designTokensInitialized: boolean = false;
private designTokenRoot: HTMLElement | null | undefined;
private prefix: string = "fast";
private shadowRootMode: ShadowRootMode | undefined = undefined;
private disambiguate: ElementDisambiguationCallback = () =>
ElementDisambiguation.definitionCallbackOnly;
constructor(private owner: any, private container: Container) {
if (owner !== null) {
owner.$$designSystem$$ = this;
}
}
public withPrefix(prefix: string): DesignSystem {
this.prefix = prefix;
return this;
}
public withShadowRootMode(mode: ShadowRootMode): DesignSystem {
this.shadowRootMode = mode;
return this;
}
public withElementDisambiguation(
callback: ElementDisambiguationCallback
): DesignSystem {
this.disambiguate = callback;
return this;
}
public withDesignTokenRoot(root: HTMLElement | null): DesignSystem {
this.designTokenRoot = root;
return this;
}
public register(...registrations: any[]): DesignSystem {
const container = this.container;
const elementDefinitionEntries: ElementDefinitionEntry[] = [];
const disambiguate = this.disambiguate;
const shadowRootMode = this.shadowRootMode;
const context: DesignSystemRegistrationContext = {
elementPrefix: this.prefix,
tryDefineElement(
params: string | ElementDefinitionParams,
elementDefinitionType?: Constructable,
elementDefinitionCallback?: ElementDefinitionCallback
) {
const extractedParams = extractTryDefineElementParams(
params,
elementDefinitionType,
elementDefinitionCallback
);
const { name, callback, baseClass } = extractedParams;
let { type } = extractedParams;
let elementName: string | null = name;
let typeFoundByName = elementTypesByTag.get(elementName);
let needsDefine = true;
while (typeFoundByName) {
const result = disambiguate(elementName, type, typeFoundByName);
switch (result) {
case ElementDisambiguation.ignoreDuplicate:
return;
case ElementDisambiguation.definitionCallbackOnly:
needsDefine = false;
typeFoundByName = void 0;
break;
default:
elementName = result as string;
typeFoundByName = elementTypesByTag.get(elementName);
break;
}
}
if (needsDefine) {
if (elementTagsByType.has(type) || type === FoundationElement) {
type = class extends type {};
}
elementTypesByTag.set(elementName, type);
elementTagsByType.set(type, elementName);
if (baseClass) {
elementTagsByType.set(baseClass, elementName!);
}
}
elementDefinitionEntries.push(
new ElementDefinitionEntry(
container,
elementName,
type,
shadowRootMode,
callback,
needsDefine
)
);
},
};
if (!this.designTokensInitialized) {
this.designTokensInitialized = true;
if (this.designTokenRoot !== null) {
DesignToken.registerRoot(this.designTokenRoot);
}
}
container.registerWithContext(context, ...registrations);
for (const entry of elementDefinitionEntries) {
entry.callback(entry);
if (entry.willDefine && entry.definition !== null) {
entry.definition.define();
}
}
return this;
}
}
class ElementDefinitionEntry implements ElementDefinitionContext {
public definition: FASTElementDefinition | null = null;
constructor(
public readonly container: Container,
public readonly name: string,
public readonly type: Constructable,
public shadowRootMode: ShadowRootMode | undefined,
public readonly callback: ElementDefinitionCallback,
public readonly willDefine: boolean
) {}
definePresentation(presentation: ComponentPresentation) {
ComponentPresentation.define(this.name, presentation, this.container);
}
defineElement(definition: ContextualElementDefinition) {
this.definition = new FASTElementDefinition(this.type, {
...definition,
name: this.name,
});
}
tagFor(type: Constructable): string {
return DesignSystem.tagFor(type)!;
}
}
/* eslint-enable @typescript-eslint/no-non-null-assertion */ | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { getNamespace, Queue, Subscription, Topic } from ".";
import * as appservice from "../appservice";
interface ServiceBusBindingDefinition extends appservice.BindingDefinition {
/**
* The name of the property in the context object to bind the actual ServiceBus message to.
*/
name: string;
/**
* The type of a topic binding. Must be 'serviceBusTrigger'.
*/
type: "serviceBusTrigger";
/**
* The direction of the binding. We only support queues and topics being inputs to functions.
*/
direction: "in";
/**
* Name of the queue to monitor. Set only if monitoring a queue, not for a topic.
*/
queueName?: pulumi.Input<string>;
/**
* Name of the topic to monitor. Set only if monitoring a topic, not for a queue.
*/
topicName?: pulumi.Input<string>;
/**
* Name of the subscription to monitor. Set only if monitoring a topic, not for a queue.
*/
subscriptionName?: pulumi.Input<string>;
/**
* The name of an app setting that contains the Service Bus connection string to use for this binding.
*/
connection: pulumi.Input<string>;
}
/**
* Data that will be passed along in the context object to the ServiceBusCallback.
*/
export interface ServiceBusContext extends appservice.Context<appservice.FunctionDefaultResponse> {
invocationId: string;
executionContext: {
invocationId: string;
functionName: string;
functionDirectory: string;
};
bindings: { message: string };
bindingData: {
deadLetterSource: any;
messageId: string;
contentType: string;
replyTo: any;
to: any;
label: any;
correlationId: any,
properties: Record<string, any>;
message: string,
sys: {
methodName: string;
utcNow: string;
},
invocationId: string;
};
}
/**
* Host settings specific to the Service Bus Queue/Topic/Subscription plugin.
*
* For more details see https://docs.microsoft.com/en-us/azure/azure-functions/functions-bindings-service-bus#host-json
*/
export interface ServiceBusHostExtensions extends appservice.HostSettings {
/** The default PrefetchCount that will be used by the underlying MessageReceiver. */
prefetchCount?: number,
messageHandlerOptions?: {
/** Whether the trigger should immediately mark as complete (autocomplete) or wait for processing to call complete. */
autoComplete?: boolean,
/** The maximum number of concurrent calls to the callback that the message pump should initiate.
* By default, the Functions runtime processes multiple messages concurrently. To direct the runtime to process only
* a single queue or topic message at a time, set maxConcurrentCalls to 1.
*/
maxConcurrentCalls?: number,
/** The maximum duration within which the message lock will be renewed automatically. */
maxAutoRenewDuration?: string,
},
}
export interface ServiceBusHostSettings extends appservice.HostSettings {
extensions?: {
serviceBus: ServiceBusHostExtensions,
}
}
/**
* Signature of the callback that can receive queue and topic notifications.
*/
export type ServiceBusCallback = appservice.Callback<ServiceBusContext, string, appservice.FunctionDefaultResponse>;
export interface ServiceBusFunctionArgs extends appservice.CallbackFunctionArgs<ServiceBusContext, string, appservice.FunctionDefaultResponse> {
/**
* The ServiceBus Queue to subscribe to.
*/
queue?: Queue;
/**
* The ServiceBus Topic to subscribe to.
*/
topic?: Topic;
/**
* The ServiceBus Subscription to subscribe the Function to.
*/
subscription?: Subscription;
}
export interface QueueEventSubscriptionArgs extends appservice.CallbackFunctionAppArgs<ServiceBusContext, string, appservice.FunctionDefaultResponse> {
/**
* The name of the resource group in which to create the event subscription. [resourceGroup] takes precedence over [resourceGroupName].
* If none of the two is supplied, the Queue's resource group will be used.
*/
resourceGroupName?: pulumi.Input<string>;
/**
* Host settings specific to the Service Bus Topic/Subscription plugin. These values can be provided here, or defaults will
* be used in their place.
*/
hostSettings?: ServiceBusHostSettings;
}
declare module "./queue" {
interface Queue {
/**
* Creates a new subscription to events fired from this Queue to the handler provided, along
* with options to control the behavior of the subscription.
* A dedicated Function App is created behind the scenes with a single Azure Function in it.
* Use [getEventFunction] if you want to compose multiple Functions into the same App manually.
*/
onEvent(
name: string, args: ServiceBusCallback | QueueEventSubscriptionArgs, opts?: pulumi.ComponentResourceOptions): QueueEventSubscription;
/**
* Creates a new Function triggered by messages in the given Queue using the callback provided.
* [getEventFunction] creates no Azure resources automatically: the returned Function should be used as part of
* a [MultiCallbackFunctionApp]. Use [onEvent] if you want to create a Function App with a single Function.
*/
getEventFunction(name: string, args: ServiceBusCallback | appservice.CallbackFunctionArgs<ServiceBusContext, string, appservice.FunctionDefaultResponse>): ServiceBusFunction;
}
}
Queue.prototype.onEvent = function(this: Queue, name, args, opts) {
const functionArgs = args instanceof Function
? <QueueEventSubscriptionArgs>{ callback: args }
: args;
return new QueueEventSubscription(name, this, functionArgs, opts);
}
Queue.prototype.getEventFunction = function(this: Queue, name, args) {
const functionArgs = args instanceof Function
? { callback: args, queue: this }
: { ...args, queue: this };
return new ServiceBusFunction(name, functionArgs);
};
export class QueueEventSubscription extends appservice.EventSubscription<ServiceBusContext, string, appservice.FunctionDefaultResponse> {
readonly queue: Queue;
constructor(
name: string, queue: Queue,
args: QueueEventSubscriptionArgs, opts: pulumi.ComponentResourceOptions = {}) {
const resourceGroupName = appservice.getResourceGroupName(args, queue.resourceGroupName);
super("azure:servicehub:QueueEventSubscription",
name,
new ServiceBusFunction(name, { ...args, queue }),
{ ...args, resourceGroupName },
pulumi.mergeOptions(
{ parent: queue, ...opts },
{ aliases: [{ type: "azure:eventhub:QueueEventSubscription" }]}));
this.queue = queue;
this.registerOutputs();
}
}
export interface GetTopicFunctionArgs extends appservice.CallbackFunctionArgs<ServiceBusContext, string, appservice.FunctionDefaultResponse> {
/**
* The ServiceBus Subscription to subscribe the Function to.
*/
subscription?: Subscription;
}
export interface TopicEventSubscriptionArgs extends GetTopicFunctionArgs, QueueEventSubscriptionArgs {
/**
* The maximum number of deliveries. Will default to 10 if not specified.
*/
maxDeliveryCount?: pulumi.Input<number>;
}
declare module "./topic" {
interface Topic {
/**
* Creates a new subscription to events fired from this Topic to the handler provided, along
* with options to control the behavior of the subscription.
* A dedicated Function App is created behind the scenes with a single Azure Function in it.
* Use [getEventFunction] if you want to compose multiple Functions into the same App manually.
*/
onEvent(
name: string, args: ServiceBusCallback | TopicEventSubscriptionArgs, opts?: pulumi.ComponentResourceOptions): TopicEventSubscription;
/**
* Creates a new Function triggered by messages in the given Topic using the callback provided.
* [getEventFunction] creates no Azure resources automatically: the returned Function should be used as part of
* a [MultiCallbackFunctionApp]. Use [onEvent] if you want to create a Function App with a single Function.
*/
getEventFunction(name: string, args: GetTopicFunctionArgs): ServiceBusFunction;
}
}
Topic.prototype.onEvent = function(this: Topic, name, args, opts) {
const functionArgs = args instanceof Function
? <TopicEventSubscriptionArgs>{ callback: args }
: args;
return new TopicEventSubscription(name, this, functionArgs, opts);
}
Topic.prototype.getEventFunction = function(this: Topic, name, args) {
return new ServiceBusFunction(name, { ...args, topic: this });
};
export class TopicEventSubscription extends appservice.EventSubscription<ServiceBusContext, string, appservice.FunctionDefaultResponse> {
readonly topic: Topic;
readonly subscription: Subscription;
constructor(
name: string, topic: Topic,
args: TopicEventSubscriptionArgs, opts: pulumi.ComponentResourceOptions = {}) {
opts = { parent: topic, ...opts };
const resourceGroupName = appservice.getResourceGroupName(args, topic.resourceGroupName);
const subscription = args.subscription || new Subscription(name, {
resourceGroupName,
namespaceName: topic.namespaceName,
topicName: topic.name,
maxDeliveryCount: pulumi.output(args.maxDeliveryCount).apply(c => c === undefined ? 10 : c),
}, opts);
super("azure:servicehub:TopicEventSubscription",
name,
new ServiceBusFunction(name, { ...args, topic, subscription }),
{ ...args, resourceGroupName },
pulumi.mergeOptions(opts, {
aliases: [{ type: "azure:eventhub:TopicEventSubscription" }] }));
this.topic = topic;
this.subscription = subscription;
this.registerOutputs();
}
}
/**
* Azure Function triggered by a ServiceBus Topic.
*/
export class ServiceBusFunction extends appservice.Function<ServiceBusContext, string, appservice.FunctionDefaultResponse> {
constructor(name: string, args: ServiceBusFunctionArgs) {
if (!args.queue && !args.topic) {
throw new Error("Either [queue] or [topic] has to be specified");
}
if (args.queue && args.topic) {
throw new Error("Either one of [queue] or [topic] has to be specified, not both");
}
if (args.queue && args.subscription) {
throw new Error("[subscription] can't be specified in combination with [queue]");
}
if (args.topic && !args.subscription) {
throw new Error("[subscription] must be specified in combination with [topic]");
}
const queueOrTopicId = (args.queue && args.queue.id) || args.topic!.id;
const namespaceName = (args.queue && args.queue.namespaceName) || args.topic!.namespaceName;
const resourceGroupName = (args.queue && args.queue.resourceGroupName) || args.topic!.resourceGroupName;
// The binding does not store the Service Bus connection string directly. Instead, the
// connection string is put into the app settings (under whatever key we want). Then, the
// .connection property of the binding contains the *name* of that app setting key.
const bindingConnectionKey = pulumi.interpolate`ServiceBus${namespaceName}ConnectionKey`;
const trigger = {
name: "message",
direction: "in",
type: "serviceBusTrigger",
queueName: args.queue && args.queue.name,
topicName: args.topic && args.topic.name,
subscriptionName: args.subscription && args.subscription.name,
connection: bindingConnectionKey,
} as ServiceBusBindingDefinition;
// Fold the queue/topic ID into the all so we don't attempt to fetch the namespace until we're sure it has been created.
const namespace = pulumi.all([namespaceName, resourceGroupName, queueOrTopicId])
.apply(([namespaceName, resourceGroupName]) =>
getNamespace({ name: namespaceName, resourceGroupName }));
const appSettings = pulumi.all([namespace.defaultPrimaryConnectionString, bindingConnectionKey]).apply(
([connectionString, key]) => ({ [key]: connectionString }));
super(name, trigger, args, appSettings);
}
} | the_stack |
import { Constant } from './Constant';
import { RecursiveArgument } from './RecursiveArgument';
import { Function } from './Function';
import { Argument } from './Argument';
import { Expression } from './Expression';
import { mXparserConstants } from './mXparserConstants';
import { java } from 'j4ts';
import { Token } from './parsertokens/Token';
/**
* Tutorial class.
*
* @author <b>Mariusz Gromada</b><br>
* <a href="mailto:mariuszgromada.org@gmail.com">mariuszgromada.org@gmail.com</a><br>
* <a href="http://github.com/mariuszgromada/MathParser.org-mXparser" target="_blank">mXparser on GitHub</a><br>
*
* @author <b>Thilo Schaber</b><br>
* Adapted for TypeScript use
*
* @version 3.0.0
*
* @see RecursiveArgument
* @see Expression
* @see Function
* @see Constant
* @class
*/
export class Tutorial {
public static main(args: string[]) {
mXparserConstants.consolePrintln$java_lang_Object(mXparserConstants.LICENSE_$LI$());
const e: Expression = Expression.create();
mXparserConstants.consolePrintln$java_lang_Object(e.getHelp$());
mXparserConstants.consolePrintln$();
mXparserConstants.consolePrintln$java_lang_Object(e.getHelp$java_lang_String("sine"));
mXparserConstants.consolePrintln$();
mXparserConstants.consolePrintln$java_lang_Object(e.getHelp$java_lang_String("inver"));
const e1: Expression = Expression.createWithExpression("2+1");
mXparserConstants.consolePrintln$java_lang_Object(e1.getExpressionString() + " = " + e1.calculate());
e1.setExpressionString("2-1");
mXparserConstants.consolePrintln$java_lang_Object(e1.getExpressionString() + " = " + e1.calculate());
const e2: Expression = Expression.createWithExpression("2-(32-4)/(23+(4)/(5))-(2-4)*(4+6-98.2)+4");
mXparserConstants.consolePrintln$java_lang_Object(e2.getExpressionString() + " = " + e2.calculate());
const e3: Expression = Expression.createWithExpression("2^3+2^(-3)+2^3^(-4)");
mXparserConstants.consolePrintln$java_lang_Object(e3.getExpressionString() + " = " + e3.calculate());
const e4: Expression = Expression.createWithExpression("2=3");
mXparserConstants.consolePrintln$java_lang_Object(e4.getExpressionString() + " = " + e4.calculate());
const e5: Expression = Expression.createWithExpression("2<3");
mXparserConstants.consolePrintln$java_lang_Object(e5.getExpressionString() + " = " + e5.calculate());
const e6: Expression = Expression.createWithExpression("(2=3) | (2<3)");
mXparserConstants.consolePrintln$java_lang_Object(e6.getExpressionString() + " = " + e6.calculate());
const e7: Expression = Expression.createWithExpression("(2=3) & (2<3)");
mXparserConstants.consolePrintln$java_lang_Object(e7.getExpressionString() + " = " + e7.calculate());
const e8: Expression = Expression.createWithExpression("sin(2)-cos(3)");
mXparserConstants.consolePrintln$java_lang_Object(e8.getExpressionString() + " = " + e8.calculate());
const e9: Expression = Expression.createWithExpression("min(3,4) + max(-2,-1)");
mXparserConstants.consolePrintln$java_lang_Object(e9.getExpressionString() + " = " + e9.calculate());
const e10: Expression = Expression.createWithExpression("C(10,5)");
mXparserConstants.consolePrintln$java_lang_Object(e10.getExpressionString() + " = " + e10.calculate());
const e11: Expression = Expression.createWithExpression("if(2<3,1,0)");
mXparserConstants.consolePrintln$java_lang_Object(e11.getExpressionString() + " = " + e11.calculate());
const e12: Expression = Expression.createWithExpression("if(3<2,1,0)");
mXparserConstants.consolePrintln$java_lang_Object(e12.getExpressionString() + " = " + e12.calculate());
const e13: Expression = Expression.createWithExpression("if(3<2, 1, if(1=1, 5, 0) )");
mXparserConstants.consolePrintln$java_lang_Object(e13.getExpressionString() + " = " + e13.calculate());
const x: Argument = Argument.createArgumentWithNameAndValue("x", 1);
let y: Argument = Argument.createArgumentWithNameAndValue("y", 2);
const z: Argument = Argument.createArgumentWithNameAndValue("z", 3);
let n: Argument = Argument.createArgumentWithNameAndValue("n", 4);
const e14: Expression = Expression.createWithExpressionAndArgumentValues("sin(x+y)-cos(y/z)", x, y, z);
mXparserConstants.consolePrintln$java_lang_Object(e14.getExpressionString() + " = " + e14.calculate());
const e15: Expression = Expression.createWithExpressionAndArgumentValues("if(x>y, x-z, if(y<z, sin(x+y), cos(z)) )", x, y, z);
mXparserConstants.consolePrintln$java_lang_Object(e15.getExpressionString() + " = " + e15.calculate());
x.setArgumentValue(5);
mXparserConstants.consolePrintln$java_lang_Object(x.getArgumentName() + " = " + x.getArgumentValue());
y = new Argument("y", "2*x+5", x);
mXparserConstants.consolePrintln$java_lang_Object(y.getArgumentName() + " = " + y.getArgumentValue());
y = new Argument("y", "sin(y)-z", y, z);
mXparserConstants.consolePrintln$java_lang_Object(y.getArgumentName() + " = " + y.getArgumentValue());
y.setArgumentExpressionString("n*sin(y)-z");
mXparserConstants.consolePrintln$java_lang_Object(y.getArgumentName() + " = ... \n syntax = " + y.checkSyntax() + "\n message = \n" + y.getErrorMessage());
y.addDefinitions(n);
mXparserConstants.consolePrintln$java_lang_Object(y.getArgumentName() + " = ... \n syntax = " + y.checkSyntax() + "\n message = \n" + y.getErrorMessage());
mXparserConstants.consolePrintln$java_lang_Object(y.getArgumentName() + " = " + y.getArgumentValue());
const e16: Expression = Expression.createWithExpression("sum(i,1,10,i)");
mXparserConstants.consolePrintln$java_lang_Object(e16.getExpressionString() + " = " + e16.calculate());
const e17: Expression = Expression.createWithExpression("sum(i,1,10,i,0.5)");
mXparserConstants.consolePrintln$java_lang_Object(e17.getExpressionString() + " = " + e17.calculate());
const e18: Expression = Expression.createWithExpression("prod(i,1,5,i)");
mXparserConstants.consolePrintln$java_lang_Object(e18.getExpressionString() + " = " + e18.calculate());
const e19: Expression = Expression.createWithExpression("prod(i,1,5,i,0.5)");
mXparserConstants.consolePrintln$java_lang_Object(e19.getExpressionString() + " = " + e19.calculate());
const e20: Expression = Expression.createWithExpressionAndArgumentValues("sin(x)-sum(n,0,10,(-1)^n*(x^(2*n+1))/(2*n+1)!)", x);
x.setArgumentValue(1);
mXparserConstants.consolePrintln$java_lang_Object("x = " + x.getArgumentValue() + ", " + e20.getExpressionString() + " = " + e20.calculate());
x.setArgumentValue(5);
mXparserConstants.consolePrintln$java_lang_Object("x = " + x.getArgumentValue() + ", " + e20.getExpressionString() + " = " + e20.calculate());
x.setArgumentValue(10);
mXparserConstants.consolePrintln$java_lang_Object("x = " + x.getArgumentValue() + ", " + e20.getExpressionString() + " = " + e20.calculate());
const d: Argument = Argument.createArgumentWithNameAndValue("d", 0.1);
const e21: Expression = Expression.createWithExpressionAndArgumentValues("2*sum(x, -1, 1, d*sqrt(1-x^2), d)", d);
mXparserConstants.consolePrintln$java_lang_Object("d = " + d.getArgumentValue() + ", " + e21.getExpressionString() + " = " + e21.calculate());
d.setArgumentValue(0.01);
mXparserConstants.consolePrintln$java_lang_Object("d = " + d.getArgumentValue() + ", " + e21.getExpressionString() + " = " + e21.calculate());
const e22: Expression = Expression.createWithExpressionAndArgumentValues("cos(x)-der(sin(x), x)", x);
mXparserConstants.consolePrintln$java_lang_Object(e22.getExpressionString() + " = " + e22.calculate());
x.setArgumentValue(0);
const e23: Expression = Expression.createWithExpressionAndArgumentValues("der-(abs(x), x)", x);
mXparserConstants.consolePrintln$java_lang_Object("x = " + x.getArgumentValue() + ", " + e23.getExpressionString() + " = " + e23.calculate());
const e24: Expression = Expression.createWithExpressionAndArgumentValues("der+(abs(x), x)", x);
mXparserConstants.consolePrintln$java_lang_Object("x = " + x.getArgumentValue() + ", " + e24.getExpressionString() + " = " + e24.calculate());
x.setArgumentValue(1);
const e25: Expression = Expression.createWithExpressionAndArgumentValues("cos(x)-der(sum(n,0,10,(-1)^n*(x^(2*n+1))/(2*n+1)!), x)", x);
x.setArgumentValue(1);
mXparserConstants.consolePrintln$java_lang_Object("x = " + x.getArgumentValue() + ", " + e25.getExpressionString() + " = " + e25.calculate());
x.setArgumentValue(5);
mXparserConstants.consolePrintln$java_lang_Object("x = " + x.getArgumentValue() + ", " + e25.getExpressionString() + " = " + e25.calculate());
x.setArgumentValue(10);
mXparserConstants.consolePrintln$java_lang_Object("x = " + x.getArgumentValue() + ", " + e25.getExpressionString() + " = " + e25.calculate());
const e26: Expression = Expression.createWithExpression("2*int(sqrt(1-x^2), x, -1, 1)");
mXparserConstants.consolePrintln$java_lang_Object(e26.getExpressionString() + " = " + e26.calculate());
const e27: Expression = Expression.createWithExpression("pi");
mXparserConstants.consolePrintln$java_lang_Object(e27.getExpressionString() + " = " + e27.calculate());
const e28: Expression = Expression.createWithExpression("e");
mXparserConstants.consolePrintln$java_lang_Object(e28.getExpressionString() + " = " + e28.calculate());
let f: Function = new Function("f", "x^2", "x");
const e29: Expression = Expression.createWithExpression("f(2)");
e29.addDefinitions(f);
mXparserConstants.consolePrintln$java_lang_Object(e29.getExpressionString() + " = " + e29.calculate());
f = new Function("f(a,b,c)=a+b+c");
const e30: Expression = Expression.createWithExpression("f(1, 2, 3)");
e30.addDefinitions(f);
mXparserConstants.consolePrintln$java_lang_Object(e30.getExpressionString() + " = " + e30.calculate());
f = new Function("f", "x^2", "x");
const g: Function = new Function("g", "f(x)^2", "x");
g.addDefinitions(f);
mXparserConstants.consolePrintln$java_lang_Object("g(2) = " + g.calculate$double_A(2));
const e31: Expression = Expression.createWithExpressionAndArgumentValues("f(x)+g(2*x)", x);
e31.addDefinitions(f, g);
mXparserConstants.consolePrintln$java_lang_Object("x = " + x.getArgumentValue() + ", " + e31.getExpressionString() + " = " + e31.calculate());
x.setArgumentValue(2);
const e32: Expression = Expression.createWithExpressionAndArgumentValues("der(g(x),x)", x);
e32.addDefinitions(g);
mXparserConstants.consolePrintln$java_lang_Object("x = " + x.getArgumentValue() + ", " + e32.getExpressionString() + " = " + e32.calculate());
f = new Function("f", "sin(x)", "x");
const F: Function = new Function("F", "int(f(t), t, 0, x)", "x");
F.addDefinitions(f);
const e33: Expression = Expression.createWithExpressionAndArgumentValues("f(x) - der(F(x),x)", x);
e33.addDefinitions(f, F);
mXparserConstants.consolePrintln$java_lang_Object("x = " + x.getArgumentValue() + ", " + e33.getExpressionString() + " = " + e33.calculate() + ", computing time : " + e33.getComputingTime() + " s.");
n = new Argument("n");
const fib1: RecursiveArgument = new RecursiveArgument("fib1", "fib1(n-1)+fib1(n-2)", n);
fib1.addBaseCase(0, 0);
fib1.addBaseCase(1, 1);
mXparserConstants.consolePrintln$java_lang_Object("fib1: ");
for(let i: number = 0; i <= 10; i++) {mXparserConstants.consolePrint(fib1.getArgumentValue$double(i) + ", ");}
mXparserConstants.consolePrintln$();
const fib2: RecursiveArgument = new RecursiveArgument("fib2", "if( n>1, fib2(n-1)+fib2(n-2), if(n=1,1,0) )", n);
mXparserConstants.consolePrintln$java_lang_Object("fib2: ");
for(let i: number = 0; i <= 10; i++) {mXparserConstants.consolePrint(fib2.getArgumentValue$double(i) + ", ");}
mXparserConstants.consolePrintln$();
const e34: Expression = Expression.createWithExpressionAndArgumentValues("sum(i, 0, 10, fib1(i))", fib1);
mXparserConstants.consolePrintln$java_lang_Object(e34.getExpressionString() + " = " + e34.calculate() + ", computing time : " + e34.getComputingTime() + " s.");
const e35: Expression = Expression.createWithExpressionAndArgumentValues("sum(i, 0, 10, fib2(i))", fib2);
mXparserConstants.consolePrintln$java_lang_Object(e35.getExpressionString() + " = " + e35.calculate() + ", computing time : " + e35.getComputingTime() + " s.");
const fib3: Function = new Function("fib3", "if(n>1, fib3(n-1)+fib3(n-2), if(n>0,1,0))", "n");
mXparserConstants.consolePrintln$java_lang_Object("fib3: ");
for(let i: number = 0; i <= 10; i++) {mXparserConstants.consolePrint(fib3.calculate$double_A(i) + ", ");}
mXparserConstants.consolePrintln$();
const e36: Expression = Expression.createWithExpression("sum(i, 0, 10, fib3(i))");
e36.addDefinitions(fib3);
mXparserConstants.consolePrintln$java_lang_Object(e36.getExpressionString() + " = " + e36.calculate() + ", computing time : " + e36.getComputingTime() + " s.");
const T: Function = new Function("T", "if(n>1, 2*x*T(n-1,x)-T(n-2,x), if(n>0, x, 1) )", "n", "x");
const k: Argument = Argument.createArgumentWithNameAndValue("k", 5);
const e37: Expression = Expression.createWithExpressionAndArgumentValues("T(k,x) - ( (x + sqrt(x^2-1))^k + (x - sqrt(x^2-1))^k)/2", k, x);
e37.addDefinitions(T);
mXparserConstants.consolePrintln$java_lang_Object(e37.getExpressionString() + " = " + e37.calculate() + ", computing time : " + e37.getComputingTime() + " s.");
const Cnk: Function = new Function("Cnk", "if( k>0, if( k<n, Cnk(n-1,k-1)+Cnk(n-1,k), 1), 1)", "n", "k");
const e38: Expression = Expression.createWithExpression("C(10,5) - Cnk(10,5)");
e38.addDefinitions(Cnk);
mXparserConstants.consolePrintln$java_lang_Object(e38.getExpressionString() + " = " + e38.calculate() + ", computing time : " + e38.getComputingTime() + " s.");
const a: Constant = new Constant("a", 5);
const b: Constant = new Constant("b", 10);
const c: Constant = new Constant("c", 15);
const e39: Expression = Expression.createWithExpression("a+b+c");
e39.addDefinitions(a, b, c);
e39.setVerboseMode();
e39.checkSyntax$();
mXparserConstants.consolePrintln$();
mXparserConstants.consolePrintln$java_lang_Object(e39.getErrorMessage());
mXparserConstants.consolePrintln$java_lang_Object(e39.getExpressionString() + " = " + e39.calculate() + ", computing time : " + e39.getComputingTime() + " s.");
}
}
Tutorial["__class"] = "org.mariuszgromada.math.mxparser.Tutorial";
Tutorial.main(null); | the_stack |
import {
classNames,
layout as templateLayout,
} from '@ember-decorators/component';
import { inject as service } from '@ember/service';
import ComputedProperty, { alias } from '@ember/object/computed';
import Component from '@ember/component';
// @ts-ignore: templates don't have types
import layout from '../templates/components/animated-orphans';
import { task, Task } from '../-private/ember-scheduler';
import { afterRender, microwait, continueMotions } from '..';
import TransitionContext, {
runToCompletion,
} from '../-private/transition-context';
import { spawnChild, childrenSettled, current } from '../-private/scheduler';
import Sprite from '../-private/sprite';
import partition from '../-private/partition';
import '../element-remove';
import MotionService from '../services/motion';
import { action } from '@ember/object';
import { Transition } from '../-private/transition';
/**
A component that adopts any orphaned sprites so they can continue animating even
after their original parent component has been destroyed. This relies on cloning
DOM nodes, and the cloned nodes will be inserted as children of animated-orphans.
```hbs
<AnimatedOrphans/>
```
@class animated-orphans
@public
*/
@templateLayout(layout)
@classNames('animated-orphans')
export default class AnimatedOrphans extends Component {
@service('-ea-motion')
motionService!: MotionService;
private _newOrphanTransitions = [] as {
removedSprites: Sprite[];
transition: Transition;
duration: number;
shouldAnimateRemoved: boolean;
}[];
private _elementToChild = new WeakMap();
private _childToTransition = new WeakMap();
private _inserted = false;
private _cycleCounter = 0;
didInsertElement() {
this._inserted = true;
this.get('motionService')
.register(this)
.observeOrphans(this.animateOrphans)
.observeAnimations(this.reanimate);
}
willDestroyElement() {
this.get('motionService')
.unregister(this)
.unobserveOrphans(this.animateOrphans)
.unobserveAnimations(this.reanimate);
}
@action
animateOrphans(
removedSprites: Sprite[],
transition: Transition,
duration: number,
shouldAnimateRemoved: boolean,
) {
this._newOrphanTransitions.push({
removedSprites: removedSprites.map((sprite: Sprite) => {
// we clone the owner objects so that our sprite garbage
// collection is entirely detached from the original
// animator's
sprite.assertHasOwner();
sprite.owner = sprite.owner.clone();
sprite.owner.flagForRemoval();
return sprite;
}),
transition,
duration,
shouldAnimateRemoved,
});
this.reanimate();
}
@action
reanimate() {
if (!this.get('startAnimation.isRunning' as any)) {
let ownSprite = new Sprite(this.element, true, null, null);
let activeSprites = this._findActiveSprites(ownSprite);
this.get('animate').perform({ ownSprite, activeSprites });
}
}
beginStaticMeasurement() {
// we don't have any impact on static layout
}
endStaticMeasurement() {}
@alias('animate.isRunning')
isAnimating!: boolean;
@(task(function*(this: AnimatedOrphans, { ownSprite, activeSprites }) {
yield this.get('startAnimation').perform(ownSprite);
let { matchingAnimatorsFinished } = (yield this.get('runAnimation').perform(
activeSprites,
ownSprite,
)) as { matchingAnimatorsFinished: Promise<void> };
yield this.get('finalizeAnimation').perform(
activeSprites,
matchingAnimatorsFinished,
);
}).restartable())
animate!: ComputedProperty<Task>;
@task(function*(this: AnimatedOrphans, ownSprite) {
yield afterRender();
ownSprite.measureFinalBounds();
})
startAnimation!: ComputedProperty<Task>;
@task(function*(this: AnimatedOrphans, activeSprites, ownSprite) {
// we don't need any static measurements, but we wait for this so
// we stay on the same timing as all the other animators
yield* this.get('motionService').staticMeasurement(() => {});
// Some of the new orphan transitions may be handing us sprites we
// already have matches for, in which case our active sprites take
// precedence.
{
let activeIds = Object.create(null);
for (let sprite of activeSprites) {
activeIds[`${sprite.owner.group}/${sprite.owner.id}`] = true;
}
for (let entry of this._newOrphanTransitions) {
entry.removedSprites = entry.removedSprites.filter((s: Sprite) => {
s.assertHasOwner();
return !activeIds[`${s.owner.group}/${s.owner.id}`];
});
}
}
// our sprites from prior animation runs are eligible to be
// matched by other animators (this is how an orphan sprites that
// are animating away can get interrupted into coming back)
let { farMatches, matchingAnimatorsFinished } = (yield this.get(
'motionService',
)
.get('farMatch')
.perform(
current(),
[],
[],
activeSprites.concat(
...this._newOrphanTransitions.map(t => t.removedSprites),
),
)) as {
matchingAnimatorsFinished: Promise<void>;
farMatches: Map<Sprite, Sprite>;
};
let cycle = this._cycleCounter++;
for (let { transition, duration, sprites } of this._groupActiveSprites(
activeSprites,
)) {
let [sentSprites, removedSprites] = partition(sprites, sprite => {
let other = farMatches.get(sprite);
if (other) {
sprite.endAtSprite(other);
if (other.revealed && !sprite.revealed) {
sprite.startAtSprite(other);
}
return true;
}
return false;
});
let context = new TransitionContext(
duration,
[],
[],
removedSprites,
sentSprites,
[],
{},
this._onMotionStart.bind(this, cycle),
this._onMotionEnd.bind(this, cycle),
);
spawnChild(function*() {
// let other animators make their own partitioning decisions
// before we start hiding the sent & received sprites
yield microwait();
sentSprites.forEach(s => s.hide());
yield* runToCompletion(context, transition);
});
}
while (this._newOrphanTransitions.length > 0) {
// This is a pop instead of a shift because we want to start the
// animations in the reverse order that they were
// scheduled. This is a consequence of Ember's
// willDestroyElement firing from top to bottom. We want
// descendants have a chance to start before their ancestors,
// because each one is going to potentially trigger DOM cloning,
// so any animated descendants need to get hidden before one of
// their ancestors clones them.
let entry = this._newOrphanTransitions.pop()!;
let {
transition,
duration,
removedSprites,
shouldAnimateRemoved,
} = entry;
if (removedSprites.length === 0) {
// This can happen due to our filtering based on activeIds
// above: some new orphan transitions may have nothing new
// that we aren't already animating.
continue;
}
for (let _sprite of removedSprites) {
// typesecript workaround for https://github.com/microsoft/TypeScript/issues/35940
let sprite: Sprite = _sprite;
sprite.assertHasOwner();
sprite.rehome(ownSprite);
this._childToTransition.set(sprite.owner, entry);
}
let [sentSprites, unmatchedRemovedSprites] = partition(
removedSprites,
sprite => {
let other = farMatches.get(sprite);
if (other) {
sprite.endAtSprite(other);
if (other.revealed && !sprite.revealed) {
sprite.startAtSprite(other);
}
return true;
}
return false;
},
);
let self = this;
spawnChild(function*() {
yield microwait();
sentSprites.forEach(s => s.hide());
// now that we've hidden any sent sprites, we can bail out
// early if there is no transition they want to run
if (!transition) {
return;
}
let removedSprites: Sprite[];
if (shouldAnimateRemoved) {
removedSprites = unmatchedRemovedSprites;
} else {
removedSprites = [];
}
// Early bail out if there's nothing left that could animate
if (removedSprites.length === 0 && sentSprites.length === 0) {
return;
}
let context = new TransitionContext(
duration,
[],
[],
removedSprites,
sentSprites,
[],
{},
self._onFirstMotionStart.bind(self, activeSprites, cycle),
self._onMotionEnd.bind(self, cycle),
);
context.prepareSprite = self._prepareSprite.bind(self);
yield* runToCompletion(context, transition);
});
}
yield childrenSettled();
return { matchingAnimatorsFinished };
})
runAnimation!: ComputedProperty<Task>;
@task(function*(activeSprites, matchingAnimatorsFinished) {
yield matchingAnimatorsFinished;
for (let sprite of activeSprites) {
sprite.element.remove();
}
})
finalizeAnimation!: ComputedProperty<Task>;
_findActiveSprites(ownSprite: Sprite) {
if (!this._inserted) {
return [];
}
return Array.from(this.element.children)
.map(element => {
let child = this._elementToChild.get(element);
if (child.shouldRemove) {
// child was not animating in the previously interrupted
// animation, so its safe to remove
element.remove();
return undefined;
} else {
let sprite = Sprite.positionedStartingAt(element, ownSprite);
sprite.owner = child;
// we need to flag each existing child for removal at the
// start of each animation. That's what reinitializes its
// removal blockers count.
child.flagForRemoval();
return sprite;
}
})
.filter(Boolean);
}
_groupActiveSprites(
activeSprites: Sprite[],
): { transition: Transition; duration: number; sprites: Sprite[] }[] {
let groups = [] as ReturnType<AnimatedOrphans['_groupActiveSprites']>;
for (let _sprite of activeSprites) {
// ts workaround for https://github.com/microsoft/TypeScript/issues/35940
let sprite: Sprite = _sprite;
sprite.assertHasOwner();
let { transition, duration } = this._childToTransition.get(sprite.owner);
let group = groups.find(g => g.transition === transition);
if (!group) {
group = { transition, duration, sprites: [] };
groups.push(group);
}
group.sprites.push(sprite);
}
return groups;
}
_prepareSprite(sprite: Sprite) {
sprite.hide();
let newElement = sprite.element.cloneNode(true) as Element;
continueMotions(sprite.element, newElement);
sprite.element = newElement;
return sprite;
}
_onFirstMotionStart(activeSprites: Sprite[], cycle: number, sprite: Sprite) {
if (activeSprites.indexOf(sprite) === -1) {
// in most animators, sprites are still living in their normal place in
// the DOM, and so they will necessarily start out with their appearance
// matching initialComputedStyles. But here we're dealing with an orphan
// who may have lost inherited styles. So we manually re-apply the
// initialComputedStyles that were snapshotted before it was moved. See
// COPIED_CSS_PROPERTIES to see exactly which property we copy (we don't
// do all of them, that sounds expensive).
//
// Also, unfortunately getComputedStyles has legacy behavior for
// line-height that gives us the "used value" not the "computed value".
// The used value doesn't inherit correctly, so we can't set it here, so
// we're pulling that one out.
let s = Object.assign({}, sprite.initialComputedStyle);
delete s['line-height'];
sprite.applyStyles(s);
this.element.appendChild(sprite.element);
sprite.lock();
sprite.reveal();
activeSprites.push(sprite);
this._elementToChild.set(sprite.element, sprite.owner);
}
sprite.assertHasOwner();
sprite.owner.block(cycle);
}
_onMotionStart(cycle: number, sprite: Sprite) {
sprite.assertHasOwner();
sprite.reveal();
sprite.owner.block(cycle);
}
_onMotionEnd(cycle: number, sprite: Sprite) {
sprite.assertHasOwner();
sprite.owner.unblock(cycle);
}
} | the_stack |
import { uuid } from 'uuidv4'
import { Op } from 'sequelize'
import each from 'jest-each'
import { Test } from '@nestjs/testing'
import { getModelToken } from '@nestjs/sequelize'
import { ForbiddenException, NotFoundException } from '@nestjs/common'
import {
CaseFileState,
CaseState,
UserRole,
} from '@island.is/judicial-system/types'
import type { User } from '@island.is/judicial-system/types'
import { LoggingModule } from '@island.is/logging'
import { Case, CaseService } from '../case'
import { CourtService } from '../court'
import { AwsS3Service } from './awsS3.service'
import { CaseFile } from './models'
import { FileService } from './file.service'
import { FileController } from './file.controller'
describe('FileController', () => {
let fileModel: {
create: jest.Mock
findAll: jest.Mock
findOne: jest.Mock
update: jest.Mock
}
let caseService: CaseService
let courtService: CourtService
let awsS3Service: AwsS3Service
let fileController: FileController
beforeEach(async () => {
fileModel = {
create: jest.fn(),
findAll: jest.fn(),
findOne: jest.fn(),
update: jest.fn(),
}
const fileModule = await Test.createTestingModule({
imports: [LoggingModule],
controllers: [FileController],
providers: [
{
provide: CaseService,
useClass: jest.fn(() => ({
findByIdAndUser: (id: string, _: User) =>
Promise.resolve({ id } as Case),
})),
},
{
provide: CourtService,
useClass: jest.fn(() => ({
uploadStream: jest.fn(),
createDocument: jest.fn(),
})),
},
{
provide: AwsS3Service,
useClass: jest.fn(() => ({
createPresignedPost: (key: string) =>
Promise.resolve({
url:
'https://s3.eu-west-1.amazonaws.com/island-is-dev-upload-judicial-system',
fields: {
key,
bucket: 'island-is-dev-upload-judicial-system',
'X-Amz-Algorithm': 'Some Algorithm',
'X-Amz-Credential': 'Some Credentials',
'X-Amz-Date': 'Some Date',
'X-Amz-Security-Token': 'Some Token',
Policy: 'Some Policy',
'X-Amz-Signature': 'Some Signature',
},
}),
deleteObject: () => Promise.resolve(true),
getSignedUrl: jest.fn(),
objectExists: () => Promise.resolve(true),
getObject: () => jest.fn(),
})),
},
{
provide: getModelToken(CaseFile),
useValue: fileModel,
},
FileService,
],
}).compile()
caseService = fileModule.get<CaseService>(CaseService)
courtService = fileModule.get<CourtService>(CourtService)
awsS3Service = fileModule.get<AwsS3Service>(AwsS3Service)
fileController = fileModule.get<FileController>(FileController)
})
describe('when uploading a case file', () => {
// RolesGuard blocks access for roles other than PROSECUTOR
const prosecutor = { role: UserRole.PROSECUTOR } as User
each`
state
${CaseState.NEW}
${CaseState.DRAFT}
${CaseState.SUBMITTED}
${CaseState.RECEIVED}
`.describe('given an uncompleted $state case', ({ state }) => {
const caseId = uuid()
beforeEach(() => {
const mockFindByIdAndUser = jest.spyOn(caseService, 'findByIdAndUser')
mockFindByIdAndUser.mockImplementation((id: string) =>
Promise.resolve({ id, state } as Case),
)
})
it('should create a presigned post', async () => {
const fileName = 'test.txt'
const type = 'text/plain'
const presignedPost = await fileController.createCasePresignedPost(
caseId,
prosecutor,
{ fileName, type },
)
expect(presignedPost).toStrictEqual({
url:
'https://s3.eu-west-1.amazonaws.com/island-is-dev-upload-judicial-system',
fields: {
key: presignedPost.fields.key,
bucket: 'island-is-dev-upload-judicial-system',
'X-Amz-Algorithm': 'Some Algorithm',
'X-Amz-Credential': 'Some Credentials',
'X-Amz-Date': 'Some Date',
'X-Amz-Security-Token': 'Some Token',
Policy: 'Some Policy',
'X-Amz-Signature': 'Some Signature',
},
})
expect(presignedPost.fields.key).toMatch(
new RegExp(`^${caseId}/.{36}/${fileName}$`),
)
})
it('should create a case file', async () => {
const id = uuid()
const timeStamp = new Date()
const fileName = 'test.txt'
const type = 'text/plain'
const size = 99999
fileModel.create.mockImplementation(
(values: {
key: string
size: number
caseId: string
name: string
}) =>
Promise.resolve({
...values,
id,
created: timeStamp,
modified: timeStamp,
}),
)
const presignedPost = await fileController.createCasePresignedPost(
caseId,
prosecutor,
{ fileName, type },
)
const file = await fileController.createCaseFile(caseId, prosecutor, {
type,
key: presignedPost.fields.key,
size,
})
expect(file).toStrictEqual({
id,
created: timeStamp,
modified: timeStamp,
caseId,
name: fileName,
type,
key: presignedPost.fields.key,
size,
})
})
})
each`
state
${CaseState.ACCEPTED}
${CaseState.REJECTED}
${CaseState.DISMISSED}
`.describe('given a completed $state case', ({ state }) => {
const caseId = uuid()
beforeEach(() => {
const mockFindByIdAndUser = jest.spyOn(caseService, 'findByIdAndUser')
mockFindByIdAndUser.mockImplementation((id: string) =>
Promise.resolve({ id, state } as Case),
)
})
it('should throw when creating a presigned post', async () => {
const fileName = 'test.txt'
const type = 'text/plain'
await expect(
fileController.createCasePresignedPost(caseId, prosecutor, {
fileName,
type,
}),
).rejects.toThrow(ForbiddenException)
})
it('should throw when creating a case file', async () => {
const type = 'text/plain'
const key = `${caseId}/${uuid()}/test.txt`
const size = 99999
await expect(
fileController.createCaseFile(caseId, prosecutor, {
type,
key,
size,
}),
).rejects.toThrow(ForbiddenException)
})
})
describe('given a non-existing (or blocked) case', () => {
const caseId = uuid()
beforeEach(() => {
const mockFindByIdAndUser = jest.spyOn(caseService, 'findByIdAndUser')
mockFindByIdAndUser.mockRejectedValueOnce(new Error('Some error'))
})
it('should throw when creating a presigned url', async () => {
const fileName = 'test.txt'
const type = 'text/plain'
await expect(
fileController.createCasePresignedPost(caseId, prosecutor, {
fileName,
type,
}),
).rejects.toThrow('Some error')
})
it('should throw when creating a case file', async () => {
const type = 'text/plain'
const key = `${caseId}/${uuid()}/test.txt`
const size = 99999
await expect(
fileController.createCaseFile(caseId, prosecutor, {
type,
key,
size,
}),
).rejects.toThrow('Some error')
})
})
})
describe('when getting all case files', () => {
// RolesGuard blocks access for the ADMIN role. Also, mockFindByIdAndUser
// blocks access for some roles to some cases. This is not relevant in
// this test.
const user = {} as User
describe('given a case', () => {
const caseId = uuid()
it('should get all case files (not deleted)', async () => {
const mockFiles = [{ id: uuid() }, { id: uuid() }]
fileModel.findAll.mockResolvedValueOnce(mockFiles)
const files = await fileController.getAllCaseFiles(caseId, user)
expect(fileModel.findAll).toHaveBeenCalledWith({
where: {
caseId,
state: { [Op.not]: CaseFileState.DELETED },
},
order: [['created', 'DESC']],
})
expect(files).toStrictEqual(mockFiles)
})
})
describe('given a non-existing (or blocked) case', () => {
const caseId = uuid()
beforeEach(() => {
const mockFindByIdAndUser = jest.spyOn(caseService, 'findByIdAndUser')
mockFindByIdAndUser.mockRejectedValueOnce(new Error('Some error'))
})
it('should throw when getting all case files', async () => {
await expect(
fileController.getAllCaseFiles(caseId, user),
).rejects.toThrow('Some error')
})
})
})
describe('when removing a case file', () => {
// RolesGuard blocks access for roles other than PROSECUTOR
const prosecutor = { role: UserRole.PROSECUTOR } as User
each`
state
${CaseState.NEW}
${CaseState.DRAFT}
${CaseState.SUBMITTED}
${CaseState.RECEIVED}
`.describe('given an uncompleted $state case', ({ state }) => {
const caseId = uuid()
beforeEach(() => {
const mockFindByIdAndUser = jest.spyOn(caseService, 'findByIdAndUser')
mockFindByIdAndUser.mockImplementation((id: string) =>
Promise.resolve({ id, state } as Case),
)
})
describe('given a case file', () => {
const fileId = uuid()
const key = `${caseId}/${fileId}/text.txt`
const mockFile = {
id: fileId,
caseId,
key,
}
beforeEach(() => {
fileModel.findOne.mockResolvedValueOnce(mockFile)
})
it('should delete the case file', async () => {
fileModel.update.mockResolvedValueOnce([1])
const mockDeleteObject = jest.spyOn(awsS3Service, 'deleteObject')
const { success } = await fileController.deleteCaseFile(
caseId,
fileId,
prosecutor,
)
expect(fileModel.findOne).toHaveBeenCalledWith({
where: {
id: fileId,
caseId,
state: { [Op.not]: CaseFileState.DELETED },
},
})
expect(fileModel.update).toHaveBeenCalledWith(
{ state: CaseFileState.DELETED },
{ where: { id: fileId } },
)
expect(mockDeleteObject).toHaveBeenCalledWith(key)
expect(success).toBe(true)
})
})
describe('given a non-existing (or deleted) case file', () => {
const fileId = uuid()
beforeEach(() => {
fileModel.findOne.mockResolvedValueOnce(null)
})
it('should throw when deleting the case file', async () => {
await expect(
fileController.deleteCaseFile(caseId, fileId, prosecutor),
).rejects.toThrow(NotFoundException)
})
})
})
each`
state
${CaseState.ACCEPTED}
${CaseState.REJECTED}
${CaseState.DISMISSED}
`.describe('given a completed $state case', ({ state }) => {
const caseId = uuid()
beforeEach(() => {
const mockFindByIdAndUser = jest.spyOn(caseService, 'findByIdAndUser')
mockFindByIdAndUser.mockImplementation((id: string) =>
Promise.resolve({ id, state } as Case),
)
})
it('should throw when deleting the case file', async () => {
const fileId = uuid()
await expect(
fileController.deleteCaseFile(caseId, fileId, prosecutor),
).rejects.toThrow(ForbiddenException)
})
})
describe('given a non-existing (or blocked) case', () => {
const caseId = uuid()
beforeEach(() => {
const mockFindByIdAndUser = jest.spyOn(caseService, 'findByIdAndUser')
mockFindByIdAndUser.mockRejectedValueOnce(new Error('Some error'))
})
it('should throw when deleting the case file', async () => {
const fileId = uuid()
await expect(
fileController.deleteCaseFile(caseId, fileId, prosecutor),
).rejects.toThrow('Some error')
})
})
})
describe('when getting a case file signed url', () => {
// RolesGuard blocks access for the ADMIN role. Also, mockFindByIdAndUser
// blocks access for some roles to some cases. This is not relevant in
// this test.
each`
state | role | userIsAssignedJudge
${CaseState.NEW} | ${UserRole.PROSECUTOR} | ${false}
${CaseState.DRAFT} | ${UserRole.PROSECUTOR} | ${false}
${CaseState.SUBMITTED} | ${UserRole.PROSECUTOR} | ${false}
${CaseState.RECEIVED} | ${UserRole.PROSECUTOR} | ${false}
${CaseState.RECEIVED} | ${UserRole.JUDGE} | ${true}
${CaseState.ACCEPTED} | ${UserRole.PROSECUTOR} | ${false}
${CaseState.ACCEPTED} | ${UserRole.REGISTRAR} | ${false}
${CaseState.ACCEPTED} | ${UserRole.JUDGE} | ${false}
${CaseState.REJECTED} | ${UserRole.PROSECUTOR} | ${false}
${CaseState.REJECTED} | ${UserRole.REGISTRAR} | ${false}
${CaseState.REJECTED} | ${UserRole.JUDGE} | ${false}
${CaseState.DISMISSED} | ${UserRole.PROSECUTOR} | ${false}
${CaseState.DISMISSED} | ${UserRole.REGISTRAR} | ${false}
${CaseState.DISMISSED} | ${UserRole.JUDGE} | ${false}
`.describe(
'given a $state case and a permitted $role user',
({ state, role, userIsAssignedJudge }) => {
const caseId = uuid()
const user = { id: uuid(), role } as User
beforeEach(() => {
const mockFindByIdAndUser = jest.spyOn(caseService, 'findByIdAndUser')
mockFindByIdAndUser.mockImplementation((id: string) =>
Promise.resolve({
id,
state,
judgeId: userIsAssignedJudge ? user.id : undefined,
} as Case),
)
})
describe('given a case file', () => {
const fileId = uuid()
const key = `${caseId}/${fileId}/test.txt`
const mockFile = {
id: fileId,
caseId,
key,
}
beforeEach(() => {
fileModel.findOne.mockResolvedValueOnce(mockFile)
})
it('should get a case file signed url', async () => {
const mockUrl = uuid()
const mockGetSignedUrl = jest.spyOn(awsS3Service, 'getSignedUrl')
mockGetSignedUrl.mockResolvedValueOnce({ url: mockUrl })
const { url } = await fileController.getCaseFileSignedUrl(
caseId,
fileId,
user,
)
expect(fileModel.findOne).toHaveBeenCalledWith({
where: {
id: fileId,
caseId,
state: { [Op.not]: CaseFileState.DELETED },
},
})
expect(mockGetSignedUrl).toHaveBeenCalledWith(key)
expect(url).toBe(mockUrl)
})
it('should throw when getting a case file signed url and the file does not exist in AWS S3', async () => {
const mockObjectExists = jest.spyOn(awsS3Service, 'objectExists')
mockObjectExists.mockResolvedValueOnce(false)
await expect(
fileController.getCaseFileSignedUrl(caseId, fileId, user),
).rejects.toThrow(NotFoundException)
expect(fileModel.update).toHaveBeenCalledWith(
{ state: CaseFileState.BOKEN_LINK },
{ where: { id: fileId } },
)
})
})
describe('given a broken link case file', () => {
const fileId = uuid()
const key = `${caseId}/${fileId}/test.txt`
const mockFile = {
id: fileId,
caseId,
state: CaseFileState.BOKEN_LINK,
key,
}
beforeEach(() => {
fileModel.findOne.mockResolvedValueOnce(mockFile)
})
it('should throw when getting a case file signed url', async () => {
await expect(
fileController.getCaseFileSignedUrl(caseId, fileId, user),
).rejects.toThrow(NotFoundException)
})
})
describe('given a non-existing (or deleted) case file', () => {
const fileId = uuid()
beforeEach(() => {
fileModel.findOne.mockResolvedValueOnce(null)
})
it('should throw when getting a case file signed url', async () => {
await expect(
fileController.getCaseFileSignedUrl(caseId, fileId, user),
).rejects.toThrow(NotFoundException)
})
})
},
)
each`
state | role
${CaseState.NEW} | ${UserRole.REGISTRAR}
${CaseState.NEW} | ${UserRole.JUDGE}
${CaseState.DRAFT} | ${UserRole.REGISTRAR}
${CaseState.DRAFT} | ${UserRole.JUDGE}
${CaseState.SUBMITTED} | ${UserRole.REGISTRAR}
${CaseState.SUBMITTED} | ${UserRole.JUDGE}
${CaseState.RECEIVED} | ${UserRole.REGISTRAR}
${CaseState.RECEIVED} | ${UserRole.JUDGE}
`.describe(
'given a $state case and a blocked $role user',
({ state, role }) => {
const caseId = uuid()
const user = { id: uuid(), role } as User
beforeEach(() => {
const mockFindByIdAndUser = jest.spyOn(caseService, 'findByIdAndUser')
mockFindByIdAndUser.mockImplementation((id: string) =>
Promise.resolve({ id, state } as Case),
)
})
it('should throw when getting a case file signed url', async () => {
const fileId = uuid()
await expect(
fileController.getCaseFileSignedUrl(caseId, fileId, user),
).rejects.toThrow(ForbiddenException)
})
},
)
describe('given a non-existing (or blocked) case', () => {
const caseId = uuid()
beforeEach(() => {
const mockFindByIdAndUser = jest.spyOn(caseService, 'findByIdAndUser')
mockFindByIdAndUser.mockRejectedValueOnce(new Error('Some error'))
})
it('should throw when getting a case file signed url', async () => {
const prosecutor = {} as User
const fileId = uuid()
await expect(
fileController.getCaseFileSignedUrl(caseId, fileId, prosecutor),
).rejects.toThrow('Some error')
})
})
})
describe('when uploading a case file to court', () => {
// RolesGuard blocks access for non court roles. Also, mockFindByIdAndUser
// blocks access for some roles to some cases. This is not relevant in
// this test.
each`
state | role
${CaseState.ACCEPTED} | ${UserRole.REGISTRAR}
${CaseState.ACCEPTED} | ${UserRole.JUDGE}
${CaseState.REJECTED} | ${UserRole.REGISTRAR}
${CaseState.REJECTED} | ${UserRole.JUDGE}
${CaseState.DISMISSED} | ${UserRole.REGISTRAR}
${CaseState.DISMISSED} | ${UserRole.JUDGE}
`.describe(
'given a $state case and a permitted $role user',
({ state, role }) => {
const caseId = uuid()
const courtId = uuid()
const courtCaseNumber = uuid()
const user = { id: uuid(), role } as User
beforeEach(() => {
const mockFindByIdAndUser = jest.spyOn(caseService, 'findByIdAndUser')
mockFindByIdAndUser.mockImplementation((id: string) =>
Promise.resolve({
id,
state,
courtId,
courtCaseNumber,
} as Case),
)
})
describe('given a case file', () => {
const fileId = uuid()
const fileName = 'test.txt'
const type = 'text/plain'
const key = `${caseId}/${fileId}/${fileName}`
const mockFile = {
id: fileId,
caseId,
name: fileName,
type,
key,
}
beforeEach(() => {
fileModel.findOne.mockResolvedValueOnce(mockFile)
})
it('should upload a case file to court', async () => {
const mockBuffer = Buffer.from(uuid())
const mockGetObject = jest.spyOn(awsS3Service, 'getObject')
mockGetObject.mockResolvedValueOnce(mockBuffer)
const mockStreamId = uuid()
const mockUploadStream = jest.spyOn(courtService, 'uploadStream')
mockUploadStream.mockResolvedValueOnce(mockStreamId)
const mockDocumentId = uuid()
const mockCreateDocument = jest.spyOn(
courtService,
'createDocument',
)
mockCreateDocument.mockResolvedValueOnce(mockDocumentId)
fileModel.update.mockResolvedValueOnce([1])
const mockDeleteObject = jest.spyOn(awsS3Service, 'deleteObject')
const { success } = await fileController.uploadCaseFileToCourt(
caseId,
fileId,
user,
)
expect(fileModel.findOne).toHaveBeenCalledWith({
where: {
id: fileId,
caseId,
state: { [Op.not]: CaseFileState.DELETED },
},
})
expect(mockGetObject).toHaveBeenCalledWith(key)
expect(mockUploadStream).toHaveBeenCalledWith(
courtId,
fileName,
type,
mockBuffer,
)
expect(mockCreateDocument).toHaveBeenCalledWith(
courtId,
courtCaseNumber,
fileName,
fileName,
mockStreamId,
)
expect(fileModel.update).toHaveBeenCalledWith(
{
state: CaseFileState.STORED_IN_COURT,
key: mockDocumentId,
},
{ where: { id: fileId } },
)
expect(mockDeleteObject).toHaveBeenCalledWith(key)
expect(success).toBe(true)
})
it('should throw when uploading a case file to court and the file does not exist in AWS S3', async () => {
const mockObjectExists = jest.spyOn(awsS3Service, 'objectExists')
mockObjectExists.mockResolvedValueOnce(false)
await expect(
fileController.uploadCaseFileToCourt(caseId, fileId, user),
).rejects.toThrow(NotFoundException)
expect(fileModel.update).toHaveBeenCalledWith(
{ state: CaseFileState.BOKEN_LINK },
{ where: { id: fileId } },
)
})
})
describe('given a broken link case file', () => {
const fileId = uuid()
const key = `${caseId}/${fileId}/test.txt`
const mockFile = {
id: fileId,
caseId,
state: CaseFileState.BOKEN_LINK,
key,
}
beforeEach(() => {
fileModel.findOne.mockResolvedValueOnce(mockFile)
})
it('should throw when uploading a case file to court', async () => {
await expect(
fileController.uploadCaseFileToCourt(caseId, fileId, user),
).rejects.toThrow(NotFoundException)
})
})
describe('given an already uploaded case file', () => {
const fileId = uuid()
const key = `${caseId}/${fileId}/test.txt`
const mockFile = {
id: fileId,
caseId,
state: CaseFileState.STORED_IN_COURT,
key,
}
beforeEach(() => {
fileModel.findOne.mockResolvedValueOnce(mockFile)
})
it('should throw when uploading a case file to court', async () => {
await expect(
fileController.uploadCaseFileToCourt(caseId, fileId, user),
).rejects.toThrow(ForbiddenException)
})
})
describe('given a non-existing (or deleted) case file', () => {
const fileId = uuid()
beforeEach(() => {
fileModel.findOne.mockResolvedValueOnce(null)
})
it('should throw when uploading a case file to court', async () => {
await expect(
fileController.uploadCaseFileToCourt(caseId, fileId, user),
).rejects.toThrow(NotFoundException)
})
})
},
)
each`
state | role
${CaseState.NEW} | ${UserRole.REGISTRAR}
${CaseState.NEW} | ${UserRole.JUDGE}
${CaseState.DRAFT} | ${UserRole.REGISTRAR}
${CaseState.DRAFT} | ${UserRole.JUDGE}
${CaseState.SUBMITTED} | ${UserRole.REGISTRAR}
${CaseState.SUBMITTED} | ${UserRole.JUDGE}
${CaseState.RECEIVED} | ${UserRole.REGISTRAR}
${CaseState.RECEIVED} | ${UserRole.JUDGE}
`.describe(
'given a $state case and a blocked $role user',
({ state, role }) => {
const caseId = uuid()
const user = { id: uuid(), role } as User
beforeEach(() => {
const mockFindByIdAndUser = jest.spyOn(caseService, 'findByIdAndUser')
mockFindByIdAndUser.mockImplementation((id: string) =>
Promise.resolve({ id, state } as Case),
)
})
it('should throw when uploading a case file to court', async () => {
const fileId = uuid()
await expect(
fileController.uploadCaseFileToCourt(caseId, fileId, user),
).rejects.toThrow(ForbiddenException)
})
},
)
describe('given a non-existing (or blocked) case', () => {
const caseId = uuid()
beforeEach(() => {
const mockFindByIdAndUser = jest.spyOn(caseService, 'findByIdAndUser')
mockFindByIdAndUser.mockRejectedValueOnce(new Error('Some error'))
})
it('should throw when uploading a case file to court', async () => {
const prosecutor = {} as User
const fileId = uuid()
await expect(
fileController.uploadCaseFileToCourt(caseId, fileId, prosecutor),
).rejects.toThrow('Some error')
})
})
})
}) | the_stack |
import KnownValues from "./KnownValues";
import { VERIFY, MINIMIZE_LOG_DATA_SIZE, SHORT_NAMES } from "../config";
import invokeIfFunction from "../invokeIfFunction";
import { consoleLog } from "./logging";
import { countObjectKeys } from "../util";
import { ValueTrackingValuePair } from "../types";
import { getShortOperationName, getLongOperationName } from "../names";
var global = Function("return this")();
// todo: would be better if the server provided this value
export const getOperationIndex = (function() {
var operationIndexBase = Math.round(
Math.random() * 1000 * 1000 * 1000 * 1000 * 1000
);
var operationIndex = operationIndexBase;
return function getOperationIndex() {
operationIndex++;
return operationIndex;
};
})();
function serializeValue(
value,
knownValues: KnownValues
): StoredSerializedValue {
// todo: consider accessing properties that are getters could have negative impact...
const type = typeof value;
if (
typeof value === "string" ||
typeof value === "number" ||
typeof value === "boolean" ||
value === null
) {
return value;
}
return getSerializedValueObject(value, type, knownValues);
}
const _bufferObj = eval("typeof Buffer === 'undefined' ? null : Buffer");
export interface SerializedValueData {
length: any;
type: string;
keys?: string[];
primitive: number | null | string | boolean;
knownValue: string | null;
knownTypes: null | any[];
}
type StoredSerializedValue = SerializedValueData | string | number | boolean;
let HtmlInputElement = global["HTMLInputElement"];
let IntlNumberFormat = Intl.NumberFormat;
export function getSerializedValueObject(
value,
type,
knownValues,
preventShortNames = false
) {
var knownValue: undefined | string =
knownValues && knownValues.getName(value);
if (type === null) {
type = typeof value;
}
var length;
if (Array.isArray(value) || type === "string") {
length = value.length;
}
var knownTypes: any[] | undefined = undefined;
if (HtmlInputElement && value instanceof HtmlInputElement) {
knownTypes = [];
knownTypes.push("HTMLInputElement");
} else if (value instanceof IntlNumberFormat) {
// use this to be able to traverse Intl.NumberFormat.format call
// format function can't be a normal known value because it's unqiue for each instance
// ... maybe a better solution would be adding each format function to knownvalues
// when is the NumberFormat instance is created
knownTypes = [];
knownTypes.push("Intl.NumberFormat");
}
try {
if (
type === "object" &&
"lastEventId" in value &&
typeof value.target === "object" &&
typeof value.target.url === "string" &&
value.target.url.startsWith("ws") &&
value.type === "message"
) {
knownTypes = [];
knownTypes.push("WebSocketMessage");
}
} catch (err) {
// some cases where there are getters that can't
// be invoked
}
var primitive;
if (["string", "number", "boolean", "null"].includes(type)) {
primitive = value;
}
let keys;
try {
if (
type === "object" &&
value !== null &&
!Array.isArray(value) &&
!knownValue &&
(!_bufferObj || !(value instanceof _bufferObj)) &&
// filter out Array like things, e.g. Uint8Array
!("length" in value && "0" in value)
) {
// todo: rethink this regarding perf
// also: when inspecting i really want the trakcing data for
// values/keys to be accessible, so maybe just storing keys makes more sense
keys = Object.keys(value);
if (keys.length > 100) {
console.log(
"Obj with more than 100 keys: " + keys.length,
keys.slice(0, 5)
);
}
if (keys.length > 5) {
keys = keys.slice(0, 5);
keys.push("...");
}
}
} catch (err) {}
if (SHORT_NAMES && !preventShortNames) {
if (type === "object") {
type = "o";
} else if (type === "function") {
type = "f";
} else if (type === "undefined") {
type = "u";
}
return {
l: length,
t: type,
p: primitive,
k: knownValue,
kt: knownTypes,
ke: keys
} as any;
} else {
return <SerializedValueData>{
length,
type,
primitive,
knownValue,
knownTypes,
keys
};
}
}
class SerializedValue implements SerializedValueData {
length: any;
type: string;
keys?: string[];
primitive: number | null | string | boolean;
knownValue: string | null;
knownTypes: null | any[];
constructor(data: SerializedValueData) {
this.length = data.length;
this.type = data.type;
this.keys = data.keys;
this.primitive = data.primitive;
this.knownValue = data.knownValue;
this.knownTypes = data.knownTypes;
}
getTruncatedUIString() {
if (this.knownValue) {
return this.knownValue;
}
if (["string", "null", "number", "boolean"].includes(this.type)) {
let ret = this.primitive + "";
if (ret.length > 200) {
return ret.slice(0, 200);
} else {
return ret;
}
}
let str = "[" + this.type + "]";
if (this.keys && this.keys.length > 0) {
str += " {" + this.keys.filter(k => k !== "__elOrigin").join(", ") + "}";
}
return str;
}
isTruthy() {
if (this.primitive) {
return !!this.primitive;
}
return this.length > 0 || (this.keys && this.keys.length > 0);
}
}
interface OperationLogInterface {
operation: string;
_result: StoredSerializedValue;
args: any;
extraArgs: any;
index: number;
astArgs: any;
stackFrames: string[];
loc: any;
runtimeArgs: any;
}
export default class OperationLog implements OperationLogInterface {
operation: string;
_result: StoredSerializedValue;
args: any;
extraArgs: any;
index: number;
astArgs: any;
stackFrames: string[];
loc: any;
runtimeArgs: any;
get result(): SerializedValue {
const resultIsSerializedValueObject =
!["string", "boolean", "number"].includes(typeof this._result) &&
this._result !== null &&
this._result &&
"type" in <any>this._result;
let sv: SerializedValueData;
if (resultIsSerializedValueObject) {
sv = <SerializedValueData>this._result;
} else {
sv = getSerializedValueObject(this._result, null, null, true);
}
return new SerializedValue(sv);
}
static createAtRuntime;
constructor({
operation,
_result,
args,
astArgs,
extraArgs,
stackFrames,
loc,
runtimeArgs,
index
}) {
this.stackFrames = stackFrames;
this.operation = operation;
this._result = _result;
this.runtimeArgs = runtimeArgs;
this.loc = loc;
this.args = args;
this.astArgs = astArgs;
this.extraArgs = extraArgs;
this.index = index;
}
}
interface CreateAtRuntimeArg {
operation: string;
result: any;
args: // Simple arg data, something like { originValue: ["hello", 2638723923] }
| { [argName: string]: ValueTrackingValuePair }
// For object literals
| {
properties: {
key: any;
type: any;
value: any;
}[];
}
// Optimization using arrays instead of objects, e.g. for call expressions, array literals,...
| (ValueTrackingValuePair | ValueTrackingValuePair[])[]
| undefined;
astArgs: any;
extraArgs: any;
loc: string;
runtimeArgs: any;
index: number;
}
OperationLog.createAtRuntime = function(
{
operation,
result,
args,
astArgs,
extraArgs,
loc,
runtimeArgs
}: CreateAtRuntimeArg,
knownValues,
op
): OperationLogInterface {
if (VERIFY && !loc) {
consoleLog(
"no loc at runtime for operation",
getLongOperationName(operation)
);
}
let canInfer = false;
if (MINIMIZE_LOG_DATA_SIZE) {
let opCanInfer = op && op.canInferResult;
if (typeof opCanInfer === "boolean") {
canInfer = opCanInfer;
} else if (typeof opCanInfer === "function" && args) {
canInfer = opCanInfer(args, extraArgs, astArgs, runtimeArgs);
}
}
if (astArgs && countObjectKeys(astArgs) === 0) {
astArgs = undefined;
}
// When args come into this function they contain both the actual value and
// the tracking value. We only want the tracking value now.
if (Array.isArray(args)) {
const newArgs: any[] = [];
for (var i = 0; i < args.length; i++) {
const arg = args[i];
if (
op["argIsArray"] &&
invokeIfFunction(op["argIsArray"]![i], arguments[0])
) {
const a: any[] = [];
for (
var arrayArgIndex = 0;
arrayArgIndex < arg.length;
arrayArgIndex++
) {
const arrayArg = arg[arrayArgIndex];
a.push(arrayArg[1]);
}
newArgs.push(a);
} else {
newArgs.push(arg[1]);
}
}
args = newArgs;
if (args.length === 1 && !args[0]) {
args = undefined;
}
} else if (args) {
// Not sure why the (args as any) is needed, but without it the UI bundle
// doesn't compile
if (operation === "objectExpression" && (args as any).properties) {
// todo: centralize this logic, shouldn't need to do if, see "arrayexpression" above also"
(args as any).properties = ((args as any).properties as any[]).map(
prop => {
return {
key: prop.key[1],
type: prop.type[1],
value: prop.value[1]
};
}
);
} else {
// only store argument operation log because ol.result === a[0]
eachArgument(args, (arg, argName, updateArg) => {
verifyArg(arg);
updateArg(arg[1]);
});
}
}
if (typeof extraArgs === "object") {
eachArgument(extraArgs, (arg, argName, updateArg) => {
verifyArg(arg);
updateArg(arg[1]);
});
}
let _result;
if (canInfer) {
// args can be inferred on BE by checking the AST loc data, or by checking argument values
} else {
_result = serializeValue(result, knownValues);
}
if (SHORT_NAMES) {
return {
o: operation,
r: _result,
e: extraArgs,
a: args,
ast: astArgs,
l: loc,
rt: runtimeArgs
} as any;
} else {
return <OperationLogInterface>{
operation,
_result,
extraArgs,
args,
astArgs,
loc,
runtimeArgs
};
}
};
// TODO: don't copy/paste this
function eachArgument(args, fn) {
const keys = Object.keys(args);
for (var i = 0; i < keys.length; i++) {
const key = keys[i];
fn(args[key], key, newValue => (args[key] = newValue));
}
}
function verifyArg(arg) {
if (
VERIFY &&
typeof arg[1] !== "number" &&
arg[1] !== null &&
arg[1] !== undefined &&
arg[1] !== false
) {
debugger;
throw Error(
"no arg operationlog found, did you only pass in an operationlog"
);
}
} | the_stack |
// All static links on the site should be put into this enum. This makes it
// easier to update all instances of a link on the site.
export enum Url {
termsOfService = "https://policies.google.com/terms",
privacyPolicy = "https://policies.google.com/privacy",
ga4MeasurementProtocol = "https://developers.google.com/analytics/devguides/collection/protocol/ga4",
ga4DataAPIGetMetadata = "https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/getMetadata",
cohortsRangeStartOffset = "https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/CohortSpec#CohortsRange.FIELDS.start_offset",
cohortsRangeEndOffset = "https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/CohortSpec#CohortsRange.FIELDS.end_offset",
ga4RequestComposerBasicRunReport = "https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport",
ga4RequestComposerBasicRunReportLimit = "https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.limit",
ga4RequestComposerBasicRunReportDimensionFilter = "https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.dimension_filter",
ga4RequestComposerBasicRunReportMetricFilter = "https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.metric_filter",
ga4RequestComposerBasicRunReportOffset = "https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.offset",
ga4RequestComposerBasicMetrics = "https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.metrics",
ga4RequestComposerBasicKeepEmptyRows = "https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.keep_empty_rows",
ga4RequestComposerBasicDimensions = "https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.dimensions",
ga4RequestComposerBasicProperty = "https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.PATH_PARAMETERS.property",
ga4RequestComposerBasicCurrencyCode = "https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.currency_code",
ga4RequestComposerBasicCohortSpec = "https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.cohort_spec",
ga4RequestComposerBasicMetricAggregations = "https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.metric_aggregations",
iso4217Wiki = "https://en.wikipedia.org/wiki/ISO_4217",
ga4DataAPI = "https://developers.google.com/analytics/devguides/reporting/data/v1",
ga4AdminAPI = "https://developers.google.com/analytics/devguides/config/admin/v1",
aboutCampaign = "https://support.google.com/analytics/answer/1033863?",
aboutCustomCampaigns = "https://support.google.com/analytics/answer/1033863",
bestPracticesForCreatingCustomCampaigns = "https://support.google.com/analytics/answer/1037445",
aboutReferralTrafficReport = "https://support.google.com/analytics/topic/3125765?",
aboutTrafficSourceDimensions = "https://support.google.com/analytics/answer/1033173",
googleAdsAutoTagging = "https://support.google.com/google-ads/answer/1752125",
iosCampaignMeasurement = "https://developers.google.com/analytics/devguides/collection/ios/v3/campaigns#url-builder",
googlePlayURLBuilder = "https://developers.google.com/analytics/devguides/collection/android/v4/campaigns#google-play-url-builder",
gaDebugger = "https://chrome.google.com/webstore/detail/google-analytics-debugger/jnkmfdileelhofjcijamephohjechhna",
analyticsJSDevsite = "https://developers.google.com/analytics/devguides/collection/analyticsjs/",
analyticsJSEnhancedEcommerce = "https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce",
googleTagManagerEnhancedEcommerce = "https://developers.google.com/tag-manager/enhanced-ecommerce",
enhancedEcommerceHelpCenter = "https://support.google.com/analytics/answer/6014841",
enhancedEcommerceDemo = "https://enhancedecommerce.appspot.com/",
gaDevToolsGitHub = "https://github.com/googleanalytics/ga-dev-tools",
gaDevToolsGitHubNewIssue = "https://github.com/googleanalytics/ga-dev-tools/issues/new?assignees=&labels=&template=bug_report.md&title=",
gaDevToolsGitHubNewFeatureRequest = "https://github.com/googleanalytics/ga-dev-tools/issues/new?assignees=&labels=&template=feature_request.md&title=",
gaDevsite = "http://developers.google.com/analytics",
gaDevsiteHelp = "http://developers.google.com/analytics/help/",
reportingApis = "https://developers.google.com/analytics/devguides/reporting/",
spreadsheetAddOn = "https://developers.google.com/analytics/solutions/google-analytics-spreadsheet-add-on",
spreadsheetAddOnExternal = "https://gsuite.google.com/marketplace/app/google_analytics/477988381226",
tagAssistantExternal = "https://chrome.google.com/webstore/detail/tag-assistant-by-google/kejbdjndbnbjgmefkgdddjlbokphdefk",
crossDomainMeasurement = "https://developers.google.com/analytics/devguides/collection/analyticsjs/cross-domain",
protocolParameters = "https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters",
commonHits = "https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide#commonhits",
crossDomainLinker = "https://developers.google.com/analytics/devguides/collection/analyticsjs/linker",
aboutTagAssistant = "https://support.google.com/tagassistant/answer/2947093",
aboutTagAssistantRecordings = "https://support.google.com/analytics/answer/6277302",
measurementProtocol = "https://developers.google.com/analytics/devguides/collection/protocol/v1",
validatingMeasurement = "https://developers.google.com/analytics/devguides/collection/protocol/v1/validating-hits",
coreReportingApi = "https://developers.google.com/analytics/devguides/reporting/core/v3/",
}
export enum GAVersion {
UniversalAnalytics = "ua",
GoogleAnalytics4 = "ga4",
}
// All data in localStorage should have its keys here.
export enum StorageKey {
gaVersion = "/ga-version",
uaColumns = "//ua-columns",
uaAccounts = "//ua-accounts",
uaCustomMetrics = "//ua-custom-metrics",
uaCustomDimensions = "//ua-custom-dimensions",
uaSegments = "//ua-segments-2",
viewSelectorData = "//view-selector/data",
ga4AccountSummaries = "//ga4-account-summaries",
ga4WebStreams = "//ga4-web-streams",
// Acount Explorer
accountExplorerAPV = "/account-explorer/apv",
// GA4 Dimensions and metrics explorer
ga4DimensionsMetrics = "/ga4/dimensions-metrics/",
ga4DimensionsMetricsExplorerAPS = "/ga4/dimensions-metrics-explorer/aps",
ga4DimensionsMetricsSearch = "/ga4/dimensions-metrics-explorer/search",
ga4DimensionsMetricsFields = "/ga4/dimensions-metrics-explorer/fields",
ga4DimensionsMetricsAccountSummaries = "/ga4/dimensions-metrics-explorer/account-summaries",
ga4DimensionsMetricsSelectedAccount = "/ga4/dimensions-metrics-explorer/selected-account",
ga4DimensionsMetricsSelectedProperty = "/ga4/dimensions-metrics-explorer/selected-property",
// GA4 Request Composer
ga4RequestComposerTab = "/ga4/request-composer/tab",
ga4RequestComposerBasicAccountSummaries = "/ga4/request-composer/basic-report/account-summaries",
ga4RequestComposerBasicSelectedAccount = "/ga4/request-composer/basic-report/selected-account",
ga4RequestComposerBasicSelectedProperty = "/ga4/request-composer/basic-report/selected-property",
ga4RequestComposerBasicSelectedPropertyString = "/ga4/request-composer/basic-report/selected-property-string",
ga4RequestComposerBasicResponse = "/ga4/request-composer/basic-report/response",
ga4RequestComposerBasicSelectedDimensions = "/ga4/request-composer/basic-report/selected-dimensions-2",
ga4RequestComposerBasicSelectedMetrics = "/ga4/request-composer/basic-report/selected-metrics-2",
ga4RequestComposerBasicShowRequestJSON = "/ga4/request-composer/basic-report/show-request-json",
ga4RequestComposerBasicCohortSpec = "/ga4/request-composer/basic-report/cohort-spec",
ga4RequestComposerBasicKeepEmptyRows = "/ga4/request-composer/basic-report/keep-empty-rows",
ga4RequestComposerBasicDimensionFilter = "/ga4/request-composer/basic-report/dimension-filter",
ga4RequestComposerBasicMetricFilter = "/ga4/request-composer/basic-report/metric-filter",
ga4RequestComposerBasicSelectedOffset = "/ga4/request-composer/basic-report/offset",
ga4RequestComposerBasicSelectedLimit = "/ga4/request-composer/basic-report/limit",
ga4RequestComposerBasicDateRanges = "/ga4/request-composer/basic-report/date-ranges",
ga4RequestComposerBasicOrderBys = "/ga4/request-composer/basic-report/order-bys",
ga4RequestComposerBasicMetricAggregations = "/ga4/request-composer/basic-report/metric-aggregations",
ga4RequestComposerBasicSelectedCurrencyCode = "/ga4/request-composer/basic-report/currency-code",
ga4RequestComposerBasicShowAdvanced = "/ga4/request-composer/basic-report/show-advanced",
ga4QueryExplorerAPS = "/ga4/query-explorer/aps",
// Query Explorer
queryExplorerAPV = "query-explorer/apv",
queryExplorerAccount = "query-explorer/account",
queryExplorerProperty = "query-explorer/property",
queryExplorerView = "query-explorer/view",
queryExplorerViewID = "query-explorer/view-id",
queryExplorerDimensions = "query-explorer/dimensions",
queryExplorerSelectedDimensions = "query-explorer/selected-dimensions-2",
queryExplorerMetrics = "query-explorer/metrics",
queryExplorerSelectedMetrics = "query-explorer/selected-metrics-2",
queryExplorerSegment = "query-explorer/segment-2",
queryExplorerSamplingLevel = "query-explorer/sampling-level",
queryExplorerShowSegmentDefinition = "query-explorer/show-segment-definition",
queryExplorerStartDate = "query-explorer/start-date",
queryExplorerEndDate = "query-explorer/end-date",
queryExplorerStartIndex = "query-explorer/start-index",
queryExplorerMaxResults = "query-explorer/max-results",
queryExplorerFilters = "query-explorer/filters",
queryExplorerIncludeEmptyRows = "query-explorer/include-empty-rows",
queryExplorerSort = "query-explorer/sort-2",
// Dimensions and metrics explorer
dimensionsMetricsExplorerColumns = "dimensions-metrics-explorer/columns-2",
dimensionsMetricsExplorerSearch = "dimensions-metrics-explorer/search",
dimensionsMetricsExplorerAllowDeprecated = "dimensions-metrics-explorer/allow-deprecated",
dimensionsMetricsExplorerOnlySegments = "dimensions-metrics-explorer/only-segments",
// Web Campaign Builder
campaignBuilderWebsiteURL = "campaign-builder/website-url",
campaignBuilderSource = "campaign-builder/source",
campaignBuilderMedium = "campaign-builder/medium",
campaignBuilderName = "campaign-builder/name",
campaignBuilderID = "campaign-builder/id",
campaignBuilderTerm = "campaign-builder/term",
campaignBuilderContent = "campaign-builder/content",
campaignBuilderUseFragment = "campaign-builder/use-fragment",
bitlyAccessToken = "bitly-auth/access-token",
bitlyCache = "bitly-auth/cache-storage",
// UA Request Composer
requestComposerAPV = "request-composer/apv",
requestComposerHistogramDimensions = "request-composer/histogram/dimensions",
requestComposerHistogramMetrics = "request-composer/histogram/metrics",
requestComposerHistogramSegment = "request-composer/histogram/segment",
histogramBuckets = "request-composer/histogram-buckets",
histogramStartDate = "request-composer/histogram-start-date",
histogramEndDate = "request-composer/histogram-end-date",
histogramFiltersExpression = "request-composer/histogram-filters-expression",
histogramSamplingLevel = "request-composer/histogram-sampling-level",
histogramRequestShowSegmentDefinition = "request-composer/histogram-request-show-segment-definition",
requestComposerPivotMetrics = "request-composer/pivot/metrics",
requestComposerPivotPivotMetrics = "request-composer/pivot/pivot-metrics",
requestComposerPivotDimensions = "request-composer/pivot/dimensions",
requestComposerPivotPivotDimensions = "request-composer/pivot/pivot-dimensions",
requestComposerPivotSegment = "request-composer/pivot-request-segment",
pivotSamplingLevel = "request-composer/pivot-sampling-level",
pivotRequestStartDate = "request-composer/pivot-request-start-date",
pivotRequestEndDate = "request-composer/pivot-request-end-date",
pivotRequestStartGroup = "request-composer/pivot-request-start-group",
pivotRequestMaxGroupCount = "request-composer/pivot-request-max-group-count",
pivotRequestPageToken = "request-composer/pivot-request-page-token",
pivotRequestPageSize = "request-composer/pivot-request-page-size",
pivotRequestIncludeEmptyRows = "request-composer/pivot-request-include-empty-rows",
pivotRequestShowSegmentDefinition = "request-composer/pivot-request-show-segment-definition",
cohortRequestSamplingLevel = "request-composer/cohort-request-sampling-level",
requestComposerCohortMetric = "request-composer/cohort/metric",
requestComposerCohortSegment = "request-composer/cohort/segment",
cohortRequestCohortSize = "request-composer/cohort-request-cohort-size",
cohortRequestShowSegmentDefinition = "request-composer/cohort-request-show-segment-definition",
requestComposerMetricExpressionDimensions = "request-composer/metric-expression/dimensions",
requestComposerMetricExpressionSegment = "request-composer/metric-expression/segment",
metricExpressionSamplingLevel = "request-composer/metric-expression-sampling-level",
metricExpressionStartDate = "request-composer/metric-expression-start-date",
metricExpressionEndDate = "request-composer/metric-expression-end-date",
metricExpressionMetricExpressions = "request-composer/metric-expression-metric-expressions",
metricExpressionMetricAliases = "request-composer/metric-expression-metric-aliases",
metricExpressionFiltersExpression = "request-composer/metric-expression-filters-expression",
metricExpressionPageToken = "request-composer/metric-expression-page-token",
metricExpressionPageSize = "request-composer/metric-expression-page-size",
metricExpressionRequestShowSegmentDefinition = "request-composer/metric-expression-show-segment-definition",
// Play Campaign URL Builder
campaignBuilderPlayAppID = "campaign-builder/play/app-id",
campaignBuilderPlaySource = "campaign-builder/play/source",
campaignBuilderPlayMedium = "campaign-builder/play/medium",
campaignBuilderPlayTerm = "campaign-builder/play/term",
campaignBuilderPlayContent = "campaign-builder/play/content",
campaignBuilderPlayName = "campaign-builder/play/name",
// IOS Campaign URL Builder
campaignBuilderIOSAPV = "campaign-builder/ios/apv-2",
campaignBuilderIOSAPS = "campaign-builder/ios/aps-2",
campaignBuilderIOSAppID = "campaign-builder/ios/app-id",
campaignBuilderIOSSource = "campaign-builder/ios/source",
campaignBuilderIOSMedium = "campaign-builder/ios/medium",
campaignBuilderIOSTerm = "campaign-builder/ios/term",
campaignBuilderIOSContent = "campaign-builder/ios/content",
campaignBuilderIOSName = "campaign-builder/ios/name",
campaignBuilderIOSPropertyIDUA = "campaign-builder/ios/property-id-ua",
campaignBuilderIOSPropertyIDGA4 = "campaign-builder/ios/property-id-ga4",
campaignBuilderIOSRedirectURL = "campaign-builder/ios/redirect-url",
campaignBuilderIOSDeviceID = "campaign-builder/ios/device-id",
campaignBuilderIOSCustomFields = "campaign-builder/ios/custom-fields",
campaignBuilderIOSAdNetwork = "campaign-builder/ios/ad-network",
campaignBuilderIOSMethod = "campaign-builder/ios/method",
campaignBuilderIOSGA4Account = "campaign-builder/ios/ga4-account",
campaignBuilderIOSGA4Property = "campaign-builder/ios/ga4-property",
// GA4 Event Builder
eventBuilderCategory = "ga4/event-builder/event-category",
eventBuilderApiSecret = "ga4/event-builder/api-secret",
eventBuilderFirebaseAppId = "ga4/event-builder/firebase-app-id",
eventBuilderMeasurementId = "ga4/event-builder/measurement-id",
eventBuilderAppInstanceId = "ga4/event-builder/app-instance-id",
eventBuilderClientId = "ga4/event-builder/client-id",
eventBuilderUserId = "ga4/event-builder/user-id",
eventBuilderTimestampMicros = "ga4/event-builder/timestamp-micros",
eventBuilderNonPersonalizedAds = "ga4/event-builder/non-personalized-ads",
eventBuilderUseFirebase = "ga4/event-builder/use-firebase",
ga4EventBuilderEvents = "ga4/event-builder/events",
ga4EventBuilderLastEventType = "ga4/event-builder/last-event-type",
ga4EventBuilderParameters = "ga4/event-builder/parameters",
ga4EventBuilderItems = "ga4/event-builder/items",
ga4EventBuilderEventName = "ga4/event-builder/event-name",
ga4EventBuilderUserProperties = "ga4/event-builder/user-properties",
}
export const EventAction = {
bitlyShorten: "bitly_shorten",
bitlyAuth: "bitly_auth",
}
export const EventCategory = {
campaignUrlBuilder: "Campaign URL Builder",
} | the_stack |
import {trace} from "../common/trace";
import {services} from "../common/coreservices";
import {
map, find, extend, filter, mergeR, unnest, tail,
omit, toJson, abstractKey, arrayTuples, allTrueR, unnestR, identity, anyTrueR
} from "../common/common";
import { isObject } from "../common/predicates";
import { not, prop, propEq, val } from "../common/hof";
import {StateDeclaration, StateOrName} from "../state/interface";
import {TransitionOptions, TransitionHookOptions, TreeChanges, IHookRegistry, IHookRegistration, IHookGetter} from "./interface";
import {TransitionHook, HookRegistry, matchState, HookBuilder, RejectFactory} from "./module";
import {Node} from "../path/node";
import {PathFactory} from "../path/pathFactory";
import {State, TargetState} from "../state/module";
import {Param} from "../params/module";
import {Resolvable} from "../resolve/module";
import {TransitionService} from "./transitionService";
import {ViewConfig} from "../view/interface";
let transitionCount = 0, REJECT = new RejectFactory();
const stateSelf: (_state: State) => StateDeclaration = prop("self");
/**
* The representation of a transition between two states.
*
* Contains all contextual information about the to/from states, parameters, resolves, as well as the
* list of states being entered and exited as a result of this transition.
*/
export class Transition implements IHookRegistry {
$id: number;
success: boolean;
private _deferred = services.$q.defer();
/**
* This promise is resolved or rejected based on the outcome of the Transition.
*
* When the transition is successful, the promise is resolved
* When the transition is unsuccessful, the promise is rejected with the [[TransitionRejection]] or javascript error
*/
promise: Promise<any> = this._deferred.promise;
private _options: TransitionOptions;
private _treeChanges: TreeChanges;
/**
* Registers a callback function as an `onBefore` Transition Hook
*
* The hook is only registered for this specific `Transition`. For global hooks, use [[TransitionService.onBefore]]
*
* See [[IHookRegistry.onBefore]]
*/
onBefore: IHookRegistration;
/**
* Registers a callback function as an `onStart` Transition Hook
*
* The hook is only registered for this specific `Transition`. For global hooks, use [[TransitionService.onStart]]
*
* See [[IHookRegistry.onStart]]
*/
onStart: IHookRegistration;
/**
* Registers a callback function as an `onEnter` State Hook
*
* The hook is only registered for this specific `Transition`. For global hooks, use [[TransitionService.onEnter]]
*
* See [[IHookRegistry.onEnter]]
*/
onEnter: IHookRegistration;
/**
* Registers a callback function as an `onRetain` State Hook
*
* The hook is only registered for this specific `Transition`. For global hooks, use [[TransitionService.onRetain]]
*
* See [[IHookRegistry.onRetain]]
*/
onRetain: IHookRegistration;
/**
* Registers a callback function as an `onExit` State Hook
*
* The hook is only registered for this specific `Transition`. For global hooks, use [[TransitionService.onExit]]
*
* See [[IHookRegistry.onExit]]
*/
onExit: IHookRegistration;
/**
* Registers a callback function as an `onFinish` Transition Hook
*
* The hook is only registered for this specific `Transition`. For global hooks, use [[TransitionService.onFinish]]
*
* See [[IHookRegistry.onFinish]]
*/
onFinish: IHookRegistration;
/**
* Registers a callback function as an `onSuccess` Transition Hook
*
* The hook is only registered for this specific `Transition`. For global hooks, use [[TransitionService.onSuccess]]
*
* See [[IHookRegistry.onSuccess]]
*/
onSuccess: IHookRegistration;
/**
* Registers a callback function as an `onError` Transition Hook
*
* The hook is only registered for this specific `Transition`. For global hooks, use [[TransitionService.onError]]
*
* See [[IHookRegistry.onError]]
*/
onError: IHookRegistration;
getHooks: IHookGetter;
/**
* Creates a new Transition object.
*
* If the target state is not valid, an error is thrown.
*
* @param fromPath The path of [[Node]]s from which the transition is leaving. The last node in the `fromPath`
* encapsulates the "from state".
* @param targetState The target state and parameters being transitioned to (also, the transition options)
* @param _transitionService The Transition Service instance
*/
constructor(fromPath: Node[], targetState: TargetState, private _transitionService: TransitionService) {
if (!targetState.valid()) {
throw new Error(targetState.error());
}
// Makes the Transition instance a hook registry (onStart, etc)
HookRegistry.mixin(new HookRegistry(), this);
// current() is assumed to come from targetState.options, but provide a naive implementation otherwise.
this._options = extend({ current: val(this) }, targetState.options());
this.$id = transitionCount++;
let toPath = PathFactory.buildToPath(fromPath, targetState);
toPath = PathFactory.applyViewConfigs(_transitionService.$view, toPath);
this._treeChanges = PathFactory.treeChanges(fromPath, toPath, this._options.reloadState);
PathFactory.bindTransitionResolve(this._treeChanges, this);
}
$from() {
return tail(this._treeChanges.from).state;
}
$to() {
return tail(this._treeChanges.to).state;
}
/**
* Returns the "from state"
*
* @returns The state object for the Transition's "from state".
*/
from(): StateDeclaration {
return this.$from().self;
}
/**
* Returns the "to state"
*
* @returns The state object for the Transition's target state ("to state").
*/
to() {
return this.$to().self;
}
/**
* Determines whether two transitions are equivalent.
*/
is(compare: (Transition|{to: any, from: any})): boolean {
if (compare instanceof Transition) {
// TODO: Also compare parameters
return this.is({ to: compare.$to().name, from: compare.$from().name });
}
return !(
(compare.to && !matchState(this.$to(), compare.to)) ||
(compare.from && !matchState(this.$from(), compare.from))
);
}
/**
* Gets transition parameter values
*
* @param pathname Pick which treeChanges path to get parameters for:
* (`'to'`, `'from'`, `'entering'`, `'exiting'`, `'retained'`)
* @returns transition parameter values for the desired path.
*/
params(pathname: string = "to"): { [key: string]: any } {
return this._treeChanges[pathname].map(prop("paramValues")).reduce(mergeR, {});
}
/**
* Get resolved data
*
* @returns an object (key/value pairs) where keys are resolve names and values are any settled resolve data,
* or `undefined` for pending resolve data
*/
resolves(): { [resolveName: string]: any } {
return map(tail(this._treeChanges.to).resolveContext.getResolvables(), res => res.data);
}
/**
* Adds new resolves to this transition.
*
* @param resolves an [[ResolveDeclarations]] object which describes the new resolves
* @param state the state in the "to path" which should receive the new resolves (otherwise, the root state)
*/
addResolves(resolves: { [key: string]: Function }, state: StateOrName = ""): void {
let stateName: string = (typeof state === "string") ? state : state.name;
let topath = this._treeChanges.to;
let targetNode = find(topath, node => node.state.name === stateName);
tail(topath).resolveContext.addResolvables(Resolvable.makeResolvables(resolves), targetNode.state);
}
/**
* Gets the previous transition, from which this transition was redirected.
*
* @returns The previous Transition, or null if this Transition is not the result of a redirection
*/
previous(): Transition {
return this._options.previous || null;
}
/**
* Get the transition options
*
* @returns the options for this Transition.
*/
options(): TransitionOptions {
return this._options;
}
/**
* Gets the states being entered.
*
* @returns an array of states that will be entered during this transition.
*/
entering(): StateDeclaration[] {
return map(this._treeChanges.entering, prop('state')).map(stateSelf);
}
/**
* Gets the states being exited.
*
* @returns an array of states that will be exited during this transition.
*/
exiting(): StateDeclaration[] {
return map(this._treeChanges.exiting, prop('state')).map(stateSelf).reverse();
}
/**
* Gets the states being retained.
*
* @returns an array of states that are already entered from a previous Transition, that will not be
* exited during this Transition
*/
retained(): StateDeclaration[] {
return map(this._treeChanges.retained, prop('state')).map(stateSelf);
}
/**
* Get the [[ViewConfig]]s associated with this Transition
*
* Each state can define one or more views (template/controller), which are encapsulated as `ViewConfig` objects.
* This method fetches the `ViewConfigs` for a given path in the Transition (e.g., "to" or "entering").
*
* @param pathname the name of the path to fetch views for:
* (`'to'`, `'from'`, `'entering'`, `'exiting'`, `'retained'`)
* @param state If provided, only returns the `ViewConfig`s for a single state in the path
*
* @returns a list of ViewConfig objects for the given path.
*/
views(pathname: string = "entering", state?: State): ViewConfig[] {
let path = this._treeChanges[pathname];
path = !state ? path : path.filter(propEq('state', state));
return path.map(prop("views")).filter(identity).reduce(unnestR, []);
}
treeChanges = () => this._treeChanges;
/**
* @ngdoc function
* @name ui.router.state.type:Transition#redirect
* @methodOf ui.router.state.type:Transition
*
* @description
* Creates a new transition that is a redirection of the current one. This transition can
* be returned from a `$transitionsProvider` hook, `$state` event, or other method, to
* redirect a transition to a new state and/or set of parameters.
*
* @returns {Transition} Returns a new `Transition` instance.
*/
redirect(targetState: TargetState): Transition {
let newOptions = extend({}, this.options(), targetState.options(), { previous: this });
targetState = new TargetState(targetState.identifier(), targetState.$state(), targetState.params(), newOptions);
let redirectTo = new Transition(this._treeChanges.from, targetState, this._transitionService);
let reloadState = targetState.options().reloadState;
// If the current transition has already resolved any resolvables which are also in the redirected "to path", then
// add those resolvables to the redirected transition. Allows you to define a resolve at a parent level, wait for
// the resolve, then redirect to a child state based on the result, and not have to re-fetch the resolve.
let redirectedPath = this.treeChanges().to;
let copyResolvesFor: Node[] = Node.matching(redirectTo.treeChanges().to, redirectedPath)
.filter(node => !reloadState || !reloadState.includes[node.state.name]);
const includeResolve = (resolve, key) => ['$stateParams', '$transition$'].indexOf(key) === -1;
copyResolvesFor.forEach((node, idx) => extend(node.resolves, filter(redirectedPath[idx].resolves, includeResolve)));
return redirectTo;
}
/** @hidden If a transition doesn't exit/enter any states, returns any [[Param]] whose value changed */
private _changedParams(): Param[] {
let {to, from} = this._treeChanges;
if (this._options.reload || tail(to).state !== tail(from).state) return undefined;
let nodeSchemas: Param[][] = to.map((node: Node) => node.paramSchema);
let [toValues, fromValues] = [to, from].map(path => path.map(x => x.paramValues));
let tuples = arrayTuples(nodeSchemas, toValues, fromValues);
return tuples.map(([schema, toVals, fromVals]) => Param.changed(schema, toVals, fromVals)).reduce(unnestR, []);
}
/**
* Returns true if the transition is dynamic.
*
* A transition is dynamic if no states are entered nor exited, but at least one dynamic parameter has changed.
*
* @returns true if the Transition is dynamic
*/
dynamic(): boolean {
let changes = this._changedParams();
return !changes ? false : changes.map(x => x.dynamic).reduce(anyTrueR, false);
}
/**
* Returns true if the transition is ignored.
*
* A transition is ignored if no states are entered nor exited, and no parameter values have changed.
*
* @returns true if the Transition is ignored.
*/
ignored(): boolean {
let changes = this._changedParams();
return !changes ? false : changes.length === 0;
}
/**
* @hidden
*/
hookBuilder(): HookBuilder {
return new HookBuilder(this._transitionService, this, <TransitionHookOptions> {
transition: this,
current: this._options.current
});
}
/**
* Runs the transition
*
* This method is generally called from the [[StateService.transitionTo]]
*
* @returns a promise for a successful transition.
*/
run (): Promise<any> {
let hookBuilder = this.hookBuilder();
let runSynchronousHooks = TransitionHook.runSynchronousHooks;
// TODO: nuke these in favor of chaining off the promise, i.e.,
// $transitions.onBefore({}, $transition$ => {$transition$.promise.then()}
const runSuccessHooks = () => runSynchronousHooks(hookBuilder.getOnSuccessHooks(), {}, true);
const runErrorHooks = ($error$) => runSynchronousHooks(hookBuilder.getOnErrorHooks(), { $error$ }, true);
// Run the success/error hooks *after* the Transition promise is settled.
this.promise.then(runSuccessHooks, runErrorHooks);
let syncResult = runSynchronousHooks(hookBuilder.getOnBeforeHooks());
if (TransitionHook.isRejection(syncResult)) {
let rejectReason = (<any> syncResult).reason;
this._deferred.reject(rejectReason);
return this.promise;
}
if (!this.valid()) {
let error = new Error(this.error());
this._deferred.reject(error);
return this.promise;
}
if (this.ignored()) {
trace.traceTransitionIgnored(this);
let ignored = REJECT.ignored();
this._deferred.reject(ignored.reason);
return this.promise;
}
// When the chain is complete, then resolve or reject the deferred
const resolve = () => {
this.success = true;
this._deferred.resolve(this);
trace.traceSuccess(this.$to(), this);
};
const reject = (error) => {
this.success = false;
this._deferred.reject(error);
trace.traceError(error, this);
return services.$q.reject(error);
};
trace.traceTransitionStart(this);
let chain = hookBuilder.asyncHooks().reduce((_chain, step) => _chain.then(step.invokeStep), syncResult);
chain.then(resolve, reject);
return this.promise;
}
isActive = () => this === this._options.current();
/**
* Checks if the Transition is valid
*
* @returns true if the Transition is valid
*/
valid() {
return !this.error();
}
/**
* The reason the Transition is invalid
*
* @returns an error message explaining why the transition is invalid
*/
error() {
let state = this.$to();
if (state.self[abstractKey])
return `Cannot transition to abstract state '${state.name}'`;
if (!Param.validates(state.parameters(), this.params()))
return `Param values not valid for state '${state.name}'`;
}
/**
* A string representation of the Transition
*
* @returns A string representation of the Transition
*/
toString () {
let fromStateOrName = this.from();
let toStateOrName = this.to();
const avoidEmptyHash = (params) =>
(params["#"] !== null && params["#"] !== undefined) ? params : omit(params, "#");
// (X) means the to state is invalid.
let id = this.$id,
from = isObject(fromStateOrName) ? fromStateOrName.name : fromStateOrName,
fromParams = toJson(avoidEmptyHash(this._treeChanges.from.map(prop('paramValues')).reduce(mergeR, {}))),
toValid = this.valid() ? "" : "(X) ",
to = isObject(toStateOrName) ? toStateOrName.name : toStateOrName,
toParams = toJson(avoidEmptyHash(this.params()));
return `Transition#${id}( '${from}'${fromParams} -> ${toValid}'${to}'${toParams} )`;
}
} | the_stack |
import { StringUtils } from './stringUtils';
import { UserColumn } from '../user/userColumn';
import { UserTable } from '../user/userTable';
import { GeoPackageConnection } from './geoPackageConnection';
import { TableMapping } from './tableMapping';
import { TableInfo } from './table/tableInfo';
import { SQLiteMaster } from './master/sqliteMaster';
import { SQLiteMasterQuery } from './master/sqliteMasterQuery';
import { SQLiteMasterColumn } from './master/sqliteMasterColumn';
export class CoreSQLUtils {
/**
* Pattern for matching numbers
*/
static NUMBER_PATTERN = '\\d+';
/**
* Create the user defined table SQL
*
* @param table user table
* @param <TColumn> column type
* @return create table SQL
*/
static createTableSQL(table: UserTable<UserColumn>): string {
// Build the create table sql
let sql = '';
sql = sql.concat('CREATE TABLE ')
.concat(StringUtils.quoteWrap(table.getTableName()))
.concat(' (');
// Add each column to the sql
let columns = table.getUserColumns().getColumns();
for (let i = 0; i < columns.length; i++) {
let column = columns[i];
if (i > 0) {
sql = sql.concat(',');
}
sql = sql.concat('\n ');
sql = sql.concat(CoreSQLUtils.columnSQL(column));
}
// Add unique constraints
table.getConstraints().all().forEach(constraint => {
sql = sql.concat(',\n ');
sql = sql.concat(constraint.buildSql());
});
sql = sql.concat('\n);');
return sql;
}
/**
* Create the column SQL in the format:
* "column_name" column_type[(max)] [NOT NULL] [PRIMARY KEY AUTOINCREMENT]
* @param column user column
* @return column SQL
*/
static columnSQL(column: UserColumn): string {
return StringUtils.quoteWrap(column.getName()) + ' ' + CoreSQLUtils.columnDefinition(column);
}
/**
* Create the column definition SQL in the format:
* column_type[(max)] [NOT NULL] [PRIMARY KEY AUTOINCREMENT]
* @param column user column
* @return column definition SQL
*/
static columnDefinition(column: UserColumn): string {
let sql = '';
sql = sql.concat(column.getType());
if (column.hasMax()) {
sql = sql.concat('(').concat(column.getMax().toString()).concat(')');
}
column.getConstraints().all().forEach(constraint => {
sql = sql.concat(' ');
sql = sql.concat(column.buildConstraintSql(constraint));
});
return sql.toString();
}
/**
* Query for the foreign keys value
*
* @param db
* connection
* @return true if enabled, false if disabled
* @since 3.3.0
*/
static foreignKeys(db: GeoPackageConnection): boolean {
let foreignKeys = db.get('PRAGMA foreign_keys', null)[0] as boolean;
return foreignKeys !== null && foreignKeys !== undefined && foreignKeys;
}
/**
* Change the foreign keys state
* @param db connection
* @param on true to turn on, false to turn off
* @return previous foreign keys value
*/
static setForeignKeys(db: GeoPackageConnection, on: boolean): boolean {
let foreignKeys = CoreSQLUtils.foreignKeys(db);
if (foreignKeys !== on) {
let sql = CoreSQLUtils.foreignKeysSQL(on);
db.run(sql);
}
return foreignKeys;
}
/**
* Create the foreign keys SQL
* @param on true to turn on, false to turn off
* @return foreign keys SQL
*/
static foreignKeysSQL(on: boolean): string {
return 'PRAGMA foreign_keys = ' + on;
}
/**
* Perform a foreign key check
* @param db connection
* @return empty list if valid or violation errors, 4 column values for each violation. see SQLite PRAGMA foreign_key_check
*/
static foreignKeyCheck(db: GeoPackageConnection): any[] {
let sql = CoreSQLUtils.foreignKeyCheckSQL(null);
return db.all(sql, null);
}
/**
* Perform a foreign key check
* @param db connection
* @param tableName table name
* @return empty list if valid or violation errors, 4 column values for each violation. see SQLite PRAGMA foreign_key_check
*/
static foreignKeyCheckForTable(db: GeoPackageConnection, tableName: string): any[] {
let sql = CoreSQLUtils.foreignKeyCheckSQL(tableName);
return db.all(sql, null);
}
/**
* Create the foreign key check SQL
* @param tableName table name
* @return foreign key check SQL
*/
static foreignKeyCheckSQL(tableName: string): string {
return 'PRAGMA foreign_key_check' + (tableName !== null && tableName !== undefined ? '(' + StringUtils.quoteWrap(tableName) + ')' : '');
}
/**
* Create the integrity check SQL
* @return integrity check SQL
*/
static integrityCheckSQL(): string {
return 'PRAGMA integrity_check';
}
/**
* Create the quick check SQL
* @return quick check SQL
*/
static quickCheckSQL(): string {
return 'PRAGMA quick_check';
}
/**
* Drop the table if it exists
* @param db connection
* @param tableName table name
*/
static dropTable(db: GeoPackageConnection, tableName: string) {
const sql = CoreSQLUtils.dropTableSQL(tableName);
db.run(sql);
}
/**
* Create the drop table if exists SQL
* @param tableName table name
* @return drop table SQL
*/
static dropTableSQL(tableName: string): string {
return 'DROP TABLE IF EXISTS ' + StringUtils.quoteWrap(tableName);
}
/**
* Drop the view if it exists
* @param db connection
* @param viewName view name
*/
static dropView(db: GeoPackageConnection, viewName: string) {
const sql = CoreSQLUtils.dropViewSQL(viewName);
db.run(sql);
}
/**
* Create the drop view if exists SQL
* @param viewName view name
* @return drop view SQL
*/
static dropViewSQL(viewName: string): string {
return 'DROP VIEW IF EXISTS ' + StringUtils.quoteWrap(viewName);
}
/**
* Transfer table content from one table to another
* @param db connection
* @param tableMapping table mapping
*/
static transferTableContentForTableMapping(db: GeoPackageConnection, tableMapping: TableMapping) {
const sql = CoreSQLUtils.transferTableContentSQL(tableMapping);
db.run(sql);
}
/**
* Create insert SQL to transfer table content from one table to another
* @param tableMapping table mapping
* @return transfer SQL
*/
static transferTableContentSQL(tableMapping: TableMapping): string {
let insert = 'INSERT INTO ';
insert = insert.concat(StringUtils.quoteWrap(tableMapping.toTable));
insert = insert.concat(' (');
let selectColumns = '';
let where = '';
if (tableMapping.hasWhere()) {
where = where.concat(tableMapping.where);
}
const columns = tableMapping.getColumns();
tableMapping.getColumnNames().forEach((key: string) => {
let toColumn = key;
let column = columns[key];
if (selectColumns.length > 0) {
insert = insert.concat(', ');
selectColumns = selectColumns.concat(', ');
}
insert = insert.concat(StringUtils.quoteWrap(toColumn));
if (column.hasConstantValue()) {
selectColumns = selectColumns.concat(column.getConstantValueAsString());
} else {
if (column.hasDefaultValue()) {
selectColumns = selectColumns.concat('ifnull(');
}
selectColumns = selectColumns.concat(StringUtils.quoteWrap(column.fromColumn));
if (column.hasDefaultValue()) {
selectColumns = selectColumns.concat(',');
selectColumns = selectColumns.concat(column.getDefaultValueAsString());
selectColumns = selectColumns.concat(')');
}
}
if (column.hasWhereValue()) {
if (where.length > 0) {
where = where.concat(' AND ');
}
where = where.concat(StringUtils.quoteWrap(column.fromColumn));
where = where.concat(' ');
where = where.concat(column.whereOperator);
where = where.concat(' ');
where = where.concat(column.getWhereValueAsString());
}
});
insert = insert.concat(') SELECT ');
insert = insert.concat(selectColumns);
insert = insert.concat(' FROM ');
insert = insert.concat(StringUtils.quoteWrap(tableMapping.fromTable));
if (where.length > 0) {
insert = insert.concat(' WHERE ');
insert = insert.concat(where);
}
return insert.toString();
}
/**
* Transfer table content to itself with new rows containing a new column
* value. All rows containing the current column value are inserted as new
* rows with the new column value.
* @param db connection
* @param tableName table name
* @param columnName column name
* @param newColumnValue new column value for new rows
* @param currentColumnValue column value for rows to insert as new rows
* @param idColumnName id column name
*/
static transferTableContent(db: GeoPackageConnection, tableName: string, columnName: string, newColumnValue: any, currentColumnValue: any, idColumnName?: string) {
let tableInfo = TableInfo.info(db, tableName);
let tableMapping = TableMapping.fromTableInfo(tableInfo);
if (idColumnName != null) {
tableMapping.removeColumn(idColumnName);
}
let tileMatrixSetNameColumn = tableMapping.getColumn(columnName);
tileMatrixSetNameColumn.constantValue = newColumnValue;
tileMatrixSetNameColumn.whereValue = currentColumnValue;
CoreSQLUtils.transferTableContentForTableMapping(db, tableMapping);
}
/**
* Get an available temporary table name. Starts with prefix_baseName and
* then continues with prefix#_baseName starting at 1 and increasing.
* @param db connection
* @param prefix name prefix
* @param baseName base name
* @return unused table name
*/
static tempTableName(db: GeoPackageConnection, prefix: string, baseName: string) {
let name = prefix + '_' + baseName;
let nameNumber = 0;
while (db.tableExists(name)) {
name = prefix + (++nameNumber) + '_' + baseName;
}
return name;
}
/**
* Modify the SQL with a name change and the table mapping modifications
* @param db optional connection, used for SQLite Master name conflict detection
* @param name statement name
* @param sql SQL statement
* @param tableMapping table mapping
* @return updated SQL, null if SQL contains a deleted column
*/
static modifySQL(db: GeoPackageConnection, name: string, sql: string, tableMapping: TableMapping): string {
let updatedSql = sql;
if (name !== null && name !== undefined && tableMapping.isNewTable()) {
let newName = CoreSQLUtils.createName(db, name, tableMapping.fromTable, tableMapping.toTable);
let updatedName = CoreSQLUtils.replaceName(updatedSql, name, newName);
if (updatedName !== null && updatedName !== undefined) {
updatedSql = updatedName;
}
let updatedTable = CoreSQLUtils.replaceName(updatedSql, tableMapping.fromTable, tableMapping.toTable);
if (updatedTable !== null && updatedTable !== undefined) {
updatedSql = updatedTable;
}
}
updatedSql = CoreSQLUtils.modifySQLWithTableMapping(updatedSql, tableMapping);
return updatedSql;
}
/**
* Modify the SQL with table mapping modifications
* @param sql SQL statement
* @param tableMapping table mapping
* @return updated SQL, null if SQL contains a deleted column
*/
static modifySQLWithTableMapping(sql: string, tableMapping: TableMapping): string {
let updatedSql = sql;
let droppedColumns = Array.from(tableMapping.droppedColumns);
for (let i = 0; i < droppedColumns.length; i++) {
let column = droppedColumns[i];
let updated = CoreSQLUtils.replaceName(updatedSql, column, ' ');
if (updated !== null && updated !== undefined) {
updatedSql = null;
break;
}
}
if (updatedSql !== null && updatedSql !== undefined) {
tableMapping.getMappedColumns().forEach(column => {
if (column.hasNewName()) {
let updated = CoreSQLUtils.replaceName(updatedSql, column.fromColumn, column.toColumn);
if (updated !== null && updated !== undefined) {
updatedSql = updated;
}
}
});
}
return updatedSql;
}
/**
* Replace the name (table, column, etc) in the SQL with the replacement.
* The name must be surrounded by non word characters (i.e. not a subset of
* another name).
* @param sql SQL statement
* @param name name
* @param replacement replacement value
* @return null if not modified, SQL value if replaced at least once
*/
static replaceName(sql: string, name: string, replacement: string): string {
let updatedSql = null;
// Quick check if contained in the SQL
if (sql.indexOf(name) >= 0) {
let updated = false;
let updatedSqlBuilder = '';
// Split the SQL apart by the name
let parts = sql.split(name);
for (let i = 0; i <= parts.length; i++) {
if (i > 0) {
// Find the character before the name
let before = '_';
let beforePart = parts[i - 1];
if (beforePart.length === 0) {
if (i == 1) {
// SQL starts with the name, allow
before = ' ';
}
} else {
before = beforePart.substring(beforePart.length - 1);
}
// Find the character after the name
let after = '_';
if (i < parts.length) {
let afterPart = parts[i];
if (afterPart.length !== 0) {
after = afterPart.substring(0, 1);
}
} else if (sql.endsWith(name)) {
// SQL ends with the name, allow
after = ' ';
} else {
break;
}
// Check the before and after characters for non word
// characters
if (before.match('\\W').length > 0 && after.match('\\W').length > 0) {
// Replace the name
updatedSqlBuilder = updatedSqlBuilder.concat(replacement);
updated = true;
} else {
// Preserve the name
updatedSqlBuilder = updatedSqlBuilder.concat(name);
}
}
// Add the part to the SQL
if (i < parts.length) {
updatedSqlBuilder = updatedSqlBuilder.concat(parts[i]);
}
}
// Set if the SQL was modified
if (updated) {
updatedSql = updatedSqlBuilder.toString();
}
}
return updatedSql;
}
/**
* Create a new name by replacing a case insensitive value with a new value.
* If no replacement is done, create a new name in the form name_#, where #
* is either 2 or one greater than an existing name number suffix. When a db
* connection is provided, check for conflicting SQLite Master names and
* increment # until an available name is found.
* @param db optional connection, used for SQLite Master name conflict detection
* @param name current name
* @param replace value to replace
* @param replacement replacement value
* @return new name
*/
static createName(db: GeoPackageConnection, name: string, replace: string, replacement: string): string {
// Attempt the replacement
let newName = name.replace(new RegExp(replace), replacement);
// If no name change was made
if (newName === name) {
let baseName = newName;
let count = 1;
// Find any existing end number: name_#
let index = baseName.lastIndexOf('_');
if (index >= 0 && index + 1 < baseName.length) {
let numberPart = baseName.substring(index + 1);
if (numberPart.match(CoreSQLUtils.NUMBER_PATTERN).length > 0) {
baseName = baseName.substring(0, index);
count = parseInt(numberPart);
}
}
// Set the new name to name_2 or name_(#+1)
newName = baseName + '_' + (++count);
if (db !== null && db !== undefined) {
// Check for conflicting SQLite Master table names
while (SQLiteMaster.count(db, null, SQLiteMasterQuery.createForColumnValue(SQLiteMasterColumn.NAME, newName)) > 0) {
newName = baseName + '_' + (++count);
}
}
}
return newName;
}
/**
* Rebuild the GeoPackage, repacking it into a minimal amount of disk space
* @param db connection
*/
static vacuum(db: GeoPackageConnection) {
db.run('VACUUM');
}
} | the_stack |
import { IDebugger } from 'debug';
import * as _ from 'lodash';
import { EOL } from 'os';
import { YESNO_RECORDING_MODE_ENV_VAR } from './consts';
import Context, { IInFlightRequest } from './context';
import { YesNoError } from './errors';
import * as file from './file';
import FilteredHttpCollection, { IFiltered } from './filtering/collection';
import { ComparatorFn } from './filtering/comparator';
import { ISerializedHttpPartialDeepMatch, MatchFn } from './filtering/matcher';
import { redact as redactRecord, Redactor } from './filtering/redact';
import {
createRecord,
formatUrl,
ISerializedHttp,
ISerializedRequest,
ISerializedResponse,
RequestSerializer,
validateSerializedHttpArray,
} from './http-serializer';
import Interceptor, { IInterceptEvent, IInterceptOptions, IProxiedEvent } from './interceptor';
import MockResponse from './mock-response';
import Recording, { RecordMode as Mode } from './recording';
const debug: IDebugger = require('debug')('yesno');
export type GenericTest = (...args: any) => Promise<any> | void;
export type GenericTestFunction = (title: string, fn: GenericTest) => any;
export type HttpFilter = string | RegExp | ISerializedHttpPartialDeepMatch | MatchFn;
export interface IRecordableTest {
test?: GenericTestFunction;
it?: GenericTestFunction;
prefix?: string;
dir: string;
}
/**
* Options to configure intercept of HTTP requests
*/
export interface IYesNoInterceptingOptions extends IInterceptOptions {
/**
* Comparator function used to determine whether an intercepted request
* matches a loaded mock.
*/
comparatorFn?: ComparatorFn;
}
/**
* Client API for YesNo
*/
export class YesNo implements IFiltered {
private readonly interceptor: Interceptor;
private readonly ctx: Context;
constructor(ctx: Context) {
this.ctx = ctx;
this.interceptor = this.createInterceptor();
}
/**
* Restore HTTP functionality
*/
public restore(): void {
debug('Disabling intercept');
this.clear();
this.interceptor.disable();
}
/**
* Spy on intercepted requests
*/
public spy(options?: IYesNoInterceptingOptions): void {
this.enable(options);
this.setMode(Mode.Spy);
}
/**
* Mock responses for intercepted requests
* @todo Reset the request counter?
*/
public mock(mocks: file.IHttpMock[], options?: IYesNoInterceptingOptions): void {
this.enable(options);
this.setMode(Mode.Mock);
this.setMocks(mocks.map(file.hydrateHttpMock));
}
/**
* Start a new recording.
*
* Depending on the configured mode, will either spy on all outbound HTTP requests
* or return mocks loaded from disc.
*
* When done, call the `complete()` on the returned recording
* to save all intercepted requests to disc if applicable.
* @param options Where to load/save mocks
* @returns A new recording.
*/
public async recording(options: file.IFileOptions): Promise<Recording> {
const mode = this.getModeByEnv();
if (mode !== Mode.Mock) {
this.spy();
} else {
this.mock(await this.load(options));
}
return new Recording({
...options,
getRecordsToSave: this.getRecordsToSave.bind(this),
mode,
});
}
/**
* Create a test function that will wrap its provided test in a recording.
*/
public test({ it, test, dir, prefix }: IRecordableTest): GenericTestFunction {
const runTest = test || it;
if (!runTest) {
throw new YesNoError('Missing "test" or "it" test function');
}
return (title: string, fn: GenericTest): GenericTestFunction => {
const filename = file.getMockFilename(prefix ? `${prefix}-${title}` : title, dir);
return runTest(title, async () => {
debug('Running test "%s"', title);
this.restore();
try {
const recording = await this.recording({ filename });
await fn();
debug('Saving test "%s"', filename);
await recording.complete();
} finally {
this.restore();
}
});
};
}
/**
* Load request/response mocks from disk
*/
public async load(options: file.IFileOptions): Promise<ISerializedHttp[]> {
debug('Loading mocks');
const records = await file.load(options as file.IFileOptions);
validateSerializedHttpArray(records);
return records;
}
/**
* Save intercepted requests
*
* Normally save is called by the complete method and will only succeed if there are
* no in-flight requests (i.e. all open requests have completed). However, if for some
* reason a request will not complete and you need to save the successful requests up to
* that point, you can set 'force' option to true and call this save method.
*
* @returns Full filename of saved JSON if generated
*/
public async save(options: file.ISaveOptions & file.IFileOptions): Promise<string | void> {
options.records = options.records || this.getRecordsToSave(options.force);
return file.save(options);
}
/**
* Clear all stateful information about requests.
*
* If used in a test suite, this should be called after each test.
*/
public clear() {
this.ctx.clear();
(this.interceptor as Interceptor).requestNumber = 0;
}
/**
* Create a filter collection
* @todo Convert everything to a match fn
* @param query
*/
public matching(filter?: HttpFilter): FilteredHttpCollection {
const normalizedFilter: ISerializedHttpPartialDeepMatch | MatchFn | undefined =
_.isString(filter) || _.isRegExp(filter) ? { url: filter } : filter;
return this.getCollection(normalizedFilter);
}
/**
* Get all intercepted requests
*/
public intercepted(): ISerializedHttp[] {
return this.getCollection().intercepted();
}
/**
* Get all loaded mocks
*/
public mocks(): ISerializedHttp[] {
return this.getCollection().mocks();
}
/**
* Redact property on all records
*/
public redact(property: string | string[], redactor?: Redactor): void {
if (this.getCollection().intercepted().length) {
return this.getCollection().redact(property, redactor);
}
this.ctx.autoRedact = { property, redactor };
}
private getModeByEnv(): Mode {
const env = (process.env[YESNO_RECORDING_MODE_ENV_VAR] || Mode.Mock).toLowerCase();
if (!Object.values(Mode).includes(env)) {
throw new YesNoError(
// tslint:disable-next-line:max-line-length
`Invalid mode "${env}" set for ${YESNO_RECORDING_MODE_ENV_VAR}. Must be one of ${Object.values(
Mode,
).join(', ')}`,
);
}
return env as Mode;
}
private getRecordsToSave(force: boolean = false): ISerializedHttp[] {
const inFlightRequests = this.ctx.inFlightRequests.filter((x) => x) as IInFlightRequest[];
if (inFlightRequests.length && !force) {
const urls = inFlightRequests
.map(
({ requestSerializer }) => `${requestSerializer.method}${formatUrl(requestSerializer)}`,
)
.join(EOL);
throw new YesNoError(
`Cannot save. Still have ${inFlightRequests.length} in flight requests: ${EOL}${urls}`,
);
}
return this.ctx.interceptedRequestsCompleted;
}
/**
* Enable intercepting requests
*/
private enable(options?: IYesNoInterceptingOptions): YesNo {
const { comparatorFn, ignorePorts = [] }: IYesNoInterceptingOptions = options || {};
debug('Enabling intercept. Ignoring ports', ignorePorts);
this.interceptor.enable({ ignorePorts });
this.ctx.comparatorFn = comparatorFn || this.ctx.comparatorFn;
return this;
}
private setMocks(mocks: ISerializedHttp[]): void {
validateSerializedHttpArray(mocks);
this.ctx.loadedMocks = mocks;
}
/**
* Determine the current mode
*/
private isMode(mode: Mode): boolean {
return this.ctx.mode === mode;
}
private createInterceptor() {
const interceptor = new Interceptor();
interceptor.on('intercept', this.onIntercept.bind(this));
interceptor.on('proxied', this.onProxied.bind(this));
return interceptor;
}
private async onIntercept(event: IInterceptEvent): Promise<void> {
this.recordRequest(event.requestSerializer, event.requestNumber);
if (!this.ctx.hasResponsesDefinedForMatchers() && !this.isMode(Mode.Mock)) {
// No need to mock, send event to its original destination
return event.proxy();
}
// proxy requst if ignore is set
if (this.ctx.hasMatchingIgnore(event.requestSerializer)) {
return event.proxy();
}
try {
const mockResponse = new MockResponse(event, this.ctx);
const sent = await mockResponse.send();
if (sent) {
// redact properties if needed
if (this.ctx.autoRedact !== null) {
const properties = _.isArray(this.ctx.autoRedact.property)
? this.ctx.autoRedact.property
: [this.ctx.autoRedact.property];
const record = createRecord({
duration: 0,
request: sent.request,
response: sent.response,
});
sent.request = redactRecord(record, properties, this.ctx.autoRedact.redactor).request;
}
this.recordResponse(sent.request, sent.response, event.requestNumber);
} else if (this.isMode(Mode.Mock)) {
throw new Error('Unexpectedly failed to send mock respond');
}
} catch (e) {
if (!(e instanceof YesNoError)) {
debug(`[#${event.requestNumber}] Mock response failed unexpectedly`, e);
e.message = `YesNo: Mock response failed: ${e.message}`;
} else {
debug(`[#${event.requestNumber}] Mock response failed`, e.message);
}
event.clientRequest.emit('error', e);
}
}
private onProxied({ requestSerializer, responseSerializer, requestNumber }: IProxiedEvent): void {
this.recordResponse(
requestSerializer.serialize(),
responseSerializer.serialize(),
requestNumber,
);
}
private setMode(mode: Mode) {
this.ctx.mode = mode;
}
private getCollection(
matcher?: ISerializedHttpPartialDeepMatch | MatchFn,
): FilteredHttpCollection {
return new FilteredHttpCollection({
context: this.ctx,
matcher,
});
}
private recordRequest(requestSerializer: RequestSerializer, requestNumber: number): void {
this.ctx.inFlightRequests[requestNumber] = {
requestSerializer,
startTime: Date.now(),
};
}
private recordResponse(
request: ISerializedRequest,
response: ISerializedResponse,
requestNumber: number,
): void {
const duration =
Date.now() - (this.ctx.inFlightRequests[requestNumber] as IInFlightRequest).startTime;
const record = createRecord({ request, response, duration });
this.ctx.interceptedRequestsCompleted[requestNumber] = record;
this.ctx.inFlightRequests[requestNumber] = null;
debug(
'Added request-response for %s %s (duration: %d)',
request.method,
record.request.host,
duration,
);
}
} | the_stack |
import { message } from 'antd';
import _ from 'lodash';
import { all, call, delay, put, takeLatest } from 'redux-saga/effects';
import { getType } from 'typesafe-actions';
import { updateRequireLoadStatus } from '@/actions/builder/component-load';
import { updateConditionBindDrawerVisible } from '@/actions/builder/condition';
import * as MOCK_ACTIONS from '@/actions/builder/more';
import * as ACTIONS from '@/actions/builder/template';
import {
clonePage,
fetchPageBuildVersion,
fetchPageLiveVersion,
fetchTemplateBuildVersion,
publishPage,
publishTemplate,
updatePageDsl,
updateTemplateDsl,
} from '@/apis/builder';
import { FileTypeEnum, VersionStatusEnum } from '@/constants/index';
import { BLANK_NODE } from '@/pages/builder/constant';
import { getBusinessI18n } from '@/pages/locale';
import { TemplateActionType } from '@/reducers/builder/template';
import * as utils from '@/services/builder';
import { store } from '@/store/index';
import { ConditionContentItem, ConditionItem } from '@/types/application/condition';
import { FuncContentItem } from '@/types/application/function';
import { VariableContent } from '@/types/application/variable';
import {
ComponentDirectiveType,
ComponentPropsType,
ComponentSaveParams,
ComponentSourceMapType,
ComponentStaticSaveParams,
ComponentStructure,
ComponentType,
DslType,
MockContent,
PageCloneParams,
PageParam,
RelationType,
} from '@/types/builder';
import { OptionsAction } from '@/types/index';
import { objectEmptyCheck } from '@/utils/object-empty-check';
import { getConditionRelationKey, getTemplateRelationKey } from '@/utils/relation';
import shortId from '@/utils/short-id';
import { differ, mergeContent, mockContent, positionInit } from './extend';
function generateId() {
return `stru_${shortId(15)}`;
}
function* disposalData(
_applicationId: string,
oldVersion: DslType,
componentSourceMap: ComponentSourceMapType,
fileType?: string,
) {
const version = _.cloneDeep<DslType>(oldVersion);
const state = store.getState().builder.template;
const versionType: string = fileType || state.versionType;
if (!version?.content) {
return;
}
const { templates = [], variables = [], conditions = [], functions = [] } = version.relations || {};
const { schemas } = version.content;
utils.setWrapperToDsl(schemas);
if (schemas && schemas.length > 0) {
const componentList: Array<ComponentStructure> = [];
if (versionType === 'page') {
schemas.forEach((item) => {
utils.generateComponentList(componentList, _.cloneDeep(item.children) || [], schemas[0].id);
});
} else {
utils.generateComponentList(componentList, _.cloneDeep(schemas));
}
componentList.forEach((component) => {
utils.setComponentSource(component, componentSourceMap);
});
const renderStructure = utils.getRenderStructure(
componentList,
versionType === 'page' ? version.content.schemas[0].id : undefined,
);
let mergedDsl: any;
let parsedComponentList: ComponentStructure[] = [];
if (versionType === 'page') {
mergedDsl = yield call(
utils.mergeDsl,
store.getState().group.application.settings.application,
version.content,
templates,
variables,
conditions,
functions,
store.getState().builder.page.locale,
);
utils.setSourceToDsl(mergedDsl.page.schemas, componentSourceMap, componentList);
utils.generateComponentList(parsedComponentList, _.cloneDeep(mergedDsl.page.schemas));
} else {
parsedComponentList = componentList;
}
return {
componentList,
renderStructure,
templates,
parsedComponentList,
parsedRenderStructure: versionType === 'page' ? mergedDsl.page.schemas : renderStructure,
};
}
return {};
}
function* fetchPageRenderTree(action: TemplateActionType) {
yield put(ACTIONS.updateLoadingStatus(true));
const { applicationId, contentId, fileType } = action.payload as PageParam;
const api: any = fileType === FileTypeEnum.page ? fetchPageBuildVersion : fetchTemplateBuildVersion;
const res = yield call(api, {
applicationId,
id: contentId,
});
if (res.code === 200) {
// render content
let renderContent: DslType | null = res.data as DslType;
// mock related
let extendPage;
const mocks: MockContent[] = [];
// deal with extend(inherit)
const extendId = renderContent?.content.extension?.extendId;
if (extendId) {
const baseRes = yield call(fetchPageLiveVersion, {
applicationId,
id: extendId,
});
if (baseRes.code === 200 && !objectEmptyCheck(baseRes.data)) {
// back up
yield put(ACTIONS.pushExtensionData({ baseContent: baseRes.data, curContent: renderContent }));
// merge
renderContent = mergeContent(_.cloneDeep(baseRes.data) as DslType, _.cloneDeep(renderContent));
// mock
const basePageContent = baseRes.data?.content;
if (basePageContent) extendPage = basePageContent;
const mockData = baseRes.data?.mock;
if (!objectEmptyCheck(mockData)) mocks.push(mockData);
}
} else {
// clear/reset
yield put(ACTIONS.pushExtensionData());
}
// handle update mock id
const mockId: string = _.get(renderContent, 'content.extension.mockId');
if (!!mockId) {
yield put(MOCK_ACTIONS.updateMockId(mockId));
}
// handle update mock data/ mock mode enable status
const mockData = renderContent?.mock;
if (mockData && typeof mockData === 'object' && Object.keys(mockData).length > 0) {
mocks.push(mockData);
// push to store
yield put(MOCK_ACTIONS.pushMock(mockData));
}
const mockModeEnable = renderContent?.mock?.enable;
yield put(MOCK_ACTIONS.updateMockMode(!!mockModeEnable));
// handle relation templates mock data
const relationTemplates = _.get(renderContent, 'relations.templates');
if (relationTemplates && Array.isArray(relationTemplates) && relationTemplates.length > 0) {
// get template mock data && generate a total one
relationTemplates.forEach((template) => {
const templateMockData = template?.mock;
if (templateMockData) mocks.push(templateMockData);
});
}
// record whole page mock data
yield put(ACTIONS.pushMocks(mocks));
if (renderContent) {
// generate component source map
const componentSourceMap: ComponentSourceMapType = {};
renderContent.components?.forEach((component: ComponentType) => {
if (component.name) {
componentSourceMap[component.name] = component;
}
});
// generate others state
const {
componentList,
renderStructure,
templates,
parsedComponentList,
parsedRenderStructure,
} = yield disposalData(applicationId, renderContent, componentSourceMap, fileType);
// generate mock
let renderContentWithMock,
mockComponentList = [],
mockParsedComponentList = [],
mockParsedRenderStructure = [];
if (!objectEmptyCheck(mocks)) {
renderContentWithMock = mockContent(_.cloneDeep(renderContent), extendPage, mocks, applicationId);
if (renderContentWithMock) {
const {
componentList: componentListWithMock,
parsedComponentList: parsedComponentListWithMock,
parsedRenderStructure: parsedRenderStructureWithMock,
} = yield disposalData(applicationId, renderContentWithMock, componentSourceMap, fileType);
mockComponentList = componentListWithMock;
mockParsedComponentList = parsedComponentListWithMock;
mockParsedRenderStructure = parsedRenderStructureWithMock;
}
} else {
renderContentWithMock = renderContent;
}
yield put(
ACTIONS.pushTemplateData({
componentList,
renderStructure,
templates,
parsedComponentList,
parsedRenderStructure,
version: renderContent,
componentSourceMap,
versionType: fileType || '',
mockVersion: renderContentWithMock,
mockComponentList,
mockParsedComponentList,
mockParsedRenderStructure,
}),
);
if (
(!renderContent?.content?.schemas || renderContent?.content?.schemas.length === 0) &&
fileType === FileTypeEnum.page
) {
yield addVersionContent(applicationId, generateId(), { width: '100%', height: '100%' });
yield put(ACTIONS.fetchPageRenderTree(applicationId, contentId || '', fileType));
}
}
} else {
message.error(res.msg);
}
yield put(ACTIONS.updateLoadingStatus(false));
yield put(updateRequireLoadStatus(true));
}
function* addVersionContent(
applicationId: string,
schemaId: string,
props: ComponentPropsType,
successCb?: (version) => void,
extentContentId?: string,
) {
const {
global: { addFailed },
} = getBusinessI18n();
const { version } = store.getState().builder.template;
const res = yield call(updatePageDsl, {
id: version.content.id,
applicationId,
content: {
id: version.content.id,
schemas: [
{
id: schemaId,
name: '',
type: '',
props,
children:
version?.content?.schemas &&
version.content.schemas.length > 0 &&
version.content.schemas[0].children
? version.content.schemas[0].children
: [],
directive: extentContentId
? {
tpl: `{{${getTemplateRelationKey(extentContentId)}}}`,
}
: undefined,
},
],
relation: extentContentId
? {
[getTemplateRelationKey(extentContentId)]: {
id: extentContentId,
type: 'template',
},
}
: {},
},
});
if (res.code === 200) {
successCb && successCb(res.data);
yield put(ACTIONS.updateVersion(res.data));
} else {
message.error(res.msg || addFailed);
}
}
function* saveComponent(action: TemplateActionType) {
const { applicationId, params, deleteSelectedComponent = true, preUpdateCb } = action.payload as {
applicationId: string;
params: ComponentStaticSaveParams;
deleteSelectedComponent: boolean;
pushLastStep: boolean;
preUpdateCb: () => void;
};
const { requireLoad } = params;
if (deleteSelectedComponent) {
yield put(ACTIONS.setSelectedComponent());
}
yield put(ACTIONS.pushLastSteps());
yield put(ACTIONS.clearNextSteps());
if (typeof preUpdateCb === 'function') {
yield preUpdateCb();
}
const { componentSourceMap, version, mockVersion, versionType } = store.getState().builder.template;
const generateParams = (type) => ({
...params,
content: {
children: params.content.children,
id: params.content.id,
label: params.content.label,
name: params.content.name,
parentId: params.content.parentId,
props: type === 'mock' ? params.content.mock : params.content.props,
wrapper: params.content.wrapper,
directive: params.content.directive,
extension: params.content.extension,
},
});
const assignVersion = _.cloneDeep(version);
const newVersion = utils.updateDsl(assignVersion, generateParams('props'), versionType);
const desposalData = yield disposalData(applicationId, newVersion, componentSourceMap);
// sync mock data & mockVersion & mockParsedRenderStructure
const mockData = params.content?.mock || {};
if (Object.keys(mockData).length > 0) {
const { folderId } = store.getState().builder.page;
yield put(MOCK_ACTIONS.updateMock({ applicationId, folderId, value: mockData }));
}
const newMockVersion = utils.updateDsl(_.cloneDeep(mockVersion), generateParams('mock'), versionType);
const {
componentList: mockComponentList,
parsedComponentList: mockParsedComponentList,
parsedRenderStructure: mockParsedRenderStructure,
} = yield disposalData(applicationId, newMockVersion, componentSourceMap);
yield put(
ACTIONS.pushTemplateData({
...desposalData,
version: newVersion,
mockVersion: newMockVersion,
mockComponentList,
mockParsedComponentList,
mockParsedRenderStructure,
}),
);
yield put(ACTIONS.updatePageEditStatus(true));
yield put(updateRequireLoadStatus(requireLoad));
}
function* appendComponent(action: TemplateActionType) {
const { componentId, desc, applicationId } = action.payload as {
componentId: string;
desc: ComponentStructure;
applicationId: string;
};
yield put(ACTIONS.pushComponentSource([desc.name]));
const state = store.getState().builder.template;
const { version, versionType } = state;
const { content } = version;
let schemaId;
if ((!content || !content.schemas) && versionType === FileTypeEnum.page) {
schemaId = generateId();
yield addVersionContent(applicationId, schemaId, { width: '100%', height: '100%' });
}
const registeredComponent = store.getState().builder.componentList.allComponent;
const parentId: string =
componentId === 'root-container' ? (content.schemas ? content.schemas[0]?.id : schemaId) : componentId;
const component = utils.newWrapperComponent(registeredComponent, desc.name, parentId);
yield put(
ACTIONS.saveComponent(applicationId, {
id: content.id,
parentId,
type: 'add',
content: component,
position: desc.position,
requireLoad: true,
}),
);
yield delay(300);
yield put(ACTIONS.setSelectedComponent(component.id));
}
function* insertComponent(action: TemplateActionType) {
const { componentId, position, desc, parentId, applicationId } = action.payload as {
componentId: string;
position: string;
desc: ComponentStructure;
parentId: string;
applicationId: string;
};
yield put(ACTIONS.pushComponentSource([desc.name]));
const state = store.getState().builder.template;
const version = state.version;
const versionType: string = state.versionType;
const renderStructure = state.renderStructure;
const registeredComponent = store.getState().builder.componentList.allComponent;
const componentParentId =
parentId === 'root-container'
? versionType === FileTypeEnum.page
? version.content.schemas[0].id
: undefined
: parentId;
const component = utils.newWrapperComponent(registeredComponent, desc.name, componentParentId);
yield put(
ACTIONS.saveComponent(applicationId, {
id: version.content.id,
parentId: componentParentId,
type: 'add',
content: component,
position:
position === 'before'
? utils.getPosition(componentId, renderStructure)
: utils.getPosition(componentId, renderStructure) + 1,
requireLoad: true,
}),
);
yield delay(300);
yield put(ACTIONS.setSelectedComponent(component.id));
}
function* publish(action: TemplateActionType) {
const { applicationId } = action.payload as { applicationId: string };
const {
global: { publishSuccess, publishFailed },
} = getBusinessI18n();
function* afterSave() {
const {
template: { version, versionType },
page: { contentId, fileType },
} = store.getState().builder;
const { id } = version;
yield put(ACTIONS.updatePublishLoading(true));
const rs = yield call(versionType === FileTypeEnum.page ? publishPage : publishTemplate, {
id,
applicationId,
status: VersionStatusEnum.release,
});
yield put(ACTIONS.updatePublishLoading(false));
if (rs.code === 200) {
message.success(publishSuccess);
yield put(ACTIONS.fetchPageRenderTree(applicationId, contentId, fileType));
} else {
message.error(rs.msg || publishFailed);
}
}
yield put(ACTIONS.saveToServer(applicationId, afterSave, true));
}
function* extendTemplate(action: TemplateActionType) {
const { contentId, successCb, applicationId } = action.payload as {
contentId: string;
successCb: () => void;
applicationId: string;
};
yield put(ACTIONS.pushLastSteps());
yield put(ACTIONS.clearNextSteps());
const state = store.getState().builder.template;
const { version, versionType } = state;
const { schemas = [{ id: undefined }] } = version.content || {};
const schemaId = schemas[0]?.id || generateId();
yield addVersionContent(
applicationId,
schemaId,
versionType === FileTypeEnum.page ? { width: '100%', height: '100%' } : {},
(_version) => {
successCb && successCb();
},
contentId,
);
}
function* deleteComponent(action: TemplateActionType) {
const { applicationId, componentId } = action.payload as { applicationId: string; componentId: string };
const state = store.getState().builder.template;
const { version, componentList, extensionData } = state;
const component = componentList.find((item: { id: string }) => item.id === componentId);
const baseNode =
extensionData.baseStructureRecord[componentId] ||
extensionData.baseStructureRecord[component?.extension?.extendId || ''];
// is the exist node
if (baseNode && component) {
yield put(
ACTIONS.saveComponent(applicationId, {
id: version.content.id,
parentId: component.parentId,
type: 'update',
content: {
...component,
name: BLANK_NODE,
},
requireLoad: false,
}),
);
} else {
yield put(
ACTIONS.saveComponent(applicationId, {
id: version.content.id,
type: 'delete',
content: {
id: componentId,
},
requireLoad: false,
}),
);
}
yield put(ACTIONS.setSelectedComponent());
}
function* rollbackComponent(action: TemplateActionType) {
const { applicationId, componentId } = action.payload as { applicationId: string; componentId: string };
const state = store.getState().builder.template;
const { version, componentList, extensionData } = state;
const component = componentList.find((item: { id: string }) => item.id === componentId);
const baseNode =
extensionData.baseStructureRecord[componentId] ||
extensionData.baseStructureRecord[component?.extension?.extendId || ''];
if (component) {
yield put(
ACTIONS.saveComponent(applicationId, {
id: version.content.id,
parentId: component.parentId,
type: 'update',
content: {
...baseNode,
id: component.id,
extension: component.extension,
},
requireLoad: true,
}),
);
}
}
function* copyComponent(action: TemplateActionType) {
const { applicationId, componentId } = action.payload as { applicationId: string; componentId: string };
const state = store.getState().builder.template;
const { version, componentList } = state;
const copyComponent = componentList.find((item: { id: string }) => item.id === componentId);
const id = generateId();
if (copyComponent) {
// remove the extendId
delete copyComponent.extension?.extendId;
yield put(
ACTIONS.saveComponent(applicationId, {
id: version.content.id,
parentId: copyComponent.parentId,
type: 'add',
content: {
...copyComponent,
id: id,
children: utils.generateCopyComponent(_.cloneDeep(copyComponent.children || []), id),
},
position: (copyComponent.position || 0) + 1,
requireLoad: false,
}),
);
}
}
function* saveEditor(action: TemplateActionType) {
const { applicationId, folderId, isWrapper } = action.payload as ComponentSaveParams;
const state = store.getState().builder.template;
const { version, mockVersion, selectedComponent, selectedWrapperComponent } = state;
const component = isWrapper ? selectedWrapperComponent : selectedComponent;
if (!component || !component.isUpdate) {
return;
}
yield put(ACTIONS.updateSelectedComponentUpdateStatus(isWrapper, false));
const { relation, variables, functions } = yield utils.searchVariableRelation({
applicationId,
folderId,
props: component.props || {},
oldRelation: version.content.relation,
});
if (relation) {
yield put(ACTIONS.updateContentRelation(utils.updateRelation(version.content.relation, relation)));
yield put(ACTIONS.updateVersionRelations({ variables, functions }));
}
// mock
const mockModeEnable = store.getState().builder.more.mockModeEnable;
if (mockModeEnable) {
const {
relation: mockRelation,
variables: mockVariables,
functions: mockFunctions,
} = yield utils.searchVariableRelation({
applicationId,
folderId,
props: component.mock || {},
oldRelation: mockVersion.content.relation,
});
if (mockRelation) {
yield put(
ACTIONS.updateContentRelation(
utils.updateRelation(mockVersion.content.relation, mockRelation),
'mock',
),
);
yield put(
ACTIONS.updateVersionRelations({ variables: mockVariables, functions: mockFunctions }, 'mock'),
);
}
}
yield put(
ACTIONS.saveComponent(
applicationId,
{
id: version.content.id,
parentId: component.parentId,
type: 'update',
content: {
children: isWrapper ? [state.selectedComponent] : component.children || [],
id: component.id,
label: component.label,
name: component.name,
parentId: component.parentId,
props: component.props || {},
mock: component.mock || {},
wrapper: component.wrapper,
directive: component.directive,
extension: component.extension,
},
requireLoad: false,
},
false,
),
);
}
function* saveToServer(action: TemplateActionType) {
const { applicationId, successCb, hideMessage = false } = action.payload as {
applicationId: string;
successCb: () => void;
hideMessage: boolean;
};
const state = store.getState().builder.template;
const { version, versionType, editStatus } = state;
if (!editStatus) {
if (typeof successCb === 'function') {
yield successCb();
}
return;
}
const {
global: { saveSuccess, saveFailed },
} = getBusinessI18n();
yield put(ACTIONS.updateSaveLoading(true));
yield delay(300);
const savedVersion = _.cloneDeep(version);
if (!savedVersion.content.relation) {
savedVersion.content.relation = {};
}
if (savedVersion.content.relation) {
for (const key in savedVersion.content.relation) {
delete savedVersion.content.relation[key].content;
}
}
const {
content: { schemas, relation },
} = savedVersion;
utils.deleteDslSource(schemas);
const errors = utils.getDslErrors(schemas, relation);
for (const componentId in errors) {
if (errors[componentId]?.length > 0) {
errors[componentId].forEach((value) => message.error(value));
yield put(ACTIONS.updateSaveLoading(false));
return;
}
}
const { extensionData } = store.getState().builder.template;
// deal position
positionInit(savedVersion.content, extensionData);
// deal with extend(inherit)
if (extensionData.baseContent) {
savedVersion.content = differ(extensionData, savedVersion.content);
}
// handle mock id
const { mockId } = store.getState().builder.more;
if (!!mockId) {
savedVersion.content.extension = Object.assign({}, savedVersion.content.extension, {
mockId,
});
}
const res = yield call(versionType === FileTypeEnum.page ? updatePageDsl : updateTemplateDsl, {
applicationId,
id: savedVersion.content.id,
content: savedVersion.content,
});
if (res.code === 200) {
!hideMessage && message.success(saveSuccess);
// if not, will not publish succeed
yield put(ACTIONS.updateVersion(res.data));
yield put(ACTIONS.updatePageEditStatus(false));
if (typeof successCb === 'function') {
yield successCb();
}
} else {
!hideMessage && message.error(res.msg || saveFailed);
}
yield put(ACTIONS.updateSaveLoading(false));
}
function* goLastStep(action: TemplateActionType) {
const { applicationId } = action.payload as PageParam;
yield put(ACTIONS.unShiftNextSteps());
yield put(ACTIONS.popLastSteps());
const state = store.getState().builder.template;
const { version, componentSourceMap, selectedComponentId } = state;
const desposalData = yield disposalData(applicationId, version, componentSourceMap);
console.log('goLastStep');
yield put(ACTIONS.pushTemplateData({ ...desposalData, version: version }));
yield put(ACTIONS.setSelectedComponent(selectedComponentId));
yield put(ACTIONS.updatePageEditStatus(true));
}
function* goNextStep(action: TemplateActionType) {
const { applicationId } = action.payload as PageParam;
yield put(ACTIONS.pushLastSteps());
yield put(ACTIONS.shiftNextSteps());
const state = store.getState().builder.template;
const { version, componentSourceMap, selectedComponentId } = state;
const desposalData = yield disposalData(applicationId, version, componentSourceMap);
console.log('goNextStep');
yield put(ACTIONS.pushTemplateData({ ...desposalData, version: version }));
yield put(ACTIONS.setSelectedComponent(selectedComponentId));
yield put(ACTIONS.updatePageEditStatus(true));
}
function* updateEditorValue(action: TemplateActionType) {
// todo variable select
const { key, value } = action.payload as { key: string; value: unknown };
yield put(ACTIONS.pushEditorValue(key, value, false));
}
/**
* update component condition
* @param actions actions
*/
function* updateComponentCondition(actions: TemplateActionType) {
const state = store.getState().builder;
const { conditions } = actions.payload as { conditions: ConditionItem[] };
const { selectedComponent, selectedWrapperComponent, version } = state.template;
const component = selectedComponent.wrapper ? selectedWrapperComponent : selectedComponent;
const { directive } = component;
const newDirective: ComponentDirectiveType = directive ? { ..._.cloneDeep(directive), if: [] } : { if: [] };
const newDirectiveIf = newDirective.if as string[];
const newRelation: RelationType = {};
const conditionRelations: ConditionContentItem[] = [];
let variableRelations: VariableContent[] = [];
let functionRelations: FuncContentItem[] = [];
conditions.forEach((condition) => {
const { content } = condition;
const { id } = content;
if (!id) {
return;
}
const relationKey = getConditionRelationKey(id);
const directiveIf = `{{${relationKey}}}`;
const exist = newDirectiveIf.find((item) => item === directiveIf);
if (!exist) {
newDirectiveIf.push(directiveIf);
}
conditionRelations.push(content);
if (condition.relations) {
const { variables = [], functions = [] } = condition.relations;
variableRelations = variableRelations.concat(variables);
functionRelations = functionRelations.concat(functions);
}
newRelation[relationKey] = { type: 'condition', content, id };
});
const { applicationId } = state.page;
yield put(
ACTIONS.saveComponent(
applicationId,
{
id: version.content.id,
parentId: component.parentId,
type: 'update',
content: {
children: component.children,
id: component.id,
label: component.label,
name: component.name,
parentId: component.parentId,
props: component.props || {},
wrapper: component.wrapper,
type: component.type,
directive: newDirective,
},
requireLoad: false,
},
false,
function* cb() {
yield put(ACTIONS.updateContentRelation(utils.updateRelation(version.content.relation, newRelation)));
yield put(
ACTIONS.updateVersionRelations({
conditions: conditionRelations,
variables: variableRelations,
functions: functionRelations,
}),
);
},
),
);
yield put(ACTIONS.pushEditorValue('directive', newDirective, selectedComponent.wrapper ? true : false));
yield put(updateConditionBindDrawerVisible(false));
}
function* pushComponentSource(action: TemplateActionType) {
const { names } = action.payload as { names: string[] };
const { allComponent } = store.getState().builder.componentList;
const newComponentSourceMap = {} as ComponentSourceMapType;
names.forEach((name) => {
const component = allComponent.find((item) => item.name === name);
if (component?.name) {
if (component) {
newComponentSourceMap[component.name] = component;
newComponentSourceMap[`${component.name}@${component.version}`] = component;
}
}
component?.components?.forEach((item) => {
if (item.name) {
newComponentSourceMap[item.name] = item;
newComponentSourceMap[`${item.name}@${item.version}`] = item;
}
});
});
yield put(ACTIONS.mergeComponentSourceMap(newComponentSourceMap));
}
function* handleClonePage(action: TemplateActionType) {
const params = action.payload as PageCloneParams;
const {
global: { cloneSuccess, cloneFailed },
} = getBusinessI18n();
const { onSuccess } = params;
yield put(ACTIONS.pushLastSteps());
yield put(ACTIONS.clearNextSteps());
const res = yield call(clonePage, params);
if (res.code === 200) {
message.success(cloneSuccess);
yield put(ACTIONS.updatePageEditStatus(false));
if (typeof onSuccess === 'function') {
yield onSuccess();
}
} else {
message.error(res.msg || cloneFailed);
}
}
function* handleClearResource(action: TemplateActionType) {
const { onSuccess } = action.payload as OptionsAction;
yield put(ACTIONS.clearComponentResource());
if (typeof onSuccess === 'function') {
onSuccess();
}
}
function* handleLocaleChange(action: TemplateActionType) {
const { applicationId } = action.payload as PageParam;
const state = store.getState().builder.template;
const { version, componentSourceMap, selectedComponentId } = state;
const desposalData = yield disposalData(applicationId, version, componentSourceMap);
yield put(ACTIONS.pushTemplateData({ ...desposalData, version: version }));
yield put(ACTIONS.setSelectedComponent(selectedComponentId));
// yield put(ACTIONS.updatePageEditStatus(true));
}
function* watch() {
yield takeLatest(getType(ACTIONS.fetchPageRenderTree), fetchPageRenderTree);
yield takeLatest(getType(ACTIONS.appendComponent), appendComponent);
yield takeLatest(getType(ACTIONS.insertComponent), insertComponent);
yield takeLatest(getType(ACTIONS.saveComponent), saveComponent);
yield takeLatest(getType(ACTIONS.publish), publish);
yield takeLatest(getType(ACTIONS.useTemplate), extendTemplate);
yield takeLatest(getType(ACTIONS.deleteComponent), deleteComponent);
yield takeLatest(getType(ACTIONS.rollbackComponent), rollbackComponent);
yield takeLatest(getType(ACTIONS.copyComponent), copyComponent);
yield takeLatest(getType(ACTIONS.saveComponentEditorValue), saveEditor);
yield takeLatest(getType(ACTIONS.saveToServer), saveToServer);
yield takeLatest(getType(ACTIONS.goLastStep), goLastStep);
yield takeLatest(getType(ACTIONS.goNextStep), goNextStep);
yield takeLatest(getType(ACTIONS.updateEditorValue), updateEditorValue);
yield takeLatest(getType(ACTIONS.updateComponentCondition), updateComponentCondition);
yield takeLatest(getType(ACTIONS.pushComponentSource), pushComponentSource);
yield takeLatest(getType(ACTIONS.clonePage), handleClonePage);
yield takeLatest(getType(ACTIONS.clearResource), handleClearResource);
yield takeLatest(getType(ACTIONS.localeChange), handleLocaleChange);
}
export default function* rootSaga() {
yield all([watch()]);
} | the_stack |
import Connection from '../../lib/twilio/connection';
import { PreflightTest } from '../../lib/twilio/preflight/preflight';
import { EventEmitter } from 'events';
import { SinonFakeTimers } from 'sinon';
import * as assert from 'assert';
import * as sinon from 'sinon';
import { inherits } from 'util';
import RTCSample from '../../lib/twilio/rtc/sample';
describe('PreflightTest', () => {
const CALL_SID = 'foo-bar';
let clock: SinonFakeTimers;
let connection: any;
let connectionContext: any;
let device: any;
let deviceFactory: any;
let deviceContext: any;
let rtcIceCandidateStatsReport: any;
let options: any;
let monitor: any;
let publisher: any;
let testSamples: any;
let edgeStub: any;
let wait: any;
const getDeviceFactory = (context: any) => {
const factory = function(this: any, token: string, options: PreflightTest.Options) {
Object.assign(this, context);
if (token) {
this.setup(token, options);
}
device = this;
};
inherits(factory, EventEmitter);
return factory;
};
const getTestSamples = () => {
const totalSampleCount = 15;
const samples = [];
let total = 0;
for (let i = 0; i < totalSampleCount; i++) {
const val = i+1;
total += val;
samples.push({
mos: val,
jitter: val,
rtt: val,
totals: {
foo: total
}
});
}
return samples;
};
beforeEach(() => {
clock = sinon.useFakeTimers();
wait = () => new Promise(r => {
setTimeout(r, 1);
clock.tick(1);
});
monitor = new EventEmitter();
monitor._thresholds = {
audioInputLevel: { maxDuration: 10 },
audioOutputLevel: { maxDuration: 10 }
};
publisher = new EventEmitter();
const outputs = new Map();
outputs.set('default', { audio: {} });
outputs.set('foo', { audio: {} });
connectionContext = {
_monitor: monitor,
mediaStream: {
callSid: CALL_SID,
version: { pc: {} },
onpcconnectionstatechange: sinon.stub(),
oniceconnectionstatechange: sinon.stub(),
ondtlstransportstatechange: sinon.stub(),
onsignalingstatechange: sinon.stub(),
outputs,
},
_publisher: publisher,
};
connection = new EventEmitter();
Object.assign(connection, connectionContext);
deviceContext = {
audio: {
disconnect: sinon.stub(),
outgoing: sinon.stub(),
},
setup: sinon.stub(),
connect: sinon.stub().returns(connection),
destroy: sinon.stub(),
disconnectAll: sinon.stub(),
region: sinon.stub().returns('foobar-region'),
edge: null,
};
edgeStub = sinon.stub().returns('foobar-edge');
sinon.stub(deviceContext, 'edge').get(edgeStub);
deviceFactory = getDeviceFactory(deviceContext);
rtcIceCandidateStatsReport = {
iceCandidateStats: ['foo', 'bar'],
selectedIceCandidatePairStats: {
localCandidate: { candidateType: 'host' },
remoteCandidate: { candidateType: 'host' },
}
};
options = {
deviceFactory,
getRTCIceCandidateStatsReport: () => Promise.resolve(rtcIceCandidateStatsReport),
};
testSamples = getTestSamples();
});
afterEach(() => {
clock.restore();
});
describe('constructor', () => {
it('should pass defaults to device', () => {
const preflight = new PreflightTest('foo', options);
sinon.assert.calledWith(deviceContext.setup, 'foo', {
codecPreferences: [Connection.Codec.PCMU, Connection.Codec.Opus],
debug: false,
edge: 'roaming',
fileInputStream: undefined,
iceServers: undefined,
preflight: true,
rtcConfiguration: undefined,
});
});
it('should pass codecPreferences to device', () => {
options.codecPreferences = [Connection.Codec.PCMU];
const preflight = new PreflightTest('foo', options);
sinon.assert.calledWith(deviceContext.setup, 'foo', {
codecPreferences: options.codecPreferences,
debug: false,
edge: 'roaming',
fileInputStream: undefined,
iceServers: undefined,
preflight: true,
rtcConfiguration: undefined,
});
});
it('should pass debug to device', () => {
options.debug = true;
const preflight = new PreflightTest('foo', options);
sinon.assert.calledWith(deviceContext.setup, 'foo', {
codecPreferences: [Connection.Codec.PCMU, Connection.Codec.Opus],
debug: true,
edge: 'roaming',
fileInputStream: undefined,
iceServers: undefined,
preflight: true,
rtcConfiguration: undefined,
});
});
it('should pass edge to device', () => {
options.edge = 'ashburn';
const preflight = new PreflightTest('foo', options);
sinon.assert.calledWith(deviceContext.setup, 'foo', {
codecPreferences: [Connection.Codec.PCMU, Connection.Codec.Opus],
debug: false,
edge: options.edge,
fileInputStream: undefined,
iceServers: undefined,
preflight: true,
rtcConfiguration: undefined,
});
sinon.assert.calledOnce(edgeStub);
});
it('should pass iceServers to device', () => {
options.iceServers = 'foo';
const preflight = new PreflightTest('foo', options);
sinon.assert.calledWith(deviceContext.setup, 'foo', {
codecPreferences: [Connection.Codec.PCMU, Connection.Codec.Opus],
debug: false,
edge: 'roaming',
fileInputStream: undefined,
iceServers: 'foo',
preflight: true,
rtcConfiguration: undefined,
});
});
it('should pass rtcConfiguration to device', () => {
options.rtcConfiguration = {foo: 'foo', iceServers: 'bar'};
const preflight = new PreflightTest('foo', options);
sinon.assert.calledWith(deviceContext.setup, 'foo', {
codecPreferences: [Connection.Codec.PCMU, Connection.Codec.Opus],
debug: false,
edge: 'roaming',
fileInputStream: undefined,
iceServers: undefined,
preflight: true,
rtcConfiguration: {foo: 'foo', iceServers: 'bar'},
});
});
});
describe('fakeMicInput', () => {
let preflight: PreflightTest;
let originalAudio: any;
let audioInstance: any;
let stream: any;
const root = global as any;
beforeEach(() => {
originalAudio = root.Audio;
stream = {
name: 'foo'
};
root.Audio = function() {
this.addEventListener = (name: string, handler: Function) => {
handler();
};
this.play = sinon.stub();
this.setAttribute = sinon.stub();
audioInstance = this;
};
options.audioContext = {
createMediaElementSource: () => ({connect: sinon.stub()}),
createMediaStreamDestination: () => ({stream}),
}
});
afterEach(() => {
root.Audio = originalAudio;
});
it('should throw if no AudioContext is found', () => {
options.audioContext = null;
assert.throws(() => { new PreflightTest('foo', {...options, fakeMicInput: true }) });
});
it('should set fakeMicInput to false by default', () => {
preflight = new PreflightTest('foo', options);
sinon.assert.calledWith(deviceContext.setup, 'foo', {
codecPreferences: [Connection.Codec.PCMU, Connection.Codec.Opus],
debug: false,
edge: 'roaming',
fileInputStream: undefined,
iceServers: undefined,
preflight: true,
rtcConfiguration: undefined,
});
});
it('should pass file input if fakeMicInput is true', () => {
preflight = new PreflightTest('foo', {...options, fakeMicInput: true });
return wait().then(() => {
sinon.assert.calledWith(deviceContext.setup, 'foo', {
codecPreferences: [Connection.Codec.PCMU, Connection.Codec.Opus],
debug: false,
edge: 'roaming',
fileInputStream: stream,
iceServers: undefined,
preflight: true,
rtcConfiguration: undefined,
});
});
});
it('should call play', () => {
preflight = new PreflightTest('foo', {...options, fakeMicInput: true });
sinon.assert.calledOnce(audioInstance.play);
});
it('should set cross origin', () => {
preflight = new PreflightTest('foo', {...options, fakeMicInput: true });
sinon.assert.calledOnce(audioInstance.setAttribute);
sinon.assert.calledWithExactly(audioInstance.setAttribute, 'crossorigin', 'anonymous');
});
it('should mute device sounds', () => {
preflight = new PreflightTest('foo', {...options, fakeMicInput: true });
return wait().then(() => {
device.emit('ready');
sinon.assert.calledOnce(deviceContext.audio.disconnect);
sinon.assert.calledOnce(deviceContext.audio.outgoing);
sinon.assert.calledWithExactly(deviceContext.audio.disconnect, false);
sinon.assert.calledWithExactly(deviceContext.audio.outgoing, false);
});
});
it('should end test after echo duration', () => {
preflight = new PreflightTest('foo', {...options, fakeMicInput: true });
return wait().then(() => {
device.emit('ready');
clock.tick(19000);
sinon.assert.notCalled(deviceContext.disconnectAll);
clock.tick(1000);
sinon.assert.calledOnce(deviceContext.disconnectAll);
});
});
it('should not start timer if fakeMicInput is false', () => {
preflight = new PreflightTest('foo', options);
return wait().then(() => {
device.emit('ready');
clock.tick(19000);
sinon.assert.notCalled(deviceContext.disconnectAll);
clock.tick(20000);
sinon.assert.notCalled(deviceContext.disconnectAll);
});
});
it('should clear echo timer on completed', () => {
preflight = new PreflightTest('foo', {...options, fakeMicInput: true });
device.emit('ready');
connection.emit('sample', testSamples[0]);
return wait().then(() => {
clock.tick(5000);
device.emit('disconnect');
clock.tick(1000);
device.emit('offline');
clock.tick(20000);
sinon.assert.notCalled(deviceContext.disconnectAll);
});
});
it('should clear echo timer on failed', () => {
preflight = new PreflightTest('foo', {...options, fakeMicInput: true });
return wait().then(() => {
device.emit('ready');
clock.tick(5000);
preflight.stop();
device.emit('offline');
clock.tick(20000);
sinon.assert.notCalled(deviceContext.disconnectAll);
});
});
it('should not mute media stream if fakeMicInput is false', () => {
preflight = new PreflightTest('foo', options);
return wait().then(() => {
device.emit('ready');
connection.emit('volume');
assert(!connectionContext.mediaStream.outputs.get('default').audio.muted);
assert(!connectionContext.mediaStream.outputs.get('foo').audio.muted);
});
});
it('should mute media stream if fakeMicInput is true', () => {
preflight = new PreflightTest('foo', {...options, fakeMicInput: true });
return wait().then(() => {
device.emit('ready');
connection.emit('volume');
assert(connectionContext.mediaStream.outputs.get('default').audio.muted);
assert(connectionContext.mediaStream.outputs.get('foo').audio.muted);
});
});
});
describe('on sample', () => {
it('should emit samples', async () => {
const onSample = sinon.stub();
const preflight = new PreflightTest('foo', options);
preflight.on('sample', onSample);
device.emit('ready');
const count = 10;
const sample = {foo: 'foo', bar: 'bar', mos: 1};
for (let i = 1; i <= count; i++) {
const data = {...sample, count: i};
connection.emit('sample', data);
await wait();
sinon.assert.callCount(onSample, i);
sinon.assert.calledWithExactly(onSample, data);
assert.deepEqual(preflight.latestSample, data)
}
});
});
describe('on warning', () => {
let preflight: PreflightTest;
beforeEach(() => {
preflight = new PreflightTest('foo', options);
});
it('should emit warning', () => {
const onWarning = sinon.stub();
preflight.on('warning', onWarning);
device.emit('ready');
const data = {foo: 'foo', bar: 'bar'};
connection.emit('warning', 'foo', data);
sinon.assert.calledOnce(onWarning);
sinon.assert.calledWithExactly(onWarning, {
description: 'Received an RTCWarning. See .rtcWarning for the RTCWarning',
name: 'foo',
rtcWarning: { bar: 'bar', foo: 'foo' },
});
});
it('should emit a warning the first time Insights fails to publish', () => {
const onWarning = sinon.stub();
preflight.on('warning', onWarning);
device.emit('ready');
publisher.emit('error');
sinon.assert.calledOnce(onWarning);
sinon.assert.calledWithExactly(onWarning, {
description: 'Received an error when attempting to connect to Insights gateway',
name: 'insights-connection-error',
});
publisher.emit('error');
sinon.assert.calledOnce(onWarning);
});
});
describe('on connected', () => {
it('should emit connected', () => {
const onConnected = sinon.stub();
const preflight = new PreflightTest('foo', options);
preflight.on('connected', onConnected);
device.emit('ready');
connection.emit('accept');
assert.equal(preflight.status, PreflightTest.Status.Connected);
sinon.assert.calledOnce(onConnected);
});
it('should populate callsid', () => {
const preflight = new PreflightTest('foo', options);
device.emit('ready');
connection.emit('accept');
assert.equal(preflight.callSid, CALL_SID);
});
it('should clear singaling timeout timer', () => {
const onFailed = sinon.stub();
const preflight = new PreflightTest('foo', options);
preflight.on('failed', onFailed);
device.emit('ready');
clock.tick(15000);
sinon.assert.notCalled(onFailed);
});
});
describe('on completed and destroy device', () => {
let preflight: PreflightTest;
beforeEach(() => {
preflight = new PreflightTest('foo', options);
preflight['_rtcIceCandidateStatsReport'] = rtcIceCandidateStatsReport;
});
it('should clear signaling timeout timer', () => {
const onFailed = sinon.stub();
preflight.on('failed', onFailed);
device.emit('ready');
clock.tick(5000);
device.emit('disconnect');
clock.tick(1000);
device.emit('offline');
clock.tick(15000);
sinon.assert.notCalled(onFailed);
});
it('should end call after device disconnects', () => {
const onCompleted = sinon.stub();
preflight.on('completed', onCompleted);
device.emit('ready');
clock.tick(14000);
device.emit('disconnect');
clock.tick(1000);
device.emit('offline');
clock.tick(10);
// endTime - startTime = duration. Should be equal to the total clock ticks
assert(preflight.endTime! - preflight.startTime === 15010);
sinon.assert.calledOnce(deviceContext.destroy);
sinon.assert.called(onCompleted);
});
it('should release all handlers', () => {
const onCompleted = sinon.stub();
preflight.on('completed', onCompleted);
device.emit('ready');
clock.tick(14000);
device.emit('disconnect');
clock.tick(1000);
device.emit('offline');
clock.tick(1000);
assert.equal(device.eventNames().length, 0);
assert.equal(connection.eventNames().length, 0);
});
it('should provide report', () => {
return new Promise(async (resolve) => {
clock.reset();
const warningData = {foo: 'foo', bar: 'bar'};
assert.equal(preflight.status, PreflightTest.Status.Connecting);
const onCompleted = (results: PreflightTest.Report) => {
// This is derived from testSamples
const expected = {
callSid: CALL_SID,
edge: 'foobar-edge',
iceCandidateStats: [ 'foo', 'bar' ],
isTurnRequired: false,
networkTiming: {
// pc, ice, and dtls starts after 15ms because of wait calls below.
// The duration are calculated base on the clock.ticks calls below.
// See "// Populate samples"
peerConnection: {
start: 15,
end: 1015,
duration: 1000,
},
dtls: {
start: 15,
end: 1015,
duration: 1000,
},
ice: {
start: 15,
end: 1015,
duration: 1000,
},
signaling: {
start: 0,
end: 1015,
duration: 1015,
}
},
samples: testSamples,
selectedEdge: 'roaming',
selectedIceCandidatePairStats: {
localCandidate: { candidateType: 'host' },
remoteCandidate: { candidateType: 'host' }
},
stats: {
jitter: {
average: 8,
max: 15,
min: 1
},
mos: {
average: 8,
max: 15,
min: 1
},
rtt: {
average: 8,
max: 15,
min: 1
}
},
testTiming: {
start: 0,
end: 15025,
duration: 15025
},
totals: testSamples[testSamples.length - 1].totals,
warnings: [{
description: 'Received an RTCWarning. See .rtcWarning for the RTCWarning',
name: 'foo',
rtcWarning: warningData,
}],
callQuality: 'excellent',
};
assert.equal(preflight.status, PreflightTest.Status.Completed);
assert.deepEqual(results, expected);
assert.deepEqual(preflight.report, expected);
resolve();
};
preflight.on('completed', onCompleted);
device.emit('ready');
// Populate samples
for (let i = 0; i < testSamples.length; i++) {
const sample = testSamples[i];
const data = {...sample};
connection.emit('sample', data);
await wait();
}
// Populate warnings
connection.emit('warning', 'foo', warningData);
// Populate callsid
connection.emit('accept');
// Populate network timings
connection.mediaStream.onpcconnectionstatechange('connecting');
connection.mediaStream.ondtlstransportstatechange('connecting');
connection.mediaStream.oniceconnectionstatechange('checking');
clock.tick(1000);
connection.mediaStream.onpcconnectionstatechange('connected');
connection.mediaStream.ondtlstransportstatechange('connected');
connection.mediaStream.oniceconnectionstatechange('connected');
connection.mediaStream.onsignalingstatechange('stable');
clock.tick(13000);
device.emit('disconnect');
clock.tick(1000);
device.emit('offline');
clock.tick(1000);
});
});
describe('call quality', () => {
it('should not include callQuality if stats are missing', (done) => {
const onCompleted = (results: PreflightTest.Report) => {
assert(!results.callQuality);
done();
};
preflight.on('completed', onCompleted);
device.emit('ready');
clock.tick(13000);
device.emit('disconnect');
clock.tick(1000);
device.emit('offline');
clock.tick(1000);
});
// Test data for different mos and expected quality
[
[4.900, PreflightTest.CallQuality.Excellent],
[4.300, PreflightTest.CallQuality.Excellent],
[4.200, PreflightTest.CallQuality.Great],
[4.100, PreflightTest.CallQuality.Great],
[4.000, PreflightTest.CallQuality.Good],
[3.900, PreflightTest.CallQuality.Good],
[3.800, PreflightTest.CallQuality.Good],
[3.700, PreflightTest.CallQuality.Good],
[3.600, PreflightTest.CallQuality.Fair],
[3.500, PreflightTest.CallQuality.Fair],
[3.200, PreflightTest.CallQuality.Fair],
[3.100, PreflightTest.CallQuality.Fair],
[3.000, PreflightTest.CallQuality.Degraded],
[2.900, PreflightTest.CallQuality.Degraded],
].forEach(([averageMos, callQuality]) => {
it(`should report quality as ${callQuality} if average mos is ${averageMos}`, () => {
return new Promise(async (resolve) => {
const onCompleted = (results: PreflightTest.Report) => {
assert.equal(results.callQuality, callQuality);
resolve();
};
preflight.on('completed', onCompleted);
device.emit('ready');
for (let i = 0; i < 10; i++) {
connection.emit('sample', {
rtt: 1,
jitter: 1,
mos: averageMos,
});
await wait();
}
clock.tick(13000);
device.emit('disconnect');
clock.tick(1000);
device.emit('offline');
clock.tick(1000);
});
});
})
});
describe('ice candidates', () => {
const passPreflight = async () => {
device.emit('ready');
connection.emit('sample', testSamples[0]);
await wait();
clock.tick(25000);
device.emit('disconnect');
clock.tick(1000);
device.emit('offline');
clock.tick(1000);
};
let candidateInfo: any;
beforeEach(() => {
candidateInfo = {
iceCandidateStats: ['foo', 'bar'],
selectedIceCandidatePairStats: {
localCandidate: { candidateType: 'host' },
remoteCandidate: { candidateType: 'host' },
}
};
});
it('should not include selectedIceCandidatePairStats if no candidates are selected', () => {
candidateInfo.selectedIceCandidatePairStats = undefined;
preflight = new PreflightTest('foo', {
...options,
getRTCIceCandidateStatsReport: () => Promise.resolve(candidateInfo),
});
return new Promise(async (resolve) => {
const onCompleted = (results: PreflightTest.Report) => {
assert.deepEqual(results.iceCandidateStats, ['foo', 'bar']);
assert(!results.selectedIceCandidatePairStats);
resolve();
};
preflight.on('completed', onCompleted);
passPreflight();
});
});
it('should not include isTurnRequired if no candidates are selected', () => {
candidateInfo.selectedIceCandidatePairStats = undefined;
preflight = new PreflightTest('foo', {
...options,
getRTCIceCandidateStatsReport: () => Promise.resolve(candidateInfo),
});
return new Promise(async (resolve) => {
const onCompleted = (results: PreflightTest.Report) => {
assert(typeof results.isTurnRequired === 'undefined');
resolve();
};
preflight.on('completed', onCompleted);
passPreflight();
});
});
it('should provide selectedIceCandidatePairStats and iceCandidateStats in the report', () => {
preflight = new PreflightTest('foo', {
...options,
getRTCIceCandidateStatsReport: () => Promise.resolve(candidateInfo),
});
return new Promise(async (resolve) => {
const onCompleted = (results: PreflightTest.Report) => {
assert.deepEqual(results.iceCandidateStats, ['foo', 'bar']);
assert.deepEqual(results.selectedIceCandidatePairStats, {
localCandidate: { candidateType: 'host' },
remoteCandidate: { candidateType: 'host' },
});
resolve();
};
preflight.on('completed', onCompleted);
passPreflight();
});
});
[
['relay', 'relay', true],
['relay', 'host', true],
['host', 'relay', true],
['host', 'host', false],
].forEach(([remoteCandidateType, localCandidateType, isTurnRequired]) => {
it(`should set isTurnRequired to ${isTurnRequired} if remote candidate is a ${remoteCandidateType} and local candidate is ${localCandidateType}`, () => {
candidateInfo.selectedIceCandidatePairStats.remoteCandidate.candidateType = remoteCandidateType;
candidateInfo.selectedIceCandidatePairStats.localCandidate.candidateType = localCandidateType;
preflight = new PreflightTest('foo', {
...options,
getRTCIceCandidateStatsReport: () => Promise.resolve(candidateInfo),
});
return new Promise(async (resolve) => {
const onCompleted = (results: PreflightTest.Report) => {
assert.equal(results.isTurnRequired, isTurnRequired);
resolve();
};
preflight.on('completed', onCompleted);
passPreflight();
});
});
});
});
});
describe('on failed', () => {
it('should clear signaling timeout timer', () => {
const onFailed = sinon.stub();
const preflight = new PreflightTest('foo', options);
preflight.on('failed', onFailed);
device.emit('ready');
clock.tick(5000);
preflight.stop();
device.emit('offline');
clock.tick(15000);
sinon.assert.calledOnce(onFailed);
});
it('should timeout after 10s by default', () => {
const onFailed = sinon.stub();
const preflight = new PreflightTest('foo', options);
preflight.on('failed', onFailed);
clock.tick(9999);
sinon.assert.notCalled(onFailed);
clock.tick(1);
sinon.assert.calledOnce(onFailed);
sinon.assert.calledWithExactly(onFailed, { code: 31901, message: "WebSocket - Connection Timeout" });
});
it('should use timeout param', () => {
const onFailed = sinon.stub();
const preflight = new PreflightTest('foo', Object.assign({ signalingTimeoutMs: 3000 }, options));
preflight.on('failed', onFailed);
clock.tick(2999);
sinon.assert.notCalled(onFailed);
clock.tick(1);
sinon.assert.calledOnce(onFailed);
sinon.assert.calledWithExactly(onFailed, { code: 31901, message: "WebSocket - Connection Timeout" });
});
it('should emit failed if Device failed to initialized', () => {
deviceContext.setup = () => {
throw 'foo';
};
const onFailed = sinon.stub();
const preflight = new PreflightTest('foo', options);
preflight.on('failed', onFailed);
clock.tick(1);
assert.equal(preflight.status, PreflightTest.Status.Failed);
sinon.assert.calledOnce(onFailed);
sinon.assert.calledWithExactly(onFailed, 'foo');
});
it('should emit failed when test is stopped and destroy device', () => {
const onFailed = sinon.stub();
const preflight = new PreflightTest('foo', options);
preflight.on('failed', onFailed);
device.emit('ready');
preflight.stop();
device.emit('offline');
clock.tick(1000);
assert.equal(preflight.status, PreflightTest.Status.Failed);
sinon.assert.calledOnce(deviceContext.destroy);
sinon.assert.calledOnce(onFailed);
sinon.assert.calledWithExactly(onFailed, {
code: 31008,
message: 'Call cancelled',
});
});
it(`should emit failed on fatal device errors and destroy device`, () => {
const onFailed = sinon.stub();
const preflight = new PreflightTest('foo', options);
preflight.on('failed', onFailed);
device.emit('ready');
device.emit('error', { code: 123 });
assert.equal(preflight.status, PreflightTest.Status.Failed);
sinon.assert.calledOnce(deviceContext.destroy);
sinon.assert.calledOnce(onFailed);
sinon.assert.calledWithExactly(onFailed, { code: 123 });
});
it('should listen to device error once', () => {
const onFailed = sinon.stub();
const preflight = new PreflightTest('foo', options);
preflight.on('failed', onFailed);
// Remove cleanup routine to test we are only subscribing once
preflight['_releaseHandlers'] = sinon.stub();
// Add stub listener so device won't crash if there are no error handlers
// This is a default behavior of an EventEmitter
device.on('error', sinon.stub());
// Triggers the test
device.emit('ready');
device.emit('error', { code: 123 });
device.emit('error', { code: 123 });
assert.equal(preflight.status, PreflightTest.Status.Failed);
sinon.assert.calledOnce(deviceContext.destroy);
sinon.assert.calledOnce(onFailed);
sinon.assert.calledWithExactly(onFailed, { code: 123 });
});
it('should stop test', () => {
const onCompleted = sinon.stub();
const preflight = new PreflightTest('foo', options);
preflight.on('completed', onCompleted);
device.emit('ready');
clock.tick(5000);
preflight.stop();
device.emit('offline');
clock.tick(15000);
device.emit('offline');
clock.tick(1000);
assert.equal(preflight.status, PreflightTest.Status.Failed);
sinon.assert.notCalled(onCompleted);
});
it('should release all handlers', () => {
const preflight = new PreflightTest('foo', options);
device.emit('ready');
preflight.stop();
device.emit('offline');
clock.tick(1000);
assert.equal(device.eventNames().length, 0);
assert.equal(connection.eventNames().length, 0);
});
it('should not emit completed event', () => {
const onCompleted = sinon.stub();
const onFailed = sinon.stub();
const preflight = new PreflightTest('foo', options);
preflight.on(PreflightTest.Events.Completed, onCompleted);
preflight.on(PreflightTest.Events.Failed, onFailed);
device.emit('ready');
clock.tick(1000);
device.emit('disconnect');
clock.tick(1000);
device.emit('offline');
clock.tick(1);
device.emit('error', { code: 123 });
clock.tick(1000);
return wait().then(() => {
sinon.assert.notCalled(onCompleted);
sinon.assert.calledOnce(onFailed);
});
});
});
describe('_getRTCStats', () => {
describe('should trim leading null mos valued samples', () => {
const createSample = ({
jitter,
mos,
rtt,
}: {
jitter: any,
mos: any,
rtt: any,
}): RTCSample => ({
audioInputLevel: 0,
audioOutputLevel: 0,
bytesReceived: 0,
bytesSent: 0,
codecName: 'foobar-codec',
jitter,
mos,
packetsLost: 0,
packetsLostFraction: 0,
packetsReceived: 0,
packetsSent: 0,
rtt,
timestamp: 0,
totals: {
bytesReceived: 0,
bytesSent: 0,
packetsLost: 0,
packetsLostFraction: 0,
packetsReceived: 0,
packetsSent: 0,
},
});
it('should return an object if there are mos samples', async () => {
const preflight = new PreflightTest('foo', options);
device.emit('ready');
[{
jitter: 100, mos: null, rtt: 1,
}, {
jitter: 0, mos: null, rtt: 0,
}, {
jitter: 0, mos: null, rtt: 0,
}, {
jitter: 1, mos: 5, rtt: 0.01,
}, {
jitter: 2, mos: 4, rtt: 0.03,
}, {
jitter: 3, mos: 3, rtt: 0.02,
}].map(createSample).forEach(
(sample: RTCSample) => connection.emit('sample', sample),
);
await wait();
const rtcStats = preflight['_getRTCStats']();
assert.deepEqual(rtcStats, {
jitter: {
average: 2,
max: 3,
min: 1,
},
mos: {
average: 4,
max: 5,
min: 3,
},
rtt: {
average: 0.02,
max: 0.03,
min: 0.01,
},
});
});
it('should return undefined if there are no mos samples', async () => {
const preflight = new PreflightTest('foo', options);
device.emit('ready');
[{
jitter: 100, mos: null, rtt: 1,
}, {
jitter: 0, mos: null, rtt: 0,
}, {
jitter: 0, mos: null, rtt: 0,
}].map(createSample).forEach(
(sample: RTCSample) => connection.emit('sample', sample),
);
await wait();
const rtcStats = preflight['_getRTCStats']();
assert.equal(rtcStats, undefined);
});
});
});
}); | the_stack |
import { FeatureStore } from '../feature-store';
import { catchError, mergeMap, tap } from 'rxjs/operators';
import { EMPTY, Observable, of } from 'rxjs';
import { createFeatureSelector, createSelector } from '../selector';
import { cold, hot } from 'jest-marbles';
import { actions$, createFeatureStore } from '../store';
import StoreCore from '../store-core';
import { counterInitialState, counterReducer, CounterState, store } from './_spec-helpers';
import { Action, Reducer } from '../models';
interface UserState {
firstName: string;
lastName: string;
city: string;
country: string;
err: string;
}
const initialState: UserState = {
firstName: 'Bruce',
lastName: 'Willis',
city: 'LA',
country: 'United States',
err: undefined,
};
const asyncUser: UserState = {
firstName: 'Steven',
lastName: 'Seagal',
city: 'LA',
country: 'United States',
err: '',
};
function fakeApiGet(): Observable<UserState> {
return cold('---a', { a: asyncUser });
}
function fakeApiWithError(): Observable<UserState> {
return cold('-#');
}
const getUserFeatureState = createFeatureSelector<UserState>('user2'); // Select From App State
const getCity = createSelector(getUserFeatureState, (state) => state.city);
const getUserFeatureState2 = createFeatureSelector<UserState>(); // Select directly from Feature State by omitting the Feature name
const getCountry = createSelector(getUserFeatureState2, (state) => state.country);
store.feature<CounterState>('someFeature', counterReducer);
const getSomeFeatureSelector = createFeatureSelector<CounterState>('someFeature');
class UserFeatureStore extends FeatureStore<UserState> {
firstName$ = this.select((state) => state.firstName);
lastName$ = this.select((state) => state.lastName);
country$ = this.select(getCountry);
city$ = store.select(getCity);
someFeatureState$ = store.select(getSomeFeatureSelector);
loadFn = this.effect((payload$) =>
payload$.pipe(mergeMap(() => fakeApiGet().pipe(tap((user) => this.setState(user)))))
);
loadFnWithError = this.effect((payload$) =>
payload$.pipe(
mergeMap(() =>
fakeApiWithError().pipe(
tap((user) => this.setState(user)),
catchError((err) => {
this.setState({ err: 'error' });
return EMPTY;
})
)
)
)
);
constructor() {
super('user2', initialState);
}
updateFirstName(firstName) {
this.setState({ firstName });
}
updateLastName(lastName) {
this.setState({ lastName });
}
updateCity(city) {
this.setState({ city }, 'updateCity');
}
updateCountry(country) {
this.setState({
...this.state, // Test updating state using `this.state`
country,
});
}
resetState() {
this.setState(initialState);
}
}
class CounterFeature extends FeatureStore<CounterState> {
counter$: Observable<number> = this.select((state) => state.counter);
constructor() {
super('counterFeature', { counter: 0 });
}
increment() {
// Update state using callback
this.setState((state) => ({ counter: state.counter + 1 }));
}
}
class CounterFeature2 extends FeatureStore<any> {
constructor() {
super('counterFeature2', {});
}
}
const userFeature: UserFeatureStore = new UserFeatureStore();
const counterFeature: CounterFeature = new CounterFeature();
describe('FeatureStore', () => {
const reducerSpy = jest.fn();
function someReducer() {
reducerSpy();
}
store.feature('someReduxReducer', someReducer);
it('should initialize the feature', () => {
const spy = jest.fn();
userFeature.select().subscribe(spy);
expect(spy).toHaveBeenCalledWith(initialState);
expect(spy).toHaveBeenCalledTimes(1);
});
it('should expose the feature key', () => {
expect(userFeature.featureKey).toBe('user2');
});
it('should update state', () => {
userFeature.updateFirstName('Nicolas');
const spy = jest.fn();
userFeature.firstName$.subscribe(spy);
expect(spy).toHaveBeenCalledWith('Nicolas');
expect(spy).toHaveBeenCalledTimes(1);
spy.mockReset();
userFeature.updateLastName('Cage');
userFeature.lastName$.subscribe(spy);
expect(spy).toHaveBeenCalledWith('Cage');
expect(spy).toHaveBeenCalledTimes(1);
spy.mockReset();
userFeature.updateCountry('Belgium'); // Test updating state using `this.state`
userFeature.country$.subscribe(spy);
expect(spy).toHaveBeenCalledWith('Belgium');
expect(spy).toHaveBeenCalledTimes(1);
userFeature.resetState();
});
it('should update state using callback', () => {
const spy = jest.fn();
counterFeature.counter$.subscribe(spy);
expect(spy).toHaveBeenCalledWith(0);
expect(spy).toHaveBeenCalledTimes(1);
counterFeature.increment();
expect(spy).toHaveBeenCalledWith(1);
expect(spy).toHaveBeenCalledTimes(2);
});
it('should select state from App State', () => {
const spy = jest.fn();
userFeature.city$.subscribe(spy);
expect(spy).toHaveBeenCalledWith('LA');
expect(spy).toHaveBeenCalledTimes(1);
});
it('should select state from Feature State', () => {
const spy = jest.fn();
userFeature.country$.subscribe(spy);
expect(spy).toHaveBeenCalledWith('United States');
expect(spy).toHaveBeenCalledTimes(1);
});
it('should select state from another Feature (created with Store.feature)', () => {
const spy = jest.fn();
userFeature.someFeatureState$.subscribe(spy);
expect(spy).toHaveBeenCalledWith(counterInitialState);
expect(spy).toHaveBeenCalledTimes(1);
});
it('should create and execute an effect', () => {
userFeature.loadFn();
expect(userFeature.firstName$).toBeObservable(hot('a--b', { a: 'Bruce', b: 'Steven' }));
});
it('should create and execute an effect and handle error', () => {
userFeature.resetState();
userFeature.loadFnWithError();
expect(userFeature.select()).toBeObservable(
hot('ab', { a: initialState, b: { ...initialState, err: 'error' } })
);
});
it('should resubscribe the effect 10 times (if side effect error is not handled)', () => {
const spy = jest.fn();
console.error = jest.fn();
function apiCallWithError() {
spy();
throw new Error();
return of('someValue');
}
const fs: FeatureStore<any> = createFeatureStore('fsWithFailingApi', {});
const load = fs.effect(mergeMap(() => apiCallWithError().pipe(tap(() => fs.setState({})))));
load();
load();
load();
load();
load();
load();
load();
load();
load();
load();
load();
load(); // #12 will not trigger the Api call anymore
load(); // #13 will not trigger the Api call anymore
expect(spy).toHaveBeenCalledTimes(11); // Api call is performed 11 Times. First time + 10 re-subscriptions
function getErrorMsg(times) {
return `MiniRx resubscribed the Effect. ONLY ${times} time(s) remaining!`;
}
expect(console.error).toHaveBeenCalledWith(
expect.stringContaining(getErrorMsg(9)),
expect.any(Error)
);
expect(console.error).toHaveBeenCalledWith(
expect.stringContaining(getErrorMsg(8)),
expect.any(Error)
);
expect(console.error).toHaveBeenCalledWith(
expect.stringContaining(getErrorMsg(7)),
expect.any(Error)
);
expect(console.error).toHaveBeenCalledWith(
expect.stringContaining(getErrorMsg(6)),
expect.any(Error)
);
expect(console.error).toHaveBeenCalledWith(
expect.stringContaining(getErrorMsg(5)),
expect.any(Error)
);
expect(console.error).toHaveBeenCalledWith(
expect.stringContaining(getErrorMsg(4)),
expect.any(Error)
);
expect(console.error).toHaveBeenCalledWith(
expect.stringContaining(getErrorMsg(3)),
expect.any(Error)
);
expect(console.error).toHaveBeenCalledWith(
expect.stringContaining(getErrorMsg(2)),
expect.any(Error)
);
expect(console.error).toHaveBeenCalledWith(
expect.stringContaining(getErrorMsg(1)),
expect.any(Error)
);
expect(console.error).toHaveBeenCalledWith(
expect.stringContaining(getErrorMsg(0)),
expect.any(Error)
);
expect(console.error).toHaveBeenCalledTimes(10); // Re-subscription with error logging stopped after 10 times
});
it('should dispatch a set-state default action', () => {
userFeature.resetState();
const spy = jest.fn();
actions$.subscribe(spy);
userFeature.updateCity('NY');
expect(spy).toHaveBeenCalledWith({
type: '@mini-rx/user2/set-state/updateCity',
payload: { city: 'NY' },
});
});
it('should run the meta reducers when state changes', () => {
const metaReducerSpy = jest.fn();
function metaReducer(reducer): Reducer<any> {
return (state, action: Action) => {
metaReducerSpy();
return reducer(state, action);
};
}
StoreCore.addMetaReducers(metaReducer);
userFeature.updateCity('NY');
counterFeature.increment();
expect(metaReducerSpy).toHaveBeenCalledTimes(2);
});
it('should create a Feature Store with functional creation methods', () => {
const fs: FeatureStore<CounterState> = createFeatureStore<CounterState>(
'funcFeatureStore',
counterInitialState
);
const getFeatureState = createFeatureSelector<CounterState>();
const getCounter = createSelector(getFeatureState, (state) => state.counter);
const counter$: Observable<number> = fs.select(getCounter);
function inc() {
fs.setState((state) => ({
counter: state.counter + 1,
}));
}
const spy = jest.fn();
counter$.subscribe(spy);
expect(spy).toHaveBeenCalledWith(1);
inc();
expect(spy).toHaveBeenCalledWith(2);
});
it('should remove the feature state when Feature Store is destroyed', () => {
const fs: FeatureStore<CounterState> = createFeatureStore<CounterState>(
'tempFsState',
counterInitialState
);
const spy = jest.fn();
store.select((state) => state).subscribe(spy);
expect(spy).toHaveBeenCalledWith(
expect.objectContaining({ tempFsState: counterInitialState })
);
fs.destroy();
expect(spy).toHaveBeenCalledWith(
expect.not.objectContaining({ tempCounter: counterInitialState })
);
});
it('should call FeatureStore.destroy when Angular ngOnDestroy is called', () => {
const fs: FeatureStore<CounterState> = createFeatureStore<CounterState>(
'tempFsState',
counterInitialState
);
const spy = jest.spyOn(fs, 'destroy');
fs.ngOnDestroy();
expect(spy).toHaveBeenCalled();
});
}); | the_stack |
import 'chrome://webui-test/mojo_webui_test_support.js';
import {keyDownOn} from 'chrome://resources/polymer/v3_0/iron-test-helpers/mock-interactions.js';
import {ProfileData, RecentlyClosedTab, Tab, TabAlertState, TabGroupColor, TabSearchApiProxyImpl, TabSearchAppElement, TabSearchItem} from 'chrome://tab-search.top-chrome/tab_search.js';
import {assertEquals, assertFalse, assertNotEquals, assertTrue} from 'chrome://webui-test/chai_assert.js';
import {flushTasks, waitAfterNextRender} from 'chrome://webui-test/test_util.js';
import {createProfileData, createTab, generateSampleDataFromSiteNames, generateSampleRecentlyClosedTabs, generateSampleRecentlyClosedTabsFromSiteNames, generateSampleTabsFromSiteNames, SAMPLE_RECENTLY_CLOSED_DATA, SAMPLE_WINDOW_DATA, SAMPLE_WINDOW_DATA_WITH_MEDIA_TAB, SAMPLE_WINDOW_HEIGHT, sampleToken} from './tab_search_test_data.js';
import {initLoadTimeDataWithDefaults} from './tab_search_test_helper.js';
import {TestTabSearchApiProxy} from './test_tab_search_api_proxy.js';
suite('TabSearchAppTest', () => {
let tabSearchApp: TabSearchAppElement;
let testProxy: TestTabSearchApiProxy;
function verifyTabIds(rows: NodeListOf<HTMLElement>, ids: number[]) {
assertEquals(ids.length, rows.length);
rows.forEach((row, index) => {
assertEquals(ids[index]!.toString(), row.getAttribute('id'));
});
}
function queryRows(): NodeListOf<HTMLElement> {
return tabSearchApp.$.tabsList.querySelectorAll(
'tab-search-item, tab-search-group-item');
}
function queryListTitle(): NodeListOf<HTMLElement> {
return tabSearchApp.$.tabsList.querySelectorAll('.list-section-title');
}
/**
* @param sampleData A mock data object containing relevant profile data for
* the test.
*/
async function setupTest(
sampleData: ProfileData,
loadTimeOverriddenData?: {[key: string]: number|string|boolean}) {
initLoadTimeDataWithDefaults(loadTimeOverriddenData);
testProxy = new TestTabSearchApiProxy();
testProxy.setProfileData(sampleData);
TabSearchApiProxyImpl.setInstance(testProxy);
tabSearchApp = document.createElement('tab-search-app');
document.body.innerHTML = '';
document.body.appendChild(tabSearchApp);
await flushTasks();
}
test('return all tabs', async () => {
await setupTest(createProfileData());
verifyTabIds(queryRows(), [1, 5, 6, 2, 3, 4]);
});
test('recently closed tab groups and tabs', async () => {
const sampleSessionId = 101;
const sampleTabCount = 5;
await setupTest(
{
windows: [{
active: true,
height: SAMPLE_WINDOW_HEIGHT,
tabs: generateSampleTabsFromSiteNames(['OpenTab1'], true),
}],
recentlyClosedTabs: generateSampleRecentlyClosedTabs(
'Sample Tab', sampleTabCount, sampleToken(0n, 1n)),
tabGroups: [],
recentlyClosedTabGroups: [{
sessionId: sampleSessionId,
id: sampleToken(0n, 1n),
color: 1,
title: 'Reading List',
tabCount: sampleTabCount,
lastActiveTime: {internalValue: BigInt(sampleTabCount + 1)},
lastActiveElapsedText: ''
}],
recentlyClosedSectionExpanded: true,
},
{
recentlyClosedDefaultItemDisplayCount: 5,
});
tabSearchApp.$.tabsList.ensureAllDomItemsAvailable();
// Assert the recently closed tab group is included in the recently closed
// items section and that the recently closed tabs belonging to it are
// filtered from the recently closed items section by default.
assertEquals(2, queryRows().length);
});
test('return all open and recently closed tabs', async () => {
await setupTest(createProfileData({
recentlyClosedTabs: SAMPLE_RECENTLY_CLOSED_DATA,
recentlyClosedSectionExpanded: true,
}));
tabSearchApp.$.tabsList.ensureAllDomItemsAvailable();
assertEquals(8, queryRows().length);
});
test('Limit recently closed tabs to the default display count', async () => {
await setupTest(
createProfileData({
windows: [{
active: true,
height: SAMPLE_WINDOW_HEIGHT,
tabs: generateSampleTabsFromSiteNames(['OpenTab1'], true),
}],
recentlyClosedTabs: generateSampleRecentlyClosedTabsFromSiteNames(
['RecentlyClosedTab1', 'RecentlyClosedTab2']),
recentlyClosedSectionExpanded: true
}),
{
recentlyClosedDefaultItemDisplayCount: 1,
});
assertEquals(2, queryRows().length);
});
test('Default tab selection when data is present', async () => {
await setupTest(createProfileData());
assertNotEquals(
-1, tabSearchApp.getSelectedIndex(),
'No default selection in the presence of data');
});
test('Search text changes tab items', async () => {
await setupTest(createProfileData({
recentlyClosedTabs: SAMPLE_RECENTLY_CLOSED_DATA,
recentlyClosedSectionExpanded: true,
}));
const searchField = tabSearchApp.$.searchField;
searchField.setValue('bing');
await flushTasks();
verifyTabIds(queryRows(), [2]);
assertEquals(0, tabSearchApp.getSelectedIndex());
searchField.setValue('paypal');
await flushTasks();
verifyTabIds(queryRows(), [100]);
assertEquals(0, tabSearchApp.getSelectedIndex());
});
test('Search text changes recently closed tab items', async () => {
const sampleSessionId = 101;
const sampleTabCount = 5;
await setupTest(
createProfileData({
windows: [{
active: true,
height: SAMPLE_WINDOW_HEIGHT,
tabs: generateSampleTabsFromSiteNames(['Open sample tab'], true),
}],
recentlyClosedTabs: generateSampleRecentlyClosedTabs(
'Sample Tab', sampleTabCount, sampleToken(0n, 1n)),
recentlyClosedTabGroups: [({
sessionId: sampleSessionId,
id: sampleToken(0n, 1n),
color: 1,
title: 'Reading List',
tabCount: sampleTabCount,
lastActiveTime: {internalValue: BigInt(sampleTabCount + 1)},
lastActiveElapsedText: ''
})],
recentlyClosedSectionExpanded: true,
}),
{
recentlyClosedDefaultItemDisplayCount: 5,
});
const searchField = tabSearchApp.$.searchField;
searchField.setValue('sample');
await flushTasks();
// Assert that the recently closed items associated to a recently closed
// group as well as the open tabs are rendered when applying a search
// criteria matching their titles.
assertEquals(6, queryRows().length);
});
test('No tab selected when there are no search matches', async () => {
await setupTest(createProfileData());
const searchField = tabSearchApp.$.searchField;
searchField.setValue('Twitter');
await flushTasks();
assertEquals(0, queryRows().length);
assertEquals(-1, tabSearchApp.getSelectedIndex());
});
test('Click on tab item triggers actions', async () => {
const tabData = createTab({
title: 'Google',
url: {url: 'https://www.google.com'},
lastActiveTimeTicks: {internalValue: BigInt(4)},
});
await setupTest(createProfileData({
windows: [{active: true, height: SAMPLE_WINDOW_HEIGHT, tabs: [tabData]}],
}));
const tabSearchItem =
tabSearchApp.$.tabsList.querySelector('tab-search-item')!;
tabSearchItem.click();
const [tabInfo] = await testProxy.whenCalled('switchToTab');
assertEquals(tabData.tabId, tabInfo.tabId);
const tabSearchItemCloseButton =
tabSearchItem.shadowRoot!.querySelector('cr-icon-button')!;
tabSearchItemCloseButton.click();
const [tabId, withSearch, closedTabIndex] =
await testProxy.whenCalled('closeTab');
assertEquals(tabData.tabId, tabId);
assertFalse(withSearch);
assertEquals(0, closedTabIndex);
});
test('Click on recently closed tab item triggers action', async () => {
const tabData: RecentlyClosedTab = {
tabId: 100,
title: 'PayPal',
url: {url: 'https://www.paypal.com'},
lastActiveElapsedText: '',
groupId: undefined,
lastActiveTime: {internalValue: BigInt(11)},
};
await setupTest(createProfileData({
windows: [{
active: true,
height: SAMPLE_WINDOW_HEIGHT,
tabs: [createTab({
title: 'Google',
url: {url: 'https://www.google.com'},
lastActiveTimeTicks: {internalValue: BigInt(4)},
})]
}],
recentlyClosedTabs: [tabData],
recentlyClosedSectionExpanded: true
}));
let tabSearchItem = tabSearchApp.$.tabsList.querySelector<HTMLElement>(
'tab-search-item[id="100"]')!;
tabSearchItem.click();
const [tabId, withSearch, isTab, index] =
await testProxy.whenCalled('openRecentlyClosedEntry');
assertEquals(tabData.tabId, tabId);
assertFalse(withSearch);
assertTrue(isTab);
assertEquals(0, index);
});
test('Click on recently closed tab group item triggers action', async () => {
const tabGroupData = {
sessionId: 101,
id: sampleToken(0n, 1n),
title: 'My Favorites',
color: TabGroupColor.kBlue,
tabCount: 1,
lastActiveTime: {internalValue: BigInt(11)},
lastActiveElapsedText: '',
};
await setupTest(createProfileData({
windows: [{
active: true,
height: SAMPLE_WINDOW_HEIGHT,
tabs: [createTab({
title: 'Google',
url: {url: 'https://www.google.com'},
lastActiveTimeTicks: {internalValue: BigInt(4)},
})]
}],
recentlyClosedTabGroups: [tabGroupData],
recentlyClosedSectionExpanded: true
}));
let tabSearchItem =
tabSearchApp.$.tabsList.querySelector('tab-search-group-item')!;
tabSearchItem.click();
const [id, withSearch, isTab, index] =
await testProxy.whenCalled('openRecentlyClosedEntry');
assertEquals(tabGroupData.sessionId, id);
assertFalse(withSearch);
assertFalse(isTab);
assertEquals(0, index);
});
test('Keyboard navigation on an empty list', async () => {
await setupTest(createProfileData({
windows: [{active: true, height: SAMPLE_WINDOW_HEIGHT, tabs: []}],
}));
const searchField = tabSearchApp.$.searchField;
keyDownOn(searchField, 0, [], 'ArrowUp');
assertEquals(-1, tabSearchApp.getSelectedIndex());
keyDownOn(searchField, 0, [], 'ArrowDown');
assertEquals(-1, tabSearchApp.getSelectedIndex());
keyDownOn(searchField, 0, [], 'Home');
assertEquals(-1, tabSearchApp.getSelectedIndex());
keyDownOn(searchField, 0, [], 'End');
assertEquals(-1, tabSearchApp.getSelectedIndex());
});
test('Keyboard navigation abides by item list range boundaries', async () => {
const testData = createProfileData();
await setupTest(testData);
const numTabs =
testData.windows.reduce((total, w) => total + w.tabs.length, 0);
const searchField = tabSearchApp.$.searchField;
keyDownOn(searchField, 0, [], 'ArrowUp');
assertEquals(numTabs - 1, tabSearchApp.getSelectedIndex());
keyDownOn(searchField, 0, [], 'ArrowDown');
assertEquals(0, tabSearchApp.getSelectedIndex());
keyDownOn(searchField, 0, [], 'ArrowDown');
assertEquals(1, tabSearchApp.getSelectedIndex());
keyDownOn(searchField, 0, [], 'ArrowUp');
assertEquals(0, tabSearchApp.getSelectedIndex());
keyDownOn(searchField, 0, [], 'End');
assertEquals(numTabs - 1, tabSearchApp.getSelectedIndex());
keyDownOn(searchField, 0, [], 'Home');
assertEquals(0, tabSearchApp.getSelectedIndex());
});
test(
'Verify all list items are present when Shift+Tab navigating from the search field to the last item',
async () => {
const siteNames = Array.from({length: 20}, (_, i) => 'site' + (i + 1));
const testData = generateSampleDataFromSiteNames(siteNames);
await setupTest(testData);
const searchField = tabSearchApp.$.searchField;
keyDownOn(searchField, 0, ['shift'], 'Tab');
await waitAfterNextRender(tabSearchApp);
// Since default actions are not triggered via simulated events we rely
// on asserting the expected DOM item count necessary to focus the last
// item is present.
assertEquals(siteNames.length, queryRows().length);
});
test('Key with modifiers should not affect selected item', async () => {
await setupTest(createProfileData());
const searchField = tabSearchApp.$.searchField;
for (const key of ['ArrowUp', 'ArrowDown', 'Home', 'End']) {
keyDownOn(searchField, 0, ['shift'], key);
assertEquals(0, tabSearchApp.getSelectedIndex());
}
});
test('refresh on tabs changed', async () => {
await setupTest(createProfileData());
verifyTabIds(queryRows(), [1, 5, 6, 2, 3, 4]);
testProxy.getCallbackRouterRemote().tabsChanged(
createProfileData({windows: []}));
await flushTasks();
verifyTabIds(queryRows(), []);
assertEquals(-1, tabSearchApp.getSelectedIndex());
});
test('On tabs changed, tab item selection preserved or updated', async () => {
const testData = createProfileData();
await setupTest(testData);
const searchField = tabSearchApp.$.searchField;
keyDownOn(searchField, 0, [], 'ArrowDown');
assertEquals(1, tabSearchApp.getSelectedIndex());
testProxy.getCallbackRouterRemote().tabsChanged(createProfileData({
windows: [testData.windows[0]!],
}));
await flushTasks();
assertEquals(1, tabSearchApp.getSelectedIndex());
testProxy.getCallbackRouterRemote().tabsChanged(createProfileData({
windows: [{
active: true,
height: SAMPLE_WINDOW_HEIGHT,
tabs: [testData.windows[0]!.tabs[0]!]
}],
}));
await flushTasks();
assertEquals(0, tabSearchApp.getSelectedIndex());
});
test('refresh on tab updated', async () => {
await setupTest(createProfileData());
verifyTabIds(queryRows(), [1, 5, 6, 2, 3, 4]);
let tabSearchItem = tabSearchApp.$.tabsList.querySelector<TabSearchItem>(
'tab-search-item[id="1"]')!;
assertEquals('Google', tabSearchItem.data.tab.title);
assertEquals('https://www.google.com', tabSearchItem.data.tab.url.url);
const updatedTab: Tab = createTab({
lastActiveTimeTicks: {internalValue: BigInt(5)},
});
const tabUpdateInfo = {
inActiveWindow: true,
tab: updatedTab,
};
testProxy.getCallbackRouterRemote().tabUpdated(tabUpdateInfo);
await flushTasks();
// tabIds are not changed after tab updated.
verifyTabIds(queryRows(), [1, 5, 6, 2, 3, 4]);
tabSearchItem =
tabSearchApp.$.tabsList.querySelector('tab-search-item[id="1"]')!;
assertEquals(updatedTab.title, tabSearchItem.data.tab.title);
assertEquals(updatedTab.url.url, tabSearchItem.data.tab.url.url);
assertEquals('www.example.com', tabSearchItem.data.hostname);
});
test('tab update for tab not in profile data adds tab to list', async () => {
await setupTest(createProfileData({
windows: [{
active: true,
height: SAMPLE_WINDOW_HEIGHT,
tabs: generateSampleTabsFromSiteNames(['OpenTab1'], true),
}],
}));
verifyTabIds(queryRows(), [1]);
const updatedTab: Tab = createTab({
tabId: 2,
lastActiveTimeTicks: {internalValue: BigInt(5)},
});
const tabUpdateInfo = {
inActiveWindow: true,
tab: updatedTab,
};
testProxy.getCallbackRouterRemote().tabUpdated(tabUpdateInfo);
await flushTasks();
verifyTabIds(queryRows(), [2, 1]);
});
test('refresh on tabs removed, no restore service', async () => {
// Simulates a scenario where there is no tab restore service available for
// the current profile and thus, on removing a tab, there are no associated
// recently closed tabs created, such as in a OTR case.
await setupTest(createProfileData());
verifyTabIds(queryRows(), [1, 5, 6, 2, 3, 4]);
testProxy.getCallbackRouterRemote().tabsRemoved({
tabIds: [1, 2],
recentlyClosedTabs: [],
});
await flushTasks();
verifyTabIds(queryRows(), [5, 6, 3, 4]);
// Assert that on removing all items, we display the no-results div.
testProxy.getCallbackRouterRemote().tabsRemoved(
{tabIds: [3, 4, 5, 6], recentlyClosedTabs: []});
await flushTasks();
assertNotEquals(
null, tabSearchApp.shadowRoot!.querySelector('#no-results'));
});
test('Closed tab appears in recently closed section', async () => {
await setupTest(createProfileData({
windows: [{
active: true,
height: SAMPLE_WINDOW_HEIGHT,
tabs:
generateSampleTabsFromSiteNames(['SampleTab', 'SampleTab2'], true),
}],
recentlyClosedSectionExpanded: true,
}));
verifyTabIds(queryRows(), [1, 2]);
testProxy.getCallbackRouterRemote().tabsRemoved({
tabIds: [1],
recentlyClosedTabs: [{
tabId: 3,
title: `SampleTab`,
url: {url: 'https://www.sampletab.com'},
lastActiveTime: {internalValue: BigInt(3)},
lastActiveElapsedText: '',
groupId: undefined,
}],
});
await flushTasks();
verifyTabIds(queryRows(), [2, 3]);
});
test('Verify visibilitychange triggers data fetch', async () => {
await setupTest(createProfileData());
assertEquals(1, testProxy.getCallCount('getProfileData'));
// When hidden visibilitychange should not trigger the data callback.
Object.defineProperty(
document, 'visibilityState', {value: 'hidden', writable: true});
document.dispatchEvent(new Event('visibilitychange'));
await flushTasks();
assertEquals(1, testProxy.getCallCount('getProfileData'));
// When visible visibilitychange should trigger the data callback.
Object.defineProperty(
document, 'visibilityState', {value: 'visible', writable: true});
document.dispatchEvent(new Event('visibilitychange'));
await flushTasks();
assertEquals(2, testProxy.getCallCount('getProfileData'));
});
test('Verify hiding document resets selection and search text', async () => {
await setupTest(createProfileData());
assertEquals(1, testProxy.getCallCount('getProfileData'));
const searchField = tabSearchApp.$.searchField;
searchField.setValue('Apple');
await flushTasks();
verifyTabIds(queryRows(), [6, 4]);
keyDownOn(searchField, 0, [], 'ArrowDown');
assertEquals('Apple', tabSearchApp.getSearchTextForTesting());
assertEquals(1, tabSearchApp.getSelectedIndex());
// When hidden visibilitychange should reset selection and search text.
Object.defineProperty(
document, 'visibilityState', {value: 'hidden', writable: true});
document.dispatchEvent(new Event('visibilitychange'));
await flushTasks();
verifyTabIds(queryRows(), [1, 5, 6, 2, 3, 4]);
assertEquals('', tabSearchApp.getSearchTextForTesting());
assertEquals(0, tabSearchApp.getSelectedIndex());
// State should match that of the hidden state when visible again.
Object.defineProperty(
document, 'visibilityState', {value: 'visible', writable: true});
document.dispatchEvent(new Event('visibilitychange'));
await flushTasks();
verifyTabIds(queryRows(), [1, 5, 6, 2, 3, 4]);
assertEquals('', tabSearchApp.getSearchTextForTesting());
assertEquals(0, tabSearchApp.getSelectedIndex());
});
test('Verify tab switch is logged correctly', async () => {
await setupTest(createProfileData());
// Make sure that tab data has been recieved.
verifyTabIds(queryRows(), [1, 5, 6, 2, 3, 4]);
// Click the first element with tabId 1.
let tabSearchItem = tabSearchApp.$.tabsList.querySelector<HTMLElement>(
'tab-search-item[id="1"]')!;
tabSearchItem.click();
// Assert switchToTab() was called appropriately for an unfiltered tab list.
await testProxy.whenCalled('switchToTab')
.then(([tabInfo, withSearch, switchedTabIndex]) => {
assertEquals(1, tabInfo.tabId);
assertFalse(withSearch);
assertEquals(0, switchedTabIndex);
});
testProxy.reset();
// Click the first element with tabId 6.
tabSearchItem = tabSearchApp.$.tabsList.querySelector<HTMLElement>(
'tab-search-item[id="6"]')!;
tabSearchItem.click();
// Assert switchToTab() was called appropriately for an unfiltered tab list.
await testProxy.whenCalled('switchToTab')
.then(([tabInfo, withSearch, switchedTabIndex]) => {
assertEquals(6, tabInfo.tabId);
assertFalse(withSearch);
assertEquals(2, switchedTabIndex);
});
// Force a change to filtered tab data that would result in a
// re-render.
const searchField = tabSearchApp.$.searchField;
searchField.setValue('bing');
await flushTasks();
verifyTabIds(queryRows(), [2]);
testProxy.reset();
// Click the only remaining element with tabId 2.
tabSearchItem = tabSearchApp.$.tabsList.querySelector<HTMLElement>(
'tab-search-item[id="2"]')!;
tabSearchItem.click();
// Assert switchToTab() was called appropriately for a tab list fitlered by
// the search query.
await testProxy.whenCalled('switchToTab')
.then(([tabInfo, withSearch, switchedTabIndex]) => {
assertEquals(2, tabInfo.tabId);
assertTrue(withSearch);
assertEquals(0, switchedTabIndex);
});
});
test('Verify showUI() is called correctly', async () => {
await setupTest(createProfileData());
await waitAfterNextRender(tabSearchApp);
// Make sure that tab data has been received.
verifyTabIds(queryRows(), [1, 5, 6, 2, 3, 4]);
// Ensure that showUI() has been called after the initial data has been
// rendered.
await testProxy.whenCalled('showUI');
// Force a change to filtered tab data that would result in a
// re-render.
const searchField = tabSearchApp.$.searchField;
searchField.setValue('bing');
await flushTasks();
await waitAfterNextRender(tabSearchApp);
verifyTabIds(queryRows(), [2]);
// |showUI()| should still have only been called once.
assertEquals(1, testProxy.getCallCount('showUI'));
});
test('Sort by most recent active tabs', async () => {
const tabs = [
createTab({
index: 0,
tabId: 1,
title: 'Google',
url: {url: 'https://www.google.com'},
lastActiveTimeTicks: {internalValue: BigInt(2)},
}),
createTab({
index: 1,
tabId: 2,
title: 'Bing',
url: {url: 'https://www.bing.com'},
lastActiveTimeTicks: {internalValue: BigInt(4)},
active: true,
}),
createTab({
index: 2,
tabId: 3,
title: 'Yahoo',
url: {url: 'https://www.yahoo.com'},
lastActiveTimeTicks: {internalValue: BigInt(3)},
}),
];
// Move active tab to the bottom of the list.
await setupTest(createProfileData({
windows: [{active: true, height: SAMPLE_WINDOW_HEIGHT, tabs}],
}));
verifyTabIds(queryRows(), [3, 1, 2]);
await setupTest(
createProfileData({
windows: [{active: true, height: SAMPLE_WINDOW_HEIGHT, tabs}],
}),
{moveActiveTabToBottom: false});
verifyTabIds(queryRows(), [2, 3, 1]);
});
test('Tab associated with TabGroup data', async () => {
const token = sampleToken(1n, 1n);
const tabs = [
createTab({
groupId: token,
title: 'Google',
url: {url: 'https://www.google.com'},
lastActiveTimeTicks: {internalValue: BigInt(2)},
}),
];
const tabGroup = {
id: token,
color: TabGroupColor.kBlue,
title: 'Search Engines',
};
await setupTest(createProfileData({
windows: [{active: true, height: SAMPLE_WINDOW_HEIGHT, tabs}],
tabGroups: [tabGroup],
}));
let tabSearchItem = tabSearchApp.$.tabsList.querySelector<TabSearchItem>(
'tab-search-item[id="1"]')!;
assertEquals('Google', tabSearchItem.data.tab.title);
assertEquals('Search Engines', tabSearchItem.data.tabGroup!.title);
});
test('Recently closed section collapse and expand', async () => {
await setupTest(createProfileData({
windows: [{
active: true,
height: SAMPLE_WINDOW_HEIGHT,
tabs: generateSampleTabsFromSiteNames(['SampleOpenTab'], true),
}],
recentlyClosedTabs: SAMPLE_RECENTLY_CLOSED_DATA,
recentlyClosedSectionExpanded: true,
}));
assertEquals(3, queryRows().length);
const recentlyClosedTitleItem = queryListTitle()[1];
assertTrue(!!recentlyClosedTitleItem);
const recentlyClosedTitleExpandButton =
recentlyClosedTitleItem!.querySelector('cr-expand-button');
assertTrue(!!recentlyClosedTitleExpandButton);
// Collapse the `Recently Closed` section and assert item count.
recentlyClosedTitleExpandButton!.click();
const [expanded] =
await testProxy.whenCalled('saveRecentlyClosedExpandedPref');
assertFalse(expanded);
assertEquals(1, queryRows().length);
// Expand the `Recently Closed` section and assert item count.
recentlyClosedTitleExpandButton!.click();
assertEquals(2, testProxy.getCallCount('saveRecentlyClosedExpandedPref'));
assertEquals(3, queryRows().length);
});
test('Show media tab in Audio & Video section', async () => {
await setupTest(
createProfileData({
windows: SAMPLE_WINDOW_DATA_WITH_MEDIA_TAB,
}),
{alsoShowMediaTabsinOpenTabsSection: false});
// One media tab and one non-media tab.
assertEquals(2, queryRows().length);
// "Audio and Video" and "Open Tabs" section should both exist.
assertEquals(2, queryListTitle().length);
});
test(
'Show media tab in Audio & Video section and Open Tabs section',
async () => {
await setupTest(
createProfileData({
windows: SAMPLE_WINDOW_DATA_WITH_MEDIA_TAB,
}),
{alsoShowMediaTabsinOpenTabsSection: true});
// Only the two media tabs should be duplicated.
assertEquals(3, queryRows().length);
// "Audio and Video" and "Open Tabs" section should both exist.
assertEquals(2, queryListTitle().length);
});
test('Tab is no longer media tab', async () => {
await setupTest(
createProfileData({
windows: SAMPLE_WINDOW_DATA_WITH_MEDIA_TAB,
}),
{alsoShowMediaTabsinOpenTabsSection: false});
const updatedTab: Tab = createTab({
alertStates: [],
tabId: 1,
lastActiveTimeTicks: {internalValue: BigInt(5)},
});
const tabUpdateInfo = {
inActiveWindow: true,
tab: updatedTab,
};
testProxy.getCallbackRouterRemote().tabUpdated(tabUpdateInfo);
await flushTasks();
// Two non-media tabs
assertEquals(2, queryRows().length);
// Only "Open Tabs" section should exist.
assertEquals(1, queryListTitle().length);
});
test(
'Tab is no longer media tab with media tabs also shown in Open Tabs section ',
async () => {
await setupTest(
createProfileData({
windows: SAMPLE_WINDOW_DATA_WITH_MEDIA_TAB,
}),
{alsoShowMediaTabsinOpenTabsSection: true});
const updatedTab: Tab = createTab({
alertStates: [],
tabId: 1,
lastActiveTimeTicks: {internalValue: BigInt(1)},
});
const tabUpdateInfo = {
inActiveWindow: true,
tab: updatedTab,
};
testProxy.getCallbackRouterRemote().tabUpdated(tabUpdateInfo);
await flushTasks();
// Two non-media tabs
assertEquals(2, queryRows().length);
// Only "Open Tabs" section should exist.
assertEquals(1, queryListTitle().length);
});
test('Non-media tab becomes media tab', async () => {
await setupTest(
createProfileData({
windows: SAMPLE_WINDOW_DATA,
}),
{alsoShowMediaTabsinOpenTabsSection: false});
assertEquals(1, queryListTitle().length);
const updatedTab: Tab = createTab({
alertStates: [TabAlertState.kAudioPlaying],
tabId: 5,
lastActiveTimeTicks: {internalValue: BigInt(1)},
});
const tabUpdateInfo = {
inActiveWindow: true,
tab: updatedTab,
};
testProxy.getCallbackRouterRemote().tabUpdated(tabUpdateInfo);
await flushTasks();
// One media tab, the rest are non-media tabs.
assertEquals(6, queryRows().length);
// "Audio and Video" and "Open Tabs" section should both exist.
assertEquals(2, queryListTitle().length);
});
test(
'Non-media tab becomes media tab with media tabs also shown in Open Tabs section ',
async () => {
await setupTest(
createProfileData({
windows: SAMPLE_WINDOW_DATA,
}),
{alsoShowMediaTabsinOpenTabsSection: true});
assertEquals(1, queryListTitle().length);
const updatedTab: Tab = createTab({
alertStates: [TabAlertState.kAudioPlaying],
tabId: 5,
lastActiveTimeTicks: {internalValue: BigInt(1)},
});
const tabUpdateInfo = {
inActiveWindow: true,
tab: updatedTab,
};
testProxy.getCallbackRouterRemote().tabUpdated(tabUpdateInfo);
await flushTasks();
// One media tab is duplicated, the rest are non-media tabs.
assertEquals(7, queryRows().length);
// "Audio and Video" and "Open Tabs" section should both exist.
assertEquals(2, queryListTitle().length);
});
test('Search for media tab', async () => {
await setupTest(
createProfileData({
windows: SAMPLE_WINDOW_DATA_WITH_MEDIA_TAB,
}),
{alsoShowMediaTabsinOpenTabsSection: false});
const searchField = tabSearchApp.$.searchField;
searchField.setValue('meet');
await flushTasks();
assertEquals(1, queryListTitle().length);
});
test(
'Search for media tab with media tabs also shown in Open Tabs section',
async () => {
await setupTest(
createProfileData({
windows: SAMPLE_WINDOW_DATA_WITH_MEDIA_TAB,
}),
{alsoShowMediaTabsinOpenTabsSection: true});
const searchField = tabSearchApp.$.searchField;
searchField.setValue('meet');
await flushTasks();
// Media tab is only shown in the Open Tabs section when a search
// criteria is applied.
assertEquals(1, queryListTitle().length);
});
}); | the_stack |
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js";
import * as msRest from "@azure/ms-rest-js";
export { BaseResource, CloudError };
/**
* Display metadata associated with the operation.
*/
export interface OperationDisplay {
/**
* Service provider: Microsoft Storage.
*/
provider?: string;
/**
* Resource on which the operation is performed etc.
*/
resource?: string;
/**
* Type of operation: get, read, delete, etc.
*/
operation?: string;
}
/**
* Dimension of blobs, possibly be blob type or access tier.
*/
export interface Dimension {
/**
* Display name of dimension.
*/
name?: string;
/**
* Display name of dimension.
*/
displayName?: string;
}
/**
* Metric specification of operation.
*/
export interface MetricSpecification {
/**
* Name of metric specification.
*/
name?: string;
/**
* Display name of metric specification.
*/
displayName?: string;
/**
* Display description of metric specification.
*/
displayDescription?: string;
/**
* Unit could be Bytes or Count.
*/
unit?: string;
/**
* Dimensions of blobs, including blob type and access tier.
*/
dimensions?: Dimension[];
/**
* Aggregation type could be Average.
*/
aggregationType?: string;
/**
* The property to decide fill gap with zero or not.
*/
fillGapWithZero?: boolean;
/**
* The category this metric specification belong to, could be Capacity.
*/
category?: string;
/**
* Account Resource Id.
*/
resourceIdDimensionNameOverride?: string;
}
/**
* One property of operation, include metric specifications.
*/
export interface ServiceSpecification {
/**
* Metric specifications of operation.
*/
metricSpecifications?: MetricSpecification[];
}
/**
* Storage REST API operation definition.
*/
export interface Operation {
/**
* Operation name: {provider}/{resource}/{operation}
*/
name?: string;
/**
* Display metadata associated with the operation.
*/
display?: OperationDisplay;
/**
* The origin of operations.
*/
origin?: string;
/**
* One property of operation, include metric specifications.
*/
serviceSpecification?: ServiceSpecification;
}
/**
* The parameters used to check the availability of the storage account name.
*/
export interface StorageAccountCheckNameAvailabilityParameters {
/**
* The storage account name.
*/
name: string;
}
/**
* The capability information in the specified sku, including file encryption, network acls, change
* notification, etc.
*/
export interface SKUCapability {
/**
* The name of capability, The capability information in the specified sku, including file
* encryption, network acls, change notification, etc.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* A string value to indicate states of given capability. Possibly 'true' or 'false'.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly value?: string;
}
/**
* The restriction because of which SKU cannot be used.
*/
export interface Restriction {
/**
* The type of restrictions. As of now only possible value for this is location.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
/**
* The value of restrictions. If the restriction type is set to location. This would be different
* locations where the SKU is restricted.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly values?: string[];
/**
* The reason for the restriction. As of now this can be "QuotaId" or
* "NotAvailableForSubscription". Quota Id is set when the SKU has requiredQuotas parameter as
* the subscription does not belong to that quota. The "NotAvailableForSubscription" is related
* to capacity at DC. Possible values include: 'QuotaId', 'NotAvailableForSubscription'
*/
reasonCode?: ReasonCode;
}
/**
* The SKU of the storage account.
*/
export interface Sku {
/**
* Gets or sets the sku name. Required for account creation; optional for update. Note that in
* older versions, sku name was called accountType. Possible values include: 'Standard_LRS',
* 'Standard_GRS', 'Standard_RAGRS', 'Standard_ZRS', 'Premium_LRS'
*/
name: SkuName;
/**
* Gets the sku tier. This is based on the SKU name. Possible values include: 'Standard',
* 'Premium'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly tier?: SkuTier;
/**
* The type of the resource, usually it is 'storageAccounts'.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly resourceType?: string;
/**
* Indicates the type of storage account. Possible values include: 'Storage', 'StorageV2',
* 'BlobStorage'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly kind?: Kind;
/**
* The set of locations that the SKU is available. This will be supported and registered Azure
* Geo Regions (e.g. West US, East US, Southeast Asia, etc.).
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly locations?: string[];
/**
* The capability information in the specified sku, including file encryption, network acls,
* change notification, etc.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly capabilities?: SKUCapability[];
/**
* The restrictions because of which SKU cannot be used. This is empty if there are no
* restrictions.
*/
restrictions?: Restriction[];
}
/**
* The CheckNameAvailability operation response.
*/
export interface CheckNameAvailabilityResult {
/**
* Gets a boolean value that indicates whether the name is available for you to use. If true, the
* name is available. If false, the name has already been taken or is invalid and cannot be used.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly nameAvailable?: boolean;
/**
* Gets the reason that a storage account name could not be used. The Reason element is only
* returned if NameAvailable is false. Possible values include: 'AccountNameInvalid',
* 'AlreadyExists'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly reason?: Reason;
/**
* Gets an error message explaining the Reason value in more detail.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly message?: string;
}
/**
* The custom domain assigned to this storage account. This can be set via Update.
*/
export interface CustomDomain {
/**
* Gets or sets the custom domain name assigned to the storage account. Name is the CNAME source.
*/
name: string;
/**
* Indicates whether indirect CName validation is enabled. Default value is false. This should
* only be set on updates.
*/
useSubDomainName?: boolean;
}
/**
* A service that allows server-side encryption to be used.
*/
export interface EncryptionService {
/**
* A boolean indicating whether or not the service encrypts the data as it is stored.
*/
enabled?: boolean;
/**
* Gets a rough estimate of the date/time when the encryption was last enabled by the user. Only
* returned when encryption is enabled. There might be some unencrypted blobs which were written
* after this time, as it is just a rough estimate.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly lastEnabledTime?: Date;
}
/**
* A list of services that support encryption.
*/
export interface EncryptionServices {
/**
* The encryption function of the blob storage service.
*/
blob?: EncryptionService;
/**
* The encryption function of the file storage service.
*/
file?: EncryptionService;
/**
* The encryption function of the table storage service.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly table?: EncryptionService;
/**
* The encryption function of the queue storage service.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly queue?: EncryptionService;
}
/**
* Properties of key vault.
*/
export interface KeyVaultProperties {
/**
* The name of KeyVault key.
*/
keyName?: string;
/**
* The version of KeyVault key.
*/
keyVersion?: string;
/**
* The Uri of KeyVault.
*/
keyVaultUri?: string;
}
/**
* The encryption settings on the storage account.
*/
export interface Encryption {
/**
* List of services which support encryption.
*/
services?: EncryptionServices;
/**
* The encryption keySource (provider). Possible values (case-insensitive): Microsoft.Storage,
* Microsoft.Keyvault. Possible values include: 'Microsoft.Storage', 'Microsoft.Keyvault'.
* Default value: 'Microsoft.Storage'.
*/
keySource: KeySource;
/**
* Properties provided by key vault.
*/
keyVaultProperties?: KeyVaultProperties;
}
/**
* Virtual Network rule.
*/
export interface VirtualNetworkRule {
/**
* Resource ID of a subnet, for example:
* /subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.Network/virtualNetworks/{vnetName}/subnets/{subnetName}.
*/
virtualNetworkResourceId: string;
/**
* The action of virtual network rule. Possible values include: 'Allow'. Default value: 'Allow'.
*/
action?: Action;
/**
* Gets the state of virtual network rule. Possible values include: 'provisioning',
* 'deprovisioning', 'succeeded', 'failed', 'networkSourceDeleted'
*/
state?: State;
}
/**
* IP rule with specific IP or IP range in CIDR format.
*/
export interface IPRule {
/**
* Specifies the IP or IP range in CIDR format. Only IPV4 address is allowed.
*/
iPAddressOrRange: string;
/**
* The action of IP ACL rule. Possible values include: 'Allow'. Default value: 'Allow'.
*/
action?: Action;
}
/**
* Network rule set
*/
export interface NetworkRuleSet {
/**
* Specifies whether traffic is bypassed for Logging/Metrics/AzureServices. Possible values are
* any combination of Logging|Metrics|AzureServices (For example, "Logging, Metrics"), or None to
* bypass none of those traffics. Possible values include: 'None', 'Logging', 'Metrics',
* 'AzureServices'. Default value: 'AzureServices'.
*/
bypass?: Bypass;
/**
* Sets the virtual network rules
*/
virtualNetworkRules?: VirtualNetworkRule[];
/**
* Sets the IP ACL rules
*/
ipRules?: IPRule[];
/**
* Specifies the default action of allow or deny when no other rules match. Possible values
* include: 'Allow', 'Deny'. Default value: 'Allow'.
*/
defaultAction: DefaultAction;
}
/**
* Identity for the resource.
*/
export interface Identity {
/**
* The principal ID of resource identity.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly principalId?: string;
/**
* The tenant ID of resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly tenantId?: string;
}
/**
* The parameters used when creating a storage account.
*/
export interface StorageAccountCreateParameters {
/**
* Required. Gets or sets the sku name.
*/
sku: Sku;
/**
* Required. Indicates the type of storage account. Possible values include: 'Storage',
* 'StorageV2', 'BlobStorage'
*/
kind: Kind;
/**
* Required. Gets or sets the location of the resource. This will be one of the supported and
* registered Azure Geo Regions (e.g. West US, East US, Southeast Asia, etc.). The geo region of
* a resource cannot be changed once it is created, but if an identical geo region is specified
* on update, the request will succeed.
*/
location: string;
/**
* Gets or sets a list of key value pairs that describe the resource. These tags can be used for
* viewing and grouping this resource (across resource groups). A maximum of 15 tags can be
* provided for a resource. Each tag must have a key with a length no greater than 128 characters
* and a value with a length no greater than 256 characters.
*/
tags?: { [propertyName: string]: string };
/**
* The identity of the resource.
*/
identity?: Identity;
/**
* User domain assigned to the storage account. Name is the CNAME source. Only one custom domain
* is supported per storage account at this time. To clear the existing custom domain, use an
* empty string for the custom domain name property.
*/
customDomain?: CustomDomain;
/**
* Provides the encryption settings on the account. If left unspecified the account encryption
* settings will remain the same. The default setting is unencrypted.
*/
encryption?: Encryption;
/**
* Network rule set
*/
networkRuleSet?: NetworkRuleSet;
/**
* Required for storage accounts where kind = BlobStorage. The access tier used for billing.
* Possible values include: 'Hot', 'Cool'
*/
accessTier?: AccessTier;
/**
* Allows https traffic only to storage service if sets to true. Default value: false.
*/
enableHttpsTrafficOnly?: boolean;
}
/**
* The URIs that are used to perform a retrieval of a public blob, queue, or table object.
*/
export interface Endpoints {
/**
* Gets the blob endpoint.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly blob?: string;
/**
* Gets the queue endpoint.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly queue?: string;
/**
* Gets the table endpoint.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly table?: string;
/**
* Gets the file endpoint.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly file?: string;
}
/**
* Describes a storage resource.
*/
export interface Resource extends BaseResource {
/**
* Resource Id
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* Resource name
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* Resource type
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
/**
* Resource location
*/
location?: string;
/**
* Tags assigned to a resource; can be used for viewing and grouping a resource (across resource
* groups).
*/
tags?: { [propertyName: string]: string };
}
/**
* The storage account.
*/
export interface StorageAccount extends Resource {
/**
* Gets the SKU.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly sku?: Sku;
/**
* Gets the Kind. Possible values include: 'Storage', 'StorageV2', 'BlobStorage'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly kind?: Kind;
/**
* The identity of the resource.
*/
identity?: Identity;
/**
* Gets the status of the storage account at the time the operation was called. Possible values
* include: 'Creating', 'ResolvingDNS', 'Succeeded'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: ProvisioningState;
/**
* Gets the URLs that are used to perform a retrieval of a public blob, queue, or table object.
* Note that Standard_ZRS and Premium_LRS accounts only return the blob endpoint.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly primaryEndpoints?: Endpoints;
/**
* Gets the location of the primary data center for the storage account.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly primaryLocation?: string;
/**
* Gets the status indicating whether the primary location of the storage account is available or
* unavailable. Possible values include: 'available', 'unavailable'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly statusOfPrimary?: AccountStatus;
/**
* Gets the timestamp of the most recent instance of a failover to the secondary location. Only
* the most recent timestamp is retained. This element is not returned if there has never been a
* failover instance. Only available if the accountType is Standard_GRS or Standard_RAGRS.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly lastGeoFailoverTime?: Date;
/**
* Gets the location of the geo-replicated secondary for the storage account. Only available if
* the accountType is Standard_GRS or Standard_RAGRS.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly secondaryLocation?: string;
/**
* Gets the status indicating whether the secondary location of the storage account is available
* or unavailable. Only available if the SKU name is Standard_GRS or Standard_RAGRS. Possible
* values include: 'available', 'unavailable'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly statusOfSecondary?: AccountStatus;
/**
* Gets the creation date and time of the storage account in UTC.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly creationTime?: Date;
/**
* Gets the custom domain the user assigned to this storage account.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly customDomain?: CustomDomain;
/**
* Gets the URLs that are used to perform a retrieval of a public blob, queue, or table object
* from the secondary location of the storage account. Only available if the SKU name is
* Standard_RAGRS.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly secondaryEndpoints?: Endpoints;
/**
* Gets the encryption settings on the account. If unspecified, the account is unencrypted.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly encryption?: Encryption;
/**
* Required for storage accounts where kind = BlobStorage. The access tier used for billing.
* Possible values include: 'Hot', 'Cool'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly accessTier?: AccessTier;
/**
* Allows https traffic only to storage service if sets to true. Default value: false.
*/
enableHttpsTrafficOnly?: boolean;
/**
* Network rule set
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly networkRuleSet?: NetworkRuleSet;
}
/**
* An access key for the storage account.
*/
export interface StorageAccountKey {
/**
* Name of the key.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly keyName?: string;
/**
* Base 64-encoded value of the key.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly value?: string;
/**
* Permissions for the key -- read-only or full permissions. Possible values include: 'Read',
* 'Full'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly permissions?: KeyPermission;
}
/**
* The response from the ListKeys operation.
*/
export interface StorageAccountListKeysResult {
/**
* Gets the list of storage account keys and their properties for the specified storage account.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly keys?: StorageAccountKey[];
}
/**
* The parameters used to regenerate the storage account key.
*/
export interface StorageAccountRegenerateKeyParameters {
/**
* The name of storage keys that want to be regenerated, possible values are key1, key2.
*/
keyName: string;
}
/**
* The parameters that can be provided when updating the storage account properties.
*/
export interface StorageAccountUpdateParameters {
/**
* Gets or sets the SKU name. Note that the SKU name cannot be updated to Standard_ZRS or
* Premium_LRS, nor can accounts of those sku names be updated to any other value.
*/
sku?: Sku;
/**
* Gets or sets a list of key value pairs that describe the resource. These tags can be used in
* viewing and grouping this resource (across resource groups). A maximum of 15 tags can be
* provided for a resource. Each tag must have a key no greater in length than 128 characters and
* a value no greater in length than 256 characters.
*/
tags?: { [propertyName: string]: string };
/**
* The identity of the resource.
*/
identity?: Identity;
/**
* Custom domain assigned to the storage account by the user. Name is the CNAME source. Only one
* custom domain is supported per storage account at this time. To clear the existing custom
* domain, use an empty string for the custom domain name property.
*/
customDomain?: CustomDomain;
/**
* Provides the encryption settings on the account. The default setting is unencrypted.
*/
encryption?: Encryption;
/**
* Required for storage accounts where kind = BlobStorage. The access tier used for billing.
* Possible values include: 'Hot', 'Cool'
*/
accessTier?: AccessTier;
/**
* Allows https traffic only to storage service if sets to true. Default value: false.
*/
enableHttpsTrafficOnly?: boolean;
/**
* Network rule set
*/
networkRuleSet?: NetworkRuleSet;
/**
* Optional. Indicates the type of storage account. Currently only StorageV2 value supported by
* server. Possible values include: 'Storage', 'StorageV2', 'BlobStorage'
*/
kind?: Kind;
}
/**
* The usage names that can be used; currently limited to StorageAccount.
*/
export interface UsageName {
/**
* Gets a string describing the resource name.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly value?: string;
/**
* Gets a localized string describing the resource name.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly localizedValue?: string;
}
/**
* Describes Storage Resource Usage.
*/
export interface Usage {
/**
* Gets the unit of measurement. Possible values include: 'Count', 'Bytes', 'Seconds', 'Percent',
* 'CountsPerSecond', 'BytesPerSecond'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly unit?: UsageUnit;
/**
* Gets the current count of the allocated resources in the subscription.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly currentValue?: number;
/**
* Gets the maximum count of the resources that can be allocated in the subscription.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly limit?: number;
/**
* Gets the name of the type of usage.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: UsageName;
}
/**
* The parameters to list SAS credentials of a storage account.
*/
export interface AccountSasParameters {
/**
* The signed services accessible with the account SAS. Possible values include: Blob (b), Queue
* (q), Table (t), File (f). Possible values include: 'b', 'q', 't', 'f'
*/
services: Services;
/**
* The signed resource types that are accessible with the account SAS. Service (s): Access to
* service-level APIs; Container (c): Access to container-level APIs; Object (o): Access to
* object-level APIs for blobs, queue messages, table entities, and files. Possible values
* include: 's', 'c', 'o'
*/
resourceTypes: SignedResourceTypes;
/**
* The signed permissions for the account SAS. Possible values include: Read (r), Write (w),
* Delete (d), List (l), Add (a), Create (c), Update (u) and Process (p). Possible values
* include: 'r', 'd', 'w', 'l', 'a', 'c', 'u', 'p'
*/
permissions: Permissions;
/**
* An IP address or a range of IP addresses from which to accept requests.
*/
iPAddressOrRange?: string;
/**
* The protocol permitted for a request made with the account SAS. Possible values include:
* 'https,http', 'https'
*/
protocols?: HttpProtocol;
/**
* The time at which the SAS becomes valid.
*/
sharedAccessStartTime?: Date;
/**
* The time at which the shared access signature becomes invalid.
*/
sharedAccessExpiryTime: Date;
/**
* The key to sign the account SAS token with.
*/
keyToSign?: string;
}
/**
* The List SAS credentials operation response.
*/
export interface ListAccountSasResponse {
/**
* List SAS credentials of storage account.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly accountSasToken?: string;
}
/**
* The parameters to list service SAS credentials of a specific resource.
*/
export interface ServiceSasParameters {
/**
* The canonical path to the signed resource.
*/
canonicalizedResource: string;
/**
* The signed services accessible with the service SAS. Possible values include: Blob (b),
* Container (c), File (f), Share (s). Possible values include: 'b', 'c', 'f', 's'
*/
resource: SignedResource;
/**
* The signed permissions for the service SAS. Possible values include: Read (r), Write (w),
* Delete (d), List (l), Add (a), Create (c), Update (u) and Process (p). Possible values
* include: 'r', 'd', 'w', 'l', 'a', 'c', 'u', 'p'
*/
permissions?: Permissions;
/**
* An IP address or a range of IP addresses from which to accept requests.
*/
iPAddressOrRange?: string;
/**
* The protocol permitted for a request made with the account SAS. Possible values include:
* 'https,http', 'https'
*/
protocols?: HttpProtocol;
/**
* The time at which the SAS becomes valid.
*/
sharedAccessStartTime?: Date;
/**
* The time at which the shared access signature becomes invalid.
*/
sharedAccessExpiryTime?: Date;
/**
* A unique value up to 64 characters in length that correlates to an access policy specified for
* the container, queue, or table.
*/
identifier?: string;
/**
* The start of partition key.
*/
partitionKeyStart?: string;
/**
* The end of partition key.
*/
partitionKeyEnd?: string;
/**
* The start of row key.
*/
rowKeyStart?: string;
/**
* The end of row key.
*/
rowKeyEnd?: string;
/**
* The key to sign the account SAS token with.
*/
keyToSign?: string;
/**
* The response header override for cache control.
*/
cacheControl?: string;
/**
* The response header override for content disposition.
*/
contentDisposition?: string;
/**
* The response header override for content encoding.
*/
contentEncoding?: string;
/**
* The response header override for content language.
*/
contentLanguage?: string;
/**
* The response header override for content type.
*/
contentType?: string;
}
/**
* The List service SAS credentials operation response.
*/
export interface ListServiceSasResponse {
/**
* List service SAS credentials of specific resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly serviceSasToken?: string;
}
/**
* An interface representing StorageManagementClientOptions.
*/
export interface StorageManagementClientOptions extends AzureServiceClientOptions {
baseUri?: string;
}
/**
* @interface
* Result of the request to list Storage operations. It contains a list of operations and a URL
* link to get the next set of results.
* @extends Array<Operation>
*/
export interface OperationListResult extends Array<Operation> {
}
/**
* @interface
* The response from the List Storage SKUs operation.
* @extends Array<Sku>
*/
export interface StorageSkuListResult extends Array<Sku> {
}
/**
* @interface
* The response from the List Storage Accounts operation.
* @extends Array<StorageAccount>
*/
export interface StorageAccountListResult extends Array<StorageAccount> {
}
/**
* @interface
* The response from the List Usages operation.
* @extends Array<Usage>
*/
export interface UsageListResult extends Array<Usage> {
}
/**
* Defines values for ReasonCode.
* Possible values include: 'QuotaId', 'NotAvailableForSubscription'
* @readonly
* @enum {string}
*/
export type ReasonCode = 'QuotaId' | 'NotAvailableForSubscription';
/**
* Defines values for SkuName.
* Possible values include: 'Standard_LRS', 'Standard_GRS', 'Standard_RAGRS', 'Standard_ZRS',
* 'Premium_LRS'
* @readonly
* @enum {string}
*/
export type SkuName = 'Standard_LRS' | 'Standard_GRS' | 'Standard_RAGRS' | 'Standard_ZRS' | 'Premium_LRS';
/**
* Defines values for SkuTier.
* Possible values include: 'Standard', 'Premium'
* @readonly
* @enum {string}
*/
export type SkuTier = 'Standard' | 'Premium';
/**
* Defines values for Kind.
* Possible values include: 'Storage', 'StorageV2', 'BlobStorage'
* @readonly
* @enum {string}
*/
export type Kind = 'Storage' | 'StorageV2' | 'BlobStorage';
/**
* Defines values for Reason.
* Possible values include: 'AccountNameInvalid', 'AlreadyExists'
* @readonly
* @enum {string}
*/
export type Reason = 'AccountNameInvalid' | 'AlreadyExists';
/**
* Defines values for KeySource.
* Possible values include: 'Microsoft.Storage', 'Microsoft.Keyvault'
* @readonly
* @enum {string}
*/
export type KeySource = 'Microsoft.Storage' | 'Microsoft.Keyvault';
/**
* Defines values for Action.
* Possible values include: 'Allow'
* @readonly
* @enum {string}
*/
export type Action = 'Allow';
/**
* Defines values for State.
* Possible values include: 'provisioning', 'deprovisioning', 'succeeded', 'failed',
* 'networkSourceDeleted'
* @readonly
* @enum {string}
*/
export type State = 'provisioning' | 'deprovisioning' | 'succeeded' | 'failed' | 'networkSourceDeleted';
/**
* Defines values for Bypass.
* Possible values include: 'None', 'Logging', 'Metrics', 'AzureServices'
* @readonly
* @enum {string}
*/
export type Bypass = 'None' | 'Logging' | 'Metrics' | 'AzureServices';
/**
* Defines values for DefaultAction.
* Possible values include: 'Allow', 'Deny'
* @readonly
* @enum {string}
*/
export type DefaultAction = 'Allow' | 'Deny';
/**
* Defines values for AccessTier.
* Possible values include: 'Hot', 'Cool'
* @readonly
* @enum {string}
*/
export type AccessTier = 'Hot' | 'Cool';
/**
* Defines values for ProvisioningState.
* Possible values include: 'Creating', 'ResolvingDNS', 'Succeeded'
* @readonly
* @enum {string}
*/
export type ProvisioningState = 'Creating' | 'ResolvingDNS' | 'Succeeded';
/**
* Defines values for AccountStatus.
* Possible values include: 'available', 'unavailable'
* @readonly
* @enum {string}
*/
export type AccountStatus = 'available' | 'unavailable';
/**
* Defines values for KeyPermission.
* Possible values include: 'Read', 'Full'
* @readonly
* @enum {string}
*/
export type KeyPermission = 'Read' | 'Full';
/**
* Defines values for UsageUnit.
* Possible values include: 'Count', 'Bytes', 'Seconds', 'Percent', 'CountsPerSecond',
* 'BytesPerSecond'
* @readonly
* @enum {string}
*/
export type UsageUnit = 'Count' | 'Bytes' | 'Seconds' | 'Percent' | 'CountsPerSecond' | 'BytesPerSecond';
/**
* Defines values for Services.
* Possible values include: 'b', 'q', 't', 'f'
* @readonly
* @enum {string}
*/
export type Services = 'b' | 'q' | 't' | 'f';
/**
* Defines values for SignedResourceTypes.
* Possible values include: 's', 'c', 'o'
* @readonly
* @enum {string}
*/
export type SignedResourceTypes = 's' | 'c' | 'o';
/**
* Defines values for Permissions.
* Possible values include: 'r', 'd', 'w', 'l', 'a', 'c', 'u', 'p'
* @readonly
* @enum {string}
*/
export type Permissions = 'r' | 'd' | 'w' | 'l' | 'a' | 'c' | 'u' | 'p';
/**
* Defines values for HttpProtocol.
* Possible values include: 'https,http', 'https'
* @readonly
* @enum {string}
*/
export type HttpProtocol = 'https,http' | 'https';
/**
* Defines values for SignedResource.
* Possible values include: 'b', 'c', 'f', 's'
* @readonly
* @enum {string}
*/
export type SignedResource = 'b' | 'c' | 'f' | 's';
/**
* Contains response data for the list operation.
*/
export type OperationsListResponse = OperationListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: OperationListResult;
};
};
/**
* Contains response data for the list operation.
*/
export type SkusListResponse = StorageSkuListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: StorageSkuListResult;
};
};
/**
* Contains response data for the checkNameAvailability operation.
*/
export type StorageAccountsCheckNameAvailabilityResponse = CheckNameAvailabilityResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: CheckNameAvailabilityResult;
};
};
/**
* Contains response data for the create operation.
*/
export type StorageAccountsCreateResponse = StorageAccount & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: StorageAccount;
};
};
/**
* Contains response data for the getProperties operation.
*/
export type StorageAccountsGetPropertiesResponse = StorageAccount & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: StorageAccount;
};
};
/**
* Contains response data for the update operation.
*/
export type StorageAccountsUpdateResponse = StorageAccount & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: StorageAccount;
};
};
/**
* Contains response data for the list operation.
*/
export type StorageAccountsListResponse = StorageAccountListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: StorageAccountListResult;
};
};
/**
* Contains response data for the listByResourceGroup operation.
*/
export type StorageAccountsListByResourceGroupResponse = StorageAccountListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: StorageAccountListResult;
};
};
/**
* Contains response data for the listKeys operation.
*/
export type StorageAccountsListKeysResponse = StorageAccountListKeysResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: StorageAccountListKeysResult;
};
};
/**
* Contains response data for the regenerateKey operation.
*/
export type StorageAccountsRegenerateKeyResponse = StorageAccountListKeysResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: StorageAccountListKeysResult;
};
};
/**
* Contains response data for the listAccountSAS operation.
*/
export type StorageAccountsListAccountSASResponse = ListAccountSasResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ListAccountSasResponse;
};
};
/**
* Contains response data for the listServiceSAS operation.
*/
export type StorageAccountsListServiceSASResponse = ListServiceSasResponse & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: ListServiceSasResponse;
};
};
/**
* Contains response data for the beginCreate operation.
*/
export type StorageAccountsBeginCreateResponse = StorageAccount & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: StorageAccount;
};
};
/**
* Contains response data for the list operation.
*/
export type UsageListResponse = UsageListResult & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: UsageListResult;
};
}; | the_stack |
import { Component, h, VNode } from "preact";
import {
KeyboardAction,
KeyboardMapping,
NormalizedKeypress,
serializeShortcut,
Shortcut,
} from "../shared/keyboard";
import { classlist, deepEqual } from "../shared/main";
import ButtonWithPopup from "./ButtonWithPopup";
import Field from "./Field";
import KeyboardShortcut, { hasShift, viewKey } from "./KeyboardShortcut";
type ShortcutError =
| { type: "CommonTextEditingShortcutConflict" }
| { type: "MacOptionKey"; printableKey: string; hasOtherModifier: boolean }
| { type: "MissingModifier"; shift: boolean }
| { type: "OtherShortcutConflict"; otherMapping: KeyboardMapping }
| { type: "UnrecognizedKey" };
type Mode = "Hints" | "Normal";
type Props = {
id: string;
name: string;
mode: Mode;
mac: boolean;
useKeyTranslations: boolean;
description?: VNode;
chars: string;
mappings: Array<KeyboardMapping>;
defaultMappings: Array<KeyboardMapping>;
capturedKeypressWithTimestamp:
| {
timestamp: number;
keypress: NormalizedKeypress;
}
| undefined;
onChange: (mappings: Array<KeyboardMapping>) => void;
onAddChange: (isOpen: boolean) => void;
};
type State = {
addingAction: KeyboardAction | undefined;
shortcutError:
| {
shortcut: Shortcut;
error: ShortcutError;
}
| undefined;
};
export default class KeyboardShortcuts extends Component<Props, State> {
state: State = {
addingAction: undefined,
shortcutError: undefined,
};
componentDidUpdate(prevProps: Props): void {
const {
capturedKeypressWithTimestamp,
mode,
mac,
useKeyTranslations,
mappings,
onAddChange,
} = this.props;
const { addingAction } = this.state;
if (
!deepEqual(
capturedKeypressWithTimestamp,
prevProps.capturedKeypressWithTimestamp
)
) {
if (
capturedKeypressWithTimestamp === undefined ||
addingAction === undefined
) {
this.setState({ shortcutError: undefined });
return;
}
const capturedKeypress = capturedKeypressWithTimestamp.keypress;
const { shortcutError } = this.state;
const shortcut: Shortcut = {
key: capturedKeypress.key,
alt: capturedKeypress.alt,
cmd: capturedKeypress.cmd,
ctrl: capturedKeypress.ctrl,
shift:
capturedKeypress.shift === undefined ? false : capturedKeypress.shift,
};
const confirm = (newShortcutError: {
shortcut: Shortcut;
error: ShortcutError;
}): void => {
if (deepEqual(shortcutError, newShortcutError)) {
this.saveMapping({
shortcut,
action: addingAction,
});
} else {
this.setState({
shortcutError: newShortcutError,
});
}
};
// The Space key is a good choice for cancelling since it cannot be used
// in hints mode (it breaks filter by text). (Outside hints mode,
// shortcuts without modifiers cannot be used anyway.)
if (shortcut.key === "Space" && !hasModifier(shortcut)) {
this.setState({
addingAction: undefined,
shortcutError: undefined,
});
onAddChange(false);
return;
}
if (!isRecognized(shortcut.key)) {
this.setState({
shortcutError: {
shortcut,
error: { type: "UnrecognizedKey" },
},
});
return;
}
if (
mode === "Normal" &&
!(hasModifier(shortcut) || isAllowedWithShiftOnly(shortcut))
) {
this.setState({
shortcutError: {
shortcut,
error: { type: "MissingModifier", shift: hasShift(shortcut) },
},
});
return;
}
const conflictingMapping = mappings.find((mapping) =>
deepEqual(mapping.shortcut, shortcut)
);
if (conflictingMapping !== undefined) {
if (conflictingMapping.action === addingAction) {
this.setState({
addingAction: undefined,
shortcutError: undefined,
});
onAddChange(false);
} else {
confirm({
shortcut,
error: {
type: "OtherShortcutConflict",
otherMapping: conflictingMapping,
},
});
}
return;
}
if (
mode === "Normal" &&
getTextEditingShortcuts(mac).some((shortcut2) =>
deepEqual(shortcut, shortcut2)
)
) {
confirm({
shortcut,
error: { type: "CommonTextEditingShortcutConflict" },
});
return;
}
const hasOtherModifier = shortcut.ctrl || shortcut.cmd;
if (
mac &&
shortcut.alt &&
capturedKeypress.printableKey !== undefined &&
!(mode === "Normal" && useKeyTranslations && hasOtherModifier) &&
!(mode === "Hints" && useKeyTranslations)
) {
confirm({
shortcut,
error: {
type: "MacOptionKey",
printableKey: capturedKeypress.printableKey,
hasOtherModifier,
},
});
return;
}
this.saveMapping({
shortcut,
action: addingAction,
});
}
}
saveMapping(newMapping: KeyboardMapping): void {
const { mappings, onChange, onAddChange } = this.props;
const newMappings = mappings
.filter((mapping) => !deepEqual(mapping.shortcut, newMapping.shortcut))
.concat(newMapping);
this.setState({
addingAction: undefined,
shortcutError: undefined,
});
onChange(newMappings);
onAddChange(false);
}
render(): VNode {
const {
id,
name,
description,
mode,
mac,
useKeyTranslations,
mappings,
defaultMappings,
chars,
onChange,
onAddChange,
} = this.props;
const { addingAction, shortcutError } = this.state;
return (
<Field
id={id}
fullWidth
label={name}
span
description={description}
changed={false}
render={() => (
<div>
<table className="ShortcutsTable">
<tbody>
{defaultMappings.map((defaultMapping, index) => {
const shortcuts = mappings
.filter(
(mapping) => mapping.action === defaultMapping.action
)
.map((mapping) => ({
key: serializeShortcut(mapping.shortcut),
shortcut: mapping.shortcut,
}))
.sort((a, b) => compare(a.key, b.key));
const changed = !(
shortcuts.length === 1 &&
shortcuts.every(({ shortcut }) =>
deepEqual(shortcut, defaultMapping.shortcut)
)
);
const isAdding = addingAction === defaultMapping.action;
const conflictingChars = getConflictingChars(
shortcuts.map(({ shortcut }) => shortcut),
chars
);
return (
<tr
key={index}
id={getKeyboardActionId(defaultMapping.action)}
>
<th className={classlist({ "is-changed": changed })}>
<p>
{describeKeyboardAction(defaultMapping.action).name}
</p>
{conflictingChars.length > 0 && (
<p className="TextSmall Error">
Overridden hint characters:{" "}
{conflictingChars.join(", ")}
</p>
)}
</th>
<td>
<div className="Spaced Spaced--center">
<div className="ShortcutsGrid">
{shortcuts.map(({ key, shortcut }) => (
<div key={key}>
<KeyboardShortcut
mac={mac}
shortcut={shortcut}
/>
<button
type="button"
title="Remove this shortcut"
className="RemoveButton"
onClick={() => {
onChange(
mappings.filter(
(mapping) =>
!deepEqual(shortcut, mapping.shortcut)
)
);
}}
>
×
</button>
</div>
))}
</div>
<div className="AddShortcutButton">
<ButtonWithPopup
title="Add shortcut"
className="AddShortcutButton-button"
open={isAdding}
buttonContent={<strong>+</strong>}
onOpenChange={(open: boolean) => {
this.setState({
addingAction: open
? defaultMapping.action
: undefined,
});
onAddChange(open);
}}
popupContent={() => (
<div
className="SpacedVertical"
style={{ width: 450 }}
>
{shortcutError === undefined ? (
<ShortcutAddDisplay
mac={mac}
defaultMapping={defaultMapping}
/>
) : (
<div className="SpacedVertical">
<KeyboardShortcut
mac={mac}
shortcut={shortcutError.shortcut}
/>
<ShortcutErrorDisplay
mode={mode}
mac={mac}
useKeyTranslations={useKeyTranslations}
error={shortcutError.error}
/>
</div>
)}
<p className="TextSmall">
<em>
Press{" "}
<KeyboardShortcut
mac={mac}
shortcut={{ key: "Space" }}
/>{" "}
to cancel.
</em>
</p>
</div>
)}
/>
</div>
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
/>
);
}
}
function ShortcutAddDisplay({
mac,
defaultMapping,
}: {
mac: boolean;
defaultMapping: KeyboardMapping;
}): VNode {
return (
<div>
<p>
<strong>Press the keyboard shortcut you’d like to use!</strong>
</p>
<div className="TextSmall SpacedVertical" style={{ marginTop: 15 }}>
<p>
Default:{" "}
<KeyboardShortcut mac={mac} shortcut={defaultMapping.shortcut} />
</p>
<p>
Note: Some browser/OS shortcuts cannot be overridden. For example,{" "}
<KeyboardShortcut
mac={mac}
shortcut={{
key: "w",
cmd: mac,
ctrl: !mac,
}}
/>{" "}
cannot be detected and always closes the current tab.
</p>
</div>
</div>
);
}
function ShortcutErrorDisplay({
mac,
mode,
useKeyTranslations,
error,
}: {
mac: boolean;
mode: Mode;
useKeyTranslations: boolean;
error: ShortcutError;
}): VNode {
switch (error.type) {
case "UnrecognizedKey":
return (
<div>
<p>
<strong>This key was not recognized.</strong>
</p>
<p>Please choose another one!</p>
</div>
);
case "MissingModifier":
if (error.shift) {
return (
<p>
<strong>
Only <KeyboardShortcut mac={mac} shortcut={{ key: "Escape" }} />{" "}
and <KeyboardShortcut mac={mac} shortcut={{ key: "F1" }} />
–
<KeyboardShortcut mac={mac} shortcut={{ key: "F12" }} /> can be
used with only{" "}
<KeyboardShortcut mac={mac} shortcut={{ key: "", shift: true }} />{" "}
for main keyboard shortcuts.
</strong>
</p>
);
}
return (
<p>
<strong>Main keyboard shortcuts must use a modifier.</strong>
</p>
);
case "OtherShortcutConflict":
return (
<div>
<p>
<strong>
This shortcut is already used for:{" "}
<span style={{ whiteSpace: "nowrap" }}>
“{describeKeyboardAction(error.otherMapping.action).name}.”
</span>
</strong>
</p>
<p>Press the shortcut again to replace, or choose another one!</p>
</div>
);
case "CommonTextEditingShortcutConflict":
return (
<div>
<p>
<strong>This is a common text editing shortcut.</strong>
</p>
<p>Press the shortcut again to override, or choose another one!</p>
</div>
);
case "MacOptionKey": {
const Highlight = error.hasOtherModifier ? "strong" : "span";
const disclaimer = (
<p>
<Highlight>This shortcut should work,</Highlight> but it might be
difficult to remember which key to press by seeing{" "}
<KeyboardShortcut shortcut={{ key: error.printableKey }} mac={mac} />{" "}
on this page. Unfortunately, that information isn’t provided by the
browser.
</p>
);
return (
<div className="SpacedVertical">
{mode === "Normal" ? (
useKeyTranslations ? (
<p>
{/* `error.hasOtherModifier` is always `false` here. */}
<strong>
If{" "}
<KeyboardShortcut
shortcut={{ key: error.printableKey, alt: true }}
mac={mac}
/>{" "}
produces a special character, you won’t be able to type that
character in text inputs if using this shortcut.
</strong>
</p>
) : (
<div>
{!error.hasOtherModifier && (
<p>
<strong>
You might not be able to type{" "}
<code>{printKey(error.printableKey)}</code> in text inputs
if using this shortcut.
</strong>
</p>
)}
{disclaimer}
</div>
)
) : (
<div>
{/* `useKeyTranslations` is always `false` here. */}
{!error.hasOtherModifier && (
<p>
<strong>
You might not be able to <em>filter by text</em> using{" "}
<code>{printKey(error.printableKey)}</code> if using this
shortcut.
</strong>
</p>
)}
{disclaimer}
</div>
)}
<p>Press the shortcut again to confirm, or choose another one!</p>
</div>
);
}
}
}
function printKey(printableKey: string): string {
return printableKey === "\u00a0"
? "non-breaking space"
: viewKey(printableKey);
}
type KeyboardActionDescription = {
name: string;
};
export function getKeyboardActionId(action: KeyboardAction): string {
return `action-${action}`;
}
export function describeKeyboardAction(
action: KeyboardAction
): KeyboardActionDescription {
switch (action) {
case "EnterHintsMode_Click":
return {
name: "Click",
};
case "EnterHintsMode_ManyClick":
return {
name: "Click many",
};
case "EnterHintsMode_ManyTab":
return {
name: "Open many tabs",
};
case "EnterHintsMode_BackgroundTab":
return {
name: "Open link in new tab",
};
case "EnterHintsMode_ForegroundTab":
return {
name: "Open link in new tab and switch to it",
};
case "EnterHintsMode_Select":
return {
name: "Select element",
};
case "ExitHintsMode":
return {
name: "Exit hints mode",
};
case "RotateHintsForward":
return {
name: "Rotate hints forward",
};
case "RotateHintsBackward":
return {
name: "Rotate hints backward",
};
case "RefreshHints":
return {
name: "Refresh hints",
};
case "TogglePeek":
return {
name: "Toggle peek mode",
};
case "Escape":
return {
name: "Exit hints mode, blur elements and clear selection",
};
case "ActivateHint":
return {
name: "Activate highlighted hint",
};
case "ActivateHintAlt":
return {
name: "Activate highlighted hint in a new tab",
};
case "Backspace":
return {
name: "Erase last entered character",
};
case "ReverseSelection":
return {
name: "Swap which end of a text selection to work on",
};
}
}
function compare(a: string, b: string): number {
return a < b ? -1 : a > b ? 1 : 0;
}
// This does not allow only shift on purpose.
//
// - Shift doesn't count as a modifier for printable keys. Example: a vs A.
// - Shift + non-printable keys are generally already taken. Example:
// Shift + ArrowRight selects text. Exception: The keys allowed by
// `isAllowedWithShiftOnly`.
function hasModifier(shortcut: Shortcut): boolean {
return shortcut.alt || shortcut.cmd || shortcut.ctrl;
}
function isAllowedWithShiftOnly(shortcut: Shortcut): boolean {
return (
shortcut.shift && (shortcut.key === "Escape" || /^F\d+$/.test(shortcut.key))
);
}
export function isRecognized(key: string): boolean {
return key !== "Dead" && key !== "Unidentified";
}
function getConflictingChars(
shortcuts: Array<Shortcut>,
charsString: string
): Array<string> {
const chars = charsString.split("");
return shortcuts.flatMap((shortcut) =>
hasModifier(shortcut)
? []
: chars.find((char) => char === shortcut.key) ?? []
);
}
export function getConflictingKeyboardActions(
defaultMappings: Array<KeyboardMapping>,
mappings: Array<KeyboardMapping>,
charsString: string
): Array<[KeyboardAction, Array<string>]> {
const chars = charsString.split("");
return defaultMappings
.map((defaultMapping): [KeyboardAction, Array<string>] => {
const shortcuts = mappings
.filter((mapping) => mapping.action === defaultMapping.action)
.map((mapping) => mapping.shortcut);
const conflicts = chars.filter((char) =>
shortcuts.some(
(shortcut) => shortcut.key === char && !hasModifier(shortcut)
)
);
return [defaultMapping.action, conflicts];
})
.filter(([, conflicts]) => conflicts.length > 0);
}
function getTextEditingShortcuts(mac: boolean): Array<Shortcut> {
function shortcut({
key,
alt = false,
cmd = false,
ctrl = false,
shift = false,
}: Partial<Shortcut> & { key: string }): Shortcut {
return { key, alt, cmd, ctrl, shift };
}
return mac
? [
shortcut({ key: "ArrowLeft", cmd: true }),
shortcut({ key: "ArrowLeft", cmd: true, shift: true }),
shortcut({ key: "ArrowLeft", alt: true }),
shortcut({ key: "ArrowLeft", alt: true, shift: true }),
shortcut({ key: "ArrowRight", cmd: true }),
shortcut({ key: "ArrowRight", cmd: true, shift: true }),
shortcut({ key: "ArrowRight", alt: true }),
shortcut({ key: "ArrowRight", alt: true, shift: true }),
shortcut({ key: "ArrowUp", cmd: true }),
shortcut({ key: "ArrowUp", cmd: true, shift: true }),
shortcut({ key: "ArrowUp", alt: true }),
shortcut({ key: "ArrowUp", alt: true, shift: true }),
shortcut({ key: "ArrowDown", cmd: true }),
shortcut({ key: "ArrowDown", cmd: true, shift: true }),
shortcut({ key: "ArrowDown", alt: true }),
shortcut({ key: "ArrowDown", alt: true, shift: true }),
shortcut({ key: "Backspace", cmd: true }),
shortcut({ key: "Backspace", alt: true }),
shortcut({ key: "a", cmd: true }),
shortcut({ key: "c", cmd: true }),
shortcut({ key: "v", cmd: true }),
shortcut({ key: "x", cmd: true }),
shortcut({ key: "z", cmd: true }),
]
: [
shortcut({ key: "ArrowLeft", ctrl: true }),
shortcut({ key: "ArrowLeft", ctrl: true, shift: true }),
shortcut({ key: "ArrowRight", ctrl: true }),
shortcut({ key: "ArrowRight", ctrl: true, shift: true }),
shortcut({ key: "ArrowUp", ctrl: true }),
shortcut({ key: "ArrowUp", ctrl: true, shift: true }),
shortcut({ key: "ArrowDown", ctrl: true }),
shortcut({ key: "ArrowDown", ctrl: true, shift: true }),
shortcut({ key: "Backspace", ctrl: true }),
shortcut({ key: "Delete", ctrl: true }),
shortcut({ key: "Home", ctrl: true }),
shortcut({ key: "End", ctrl: true }),
shortcut({ key: "a", ctrl: true }),
shortcut({ key: "c", ctrl: true }),
shortcut({ key: "v", ctrl: true }),
shortcut({ key: "x", ctrl: true }),
shortcut({ key: "z", ctrl: true }),
];
} | the_stack |
import {
expect
} from 'chai';
import {
generate, simulate
} from 'simulate-event';
import {
each, every
} from '@phosphor/algorithm';
import {
MessageLoop
} from '@phosphor/messaging';
import {
SplitPanel, SplitLayout, Widget
} from '@phosphor/widgets';
const renderer: SplitPanel.IRenderer = {
createHandle: () => document.createElement('div')
};
class LogSplitPanel extends SplitPanel {
events: string[] = [];
handleEvent(event: Event): void {
super.handleEvent(event);
this.events.push(event.type);
}
}
describe('@phosphor/widgets', () => {
describe('SplitPanel', () => {
describe('#constructor()', () => {
it('should accept no arguments', () => {
let panel = new SplitPanel();
expect(panel).to.be.an.instanceof(SplitPanel);
});
it('should accept options', () => {
let panel = new SplitPanel({
orientation: 'vertical', spacing: 5, renderer
});
expect(panel.orientation).to.equal('vertical');
expect(panel.spacing).to.equal(5);
expect(panel.renderer).to.equal(renderer);
});
it('should accept a layout option', () => {
let layout = new SplitLayout({ renderer });
let panel = new SplitPanel({ layout });
expect(panel.layout).to.equal(layout);
});
it('should ignore other options if a layout is given', () => {
let ignored = Object.create(renderer);
let layout = new SplitLayout({ renderer });
let panel = new SplitPanel({
layout, orientation: 'vertical', spacing: 5, renderer: ignored
});
expect(panel.layout).to.equal(layout);
expect(panel.orientation).to.equal('horizontal');
expect(panel.spacing).to.equal(4);
expect(panel.renderer).to.equal(renderer);
});
it('should add the `p-SplitPanel` class', () => {
let panel = new SplitPanel();
expect(panel.hasClass('p-SplitPanel')).to.equal(true);
});
});
describe('#dispose()', () => {
it('should dispose of the resources held by the panel', () => {
let panel = new LogSplitPanel();
let layout = panel.layout as SplitLayout;
let widgets = [new Widget(), new Widget(), new Widget()];
each(widgets, w => { panel.addWidget(w); });
Widget.attach(panel, document.body);
simulate(layout.handles[0], 'mousedown');
expect(panel.events).to.contain('mousedown');
simulate(panel.node, 'keydown');
expect(panel.events).to.contain('keydown');
let node = panel.node;
panel.dispose();
expect(every(widgets, w => w.isDisposed));
simulate(node, 'contextmenu');
expect(panel.events).to.not.contain('contextmenu');
});
});
describe('#orientation', () => {
it('should get the layout orientation for the split panel', () => {
let panel = new SplitPanel();
expect(panel.orientation).to.equal('horizontal');
});
it('should set the layout orientation for the split panel', () => {
let panel = new SplitPanel();
panel.orientation = 'vertical';
expect(panel.orientation).to.equal('vertical');
});
});
describe('#spacing', () => {
it('should default to `4`', () => {
let panel = new SplitPanel();
expect(panel.spacing).to.equal(4);
});
it('should set the spacing for the panel', () => {
let panel = new SplitPanel();
panel.spacing = 10;
expect(panel.spacing).to.equal(10);
});
});
describe('#renderer', () => {
it('should get the renderer for the panel', () => {
let panel = new SplitPanel({ renderer });
expect(panel.renderer).to.equal(renderer);
});
});
describe('#handles', () => {
it('should get the read-only sequence of the split handles in the panel', () => {
let panel = new SplitPanel();
let widgets = [new Widget(), new Widget(), new Widget()];
each(widgets, w => { panel.addWidget(w); });
expect(panel.handles.length).to.equal(3);
});
});
describe('#relativeSizes()', () => {
it('should get the current sizes of the widgets in the panel', () => {
let panel = new SplitPanel();
let widgets = [new Widget(), new Widget(), new Widget()];
each(widgets, w => { panel.addWidget(w); });
let sizes = panel.relativeSizes();
expect(sizes).to.deep.equal([1/3, 1/3, 1/3]);
});
});
describe('#setRelativeSizes()', () => {
it('should set the desired sizes for the widgets in the panel', () => {
let panel = new SplitPanel();
let widgets = [new Widget(), new Widget(), new Widget()];
each(widgets, w => { panel.addWidget(w); });
panel.setRelativeSizes([10, 20, 30]);
let sizes = panel.relativeSizes();
expect(sizes).to.deep.equal([10/60, 20/60, 30/60]);
});
it('should ignore extra values', () => {
let panel = new SplitPanel();
let widgets = [new Widget(), new Widget(), new Widget()];
each(widgets, w => { panel.addWidget(w); });
panel.setRelativeSizes([10, 30, 40, 20]);
let sizes = panel.relativeSizes();
expect(sizes).to.deep.equal([10/80, 30/80, 40/80]);
});
});
describe('#handleEvent()', () => {
let panel: LogSplitPanel;
let layout: SplitLayout;
beforeEach(() => {
panel = new LogSplitPanel();
layout = panel.layout as SplitLayout;
let widgets = [new Widget(), new Widget(), new Widget()];
each(widgets, w => { panel.addWidget(w); });
panel.setRelativeSizes([10, 10, 10, 20]);
Widget.attach(panel, document.body);
MessageLoop.flush();
});
afterEach(() => {
panel.dispose();
});
context('mousedown', () => {
it('should attach other event listeners', () => {
simulate(layout.handles[0], 'mousedown');
expect(panel.events).to.contain('mousedown');
simulate(document.body, 'mousemove');
expect(panel.events).to.contain('mousemove');
simulate(document.body, 'keydown');
expect(panel.events).to.contain('keydown');
simulate(document.body, 'contextmenu');
expect(panel.events).to.contain('contextmenu');
simulate(document.body, 'mouseup');
expect(panel.events).to.contain('mouseup');
});
it('should be a no-op if it is not the left button', () => {
simulate(layout.handles[0], 'mousedown', { button: 1 });
expect(panel.events).to.contain('mousedown');
simulate(document.body, 'mousemove');
expect(panel.events).to.not.contain('mousemove');
});
});
context('mousemove', () => {
it('should move the handle right', (done) => {
let handle = layout.handles[1];
let rect = handle.getBoundingClientRect();
simulate(handle, 'mousedown');
simulate(document.body, 'mousemove', { clientX: rect.left + 10, clientY: rect.top });
requestAnimationFrame(() => {
let newRect = handle.getBoundingClientRect();
expect(newRect.left).to.not.equal(rect.left);
done();
});
});
it('should move the handle down', (done) => {
panel.orientation = 'vertical';
each(panel.widgets, w => { w.node.style.minHeight = '20px'; });
let handle = layout.handles[1];
let rect = handle.getBoundingClientRect();
simulate(handle, 'mousedown');
simulate(document.body, 'mousemove', { clientX: rect.left, clientY: rect.top - 2 });
requestAnimationFrame(() => {
let newRect = handle.getBoundingClientRect();
expect(newRect.top).to.not.equal(rect.top);
done();
});
});
});
context('mouseup', () => {
it('should remove the event listeners', () => {
simulate(layout.handles[0], 'mousedown');
expect(panel.events).to.contain('mousedown');
simulate(document.body, 'mouseup');
expect(panel.events).to.contain('mouseup');
simulate(document.body, 'mousemove');
expect(panel.events).to.not.contain('mousemove');
simulate(document.body, 'keydown');
expect(panel.events).to.not.contain('keydown');
simulate(document.body, 'contextmenu');
expect(panel.events).to.not.contain('contextmenu');
});
it('should be a no-op if not the left button', () => {
simulate(layout.handles[0], 'mousedown');
expect(panel.events).to.contain('mousedown');
simulate(document.body, 'mouseup', { button: 1 });
expect(panel.events).to.contain('mouseup');
simulate(document.body, 'mousemove');
expect(panel.events).to.contain('mousemove');
});
});
context('keydown', () => {
it('should release the mouse if `Escape` is pressed', () => {
simulate(layout.handles[0], 'mousedown');
simulate(panel.node, 'keydown', { keyCode: 27 });
expect(panel.events).to.contain('keydown');
simulate(panel.node, 'mousemove');
expect(panel.events).to.not.contain('mousemove');
});
});
context('contextmenu', () => {
it('should prevent events during drag', () => {
simulate(layout.handles[0], 'mousedown');
let evt = generate('contextmenu');
let cancelled = !document.body.dispatchEvent(evt);
expect(cancelled).to.equal(true);
expect(panel.events).to.contain('contextmenu');
});
});
});
describe('#onAfterAttach()', () => {
it('should attach a mousedown listener to the node', () => {
let panel = new LogSplitPanel();
Widget.attach(panel, document.body);
simulate(panel.node, 'mousedown');
expect(panel.events).to.contain('mousedown');
panel.dispose();
});
});
describe('#onBeforeDetach()', () => {
it('should remove all listeners', () => {
let panel = new LogSplitPanel();
Widget.attach(panel, document.body);
simulate(panel.node, 'mousedown');
expect(panel.events).to.contain('mousedown');
Widget.detach(panel);
panel.events = [];
simulate(panel.node, 'mousedown');
expect(panel.events).to.not.contain('mousedown');
simulate(document.body, 'keyup');
expect(panel.events).to.not.contain('keyup');
});
});
describe('#onChildAdded()', () => {
it('should add a class to the child widget', () => {
let panel = new SplitPanel();
let widget = new Widget();
panel.addWidget(widget);
expect(widget.hasClass('p-SplitPanel-child')).to.equal(true);
});
});
describe('#onChildRemoved()', () => {
it('should remove a class to the child widget', () => {
let panel = new SplitPanel();
let widget = new Widget();
panel.addWidget(widget);
widget.parent = null;
expect(widget.hasClass('p-SplitPanel-child')).to.equal(false);
});
});
describe('.Renderer()', () => {
describe('#createHandle()', () => {
it('should create a new handle node', () => {
let renderer = new SplitPanel.Renderer();
let node1 = renderer.createHandle();
let node2 = renderer.createHandle();
expect(node1).to.be.an.instanceof(HTMLElement);
expect(node2).to.be.an.instanceof(HTMLElement);
expect(node1).to.not.equal(node2);
});
it('should add the "p-SplitPanel-handle" class', () => {
let renderer = new SplitPanel.Renderer();
let node = renderer.createHandle();
expect(node.classList.contains('p-SplitPanel-handle')).to.equal(true);
});
});
});
describe('.defaultRenderer', () => {
it('should be an instance of `Renderer`', () => {
expect(SplitPanel.defaultRenderer).to.be.an.instanceof(SplitPanel.Renderer);
});
});
describe('.getStretch()', () => {
it('should get the split panel stretch factor for the given widget', () => {
let widget = new Widget();
expect(SplitPanel.getStretch(widget)).to.equal(0);
});
});
describe('.setStretch()', () => {
it('should set the split panel stretch factor for the given widget', () => {
let widget = new Widget();
SplitPanel.setStretch(widget, 10);
expect(SplitPanel.getStretch(widget)).to.equal(10);
});
});
});
}); | the_stack |
import { left, right, chompLeft } from "string-left-right";
import { rApply } from "ranges-apply";
import { version as v } from "../package.json";
const version: string = v;
function isStr(something: any): boolean {
return typeof something === "string";
}
function stringifyPath(something: any): string {
if (Array.isArray(something)) {
return something.join(".");
}
if (isStr(something)) {
return something;
}
return String(something);
}
function stringifyAndEscapeValue(something: any): string {
console.log(
`020 ██ stringifyAndEscapeValue() called with ${JSON.stringify(
something,
null,
0
)} (${typeof something})`
);
// since incoming strings will come already wrapped with legit double quotes, we don't need to escape them
if (
isStr(something) &&
something.startsWith(`"`) &&
something.endsWith(`"`)
) {
return `${JSON.stringify(
something.slice(1, something.length - 1),
null,
0
)}`;
}
return JSON.stringify(something, null, 0);
}
/* istanbul ignore next */
function isNotEscape(str: string, idx: number): boolean {
if (str[idx] !== "\\") {
// log(`045 yes, it's not excaped`);
return true;
}
const temp = chompLeft(str, idx, { mode: 1 }, "\\");
// log(
// `${`\u001b[${33}m${`temp`}\u001b[${39}m`} = ${JSON.stringify(
// temp,
// null,
// 4
// )}; ${`\u001b[${33}m${`(idx - temp) % 2`}\u001b[${39}m`} = ${(idx - temp) %
// 2}`
// );
if (typeof temp === "number" && (idx - temp) % 2 !== 0) {
// log(`059 yes, it's not excaped`);
return true;
}
// log(`062 no, it's excaped!`);
return false;
}
interface Inputs {
str: string;
path: string;
valToInsert?: string | number;
mode: "set" | "del";
}
function main({ str, path, valToInsert, mode }: Inputs) {
let i = 0;
function log(something: any) {
// if (i > 80 && str[i] && str[i].trim()) {
// if (str[i] && str[i].trim()) {
if (str[i] !== " ") {
console.log(something);
}
}
const len = str.length;
const ranges = [];
log(`077 main(): MODE=${mode}`);
// bad characters
const badChars = ["{", "}", "[", "]", ":", ","];
let calculatedValueToInsert = valToInsert;
// if string is passed and it's not wrapped with double quotes,
// we must wrap it with quotes, we can't write it to JSON like that!
if (
isStr(valToInsert) &&
!(valToInsert as string).startsWith(`"`) &&
!(valToInsert as string).startsWith(`{`)
) {
calculatedValueToInsert = `"${valToInsert}"`;
}
// state trackers are arrays because both can be mixed of nested elements.
// Imagine, you caught the ending of an array. How do you know, are you within
// a (parent) array or within a (parent) object now?
// We are going to record starting indexes of each object or array opening,
// then pop them upon ending. This way we'll know exactly what's the depth
// and where we are currently.
const withinObjectIndexes = [];
const withinArrayIndexes = [];
let currentlyWithinObject = false;
let currentlyWithinArray = false;
// this mode is activated to instruct that the value must be replaced,
// no matter how deeply nested it is. It is activated once the path is matched.
// When this is on, we stop iterating each key/value and we capture only
// the whole value.
let replaceThisValue = false;
let keyStartedAt: number | null = null;
let keyEndedAt: number | null = null;
let valueStartedAt: number | null = null;
let valueEndedAt: number | null = null;
let keyName: string | null = null;
let keyValue: string | null = null;
let withinQuotesSince: number | undefined;
function withinQuotes() {
return typeof withinQuotesSince === "number";
}
let itsTheFirstElem = false;
const skipUntilTheFollowingIsMet = [];
function reset() {
keyStartedAt = null;
keyEndedAt = null;
valueStartedAt = null;
valueEndedAt = null;
keyName = null;
keyValue = null;
}
reset();
// it's object-path notation - arrays are joined with dots too -
// "arr.0.el.1.val" - instead of - "arr[0].el[1].val"
// we keep it as array so that we can array.push/array.pop to go levels up and down
const currentPath: (string | number)[] = [];
for (i = 0; i < len; i++) {
//
//
//
//
// TOP
//
//
//
//
// Logging:
// ███████████████████████████████████████
log(
`\n\u001b[${36}m${`===============================`}\u001b[${39}m \u001b[${35}m${`str[ ${i} ] = ${
str[i] && str[i].trim() ? str[i] : JSON.stringify(str[i], null, 0)
}`}\u001b[${39}m \u001b[${36}m${`===============================`}\u001b[${39}m\n`
);
// "within X" stage toggles
// openings are easy:
if (typeof withinQuotesSince !== "number" && str[i - 1] === "[") {
currentlyWithinArray = true;
if (str[i] !== "]") {
currentlyWithinObject = false;
console.log(
`175 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`currentlyWithinArray`}\u001b[${39}m`} = ${currentlyWithinArray}; ${`\u001b[${33}m${`currentlyWithinObject`}\u001b[${39}m`} = ${currentlyWithinObject}`
);
}
}
if (typeof withinQuotesSince !== "number" && str[i - 1] === "{") {
currentlyWithinObject = true;
if (str[i] !== "}") {
currentlyWithinArray = false;
console.log(
`185 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`currentlyWithinArray`}\u001b[${39}m`} = ${currentlyWithinArray}; ${`\u001b[${33}m${`currentlyWithinObject`}\u001b[${39}m`} = ${currentlyWithinObject}`
);
}
}
if (
typeof withinQuotesSince !== "number" &&
str[i] === "{" &&
isNotEscape(str, i - 1) &&
!replaceThisValue
) {
console.log(`196 object's start caught`);
if (currentlyWithinArray) {
// we can't push here first zero because opening bracket pushes the first
// zero in path - we only bump for second element onwards -
// that's needed to support empty arrays - if we waited for some value
// to be inside in order to bump the path, empty array inside an array
// would never get correct path and thus deleted/set.
//
if (!itsTheFirstElem) {
log(
`198 ${`\u001b[${33}m${`currentPath`}\u001b[${39}m`} = ${JSON.stringify(
currentPath,
null,
4
)}`
);
currentPath[currentPath.length - 1] =
(currentPath[currentPath.length - 1] as number) + 1;
log(
`207 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`currentPath[${
currentPath.length - 1
}]`}\u001b[${39}m`} = ${currentPath[currentPath.length - 1]}`
);
}
}
withinObjectIndexes.push(i);
log(
`215 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} ${`\u001b[${33}m${`withinObjectIndexes`}\u001b[${39}m`} = ${JSON.stringify(
withinObjectIndexes,
null,
4
)}`
);
}
if (
typeof withinQuotesSince !== "number" &&
str[i] === "}" &&
isNotEscape(str, i - 1) &&
!replaceThisValue
) {
withinObjectIndexes.pop();
log(
`231 ${`\u001b[${31}m${`POP`}\u001b[${39}m`} ${`\u001b[${33}m${`withinObjectIndexes`}\u001b[${39}m`} = ${JSON.stringify(
withinObjectIndexes,
null,
4
)}`
);
}
if (
typeof withinQuotesSince !== "number" &&
str[i] === "]" &&
isNotEscape(str, i - 1) &&
!replaceThisValue
) {
console.log(`254 inside sq. bracket clauses`);
withinArrayIndexes.pop();
log(
`248 ${`\u001b[${32}m${`POP`}\u001b[${39}m`} ${`\u001b[${33}m${`withinArrayIndexes`}\u001b[${39}m`} = ${JSON.stringify(
withinArrayIndexes,
null,
4
)}`
);
currentPath.pop();
log(`256 POP path, now = ${JSON.stringify(currentPath, null, 4)}`);
log(`258 ${`\u001b[${31}m${`RESET`}\u001b[${39}m`}`);
reset();
console.log(
`271 FIY, currentlyWithinObject = ${currentlyWithinObject}; currentlyWithinArray = ${currentlyWithinArray}`
);
if (itsTheFirstElem) {
itsTheFirstElem = false;
log(
`267 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`itsTheFirstElem`}\u001b[${39}m`} = ${itsTheFirstElem}`
);
}
}
if (typeof withinQuotesSince !== "number" && str[i] === "]") {
console.log(`282`);
if (!withinArrayIndexes.length) {
currentlyWithinArray = false;
console.log(
`286 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`currentlyWithinArray`}\u001b[${39}m`} = ${currentlyWithinArray}`
);
if (withinObjectIndexes.length && !currentlyWithinObject) {
currentlyWithinObject = true;
console.log(
`291 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} currentlyWithinObject = ${currentlyWithinObject}`
);
}
} else if (
withinArrayIndexes.length &&
(!withinObjectIndexes.length ||
withinArrayIndexes[withinArrayIndexes.length - 1] >
withinObjectIndexes[withinObjectIndexes.length - 1])
) {
console.log(
`301 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`currentlyWithinArray`}\u001b[${39}m`} = ${currentlyWithinArray}`
);
currentlyWithinArray = true;
}
}
if (typeof withinQuotesSince !== "number" && str[i] === "}") {
if (!withinObjectIndexes.length) {
console.log(
`310 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`currentlyWithinObject`}\u001b[${39}m`} = ${currentlyWithinObject}`
);
currentlyWithinObject = false;
} else if (
!withinArrayIndexes.length ||
withinObjectIndexes[withinObjectIndexes.length - 1] >
withinArrayIndexes[withinArrayIndexes.length - 1]
) {
console.log(
`319 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`currentlyWithinObject`}\u001b[${39}m`} = ${currentlyWithinObject}`
);
currentlyWithinObject = true;
}
}
// for arrays, this is the beginning of what to replace
console.log(`326 above of beginning of what to replace in arrays`);
if (
currentlyWithinArray &&
stringifyPath(path) === currentPath.join(".") &&
!replaceThisValue &&
str[i].trim()
// (stringifyPath(path) === currentPath.join(".") ||
// currentPath.join(".").endsWith(`.${stringifyPath(path)}`))
) {
console.log(`335 arrays - beginning of what to replace`);
replaceThisValue = true;
log(
`329 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`replaceThisValue`}\u001b[${39}m`} = ${replaceThisValue}`
);
valueStartedAt = i;
log(
`334 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`valueStartedAt`}\u001b[${39}m`} = ${valueStartedAt}`
);
}
if (
typeof withinQuotesSince !== "number" &&
str[i] === "[" &&
isNotEscape(str, i - 1) &&
!replaceThisValue
) {
console.log(`353 array's start caught`);
withinArrayIndexes.push(i);
itsTheFirstElem = true;
log(
`348 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} ${`\u001b[${33}m${`withinArrayIndexes`}\u001b[${39}m`} = ${JSON.stringify(
withinArrayIndexes,
null,
4
)}; ${`\u001b[${33}m${`itsTheFirstElem`}\u001b[${39}m`} = ${itsTheFirstElem}`
);
// if (left(str, i) !== null) {
// console.log(`356 it's not root-level array, so push zero into path`);
currentPath.push(0);
log(
`359 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} zero to path, now = ${JSON.stringify(
currentPath,
null,
0
)}`
);
// }
}
// catch comma within arrays
if (
currentlyWithinArray &&
str[i] === "," &&
itsTheFirstElem &&
!(typeof valueStartedAt === "number" && valueEndedAt === null) // precaution against comma within a string value
) {
// that empty array will have itsTheFirstElem still on:
// "e": [{}, ...],
itsTheFirstElem = false;
log(
`379 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`itsTheFirstElem`}\u001b[${39}m`} = ${itsTheFirstElem}`
);
}
//
//
//
//
//
//
//
//
// MIDDLE
//
//
//
//
//
//
//
//
// catch the start of a value
// in arrays, there are no keys, only values
//
// path-wise, object paths are calculated from the end of a key. Array paths
// are calculated from the start of the value (there are no keys). It's from
// the start, not from the end because it can be a big nested object, and
// by the time we'd reach its end, we'd have new keys and values recorded.
if (
!replaceThisValue &&
valueStartedAt === null &&
str[i].trim() &&
!badChars.includes(str[i]) &&
(currentlyWithinArray || (!currentlyWithinArray && keyName !== null))
) {
log(`415 catching the start of a value clauses`);
valueStartedAt = i;
log(
`418 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`valueStartedAt`}\u001b[${39}m`} = ${valueStartedAt}`
);
// calculate the path on arrays
if (currentlyWithinArray) {
if (itsTheFirstElem) {
itsTheFirstElem = false;
log(
`426 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`itsTheFirstElem`}\u001b[${39}m`} = ${itsTheFirstElem}`
);
} else if (typeof currentPath[currentPath.length - 1] === "number") {
currentPath[currentPath.length - 1] =
(currentPath[currentPath.length - 1] as number) + 1;
log(
`432 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`currentPath[${
currentPath.length - 1
}]`}\u001b[${39}m`} = ${currentPath[currentPath.length - 1]}`
);
}
}
}
// catch the end of a value
if (
!replaceThisValue &&
typeof withinQuotesSince !== "number" &&
(currentlyWithinArray || (!currentlyWithinArray && keyName !== null)) &&
typeof valueStartedAt === "number" &&
valueStartedAt < i &&
valueEndedAt === null &&
((str[valueStartedAt] === `"` && str[i] === `"` && str[i - 1] !== `\\`) ||
(str[valueStartedAt] !== `"` && !str[i].trim()) ||
["}", ","].includes(str[i]))
) {
log(`451 catching the end of a value clauses`);
keyValue = str.slice(
valueStartedAt,
str[valueStartedAt] === `"` ? i + 1 : i
);
log(
`457 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`keyValue`}\u001b[${39}m`} = ${keyValue}`
);
valueEndedAt = i;
log(
`461 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`valueEndedAt`}\u001b[${39}m`} = ${valueEndedAt}`
);
}
// catch the start of a key
if (
!replaceThisValue &&
!currentlyWithinArray &&
str[i] === `"` &&
str[i - 1] !== `\\` &&
keyName === null &&
keyStartedAt === null &&
keyEndedAt === null &&
str[i + 1]
) {
keyStartedAt = i + 1;
log(
`478 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`keyStartedAt`}\u001b[${39}m`} = ${keyStartedAt}`
);
}
// catch the end of a key
//
// path-wise, object paths are calculated from the end of a key. Array paths
// are calculated from the start of the value (there are no keys). It's from
// the start, not from the end because it can be a big nested object, and
// by the time we'd reach its end, we'd have new keys and values recorded.
if (
!replaceThisValue &&
!currentlyWithinArray &&
str[i] === `"` &&
str[i - 1] !== `\\` &&
keyEndedAt === null &&
typeof keyStartedAt === "number" &&
valueStartedAt === null &&
keyStartedAt < i
) {
keyEndedAt = i + 1;
keyName = str.slice(keyStartedAt, i);
log(
`501 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`keyEndedAt`}\u001b[${39}m`} = ${keyEndedAt}; ${`\u001b[${33}m${`keyName`}\u001b[${39}m`} = ${keyName}`
);
// set the path
currentPath.push(keyName);
log(`506 PUSH to path, now = ${JSON.stringify(currentPath, null, 4)}`);
// array cases don't come here so there are no conditionals for currentlyWithinArray
if (
stringifyPath(path) === currentPath.join(".") // ||
// currentPath.join(".").endsWith(`.${stringifyPath(path)}`)
) {
replaceThisValue = true;
log(
`515 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`replaceThisValue`}\u001b[${39}m`} = ${replaceThisValue}`
);
}
}
if (
!replaceThisValue &&
typeof withinQuotesSince !== "number" &&
str[i] === "," &&
currentlyWithinObject
) {
console.log(
`537 COMMA within object caught - before popping, ${`\u001b[${33}m${`currentPath`}\u001b[${39}m`} = ${JSON.stringify(
currentPath,
null,
0
)}`
);
currentPath.pop();
log(
`535 POP(), now ${`\u001b[${33}m${`currentPath`}\u001b[${39}m`} = ${JSON.stringify(
currentPath,
null,
0
)}`
);
}
if (
!replaceThisValue &&
((typeof valueEndedAt === "number" && i >= valueEndedAt) ||
(["}", "]"].includes(str[left(str, i) as number]) &&
["}", "]"].includes(str[i])) ||
(str[i] === "}" && str[left(str, i) as number] === "{")) &&
str[i].trim()
) {
log(
`552 ${`\u001b[${36}m${`██`}\u001b[${39}m`} catch the end of a key-value pair clauses`
);
if (
str[i] === "," &&
!["}", "]"].includes(str[right(str, i) as number])
) {
log(`555 ${`\u001b[${31}m${`RESET`}\u001b[${39}m`}`);
reset();
} else if (str[i] === "}") {
log(`558 closing curlie caught`);
if (valueEndedAt || str[left(str, i) as number] !== "{") {
console.log(
`574 before popping, ${`\u001b[${33}m${`currentPath`}\u001b[${39}m`} = ${JSON.stringify(
currentPath,
null,
0
)}`
);
currentPath.pop();
log(
`569 POP(), now ${`\u001b[${33}m${`currentPath`}\u001b[${39}m`} = ${JSON.stringify(
currentPath,
null,
0
)}`
);
}
log(`577 currently, currentlyWithinObject: ${currentlyWithinObject}`);
log(`578 currently, currentlyWithinArray: ${currentlyWithinArray}`);
if (
withinArrayIndexes.length &&
withinObjectIndexes.length &&
withinArrayIndexes[withinArrayIndexes.length - 1] >
withinObjectIndexes[withinObjectIndexes.length - 1]
) {
currentlyWithinObject = false;
currentlyWithinArray = true;
console.log(
`602 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`currentlyWithinObject`}\u001b[${39}m`} = ${currentlyWithinObject}; ${`\u001b[${33}m${`currentlyWithinArray`}\u001b[${39}m`} = ${currentlyWithinArray}`
);
}
// also reset but don't touch the path - rabbit hole goes deeper
log(`616 ${`\u001b[${31}m${`RESET`}\u001b[${39}m`}`);
reset();
}
}
// catch plain object as a value
if (
!replaceThisValue &&
str[i] === "{" &&
isStr(keyName) &&
valueStartedAt === null &&
keyValue === null
) {
// also reset but don't touch the path - rabbit hole goes deeper
log(`630 ${`\u001b[${31}m${`RESET`}\u001b[${39}m`}`);
reset();
}
// catch the start of the value when replaceThisValue is on
if (
str[i].trim() &&
replaceThisValue &&
valueStartedAt === null &&
typeof keyEndedAt === "number" &&
i > keyEndedAt &&
![":"].includes(str[i])
) {
valueStartedAt = i;
log(
`644 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`valueStartedAt`}\u001b[${39}m`} = ${valueStartedAt}`
);
}
// enable withinQuotesSince
if (
str[i] === `"` &&
isNotEscape(str, i - 1) &&
((typeof keyStartedAt === "number" && keyEndedAt === null) ||
(typeof valueStartedAt === "number" && valueEndedAt === null)) &&
typeof withinQuotesSince !== "number"
) {
withinQuotesSince = i;
log(
`658 SET ${`\u001b[${33}m${`withinQuotesSince`}\u001b[${39}m`} = ${withinQuotesSince}; withinQuotes = ${withinQuotes()}`
);
}
// The "skipUntilTheFollowingIsMet".
//
// Calculate going levels deep - curlies within quotes within brackets etc.
// idea is, once we stumble upon opening bracket/curlie or first double quote,
// no matter what follows, at first we march forward until we meet the first
// closing counterpart. Then we continue seeking what we came.
if (
skipUntilTheFollowingIsMet.length &&
str[i] ===
skipUntilTheFollowingIsMet[skipUntilTheFollowingIsMet.length - 1] &&
isNotEscape(str, i - 1)
) {
console.log(`666 POP clause`);
skipUntilTheFollowingIsMet.pop();
log(
`677 ${`\u001b[${32}m${`POP`}\u001b[${39}m`} skipUntilTheFollowingIsMet = ${JSON.stringify(
skipUntilTheFollowingIsMet,
null,
4
)}`
);
} else if (
(typeof withinQuotesSince !== "number" || withinQuotesSince === i) &&
replaceThisValue &&
!currentlyWithinArray &&
typeof valueStartedAt === "number"
) {
console.log(`681 about to catch various opening brackets/quotes`);
if (str[i] === "{" && isNotEscape(str, i - 1)) {
console.log(`683`);
skipUntilTheFollowingIsMet.push("}");
log(
`695 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} ${`\u001b[${33}m${`skipUntilTheFollowingIsMet`}\u001b[${39}m`} = ${JSON.stringify(
skipUntilTheFollowingIsMet,
null,
4
)}`
);
} else if (str[i] === "[" && isNotEscape(str, i - 1)) {
console.log(`693`);
skipUntilTheFollowingIsMet.push("]");
log(
`705 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} ${`\u001b[${33}m${`skipUntilTheFollowingIsMet`}\u001b[${39}m`} = ${JSON.stringify(
skipUntilTheFollowingIsMet,
null,
4
)}`
);
} else if (str[i] === `"` && isNotEscape(str, i - 1)) {
console.log(`703`);
skipUntilTheFollowingIsMet.push(`"`);
log(
`715 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} ${`\u001b[${33}m${`skipUntilTheFollowingIsMet`}\u001b[${39}m`} = ${JSON.stringify(
skipUntilTheFollowingIsMet,
null,
4
)}`
);
}
console.log(`713`);
}
//
//
//
//
//
//
//
//
//
// BOTTOM
//
//
//
//
//
//
//
//
// disable withinQuotesSince
if (
str[i] === `"` &&
isNotEscape(str, i - 1) &&
typeof withinQuotesSince === "number" &&
withinQuotesSince !== i
) {
withinQuotesSince = undefined;
log(
`753 RESET ${`\u001b[${33}m${`withinQuotesSince`}\u001b[${39}m`} = ${withinQuotesSince}; withinQuotes = ${withinQuotes()}`
);
}
// catch the end of the value when replaceThisValue is on
if (
replaceThisValue &&
Array.isArray(skipUntilTheFollowingIsMet) &&
!skipUntilTheFollowingIsMet.length &&
typeof valueStartedAt === "number" &&
i > valueStartedAt
) {
log(
`766 within catch the end of the value when replaceThisValue is on clauses`
);
if (
typeof withinQuotesSince !== "number" &&
((str[valueStartedAt] === "[" && str[i] === "]") ||
(str[valueStartedAt] === "{" && str[i] === "}") ||
(str[valueStartedAt] === `"` && str[i] === `"`) ||
(!["[", "{", `"`].includes(str[valueStartedAt]) &&
str[valueStartedAt].trim() &&
(!str[i].trim() ||
(badChars.includes(str[i]) && isNotEscape(str, i - 1))))) // cover numeric, bool, null etc, without quotes
) {
log(
`780 INSIDE CATCH-END CLAUSES currently ${`\u001b[${33}m${`str[valueStartedAt=${valueStartedAt}]`}\u001b[${39}m`} = ${JSON.stringify(
str[valueStartedAt],
null,
4
)}`
);
if (mode === "set") {
// 1. if set()
log(`789 ${`\u001b[${32}m${`RETURN`}\u001b[${39}m`}`);
let extraLineBreak = "";
if (
str
.slice(valueStartedAt, i + (str[i].trim() ? 1 : 0))
.includes("\n") &&
str[i + (str[i].trim() ? 1 : 0)] !== "\n"
) {
extraLineBreak = "\n";
}
let endingPartsBeginning = i + (str[i].trim() ? 1 : 0);
console.log(
`792 SET ${`\u001b[${33}m${`endingPartsBeginning`}\u001b[${39}m`} = ${JSON.stringify(
endingPartsBeginning,
null,
4
)}`
);
if (
(currentlyWithinArray &&
![`"`, `[`, `{`].includes(str[valueStartedAt]) &&
str[right(str, endingPartsBeginning - 1) as number] !== "]") ||
(str[endingPartsBeginning - 1] === "," &&
str[valueStartedAt - 1] !== `"`)
) {
console.log(
`807 endingPartsBeginning before = ${endingPartsBeginning}`
);
endingPartsBeginning -= 1;
console.log(
`811 endingPartsBeginning after = ${endingPartsBeginning}`
);
}
if (currentlyWithinArray && str[valueStartedAt - 1] === `"`) {
console.log(`816 valueStartedAt before = ${valueStartedAt}`);
valueStartedAt = valueStartedAt - 1;
console.log(`818 valueStartedAt after = ${valueStartedAt}`);
}
console.log(
`RETURNING:\n${`\u001b[${36}m${`[0, ${valueStartedAt}]`}\u001b[${39}m`}: ${JSON.stringify(
str.slice(0, valueStartedAt),
null,
0
)}\nstringifyAndEscapeValue(calculatedValueToInsert) = ${JSON.stringify(
stringifyAndEscapeValue(calculatedValueToInsert),
null,
0
)}\n${`\u001b[${36}m${`[${endingPartsBeginning}, ${str.length}]`}\u001b[${39}m`}: ${JSON.stringify(
str.slice(endingPartsBeginning),
null,
0
)}`
);
return `${str.slice(0, valueStartedAt)}${stringifyAndEscapeValue(
calculatedValueToInsert
)}${extraLineBreak}${str.slice(endingPartsBeginning)}`;
}
if (mode === "del") {
// 1. if del()
log(`848 ${`\u001b[${32}m${`RETURN`}\u001b[${39}m`}`);
log(
`851 ${`\u001b[${33}m${`keyStartedAt`}\u001b[${39}m`} = ${JSON.stringify(
keyStartedAt,
null,
4
)}; val = ${
((currentlyWithinArray
? valueStartedAt
: keyStartedAt) as number) - 1
}`
);
let startingPoint = left(
str,
((currentlyWithinArray ? valueStartedAt : keyStartedAt) as number) -
1
);
if (typeof startingPoint === "number") {
startingPoint++;
}
log(
`864 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} initial ${`\u001b[${33}m${`startingPoint`}\u001b[${39}m`} = ${startingPoint}`
);
let endingPoint = i + (str[i].trim() ? 1 : 0);
if (
typeof startingPoint === "number" &&
str[startingPoint - 1] === "," &&
["}", "]"].includes(str[right(str, endingPoint - 1) as number])
) {
startingPoint -= 1;
log(
`873 SET ${`\u001b[${33}m${`startingPoint`}\u001b[${39}m`} = ${startingPoint}`
);
}
if (str[endingPoint] === ",") {
endingPoint += 1;
log(
`879 SET ${`\u001b[${33}m${`endingPoint`}\u001b[${39}m`} = ${endingPoint}`
);
}
log(
`883 ${`\u001b[${33}m${`startingPoint`}\u001b[${39}m`} = ${JSON.stringify(
startingPoint,
null,
4
)}; ${`\u001b[${33}m${`endingPoint`}\u001b[${39}m`} = ${JSON.stringify(
endingPoint,
null,
4
)};`
);
ranges.push([startingPoint, endingPoint]);
log(
`896 ${`\u001b[${32}m${`FINAL PUSH`}\u001b[${39}m`} ${`\u001b[${33}m${`ranges`}\u001b[${39}m`} = ${JSON.stringify(
ranges,
null,
4
)}`
);
log(`902 then ${`\u001b[${31}m${`BREAK`}\u001b[${39}m`}`);
break;
}
}
// 2. replace non-quoted values
}
log(
`${`\u001b[${withinQuotesSince ? 32 : 31}m${`withinQuotesSince${
typeof withinQuotesSince === "number" ? `=${withinQuotesSince}` : ""
}`}\u001b[${39}m`}; ${`\u001b[${
currentlyWithinObject ? 32 : 31
}m${`currentlyWithinObject`}\u001b[${39}m`}; ${`\u001b[${
currentlyWithinArray ? 32 : 31
}m${`currentlyWithinArray`}\u001b[${39}m`}; ${`\u001b[${
replaceThisValue ? 32 : 31
}m${`replaceThisValue`}\u001b[${39}m`}; ${`\u001b[${
itsTheFirstElem ? 32 : 31
}m${`itsTheFirstElem`}\u001b[${39}m`}; ${`\u001b[${
skipUntilTheFollowingIsMet.length ? 32 : 31
}m${`skipUntilTheFollowingIsMet${
skipUntilTheFollowingIsMet
? `: ${JSON.stringify(skipUntilTheFollowingIsMet, null, 0)}`
: ""
}`}\u001b[${39}m`}`
);
log(`current path: ${JSON.stringify(currentPath.join("."), null, 0)}`);
log(
`${`\u001b[${33}m${`keyName`}\u001b[${39}m`} = ${keyName}; ${`\u001b[${33}m${`keyValue`}\u001b[${39}m`} = ${keyValue}; ${`\u001b[${33}m${`keyStartedAt`}\u001b[${39}m`} = ${keyStartedAt}; ${`\u001b[${33}m${`keyEndedAt`}\u001b[${39}m`} = ${keyEndedAt}; ${`\u001b[${33}m${`valueStartedAt`}\u001b[${39}m`} = ${valueStartedAt}; ${`\u001b[${33}m${`valueEndedAt`}\u001b[${39}m`} = ${valueEndedAt}`
);
log(
`${`\u001b[${33}m${`withinArrayIndexes`}\u001b[${39}m`} = ${JSON.stringify(
withinArrayIndexes,
null,
0
)}; ${`\u001b[${33}m${`withinObjectIndexes`}\u001b[${39}m`} = ${JSON.stringify(
withinObjectIndexes,
null,
0
)};`
);
}
log(`\n\u001b[${36}m${`=============================== FIN.`}\u001b[${39}m`);
log(
`947 RETURN applied ${JSON.stringify(rApply(str, ranges as any), null, 4)}`
);
return rApply(str, ranges as any);
}
function set(str: string, path: string, valToInsert: string | number): string {
console.log(`955 set()`);
if (!isStr(str) || !str.length) {
throw new Error(
`edit-package-json/set(): [THROW_ID_01] first input argument must be a non-empty string. It was given as ${JSON.stringify(
str,
null,
4
)} (type ${typeof str})`
);
}
return main({ str, path, valToInsert, mode: "set" });
}
function del(str: string, path: string): string {
console.log(`969 del()`);
if (!isStr(str) || !str.length) {
throw new Error(
`edit-package-json/del(): [THROW_ID_02] first input argument must be a non-empty string. It was given as ${JSON.stringify(
str,
null,
4
)} (type ${typeof str})`
);
}
// absence of what to insert means delete
return main({ str, path, mode: "del" });
}
export { set, del, version }; | the_stack |
import * as React from 'react';
import { useState, useEffect, useReducer } from 'react';
import styled from 'styled-components';
import { Button, Grommet, Text } from 'grommet';
import { grommet } from 'grommet/themes';
import { FormPrevious, FormNext } from "grommet-icons";
import * as actions from '../actions/actions';
import changeDisplayOfSidePanel from '../reducers/ChangeDisplayOfSidePanel';
import SidePanel from './SidePanel';
import ResultsContainer from './mainpanel/ResultsContainer';
import OmniBoxContainer from '../containers/omnibox/OmniBoxContainer';
const InvisibleHeader = styled.div`
height: 40px;
width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
background-color: #F7F9FD;
-webkit-app-region: drag;
transition: all 0.2s ease-in-out;
`;
const SRightHeaderWrapper = styled.div`
display: flex;
justify-content: center;
align-items: center;
margin: 0px 5px;
cursor: pointer;
`
const SHomepageWrapper = styled.div`
display: flex;
flex-direction: column;
height: 100vh;
width: 100vw;
transition: all 0.2s;
`;
interface ISRightPanelProps {
sidePanelVisibility: boolean;
}
const SMainPanelWrapper = styled.div`
display: flex;
height: 100%;
width: 100%;
transition: all 0.2s ease-in-out;
`
const SLeftPanelWrapper = styled.div`
height: 100%;
width: 100%;
display: flex;
flex-direction: column;
padding: 15px 10px 15px 15px;
background: #E6EAF2;
transition: all 0.2s ease-in-out;
`
const SRightPanelWrapper = styled.div<ISRightPanelProps>`
height: 100%;
width: ${({ sidePanelVisibility }) => sidePanelVisibility ? '250px' : '0px'};
transition: all 0.2s ease-in-out;
`
let relationships = {};
const alias = {};
const HomePage = ({ pgClient, tableData, setCurrentView }) => {
const [omniBoxView, setOmniBoxView] = useState('SQL');
const [overThreeTablesSelected, setOverThreeTablesSelected] = useState(false);
const [selectedForQueryTables, setSelectedForQueryTables] = useState({});
const [loadingQueryStatus, setLoadingQueryStatus] = useState(false);
const [activeDisplayInResultsTab, setActiveDisplayInResultsTab] = useState(
'Tables'
);
const [activeTableInPanel, setActiveTableInPanel] = useState({});
const [userInputForTables, setUserInputForTables] = useState('');
const [data, setData] = useState([]); // data from database
const [userInputQuery, setUserInputQuery] = useState(
'SELECT * FROM [table name]'
);
const [queryResult, setQueryResult] = useState({
status: 'No query',
message: []
});
const [sidePanelVisibility, setSidePanelVisibility] = useState(true);
const [redirectDueToInactivity, setRedirectDueToInactivity] = useState(false);
const [activePanel, dispatchSidePanelDisplay] = useReducer(
changeDisplayOfSidePanel,
'info'
);
const [queryResultError, setQueryResultError] = useState({
status: false,
message: ''
});
const resetQuerySelection = () => {
relationships = {};
setOverThreeTablesSelected(false)
setUserInputQuery('SELECT * FROM [table name]');
setSelectedForQueryTables({});
setQueryResultError({
status: false,
message: ''
});
};
// Track user inactivity, logout after 15 minutes
const [inactiveTime, setInactiveTime] = useState(0);
const [intervalId, captureIntervalId] = useState();
const logOut = () => {
setRedirectDueToInactivity(true);
clearInterval(intervalId);
}
useEffect(() => {
captureIntervalId(setInterval(() => setInactiveTime(inactiveTime => inactiveTime + 1), 60000));
return () => clearInterval(intervalId);
}, []);
useEffect(() => { if (inactiveTime >= 15) logOut() }, [inactiveTime]);
const captureQuerySelections = e => {
const selectedTableName = e.target.dataset.tablename;
const selectedColumnName = e.target.dataset.columnname;
let firstColumn = true;
let firstTable = true;
let pk = '';
const temp = selectedForQueryTables;
let columns = '';
let tables = '';
let query = '';
relationships[selectedTableName] = [];
// get relationships of FK
data.forEach(table => {
if (table.table_name === selectedTableName) {
pk = table.primaryKey;
table.foreignKeys.forEach(foreignkey => {
relationships[selectedTableName].push({
tablename: foreignkey.table_name,
colname: foreignkey.column_name,
fktablename: foreignkey.foreign_table_name,
fkcolname: foreignkey.foreign_column_name
});
});
}
});
// get relationships of PK
data.forEach(table => {
table.foreignKeys.forEach(foreignkey => {
if (
foreignkey.foreign_column_name == pk &&
foreignkey.foreign_table_name == selectedTableName
) {
relationships[selectedTableName].push({
tablename: foreignkey.foreign_table_name,
colname: foreignkey.foreign_column_name,
fktablename: foreignkey.table_name,
fkcolname: foreignkey.column_name
});
}
});
});
// builds the object used to write the query
for (let i = 0; i < data.length; i++) {
if (data[i].table_name === selectedTableName) {
// builds query selection object
// check if table already exists in query
if (Object.keys(temp).includes(selectedTableName)) {
// check if column name already exists
if (temp[selectedTableName].columns.includes(selectedColumnName)) {
// remove the column if it exists
const startIndex = temp[selectedTableName].columns.indexOf(
selectedColumnName
);
temp[selectedTableName].columns = temp[selectedTableName].columns
.slice(0, startIndex)
.concat(temp[selectedTableName].columns.slice(startIndex + 1));
// add it to the columns
} else {
temp[selectedTableName].columns.push(selectedColumnName);
}
// check if all items are selected
if (
temp[selectedTableName].columns.length ===
temp[selectedTableName].columncount
) {
temp[selectedTableName].all = true;
} else {
temp[selectedTableName].all = false;
}
// delete entire object if the columns are now empty
if (temp[selectedTableName].columns.length === 0) {
// if empty after removing
delete temp[selectedTableName];
delete relationships[selectedTableName];
delete alias[selectedTableName];
}
} else {
// first row and first table to be selected
temp[selectedTableName] = {
all: false,
columncount: data[i].columns.length,
columns: [selectedColumnName]
};
}
}
}
// query generation
// for no tables
if (Object.keys(temp).length === 0) {
query = 'SELECT * FROM[table name]';
}
// for one table
if (Object.keys(temp).length === 1) {
for (const table in temp) {
// check if all has been selected
if (temp[table].all) columns += '*';
else {
for (let i = 0; i < temp[table].columns.length; i++) {
if (firstColumn) {
columns += temp[table].columns[i];
firstColumn = false;
} else columns += `, ${temp[table].columns[i]}`;
}
}
}
tables = Object.keys(temp)[0];
query = `SELECT ${columns} FROM ${tables}`;
}
let previousTablePointer;
// for multiple joins
if (Object.keys(temp).length === 2) {
for (const table in temp) {
// loop through each table
let aliasIndex = 0;
let tableInitial = table[0];
while (Object.values(alias).includes(table[aliasIndex])) {
tableInitial += table[aliasIndex + 1];
aliasIndex++; // initial of each table
}
alias[table] = tableInitial;
tableInitial += '.';
// check if all the columns have been selected
if (temp[table].all) {
if (firstColumn) {
columns += `${tableInitial}*`;
firstColumn = false;
} else columns += `, ${tableInitial}*`;
} else {
// add each individual column name
for (let i = 0; i < temp[table].columns.length; i++) {
if (firstColumn) {
columns += tableInitial + temp[table].columns[i];
firstColumn = false;
} else {
columns += `, ${tableInitial}${temp[table].columns[i]}`;
}
}
}
// create the table name
if (firstTable) {
tables += `${table} as ${table[0]}`;
firstTable = false;
} else {
tables += ` INNER JOIN ${table} as ${alias[table]}`;
let rel = '';
relationships[table].forEach(relation => {
if (
relation.fktablename === previousTablePointer &&
relation.tablename === table
) {
rel =
`${alias[previousTablePointer]
}.${
relation.fkcolname
}=${
tableInitial + relation.colname}`;
}
});
tables += ` ON ${rel}`;
}
previousTablePointer = table;
}
// final query
query = `SELECT ${columns} FROM ${tables}`;
}
//error handle for 3+ joins
if (Object.keys(temp).length > 2) {
setOverThreeTablesSelected(true)
} else {
setOverThreeTablesSelected(false)
}
setUserInputQuery(query);
setSelectedForQueryTables(temp);
};
const togglePanelVisibility = () => {
if (sidePanelVisibility) {
setSidePanelVisibility(false);
setActiveTableInPanel({});
} else setSidePanelVisibility(true);
};
const captureSelectedTable = e => {
const { tablename } = e.target.dataset;
let selectedPanelInfo = {};
let primaryKey;
data.forEach(table => {
if (table.table_name === tablename) {
primaryKey = table.primaryKey;
selectedPanelInfo = table;
}
});
selectedPanelInfo.foreignKeysOfPrimary = {};
data.forEach(table => {
table.foreignKeys.forEach(foreignKey => {
if (
foreignKey.foreign_column_name == primaryKey &&
foreignKey.foreign_table_name == tablename
) {
selectedPanelInfo.foreignKeysOfPrimary[foreignKey.table_name] =
foreignKey.column_name;
}
});
});
setActiveTableInPanel('info');
setSidePanelVisibility(true);
setActiveTableInPanel(selectedPanelInfo);
dispatchSidePanelDisplay(actions.changeToInfoPanel());
};
// Fetches database information
useEffect((): void => {
setData(tableData);
}, [tableData]);
useEffect(() => {
if (queryResult.statusCode === 'Success') {
setQueryResult({
status: queryResult.message.length === 0 ? 'No results' : 'Success',
message: queryResult.message
});
setActiveDisplayInResultsTab('Query Results');
}
if (queryResult.statusCode === 'Invalid Request') {
setQueryResultError({
status: true,
message: queryResult.message
});
}
if (queryResult.statusCode === 'Syntax Error') {
setQueryResultError({
status: true,
message: `Syntax error in retrieving query results.
Error on: ${userInputQuery.slice(
0,
parseInt(queryResult.err.position) - 1
)} "
${userInputQuery.slice(
parseInt(queryResult.err.position) - 1,
parseInt(queryResult.err.position)
)} "
${userInputQuery.slice(parseInt(queryResult.err.position))};`
});
}
setLoadingQueryStatus(false);
}, [queryResult]);
return (
<Grommet theme={grommet}>
{redirectDueToInactivity && setCurrentView('loginPage')}
<SHomepageWrapper onMouseMove={() => setInactiveTime(0)}>
<InvisibleHeader>
<div></div>
<SRightHeaderWrapper onClick={togglePanelVisibility}>
<Text style={{ cursor: 'pointer', fontFamily: 'Poppins' }}> Menu</Text>
<Button
plain={true}
fill={false}
alignSelf="start"
margin="5px 0px"
style={{ cursor: 'pointer' }}
icon={sidePanelVisibility ? <FormNext size="medium" /> : <FormPrevious size="medium" />}
/>
</SRightHeaderWrapper>
</InvisibleHeader>
<SMainPanelWrapper className="main">
<SLeftPanelWrapper className="left">
<OmniBoxContainer
pgClient={pgClient}
setQueryResult={setQueryResult}
omniBoxView={omniBoxView}
setOmniBoxView={setOmniBoxView}
userInputForTables={userInputForTables}
loadingQueryStatus={loadingQueryStatus}
userInputQuery={userInputQuery}
setQueryResultError={setQueryResultError}
setLoadingQueryStatus={setLoadingQueryStatus}
setUserInputQuery={setUserInputQuery}
queryResultError={queryResultError}
setUserInputForTables={setUserInputForTables}
setActiveDisplayInResultsTab={setActiveDisplayInResultsTab}
/>
<ResultsContainer
relationships={relationships}
resetQuerySelection={resetQuerySelection}
captureQuerySelections={captureQuerySelections}
captureSelectedTable={captureSelectedTable}
activeDisplayInResultsTab={activeDisplayInResultsTab}
queryResult={queryResult}
data={data}
userInputForTables={userInputForTables}
setActiveDisplayInResultsTab={setActiveDisplayInResultsTab}
activeTableInPanel={activeTableInPanel}
selectedForQueryTables={selectedForQueryTables}
overThreeTablesSelected={overThreeTablesSelected}
/>
</SLeftPanelWrapper>
<SRightPanelWrapper className="right" sidePanelVisibility={sidePanelVisibility}>
{/* <Collapsible open={sidePanelVisibility} direction="horizontal" className="collapsible" style={{ height: "100%" }}> */}
<SidePanel
setCurrentView={setCurrentView}
intervalId={intervalId}
activePanel={activePanel}
dispatchSidePanelDisplay={dispatchSidePanelDisplay}
activeTableInPanel={activeTableInPanel}
sidePanelVisibility={sidePanelVisibility}
/>
{/* </Collapsible> */}
</SRightPanelWrapper>
</SMainPanelWrapper>
</SHomepageWrapper>
</Grommet >
);
};
export default HomePage; | the_stack |
const FileSync = require('lowdb/adapters/FileSync');
const low = require('lowdb');
/**
* Map-Interfaces are only there to be able to quick develop features
* if there are more options needed to be stored in database
* */
interface UserMap {
[userId: string]: number;
// id => (value:number = timestamp)
}
interface LikeMap {
[postId: string]: number;
// id => (value:number = timestamp)
}
export class StorageService {
protected readonly followerPath: string = 'followers';
protected readonly unfollowsPath: string = 'unfollows';
protected readonly likesPath: string = 'likes';
protected readonly dislikesPath: string = 'dislikes';
protected readonly followerObject = followerId =>
`${this.followerPath}.${followerId}`;
protected readonly unfollowerObject = followerId =>
`${this.unfollowsPath}.${followerId}`;
protected readonly likeObject = postId => `${this.likesPath}.${postId}`;
protected readonly disLikeObject = dislikeId =>
`${this.dislikesPath}.${dislikeId}`;
private adapter = new FileSync('db.json', {
defaultValue: {
[this.followerPath]: {},
[this.unfollowsPath]: {},
[this.likesPath]: {},
[this.dislikesPath]: {},
},
serialize: data => JSON.stringify(data),
deserialize: stringData => JSON.parse(stringData),
});
private database;
private waitTimeBeforeDeleteData: number;
private unfollowWaitTime: number;
constructor(options?:{
waitTimeBeforeDeleteData: number, // in minutes
unfollowWaitTime: number // in minutes
}) {
this.database = new low(this.adapter);
if(!options){
options = {
waitTimeBeforeDeleteData: 10080,
unfollowWaitTime: 4320
};
}
this.waitTimeBeforeDeleteData = (options.waitTimeBeforeDeleteData > 0)?options.waitTimeBeforeDeleteData * 60 : 10080 * 60;
this.unfollowWaitTime = (options.unfollowWaitTime > 0)?options.unfollowWaitTime * 60 : 4320 * 60;
}
//region has functions
/**
* checks if like exists in database
* */
public hasLike(postId: string): boolean {
return !!this.database.get(this.likeObject(postId)).value();
}
/**
* checks if dislike exists in database
* */
public hasDisLike(postId: string): boolean {
return !!this.database.get(this.disLikeObject(postId)).value();
}
/**
* checks if follower exists in database
* */
public hasFollower(followerId: string): boolean {
return !!this.database.get(this.followerObject(followerId)).value();
}
/**
* checks if unfollowed exists in database
* */
public hasUnFollowed(followerId: string): boolean {
return !!this.database.get(this.unfollowerObject(followerId)).value();
}
//endregion
//region length functions
/**
* gets the actual count of likes in database
* */
public getLikesLength() {
return Object.keys(this.getLikes()).length;
}
/**
* gets the actual count of dislikes in database
* */
public getDisLikesLength() {
return Object.keys(this.getDisLikes()).length;
}
/**
* gets the actual count of followers in database
* */
public getFollowersLength() {
return Object.keys(this.getFollowers()).length;
}
/**
* gets the actual count of unfollowed in database
* */
public getUnFollowsLength() {
return Object.keys(this.getUnfollowed()).length;
}
/**
* get number of the unfollowable users
* @returns count of the unfollowable users
* */
public getUnfollowableLength(time: number = this.unfollowWaitTime): number {
return Object.keys(this.getUnfollowable(time)).length;
}
/**
* get number of the dislikeable posts
* @returns count of the dislikeable posts
* */
public getDislikeableLength(time: number = 86400): number {
return Object.keys(this.getDislikeable(time)).length;
}
//endregion
//region get all from object
/**
* get all likes
* */
public getLikes(): LikeMap {
return this.database.get(this.likesPath).value();
}
/**
* get all disliked users
* */
public getDisLikes(): LikeMap {
return this.database.get(this.dislikesPath).value();
}
/**
* get all followed users
* */
public getFollowers(): UserMap {
return this.database.get(this.followerPath).value();
}
/**
* get all unfollowed users
* */
public getUnfollowed(): UserMap {
return this.database.get(this.unfollowsPath).value();
}
//endregion
//region clean functions
/**
* method to clear out all outdated data of the database
* */
public cleanUp(): void {
const unfollowed = this.getUnfollowed();
const disliked = this.getDisLikes();
/*clean up unfollowed*/
Object.keys(unfollowed).forEach(userId => {
if (
new Date(
unfollowed[userId] + this.waitTimeBeforeDeleteData * 1000,
).getTime() < new Date(Date.now()).getTime()
) {
// can delete, time passed
this.removeUnfollowed(userId);
}
});
/*clean up dislikes*/
Object.keys(disliked).forEach(postId => {
if (
new Date(
disliked[postId] + this.waitTimeBeforeDeleteData * 1000,
).getTime() < new Date(Date.now()).getTime()
) {
// can delete, time passed
this.removeDisLike(postId);
}
});
}
public wipeData(): void {
this.database.set(this.followerPath, {}).write();
this.database.set(this.unfollowsPath, {}).write();
this.database.set(this.likesPath, {}).write();
this.database.set(this.dislikesPath, {}).write();
}
//endregion
//region can functions
/**
* if post with specific postId can be liked
* based on if already liked or already disliked
* */
public canLike(postId: string): boolean {
return this.hasLike(postId) === false && this.hasDisLike(postId) === false;
}
/**
* if user with specific userId can be followed
* based on if already followed or already unfollowed
* */
public canFollow(userId: string): boolean {
return (
this.hasFollower(userId) === false && this.hasUnFollowed(userId) === false
);
}
//endregion
/**
* method to get all unfollowable users at the current moment.
* @param unfollowAllowedTime, minimum seconds that passed by to declare user to be unfollowable
* @retuns object containing all users that can be unfollowed at the moment
* */
public getUnfollowable(unfollowAllowedTime: number = this.unfollowWaitTime): UserMap {
const followed = this.getFollowers();
const canUnfollow = {};
Object.keys(followed).forEach(key => {
if (
new Date(followed[key] + unfollowAllowedTime * 1000).getTime() <
new Date(Date.now()).getTime()
) {
// can unfollow, time passed
canUnfollow[key] = followed[key];
}
});
return canUnfollow;
}
/**
* method to get all dislikeable users at the current moment.
* @param dislikeAllowTime, minimum seconds that passed by to declare user to be dislikeable
* @retuns object containing all posts that can be disliked at the moment
* */
public getDislikeable(dislikeAllowTime: number = 86400): LikeMap {
const likes = this.getLikes();
const canDislike = {};
Object.keys(likes).forEach(key => {
if (
new Date(likes[key] + dislikeAllowTime * 1000).getTime() <
new Date(Date.now()).getTime()
) {
// can dislike, time passed
canDislike[key] = likes[key];
}
});
return canDislike;
}
/**
* Removes followed user from followers and add him to the unfollowed list
* */
public unFollowed(userId: string) {
//remove from followers
this.removeFollower(userId);
//add to unfollowed
this.addUnfollowed(userId);
}
/**
* Removes liked post from liked posts and add it to the disliked ones
* */
public disLiked(postId: string) {
this.removeLike(postId);
this.addDisLiked(postId);
}
//region remove functions
private removeLike(postId: string) {
if (this.hasLike(postId) === true) {
//remove from likes
this.database
.set(
this.likesPath,
this.database
.get(this.likesPath)
.omit(postId)
.value(),
)
.write();
}
//else do nothing, like not present
}
private removeDisLike(postId: string) {
if (this.hasDisLike(postId) === true) {
//remove from dislikes
this.database
.set(
this.dislikesPath,
this.database
.get(this.dislikesPath)
.omit(postId)
.value(),
)
.write();
}
//else do nothing, dislike not present
}
private removeFollower(userId: string) {
if (this.hasFollower(userId) === true) {
//remove from followers
this.database
.set(
this.followerPath,
this.database
.get(this.followerPath)
.omit(userId)
.value(),
)
.write();
}
//else do nothing, follower not present
}
private removeUnfollowed(userId: string) {
if (this.hasUnFollowed(userId) === true) {
//remove from followers
this.database
.set(
this.unfollowsPath,
this.database
.get(this.unfollowsPath)
.omit(userId)
.value(),
)
.write();
}
//else do nothing, unfollowed not present
}
//endregion
//region add functions
/**
* Adds a follower to the followers list
* */
public addFollower(followerId: string) {
this.database.set(`${this.followerPath}.${followerId}`, Date.now()).write();
}
/**
* Adds a post to the liked posts list
* */
public addLike(postId: string) {
this.database.set(this.likeObject(postId), Date.now()).write();
}
/**
* Add user to the already followed and unfollowed again list
* */
private addUnfollowed(userId: string) {
this.database.set(this.unfollowerObject(userId), Date.now()).write();
}
/**
* Adds post to the already liked and disliked again list
* */
private addDisLiked(postId: string) {
this.database.set(this.disLikeObject(postId), Date.now()).write();
}
//endregion
} | the_stack |
import * as indent from 'indent-string';
import { pull, union, head, concat, trim } from 'lodash';
import { Param, Widget } from './models/flutter-model';
import { findAndRemoveParam, findParam, multiline, unquote, getWidgetChildren } from './tools';
import { Options } from './watcher';
import { camelCase, upperCaseFirst } from 'change-case';
/** A flutter-view parameter */
type FVParam = {
name: string,
type?: string,
value?: string,
optional?: boolean
}
/**
* Render the text for the .dart file, containing the dart functions to create the widgets
* @param widgets the widgets code to render
* @param imports imports to add to the file
* @param options flutter-view options
* @returns the generated dart code
*/
export function renderDartFile(dartFile: string, widgets: Widget[], imports: string[], options: Options) : string {
const pugFileName = dartFile.replace('.dart', '.pug')
const allImports = union(options.imports, imports)
return multiline(
renderClassImports(allImports),
'',
widgets
.filter(isFlutterView)
.map(widget=>renderFlutterView(widget, options))
.join('\r\n\r\n'),
renderHelperFunctions(options)
)
/**
* Renders as dart text a list of imports.
* @param imports a list of imports to render as code
* @returns the generated dart code
*/
function renderClassImports(imports: string[]) : string {
if(!imports) return ''
return imports.map(_import => `// ignore: unused_import\nimport '${_import}';`).join('\r\n')
}
/**
* Render a single widget function that builds a flutter-view widget tree
* @param widget the widget to render
* @param options flutter-view options
* @returns the generated dart code
*/
function renderFlutterView(widget: Widget, options: Options) : string | null {
const fields = getFlutterViewParameters(widget)
const child = head(getWidgetChildren(widget))
let returnType = child.name
switch(returnType) {
case 'Slot':
case 'Call': { returnType = 'Widget'; break }
case 'Array': { returnType = 'List'; break }
default: {
const dotPosition = returnType.indexOf('.')
if(dotPosition > 0) returnType = returnType.substr(0, dotPosition)
}
}
return multiline(
'// ignore: non_constant_identifier_names',
`${returnType} ${renderFlutterViewConstructor(widget.name, fields)} {`,
indent(renderFlutterViewBody(child, options), options.indentation),
`}`
)
}
/**
* Extract the flutter-view params from the top level widget
* @param widget a top level widget, representing the widget function
* @returns a list of fields
*/
function getFlutterViewParameters(widget: Widget) : FVParam[] {
function toFVParam(param: Param) {
const paramValueRegExp = /([a-z\-]+)(\[[a-zA-Z]+\])?(\?)?/g // format: appModel[AppModel]?
const match = paramValueRegExp.exec(param.value.toString())
return match ? {
name: camelCase(match[1]),
type: trim(match[2], '[]'),
optional: match[3] == '?'
} : null
}
if(widget.params) {
return widget.params
.filter(p=>p.type=='expression' && !p.resolved && p.value)
.map(toFVParam)
.filter(p=>p)
} else {
return []
}
}
/**
* Renders the constructor of a flutter view
* @param name The name of the flutter view
* @param params the flutter view fields to add to the constructor
* @returns the generated dart code
*/
function renderFlutterViewConstructor(name: string, params: FVParam[]) : string {
function renderParameter(param: FVParam) : string {
const required = !param.optional ? '@required ' : ''
const defaultValue = param.type == 'bool' ? ' = false' : ''
const declaration = param.type ? `${param.type} ${param.name}${defaultValue}` : param.name
return required + declaration
}
if(params.length > 0) {
return `${name}({ ${params.map(param=>renderParameter(param)).join(', ')} })`
} else {
return `${name}()`
}
}
function renderFlutterViewBody(widget: Widget, options: Options) {
const widgetCode = renderWidget(widget, options)
return `return ${widgetCode};`;
}
/**
* The most important method, this one recursively builds the whole tree into code.
* It will go into the parameters of the widget, extract the widgets from there, and
* then render that code, etc. The result is the rendered code of the full widget.
* @param widget the widget to render, including its descendants (through its parameters)
* @param options the flutter-view options
* @returns the generated dart code
*/
function renderWidget(widget: Widget, options: Options) : string {
if(!widget) return '\n'
if(widget.name=='Call') {
const methodParam = findAndRemoveParam(widget, 'method', {
includeExpressions: true,
includeResolved: true
})
if(!methodParam || !methodParam.value) throw 'call tags requires a method property'
const method = methodParam.value
return multiline(
`${method}(`,
indent(renderParams(widget, options), options.indentation),
')'
)
}
if(widget.name=='Slot') {
// if the slot has a direct value, render that value
const valueParam = findParam(widget, undefined, true)
if(valueParam && valueParam.value) {
if(valueParam.type == 'expression') return valueParam.value.toString()
if(valueParam.type == 'literal') return '"' + valueParam.value.toString() + '"'
}
// if the slot has children, render them as options, since only one gets shown at max
const childrenParam = findParam(widget, 'children', true)
if(!childrenParam || !childrenParam.value) return 'Container()'
const children = childrenParam.value as Widget[]
return multiline(
children.map(child=>renderSlotChild(child)).join(':\n'),
'// ignore: dead_code',
': Container()'
)
/**
* render a single optional slot child
* @param child the child to add to the slot
*/
function renderSlotChild(child: Widget) {
const ifParam = findAndRemoveParam(child, 'if')
if(ifParam && ifParam.value) {
return multiline(
`(${ifParam.value}) ?`,
indent(multiline(
'// ignore: dead_code',
renderWidget(child, options)
), options.indentation)
)
} else {
return multiline(
`true ?`,
indent(multiline(
'// ignore: dead_code',
renderWidget(child, options)
), options.indentation)
)
}
}
}
// if this is a function, create a Dart function which returns the child tree
// of the function
if(widget.name=='Function') {
const paramsParam = findParam(widget, 'params', true)
const params = paramsParam ? paramsParam.value : ''
const childParam = findParam(widget, 'child', true)
if(!childParam || !childParam.value) return 'null'
const child = childParam.value as Widget
return multiline(
`(${params}) {`,
indent(`return ${renderWidget(child, options)};`, options.indentation),
`}`
)
}
// if this widget has an if property, write code that either renders the widget,
// or that replaces it with an empty container.
const ifParam = findParam(widget, 'if', true)
const forParam = findParam(widget, 'for', true)
if(ifParam) {
pull(widget.params, ifParam)
const elseValue = (forParam && forParam.value) ? '[Container()]' : 'Container()'
if(ifParam.value) {
return `${unquote(ifParam.value.toString())} ? ${renderWidget(widget, options)} : ${elseValue}`
} else {
console.warn(`${widget.name} has an if property without a condition`)
}
}
// if this widget has a for property, repeatedly render it
if(forParam) {
const result = parseForExpression(forParam.value.toString())
pull(widget.params, forParam)
return multiline(
(result.index)
? multiline(
`(${result.list} as List).asMap().entries.map((entry) {`,
indent(multiline(
`final index = entry.key;`,
`final ${result.param} = entry.value;`
), options.indentation)
)
: `(${result.list} as List).map((${result.param}) {`,
indent(multiline(
`return`,
renderWidget(widget, options)+';'
), options.indentation),
`}).toList()`,
)
}
// remove id and class attributes
const ids = findAndRemoveParam(widget, 'id', {
includeExpressions: true,
includeResolved: true
})
const classes = findAndRemoveParam(widget, 'class', {
includeExpressions: true,
includeResolved: true
})
// create comment line based on ids and classes on the tag
let separatorComment : string
if(options.showCommentsInDart) {
let htmlIdentifiers = []
if(ids && ids.value) {
htmlIdentifiers = concat(htmlIdentifiers, ids.value.toString().split(' '))
}
if(classes && classes.value) {
htmlIdentifiers = concat(htmlIdentifiers, classes.value.toString().split(' '))
}
if(htmlIdentifiers.length > 0) {
separatorComment = htmlIdentifiers.map(name=>name.toUpperCase()).join(' / ')
}
}
// render the widget class with the parameters
const genericParams = widget.generics ? `<${widget.generics.join(',')}>` : ''
const constructorParam = findAndRemoveParam(widget, 'constructor', {
includeExpressions: true,
includeResolved: true
})
const name = constructorParam ? `${widget.name}.${constructorParam.value}` : widget.name
let pugLineComment = ''
if(options.showPugLineNumbers && widget.pugLine != null) {
pugLineComment = `// project://${pugFileName}#${widget.pugLine},${widget.pugColumn}`
}
return multiline(
separatorComment ? `\n//-- ${separatorComment} ----------------------------------------------------------` : null,
`${widget.constant?'const ':''}${name}${genericParams}( ${pugLineComment}`,
indent(renderParams(widget, options), options.indentation),
`)`
)
}
/**
* Renders the parameters of a widget. Since a parameter can contain another widget,
* this is part of the recursive process of renderWidget.
* @param widget the widget to render the parameters for
* @param options the flutter-view options
* @returns the generated dart code
*/
function renderParams(widget: Widget, options: Options) : string {
const renderedParams : string[] = []
const paramsToRender = widget.params ? widget.params.filter(param=>param.name!='const') : null
if(paramsToRender) {
for(var param of paramsToRender) {
if(param.name) {
const name = unquote(param.name)
renderedParams.push(`${name}: ${renderParamValue(param, options)}`)
} else {
renderedParams.push(renderParamValue(param, options))
}
}
}
const trailing = (paramsToRender && paramsToRender.length > 0) ? ',' : ''
return renderedParams.join(',\n') + trailing
}
/**
* Renders the value of a widget parameter. Since a parameter can contain another widget,
* this is part of the recursive process of renderWidget.
* @param widget the widget to render the parameters for
* @param options the flutter-view options
* @returns the generated dart code
*/
function renderParamValue(param: Param, options: Options) : string {
switch(param.type) {
case 'literal': {
return `'${param.value}'`
}
case 'expression': {
return `${param.value ? param.value.toString() : ''}`
}
case 'closure': {
if(!param.value) return ''
return `() { ${param.value}; }`
}
case 'widget': {
const value = param.value as Widget
const _const = findParam(value, 'const', true) ? 'const ' : ''
return `${_const}${renderWidget(param.value as Widget, options)}`
}
case 'array': {
const widgets = param.value as Widget[]
const values = widgets.map(widget=>`${renderWidget(widget, options)}`)
return multiline(
`[`,
indent(values.join(',\n'), options.indentation),
`]`
)
}
case 'widgets': {
const widgets = param.value as Widget[]
const values = widgets.map(widget=>`${renderWidget(widget, options)}`)
// in for loops we generate arrays. these arrays may already be in an array,
// so we will want to flatten these arrays of arrays before adding them
return multiline(
`__flatten([`,
indent(values.join(',\n'), options.indentation),
`])`
)
}
}
throw `unknown parameter type ${param.type}`
}
/**
* Render the helper methods for the widget, to be added to the dartfile,
* so we do not need to import an external lib.
* @param options the flutter-view options
* @returns the generated dart code
*/
function renderHelperFunctions(options: Options) : string {
return multiline(
'// ignore: unused_element',
'__flatten(List list) {',
indent(
multiline(
'return List<Widget>.from(list.expand((item) {',
indent(
'return item is Iterable ? item : [item as Widget];',
options.indentation
),
'}));'
),
options.indentation
),
'}'
)
}
}
/**
* Parse the parameter passed into a for tag
* @param expression the parameter passed
* @returns the name of the iterating parameter and the name of the list being iterated
*/
function parseForExpression(expression: string) : { param: string, index?: string, list: string } {
const regexp3params = /(\w+), (\w+)? in ([\$\(\)\w.]+)/g
const match3 = regexp3params.exec(expression)
if(match3) return { param: match3[1], index: match3[2], list: match3[3] }
const regexp2params = /(\w+) in ([\$\(\)\w.]+)/g
const match2 = regexp2params.exec(expression)
if(match2) return { param: match2[1], list: match2[2] }
throw `Invalid for expression: "${expression}"`
}
function isFlutterView(widget: Widget) {
return !!findParam(widget, 'flutterView', true)
} | the_stack |
import { find, throttle } from "@daybrush/utils";
import {
RenderGuidelineInfo, Renderer, RenderGuidelineInnerInfo,
MoveableManagerInterface, SnappableProps, SnapGuideline,
SnappableOptions, SnappableRenderType, GapGuideline, SnappableState,
} from "../../types";
import { prefix, flat, groupBy } from "../../utils";
const DIRECTION_NAMES = {
horizontal: [
"left",
"top",
"width",
"Y",
"X",
] as const,
vertical: [
"top", "left", "height", "X", "Y",
] as const,
} as const;
export function groupByElementGuidelines(
guidelines: SnapGuideline[],
clientPos: number,
size: number,
index: number
) {
const groupInfos: Array<[Element, number, any]> = [];
const group = groupBy(
guidelines.filter(({ element, gap }) => element && !gap),
({ element, pos }) => {
const elementPos = pos[index];
const sign = Math.min(0, elementPos - clientPos) < 0 ? -1 : 1;
const groupKey = `${sign}_${pos[index ? 0 : 1]}`;
const groupInfo = find(groupInfos, ([groupElement, groupPos]) => {
return element === groupElement && elementPos === groupPos;
});
if (groupInfo) {
return groupInfo[2];
}
groupInfos.push([element!, elementPos, groupKey]);
return groupKey;
}
);
group.forEach((elementGuidelines) => {
elementGuidelines.sort((a, b) => {
const result =
getElementGuidelineDist(a.pos[index], a.size, clientPos, size)
.size -
getElementGuidelineDist(b.pos[index], a.size, clientPos, size)
.size;
return result || a.pos[index ? 0 : 1] - b.pos[index ? 0 : 1];
});
});
return group;
}
export function getElementGuidelineDist(
elementPos: number,
elementSize: number,
targetPos: number,
targetSize: number
) {
// relativePos < 0 => element(l) --- (r)target
// relativePos > 0 => target(l) --- (r)element
const relativePos = elementPos - targetPos;
const startPos = relativePos < 0 ? relativePos + elementSize : targetSize;
const endPos = relativePos < 0 ? 0 : relativePos;
const size = endPos - startPos;
return {
size,
pos: startPos,
};
}
export function renderGuideline(info: RenderGuidelineInfo, React: Renderer): any {
const { direction, classNames, size, pos, zoom, key } = info;
const isHorizontal = direction === "horizontal";
const scaleDirection = isHorizontal ? "Y" : "X";
// const scaleDirection2 = isHorizontal ? "Y" : "X";
return React.createElement("div", {
key,
className: classNames.join(" "),
style: {
[isHorizontal ? "width" : "height"]: `${size}`,
transform: `translate(${pos[0]}, ${pos[1]}) translate${scaleDirection}(-50%) scale${scaleDirection}(${zoom})`,
},
});
}
export function renderInnerGuideline(info: RenderGuidelineInnerInfo, React: Renderer): any {
return renderGuideline({
...info,
classNames: [
prefix("line", "guideline", info.direction),
...info.classNames,
].filter(className => className) as string[],
size: info.size || `${info.sizeValue}px`,
pos: info.pos || info.posValue.map(v => `${throttle(v, 0.1)}px`),
}, React);
}
export function renderElementGroups(
moveable: MoveableManagerInterface<SnappableProps>,
direction: "vertical" | "horizontal",
groups: SnapGuideline[][],
minPos: number,
clientPos: number,
clientSize: number,
targetPos: number,
snapThreshold: number,
snapDigit: number,
index: number,
snapDistFormat: Required<SnappableOptions>["snapDistFormat"],
React: Renderer
) {
const { zoom, isDisplaySnapDigit = true } = moveable.props;
const [posName1, posName2, sizeName, , scaleDirection] = DIRECTION_NAMES[direction];
return flat(
groups.map((elementGuidelines, i) => {
let isFirstRenderSize = true;
return elementGuidelines.map(({ pos, size }, j) => {
const {
pos: linePos,
size: lineSize,
} = getElementGuidelineDist(
pos[index],
size,
clientPos,
clientSize
);
if (lineSize < snapThreshold) {
return null;
}
const isRenderSize = isFirstRenderSize;
isFirstRenderSize = false;
const snapSize =
isDisplaySnapDigit && isRenderSize
? parseFloat(lineSize.toFixed(snapDigit))
: 0;
return (
<div
key={`${direction}LinkGuideline${i}-${j}`}
className={prefix("guideline-group", direction)}
style={{
[posName1]: `${minPos + linePos}px`,
[posName2]: `${-targetPos + pos[index ? 0 : 1]}px`,
[sizeName]: `${lineSize}px`,
}}
>
{renderInnerGuideline(
{
direction: direction,
classNames: [prefix("dashed")],
size: "100%",
posValue: [0, 0],
sizeValue: lineSize,
zoom: zoom!,
},
React
)}
<div
className={prefix("size-value")}
style={{
transform: `translate${scaleDirection}(-50%) scale(${zoom})`,
}}
>
{snapSize > 0 ? snapDistFormat(snapSize) : ""}
</div>
</div>
);
});
})
);
}
export function renderSnapPoses(
moveable: MoveableManagerInterface,
direction: string,
snapPoses: SnappableRenderType[],
minPos: number,
targetPos: number,
size: number,
index: number,
React: Renderer
) {
const { zoom } = moveable.props;
return snapPoses.map(({ type, pos }, i) => {
const renderPos = [0, 0];
renderPos[index] = minPos;
renderPos[index ? 0 : 1] = -targetPos + pos;
return renderInnerGuideline(
{
key: `${direction}TargetGuideline${i}`,
classNames: [prefix("target", "bold", type)],
posValue: renderPos,
sizeValue: size,
zoom: zoom!,
direction: direction,
},
React
);
});
}
export function filterElementInnerGuidelines(
moveable: MoveableManagerInterface<SnappableProps>,
guidelines: SnapGuideline[],
index: number,
targetPos: number[],
clientPos: number[],
targetSizes: number[],
) {
const { isDisplayInnerSnapDigit } = moveable.props;
const innerGuidelines: SnapGuideline[] = [];
const otherIndex = index ? 0 : 1;
const targetContentPos = targetPos[index];
const targetContentSize = targetSizes[index];
let gapGuidelines: GapGuideline[] = [];
let nextGuidelines = guidelines.filter(guideline => {
const { element, pos, size } = guideline;
if (
isDisplayInnerSnapDigit && element
&& pos[index] < targetContentPos && targetContentPos + targetContentSize < pos[index] + size
) {
innerGuidelines.push(guideline);
const contentPos = pos[index] - targetContentPos;
const inlinePos = pos[otherIndex] - targetPos[otherIndex];
gapGuidelines.push({
...guideline,
inner: true,
gap: contentPos,
renderPos: index ? [inlinePos, contentPos] : [contentPos, inlinePos],
});
gapGuidelines.push({
...guideline,
inner: true,
gap: pos[index] + size - targetContentPos - targetContentSize,
renderPos: index ? [inlinePos, targetContentSize] : [targetContentSize, inlinePos],
});
return false;
}
return true;
});
nextGuidelines = nextGuidelines.filter(guideline1 => {
const {
element: element1,
pos: pos1,
size: size1,
} = guideline1;
const contentPos1 = pos1[index];
if (!element1) {
return true;
}
return nextGuidelines.every(guideline2 => {
const {
element: element2,
pos: pos2,
size: size2,
} = guideline2;
const contentPos2 = pos2[index];
if (!element2 || guideline1 === guideline2) {
return true;
}
return contentPos1 + size1 <= contentPos2
|| contentPos2 + size2 <= contentPos1
|| (contentPos1 < contentPos2 && contentPos2 + size2 < contentPos1 + size1);
});
});
const groups = groupByElementGuidelines(
nextGuidelines,
clientPos[index],
targetContentSize,
index,
);
gapGuidelines = gapGuidelines.filter(guideline => {
const gap = guideline.gap!;
const inlinePos = guideline.pos[otherIndex];
return groups.every(group => {
return group.every(groupGuideline => {
const groupPos = groupGuideline.pos;
const renderPos = -targetContentPos + groupPos[index];
if (groupPos[otherIndex] !== inlinePos) {
return true;
}
if (gap < 0 && renderPos < 0) {
return false;
}
if (gap > 0 && renderPos > targetSizes[index]) {
return false;
}
return true;
});
});
});
return {
guidelines: nextGuidelines,
groups,
gapGuidelines,
};
}
export function renderGuidelines(
moveable: MoveableManagerInterface<SnappableProps>,
direction: string,
guidelines: SnapGuideline[],
targetPos: number[],
React: Renderer
) {
const { zoom } = moveable.props;
return guidelines.filter(({ hide }) => {
return !hide;
}).map((guideline, i) => {
const { pos, size, element } = guideline;
const renderPos = [
-targetPos[0] + pos[0],
-targetPos[1] + pos[1],
];
return renderInnerGuideline(
{
key: `${direction}Guideline${i}`,
classNames: element ? [prefix("bold")] : [],
direction: direction,
posValue: renderPos,
sizeValue: size,
zoom: zoom!,
},
React
);
});
}
export function renderGapGuidelines(
moveable: MoveableManagerInterface<SnappableProps, SnappableState>,
direction: "vertical" | "horizontal",
gapGuidelines: GapGuideline[],
snapDistFormat: Required<SnappableOptions>["snapDistFormat"],
React: any
): any[] {
const { snapDigit = 0, isDisplaySnapDigit = true, zoom } = moveable.props;
const scaleDirection = direction === "horizontal" ? "X" : "Y";
const sizeName = direction === "horizontal" ? "width" : "height";
return gapGuidelines.map(({ renderPos, gap, className, inner }, i) => {
const absGap = Math.abs(gap!);
const snapSize = isDisplaySnapDigit
? parseFloat(absGap.toFixed(snapDigit))
: 0;
return (
<div
key={`${direction}GapGuideline${i}`}
className={prefix("guideline-group", direction)}
style={{
left: `${renderPos[0]}px`,
top: `${renderPos[1]}px`,
[sizeName]: `${absGap}px`,
}}
>
{renderInnerGuideline(
{
direction: direction,
classNames: [prefix(inner ? "dashed" : "gap"), className],
size: "100%",
posValue: [0, 0],
sizeValue: absGap,
zoom: zoom!,
},
React
)}
<div
className={prefix("size-value", "gap")}
style={{
transform: `translate${scaleDirection}(-50%) scale(${zoom})`,
}}
>
{snapSize > 0 ? snapDistFormat(snapSize) : ""}
</div>
</div>
);
});
} | the_stack |
import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.m.js';
import 'chrome://resources/cr_elements/cr_link_row/cr_link_row.js';
import 'chrome://resources/cr_elements/shared_style_css.m.js';
import './collapse_radio_button.js';
import './secure_dns.js';
import '../controls/settings_radio_group.js';
import '../controls/settings_toggle_button.js';
import '../icons.js';
import '../prefs/prefs.js';
import '../settings_shared_css.js';
import './disable_safebrowsing_dialog.js';
import {assert} from 'chrome://resources/js/assert.m.js';
import {focusWithoutInk} from 'chrome://resources/js/cr/ui/focus_without_ink.m.js';
import {I18nMixin, I18nMixinInterface} from 'chrome://resources/js/i18n_mixin.js';
import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {SettingsRadioGroupElement} from '../controls/settings_radio_group.js';
import {loadTimeData} from '../i18n_setup.js';
import {MetricsBrowserProxy, MetricsBrowserProxyImpl, PrivacyElementInteractions, SafeBrowsingInteractions} from '../metrics_browser_proxy.js';
import {OpenWindowProxyImpl} from '../open_window_proxy.js';
import {PrefsMixin, PrefsMixinInterface} from '../prefs/prefs_mixin.js';
import {routes} from '../route.js';
import {Route, RouteObserverMixin, RouteObserverMixinInterface, Router} from '../router.js';
import {SettingsCollapseRadioButtonElement} from './collapse_radio_button.js';
import {SettingsDisableSafebrowsingDialogElement} from './disable_safebrowsing_dialog.js';
import {PrivacyPageBrowserProxy, PrivacyPageBrowserProxyImpl} from './privacy_page_browser_proxy.js';
/**
* Enumeration of all safe browsing modes. Must be kept in sync with the enum
* of the same name located in:
* chrome/browser/safe_browsing/generated_safe_browsing_pref.h
*/
export enum SafeBrowsingSetting {
ENHANCED = 0,
STANDARD = 1,
DISABLED = 2,
}
type FocusConfig = Map<string, (string|(() => void))>;
export interface SettingsSecurityPageElement {
$: {
safeBrowsingRadioGroup: SettingsRadioGroupElement,
safeBrowsingEnhanced: SettingsCollapseRadioButtonElement,
safeBrowsingStandard: SettingsCollapseRadioButtonElement,
safeBrowsingDisabled: SettingsCollapseRadioButtonElement,
};
}
const SettingsSecurityPageElementBase =
RouteObserverMixin(I18nMixin(PrefsMixin(PolymerElement))) as {
new (): PolymerElement & I18nMixinInterface &
RouteObserverMixinInterface & PrefsMixinInterface
};
export class SettingsSecurityPageElement extends
SettingsSecurityPageElementBase {
static get is() {
return 'settings-security-page';
}
static get template() {
return html`{__html_template__}`;
}
static get properties() {
return {
/**
* Preferences state.
*/
prefs: {
type: Object,
notify: true,
},
/**
* Whether the HTTPS-Only Mode setting should be displayed.
*/
showHttpsOnlyModeSetting_: {
type: Boolean,
readOnly: true,
value: function() {
return loadTimeData.getBoolean('showHttpsOnlyModeSetting');
},
},
/**
* Whether the secure DNS setting should be displayed.
*/
showSecureDnsSetting_: {
type: Boolean,
readOnly: true,
value: function() {
return loadTimeData.getBoolean('showSecureDnsSetting');
},
},
// <if expr="chromeos or lacros">
/**
* Whether a link to secure DNS OS setting should be displayed.
*/
showSecureDnsSettingLink_: {
type: Boolean,
readOnly: true,
value: function() {
return loadTimeData.getBoolean('showSecureDnsSettingLink');
},
},
// </if>
/**
* Valid safe browsing states.
*/
safeBrowsingSettingEnum_: {
type: Object,
value: SafeBrowsingSetting,
},
enableSecurityKeysSubpage_: {
type: Boolean,
readOnly: true,
value() {
return loadTimeData.getBoolean('enableSecurityKeysSubpage');
}
},
focusConfig: {
type: Object,
observer: 'focusConfigChanged_',
},
showDisableSafebrowsingDialog_: Boolean,
};
}
private showHttpsOnlyModeSetting_: boolean;
private showSecureDnsSetting_: boolean;
// <if expr="chromeos or lacros">
private showSecureDnsSettingLink_: boolean;
// </if>
private enableSecurityKeysSubpage_: boolean;
focusConfig: FocusConfig;
private showDisableSafebrowsingDialog_: boolean;
private browserProxy_: PrivacyPageBrowserProxy =
PrivacyPageBrowserProxyImpl.getInstance();
private metricsBrowserProxy_: MetricsBrowserProxy =
MetricsBrowserProxyImpl.getInstance();
private focusConfigChanged_(_newConfig: FocusConfig, oldConfig: FocusConfig) {
assert(!oldConfig);
// <if expr="use_nss_certs">
if (routes.CERTIFICATES) {
this.focusConfig.set(routes.CERTIFICATES.path, () => {
focusWithoutInk(
assert(this.shadowRoot!.querySelector('#manageCertificates')!));
});
}
// </if>
if (routes.SECURITY_KEYS) {
this.focusConfig.set(routes.SECURITY_KEYS.path, () => {
focusWithoutInk(assert(
this.shadowRoot!.querySelector('#security-keys-subpage-trigger')!));
});
}
}
ready() {
super.ready();
// Expand initial pref value manually because automatic
// expanding is disabled.
const prefValue = this.getPref('generated.safe_browsing').value;
if (prefValue === SafeBrowsingSetting.ENHANCED) {
this.$.safeBrowsingEnhanced.expanded = true;
} else if (prefValue === SafeBrowsingSetting.STANDARD) {
this.$.safeBrowsingStandard.expanded = true;
}
}
/**
* RouteObserverMixin
*/
currentRouteChanged(route: Route) {
if (route === routes.SECURITY) {
this.metricsBrowserProxy_.recordSafeBrowsingInteractionHistogram(
SafeBrowsingInteractions.SAFE_BROWSING_SHOWED);
const queryParams = Router.getInstance().getQueryParameters();
const section = queryParams.get('q');
if (section === 'enhanced') {
this.$.safeBrowsingEnhanced.expanded = true;
this.$.safeBrowsingStandard.expanded = false;
}
}
}
/**
* Updates the buttons' expanded status by propagating previous click
* events
*/
private updateCollapsedButtons_() {
this.$.safeBrowsingEnhanced.updateCollapsed();
this.$.safeBrowsingStandard.updateCollapsed();
}
/**
* Possibly displays the Safe Browsing disable dialog based on the users
* selection.
*/
private onSafeBrowsingRadioChange_() {
const selected =
Number.parseInt(this.$.safeBrowsingRadioGroup.selected, 10);
const prefValue = this.getPref('generated.safe_browsing').value;
if (prefValue !== selected) {
this.recordInteractionHistogramOnRadioChange_(selected);
this.recordActionOnRadioChange_(selected);
}
if (selected === SafeBrowsingSetting.DISABLED) {
this.showDisableSafebrowsingDialog_ = true;
} else {
this.updateCollapsedButtons_();
this.$.safeBrowsingRadioGroup.sendPrefChange();
}
}
private getDisabledExtendedSafeBrowsing_(): boolean {
return this.getPref('generated.safe_browsing').value !==
SafeBrowsingSetting.STANDARD;
}
private getPasswordsLeakToggleSubLabel_(): string {
let subLabel = this.i18n('passwordsLeakDetectionGeneralDescription');
// If the backing password leak detection preference is enabled, but the
// generated preference is off and user control is disabled, then additional
// text explaining that the feature will be enabled if the user signs in is
// added.
const generatedPref = this.getPref('generated.password_leak_detection');
if (this.getPref('profile.password_manager_leak_detection').value &&
!generatedPref.value && generatedPref.userControlDisabled) {
subLabel +=
' ' + // Whitespace is a valid sentence separator w.r.t. i18n.
this.i18n('passwordsLeakDetectionSignedOutEnabledDescription');
}
return subLabel;
}
private onManageCertificatesClick_() {
// <if expr="use_nss_certs">
Router.getInstance().navigateTo(routes.CERTIFICATES);
// </if>
// <if expr="is_win or is_macosx">
this.browserProxy_.showManageSSLCertificates();
// </if>
this.metricsBrowserProxy_.recordSettingsPageHistogram(
PrivacyElementInteractions.MANAGE_CERTIFICATES);
}
private onAdvancedProtectionProgramLinkClick_() {
window.open(loadTimeData.getString('advancedProtectionURL'));
}
private onSecurityKeysClick_() {
Router.getInstance().navigateTo(routes.SECURITY_KEYS);
}
private onSafeBrowsingExtendedReportingChange_() {
this.metricsBrowserProxy_.recordSettingsPageHistogram(
PrivacyElementInteractions.IMPROVE_SECURITY);
}
/**
* Handles the closure of the disable safebrowsing dialog, reselects the
* appropriate radio button if the user cancels the dialog, and puts focus on
* the disable safebrowsing button.
*/
private onDisableSafebrowsingDialogClose_() {
const confirmed =
this.shadowRoot!.querySelector('settings-disable-safebrowsing-dialog')!
.wasConfirmed();
this.recordInteractionHistogramOnSafeBrowsingDialogClose_(confirmed);
this.recordActionOnSafeBrowsingDialogClose_(confirmed);
// Check if the dialog was confirmed before closing it.
if (confirmed) {
this.$.safeBrowsingRadioGroup.sendPrefChange();
this.updateCollapsedButtons_();
} else {
this.$.safeBrowsingRadioGroup.resetToPrefValue();
}
this.showDisableSafebrowsingDialog_ = false;
// Set focus back to the no protection button regardless of user interaction
// with the dialog, as it was the entry point to the dialog.
focusWithoutInk(assert(this.$.safeBrowsingDisabled));
}
private onEnhancedProtectionExpandButtonClicked_() {
this.recordInteractionHistogramOnExpandButtonClicked_(
SafeBrowsingSetting.ENHANCED);
this.recordActionOnExpandButtonClicked_(SafeBrowsingSetting.ENHANCED);
}
private onStandardProtectionExpandButtonClicked_() {
this.recordInteractionHistogramOnExpandButtonClicked_(
SafeBrowsingSetting.STANDARD);
this.recordActionOnExpandButtonClicked_(SafeBrowsingSetting.STANDARD);
}
// <if expr="chromeos or lacros">
private onOpenChromeOSSecureDnsSettingsClicked_() {
const path =
loadTimeData.getString('chromeOSPrivacyAndSecuritySectionPath');
OpenWindowProxyImpl.getInstance().openURL(`chrome://os-settings/${path}`);
}
// </if>
private recordInteractionHistogramOnRadioChange_(safeBrowsingSetting:
SafeBrowsingSetting) {
let action;
if (safeBrowsingSetting === SafeBrowsingSetting.ENHANCED) {
action =
SafeBrowsingInteractions.SAFE_BROWSING_ENHANCED_PROTECTION_CLICKED;
} else if (safeBrowsingSetting === SafeBrowsingSetting.STANDARD) {
action =
SafeBrowsingInteractions.SAFE_BROWSING_STANDARD_PROTECTION_CLICKED;
} else {
action =
SafeBrowsingInteractions.SAFE_BROWSING_DISABLE_SAFE_BROWSING_CLICKED;
}
this.metricsBrowserProxy_.recordSafeBrowsingInteractionHistogram(action);
}
private recordInteractionHistogramOnExpandButtonClicked_(
safeBrowsingSetting: SafeBrowsingSetting) {
this.metricsBrowserProxy_.recordSafeBrowsingInteractionHistogram(
safeBrowsingSetting === SafeBrowsingSetting.ENHANCED ?
SafeBrowsingInteractions
.SAFE_BROWSING_ENHANCED_PROTECTION_EXPAND_ARROW_CLICKED :
SafeBrowsingInteractions
.SAFE_BROWSING_STANDARD_PROTECTION_EXPAND_ARROW_CLICKED);
}
private recordInteractionHistogramOnSafeBrowsingDialogClose_(confirmed:
boolean) {
this.metricsBrowserProxy_.recordSafeBrowsingInteractionHistogram(
confirmed ? SafeBrowsingInteractions
.SAFE_BROWSING_DISABLE_SAFE_BROWSING_DIALOG_CONFIRMED :
SafeBrowsingInteractions
.SAFE_BROWSING_DISABLE_SAFE_BROWSING_DIALOG_DENIED);
}
private recordActionOnRadioChange_(safeBrowsingSetting: SafeBrowsingSetting) {
let actionName;
if (safeBrowsingSetting === SafeBrowsingSetting.ENHANCED) {
actionName = 'SafeBrowsing.Settings.EnhancedProtectionClicked';
} else if (safeBrowsingSetting === SafeBrowsingSetting.STANDARD) {
actionName = 'SafeBrowsing.Settings.StandardProtectionClicked';
} else {
actionName = 'SafeBrowsing.Settings.DisableSafeBrowsingClicked';
}
this.metricsBrowserProxy_.recordAction(actionName);
}
private recordActionOnExpandButtonClicked_(safeBrowsingSetting:
SafeBrowsingSetting) {
this.metricsBrowserProxy_.recordAction(
safeBrowsingSetting === SafeBrowsingSetting.ENHANCED ?
'SafeBrowsing.Settings.EnhancedProtectionExpandArrowClicked' :
'SafeBrowsing.Settings.StandardProtectionExpandArrowClicked');
}
private recordActionOnSafeBrowsingDialogClose_(confirmed: boolean) {
this.metricsBrowserProxy_.recordAction(
confirmed ? 'SafeBrowsing.Settings.DisableSafeBrowsingDialogConfirmed' :
'SafeBrowsing.Settings.DisableSafeBrowsingDialogDenied');
}
}
customElements.define(
SettingsSecurityPageElement.is, SettingsSecurityPageElement); | the_stack |
import {Constants} from "../../../../scripts/constants";
import {ClipperState} from "../../../../scripts/clipperUI/clipperState";
import {ClipMode} from "../../../../scripts/clipperUI/clipMode";
import {Status} from "../../../../scripts/clipperUI/status";
import {AugmentationModel} from "../../../../scripts/contentCapture/augmentationHelper";
import {AugmentationPreview} from "../../../../scripts/clipperUI/components/previewViewer/augmentationPreview";
import {Assert} from "../../../assert";
import {MithrilUtils} from "../../../mithrilUtils";
import {MockProps} from "../../../mockProps";
import {TestModule} from "../../../testModule";
declare function require(name: string);
export class AugmentationPreviewTests extends TestModule {
private stringsJson = require("../../../../strings.json");
private sansSerifFontFamily = this.stringsJson["WebClipper.FontFamily.Preview.SansSerifDefault"];
private sansSerifDefaultFontSize = this.stringsJson["WebClipper.FontSize.Preview.SansSerifDefault"];
private serifFontFamily = this.stringsJson["WebClipper.FontFamily.Preview.SerifDefault"];
private fontSizeStep = Constants.Settings.fontSizeStep;
protected module() {
return "augmentationPreview";
}
protected tests() {
test("The tab order flow from the header to the preview title is correct in Augmentation mode", () => {
let mockClipperState = this.getMockAugmentationModeState();
let defaultComponent = <AugmentationPreview clipperState={mockClipperState} />;
MithrilUtils.mountToFixture(defaultComponent);
MithrilUtils.simulateAction(() => {
document.getElementById(Constants.Ids.serif).click();
});
Assert.tabOrderIsIncremental([Constants.Ids.highlightButton, Constants.Ids.serif, Constants.Ids.decrementFontSize,
Constants.Ids.incrementFontSize, Constants.Ids.previewHeaderInput]);
MithrilUtils.simulateAction(() => {
document.getElementById(Constants.Ids.sansSerif).click();
});
Assert.tabOrderIsIncremental([Constants.Ids.highlightButton, Constants.Ids.sansSerif, Constants.Ids.decrementFontSize,
Constants.Ids.incrementFontSize, Constants.Ids.previewHeaderInput]);
});
test("When a pair of codependent buttons have conditional attributes, they both respond with the same behavior when clicked and have different values from each other", () => {
let mockClipperState = this.getMockAugmentationModeState();
let defaultComponent = <AugmentationPreview clipperState={mockClipperState} />;
MithrilUtils.mountToFixture(defaultComponent);
MithrilUtils.simulateAction(() => {
document.getElementById(Constants.Ids.serif).click();
});
let selectedTabIndices = [document.getElementById(Constants.Ids.serif).tabIndex];
let unselectedTabIndices = [document.getElementById(Constants.Ids.sansSerif).tabIndex];
MithrilUtils.simulateAction(() => {
document.getElementById(Constants.Ids.sansSerif).click();
});
selectedTabIndices.push(document.getElementById(Constants.Ids.sansSerif).tabIndex);
unselectedTabIndices.push(document.getElementById(Constants.Ids.serif).tabIndex);
strictEqual(selectedTabIndices[0], selectedTabIndices[1], "When the serif button is clicked the tabIndex should be the same as the tabIndex of the sansSerif button when clicked");
ok(selectedTabIndices[0] > 0, "Selected tabIndex should be greater than 0");
strictEqual(unselectedTabIndices[0], unselectedTabIndices[1], "When the serif button is not clicked the tabIndex should be the same as the tabIndex of the sansSerif button when not clicked");
strictEqual(unselectedTabIndices[0], -1, "The unselected tabsIndices should be -1");
});
test("The aria-posinset attribute should flow in order, assuming they are all available", () => {
let mockClipperState = this.getMockAugmentationModeState();
let defaultComponent = <AugmentationPreview clipperState={mockClipperState} />;
MithrilUtils.mountToFixture(defaultComponent);
Assert.checkAriaSetAttributes([Constants.Ids.sansSerif, Constants.Ids.serif]);
});
test("The augmentation header and all related controls should be displayed in Augmentation mode", () => {
let mockClipperState = this.getMockAugmentationModeState();
let defaultComponent = <AugmentationPreview clipperState={mockClipperState} />;
MithrilUtils.mountToFixture(defaultComponent);
ok(!document.getElementById(Constants.Ids.addRegionControl), "The region control should not exist");
ok(document.getElementById(Constants.Ids.highlightControl), "The highlight control should exist");
ok(document.getElementById(Constants.Ids.serifControl), "The font family control should exist");
ok(document.getElementById(Constants.Ids.decrementFontSize), "The decrement font size control should exist");
ok(document.getElementById(Constants.Ids.incrementFontSize), "The increment font size control should exist");
});
test("The editable title of the page should be displayed in the preview title in Augmentation mode", () => {
let mockClipperState = this.getMockAugmentationModeState();
let defaultComponent = <AugmentationPreview clipperState={mockClipperState} />;
MithrilUtils.mountToFixture(defaultComponent);
let previewHeaderInput = document.getElementById(Constants.Ids.previewHeaderInput) as HTMLTextAreaElement;
strictEqual(previewHeaderInput.value, mockClipperState.previewGlobalInfo.previewTitleText,
"The title of the page should be displayed in the preview title");
ok(!previewHeaderInput.readOnly);
});
test("The augmented content of the page should be displayed in the highlightable preview body in Augmentation Mode", () => {
let mockClipperState = this.getMockAugmentationModeState();
let defaultComponent = <AugmentationPreview clipperState={mockClipperState} />;
MithrilUtils.mountToFixture(defaultComponent);
strictEqual(document.getElementById(Constants.Ids.highlightablePreviewBody).innerHTML,
mockClipperState.augmentationPreviewInfo.previewBodyHtml,
"The editable augmentation result content is displayed in the preview body's highlightable portion");
});
test("When the augmentation successfully completes, but no data is returned, the preview should indicate no content was found in Augmentation mode", () => {
let clipperState = MockProps.getMockClipperState();
clipperState.currentMode.set(ClipMode.Augmentation);
clipperState.augmentationResult = {
data: undefined,
status: Status.Succeeded
};
MithrilUtils.mountToFixture(<AugmentationPreview clipperState={clipperState} />);
let previewHeaderInput = document.getElementById(Constants.Ids.previewHeaderInput) as HTMLTextAreaElement;
strictEqual(previewHeaderInput.value, this.stringsJson["WebClipper.Preview.NoContentFound"],
"The preview title should display a message indicating no content was found");
ok(previewHeaderInput.readOnly);
strictEqual(document.getElementById(Constants.Ids.previewBody).innerText, "",
"The preview body should be empty");
});
test("When the call to augmentation has not started, the preview should indicate that it is loading in Augmentation mode", () => {
let clipperState = MockProps.getMockClipperState();
clipperState.currentMode.set(ClipMode.Augmentation);
clipperState.augmentationResult = {
data: undefined,
status: Status.NotStarted
};
MithrilUtils.mountToFixture(<AugmentationPreview clipperState={clipperState} />);
let previewHeaderInput = document.getElementById(Constants.Ids.previewHeaderInput) as HTMLTextAreaElement;
strictEqual(previewHeaderInput.value, this.stringsJson["WebClipper.Preview.LoadingMessage"],
"The preview title should display a loading message");
ok(previewHeaderInput.readOnly);
let previewBody = document.getElementById(Constants.Ids.previewBody);
strictEqual(previewBody.getElementsByClassName(Constants.Classes.spinner).length, 1,
"The spinner should be present in the preview body");
});
test("When augmentation is in progress, the preview should indicate that it is loading in Augmentation mode", () => {
let clipperState = MockProps.getMockClipperState();
clipperState.currentMode.set(ClipMode.Augmentation);
clipperState.augmentationResult = {
data: undefined,
status: Status.InProgress
};
MithrilUtils.mountToFixture(<AugmentationPreview clipperState={clipperState} />);
let previewHeaderInput = document.getElementById(Constants.Ids.previewHeaderInput) as HTMLTextAreaElement;
strictEqual(previewHeaderInput.value, this.stringsJson["WebClipper.Preview.LoadingMessage"],
"The preview title should display a loading message");
ok(previewHeaderInput.readOnly);
let previewBody = document.getElementById(Constants.Ids.previewBody);
strictEqual(previewBody.getElementsByClassName(Constants.Classes.spinner).length, 1,
"The spinner should be present in the preview body");
});
test("When the call to augmentation has not started, the preview should indicate that it is loading, even when data is defined in Augmentation mode", () => {
let clipperState = MockProps.getMockClipperState();
clipperState.currentMode.set(ClipMode.Augmentation);
clipperState.augmentationResult = {
data: undefined,
status: Status.NotStarted
};
MithrilUtils.mountToFixture(<AugmentationPreview clipperState={clipperState} />);
let previewHeaderInput = document.getElementById(Constants.Ids.previewHeaderInput) as HTMLTextAreaElement;
strictEqual(previewHeaderInput.value, this.stringsJson["WebClipper.Preview.LoadingMessage"],
"The preview title should display a loading message");
ok(previewHeaderInput.readOnly);
let previewBody = document.getElementById(Constants.Ids.previewBody);
strictEqual(previewBody.getElementsByClassName(Constants.Classes.spinner).length, 1,
"The spinner should be present in the preview body");
});
test("When augmentation is in progress, the preview should indicate that it is loading, even when data is defined in Augmentation mode", () => {
let clipperState = MockProps.getMockClipperState();
clipperState.currentMode.set(ClipMode.Augmentation);
clipperState.augmentationResult = {
data: undefined,
status: Status.InProgress
};
MithrilUtils.mountToFixture(<AugmentationPreview clipperState={clipperState} />);
let previewHeaderInput = document.getElementById(Constants.Ids.previewHeaderInput) as HTMLTextAreaElement;
strictEqual(previewHeaderInput.value, this.stringsJson["WebClipper.Preview.LoadingMessage"],
"The preview title should display a loading message");
ok(previewHeaderInput.readOnly);
let previewBody = document.getElementById(Constants.Ids.previewBody);
strictEqual(previewBody.getElementsByClassName(Constants.Classes.spinner).length, 1,
"The spinner should be present in the preview body");
});
test("When the augmentation response is a failure, the preview should display an error message in Augmentation mode", () => {
let expectedMessage = "An error message.";
let clipperState = MockProps.getMockClipperState();
clipperState.currentMode.set(ClipMode.Augmentation);
clipperState.augmentationResult = {
data: {
failureMessage: expectedMessage
},
status: Status.Failed
};
MithrilUtils.mountToFixture(<AugmentationPreview clipperState={clipperState} />);
let previewHeaderInput = document.getElementById(Constants.Ids.previewHeaderInput) as HTMLTextAreaElement;
strictEqual(previewHeaderInput.value, expectedMessage,
"The title of the page should be displayed in the preview title");
ok(previewHeaderInput.readOnly);
});
test("The default font-size and font-family should be the same as those specified in strings.json in Augmentation mode", () => {
let mockClipperState = this.getMockAugmentationModeState();
let defaultComponent = <AugmentationPreview clipperState={mockClipperState} />;
MithrilUtils.mountToFixture(defaultComponent);
let previewBody = document.getElementById(Constants.Ids.previewBody);
strictEqual(previewBody.style.fontSize, this.sansSerifDefaultFontSize);
strictEqual(previewBody.style.fontFamily, this.sansSerifFontFamily);
});
test("On clicking Serif, the fontFamily should be changed to the fontFamily specified in strings.json, and then back upon clicking Sans-Serif in Augmentation mode", () => {
let mockClipperState = this.getMockAugmentationModeState();
let defaultComponent = <AugmentationPreview clipperState={mockClipperState} />;
MithrilUtils.mountToFixture(defaultComponent);
let serifButton = document.getElementById(Constants.Ids.serif);
let sansSerifButton = document.getElementById(Constants.Ids.sansSerif);
MithrilUtils.simulateAction(() => {
serifButton.click();
});
let previewBody = document.getElementById(Constants.Ids.previewBody);
strictEqual(this.serifFontFamily, previewBody.style.fontFamily);
MithrilUtils.simulateAction(() => {
sansSerifButton.click();
});
strictEqual(this.sansSerifFontFamily, previewBody.style.fontFamily);
});
test("Clicking on the same fontFamily button multiple times should only set that fontFamily once in Augmentation mode", () => {
let mockClipperState = this.getMockAugmentationModeState();
let defaultComponent = <AugmentationPreview clipperState={mockClipperState} />;
MithrilUtils.mountToFixture(defaultComponent);
let serifButton = document.getElementById(Constants.Ids.serif);
MithrilUtils.simulateAction(() => {
serifButton.click();
});
let previewBody = document.getElementById(Constants.Ids.previewBody);
strictEqual(this.serifFontFamily, previewBody.style.fontFamily);
MithrilUtils.simulateAction(() => {
serifButton.click();
});
strictEqual(this.serifFontFamily, previewBody.style.fontFamily);
});
test("The default fontSize should be the sansSerif default fontSize, and should increment by two and decrement by two for each click on up and down respectively in Augmentation mode", () => {
let mockClipperState = this.getMockAugmentationModeState();
let defaultComponent = <AugmentationPreview clipperState={mockClipperState} />;
MithrilUtils.mountToFixture(defaultComponent);
let increaseFontSizeButton = document.getElementById(Constants.Ids.incrementFontSize);
let decreaseFontSizeButton = document.getElementById(Constants.Ids.decrementFontSize);
let defaultFontSize = parseInt(this.sansSerifDefaultFontSize, 10);
let largerFontSize = defaultFontSize + 2 * this.fontSizeStep;
let smallerFontSize = defaultFontSize - this.fontSizeStep;
let previewBody = document.getElementById(Constants.Ids.previewBody);
strictEqual(parseInt(previewBody.style.fontSize, 10), parseInt(this.sansSerifDefaultFontSize, 10));
MithrilUtils.simulateAction(() => {
decreaseFontSizeButton.click();
});
strictEqual(parseInt(previewBody.style.fontSize, 10), smallerFontSize);
MithrilUtils.simulateAction(() => {
increaseFontSizeButton.click();
increaseFontSizeButton.click();
increaseFontSizeButton.click();
});
strictEqual(parseInt(previewBody.style.fontSize, 10), largerFontSize);
});
test("If the user tries to increase beyond the maximum fontSize for either Serif or SansSerif, it should cap at the max font size defined in strings.json in Augmentation mode", () => {
let maximumFontSize = Constants.Settings.maximumFontSize;
let numClicks = (maximumFontSize - parseInt(this.sansSerifDefaultFontSize, 10)) / this.fontSizeStep;
let mockClipperState = this.getMockAugmentationModeState();
let defaultComponent = <AugmentationPreview clipperState={mockClipperState} />;
MithrilUtils.mountToFixture(defaultComponent);
let increaseFontSizeButton = document.getElementById(Constants.Ids.incrementFontSize);
let previewBody = document.getElementById(Constants.Ids.previewBody);
MithrilUtils.simulateAction(() => {
for (let i = 0; i < (numClicks + 5); i++) {
increaseFontSizeButton.click();
}
});
strictEqual(parseInt(previewBody.style.fontSize, 10), maximumFontSize);
});
test("If the user tries to decrease beyond the minimum fontSize for either Serif or SansSerif, it should reset at the minimum font size in Augmentation mode", () => {
let minimumFontSize = Constants.Settings.minimumFontSize;
let numClicks = (parseInt(this.sansSerifDefaultFontSize, 10) - minimumFontSize) / this.fontSizeStep;
let mockClipperState = this.getMockAugmentationModeState();
let defaultComponent = <AugmentationPreview clipperState={mockClipperState} />;
MithrilUtils.mountToFixture(defaultComponent);
let decreaseFontSizeButton = document.getElementById(Constants.Ids.decrementFontSize);
let previewBody = document.getElementById(Constants.Ids.previewBody);
MithrilUtils.simulateAction(() => {
for (let i = 0; i < (numClicks + 5); i++) {
decreaseFontSizeButton.click();
}
});
strictEqual(parseInt(previewBody.style.fontSize, 10), minimumFontSize);
});
test("The default internal state should show that 'Highlighting' is disabled in Augmentation mode", () => {
let mockClipperState = this.getMockAugmentationModeState();
let defaultComponent = <AugmentationPreview clipperState={mockClipperState} />;
let augmentationPreview = MithrilUtils.mountToFixture(defaultComponent);
let highlightButton = document.getElementById(Constants.Ids.highlightButton);
ok(!augmentationPreview.props.clipperState.previewGlobalInfo.highlighterEnabled);
strictEqual(highlightButton.className.indexOf("active"), -1, "The active class should not be applied to the highlight button");
});
test("If the user clicks the highlight button, the internal state should show that 'Highlighting' is enabled in Augmentation mode", () => {
let mockClipperState = this.getMockAugmentationModeState();
let defaultComponent = <AugmentationPreview clipperState={mockClipperState} />;
let augmentationPreview = MithrilUtils.mountToFixture(defaultComponent);
let highlightButton = document.getElementById(Constants.Ids.highlightButton);
MithrilUtils.simulateAction(() => {
highlightButton.click();
});
ok(augmentationPreview.props.clipperState.previewGlobalInfo.highlighterEnabled);
notStrictEqual(highlightButton.className.indexOf("active"), -1, "The active class should be applied to the highlight button");
});
test("If the user selects something in the highlightable preview body, then clicks the highlight button, the internal state should show that 'Highlighting' is disabled in Augmentation mode, and the item should be highlighted", () => {
let mockClipperState = this.getMockAugmentationModeState();
let defaultComponent = <AugmentationPreview clipperState={mockClipperState} />;
let augmentationPreview = MithrilUtils.mountToFixture(defaultComponent);
// This id is necessary for the highlighting to be enabled on this element's children
let paragraph = document.createElement("p");
let paragraphId = "para";
paragraph.id = paragraphId;
let innerText = "Test";
paragraph.innerHTML = innerText;
document.getElementById(Constants.Ids.highlightablePreviewBody).appendChild(paragraph);
let highlightButton = document.getElementById(Constants.Ids.highlightButton);
MithrilUtils.simulateAction(() => {
// Simulate a selection (http://stackoverflow.com/questions/6139107/programatically-select-text-in-a-contenteditable-html-element)
let range = document.createRange();
range.selectNodeContents(paragraph);
let sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
highlightButton.click();
});
ok(!augmentationPreview.props.clipperState.previewGlobalInfo.highlighterEnabled);
strictEqual(highlightButton.className.indexOf("active"), -1, "The active class should not be applied to the highlight button");
let childSpans = paragraph.getElementsByClassName(Constants.Classes.highlighted);
strictEqual(childSpans.length, 1, "There should only be one highlighted element");
strictEqual((childSpans[0] as HTMLElement).innerText, innerText,
"The highlighted element should be the inner text of the paragraph");
});
test("If the user selects something outside the highlightable preview body, then clicks the highlight button, the internal state should show that 'Highlighting' is enabled in Augmentation mode, and nothing should be highlighted", () => {
let mockClipperState = this.getMockAugmentationModeState();
let defaultComponent = <AugmentationPreview clipperState={mockClipperState} />;
let augmentationPreview = MithrilUtils.mountToFixture(defaultComponent);
// This id is necessary for the highlighting to be enabled on this element's children
let paragraph = document.createElement("p");
let paragraphId = "para";
paragraph.id = paragraphId;
let innerText = "Test";
paragraph.innerHTML = innerText;
// Note this is outside the preview body
MithrilUtils.getFixture().appendChild(paragraph);
let highlightButton = document.getElementById(Constants.Ids.highlightButton);
MithrilUtils.simulateAction(() => {
let range = document.createRange();
range.selectNodeContents(paragraph);
let sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
highlightButton.click();
});
ok(augmentationPreview.props.clipperState.previewGlobalInfo.highlighterEnabled);
notStrictEqual(highlightButton.className.indexOf("active"), -1, "The active class should be applied to the highlight button");
let childSpans = paragraph.getElementsByClassName(Constants.Classes.highlighted);
strictEqual(childSpans.length, 0, "There should only be one highlighted element");
});
test("If the user is highlighting (i.e., highlighting mode is active), then the 'active' class should be applied to the highlightButton in Augmentation mode", () => {
let mockClipperState = this.getMockAugmentationModeState();
let defaultComponent = <AugmentationPreview clipperState={mockClipperState} />;
MithrilUtils.mountToFixture(defaultComponent);
let highlightButton = document.getElementById(Constants.Ids.highlightButton);
MithrilUtils.simulateAction(() => {
highlightButton.click();
});
// We do this to manually trigger a config call
MithrilUtils.simulateAction(() => {});
notStrictEqual(highlightButton.className.indexOf("active"), -1, "The active class should be applied to the highlight button");
});
test("If the user is not highlighting (i.e., highlighting mode is active), then the 'active' class should not be applied to the highlightButton in Augmentation mode", () => {
let mockClipperState = this.getMockAugmentationModeState();
let defaultComponent = <AugmentationPreview clipperState={mockClipperState} />;
MithrilUtils.mountToFixture(defaultComponent);
let highlightButton = document.getElementById(Constants.Ids.highlightButton);
strictEqual(highlightButton.className.indexOf("active"), -1, "The active class should not be applied to the highlight button");
});
test("If the editable title feature is disabled, it should be readonly", () => {
let mockClipperState = this.getMockAugmentationModeState();
mockClipperState.injectOptions.enableEditableTitle = false;
let defaultComponent = <AugmentationPreview clipperState={mockClipperState} />;
MithrilUtils.mountToFixture(defaultComponent);
let previewHeaderInput = document.getElementById(Constants.Ids.previewHeaderInput) as HTMLTextAreaElement;
strictEqual(previewHeaderInput.value, mockClipperState.previewGlobalInfo.previewTitleText,
"The title of the page should be displayed in the preview title");
ok(previewHeaderInput.readOnly);
});
}
private getMockAugmentationModeState(): ClipperState {
let state = MockProps.getMockClipperState() as ClipperState;
state.currentMode.set(ClipMode.Augmentation);
state.augmentationResult = {
data: {
ContentInHtml: "Jello World content in all its jelly goodness.",
ContentModel: AugmentationModel.Product,
ContentObjects: [],
PageMetadata: {
AutoPageTags: "Product",
AutoPageTagsCodes: "Product"
}
},
status: Status.Succeeded
};
return state;
}
}
(new AugmentationPreviewTests()).runTests(); | the_stack |
import produce from 'immer';
import { config, getDefaultPlatform, OSGiVersionMax } from './config';
import { Addon, BuildType, Mode, NATIVE_ALL, Preset } from './types';
import type { RadioOptions } from './ConnectedRadio';
import type {
Binding,
BindingDefinition,
BindingMapSelection,
BuildStore,
BuildStoreSnapshot,
Version,
Language,
Native,
} from './types';
export enum Action {
BUILD_STATUS = 'BUILD/STATUS',
SELECT_TYPE = 'BUILD/SELECT_TYPE',
SELECT_MODE = 'BUILD/SELECT_MODE',
SELECT_PRESET = 'BUILD/SELECT_PRESET',
SELECT_LANGUAGE = 'BUILD/SELECT_LANGUAGE',
SELECT_VERSION = 'BUILD/SELECT_VERSION',
TOGGLE_DESCRIPTIONS = 'BUILD/TOGGLE_DESCRIPTIONS',
TOGGLE_SOURCE = 'BUILD/TOGGLE_SOURCE',
TOGGLE_JAVADOC = 'BUILD/TOGGLE_JAVADOC',
TOGGLE_INCLUDE_JSON = 'BUILD/TOGGLE_INCLUDE_JSON',
TOGGLE_OSGI = 'BUILD/TOGGLE_OSGI',
TOGGLE_COMPACT = 'BUILD/TOGGLE_COMPACT',
TOGGLE_HARDCODED = 'BUILD/TOGGLE_HARDCODED',
TOGGLE_PLATFORM = 'BUILD/TOGGLE_PLATFORM',
TOGGLE_ARTIFACT = 'BUILD/TOGGLE_ARTIFACT',
TOGGLE_ADDON = 'BUILD/TOGGLE_ADDON',
CONFIG_LOAD = 'BUILD/CONFIG_LOAD',
}
export type ActionMessage =
| ActionBuildTypeSelect
| ActionConfigLoad
| ActionModeSelect
| ActionPresetSelect
| ActionLanguageSelect
| ActionVersionSelect
| ActionToggle<
| Action.TOGGLE_DESCRIPTIONS
| Action.TOGGLE_SOURCE
| Action.TOGGLE_JAVADOC
| Action.TOGGLE_INCLUDE_JSON
| Action.TOGGLE_HARDCODED
| Action.TOGGLE_OSGI
| Action.TOGGLE_COMPACT
>
| ActionArtifactToggle
| ActionPlatformToggle
| ActionAddonToggle;
export interface ActionToggle<T> {
type: T;
}
// Select/deselect a build type (e.g. Release, Nightly)
export interface ActionBuildTypeSelect {
type: Action.SELECT_TYPE;
build: BuildType | null;
}
export const createActionBuiltTypeSelect = (build: BuildType | null): ActionBuildTypeSelect => ({
type: Action.SELECT_TYPE,
build,
});
// Load previously save configuration
export interface ActionConfigLoad {
type: Action.CONFIG_LOAD;
payload: BuildStoreSnapshot;
}
export const createActionConfigLoad = (payload: BuildStoreSnapshot): ActionConfigLoad => ({
type: Action.CONFIG_LOAD,
payload,
});
// Change Mode
export interface ActionModeSelect {
type: Action.SELECT_MODE;
mode: Mode;
}
export const createActionModeSelect = (mode: Mode): ActionModeSelect => ({
type: Action.SELECT_MODE,
mode,
});
// Select Preset
export interface ActionPresetSelect {
type: Action.SELECT_PRESET;
preset: Preset;
}
export const createActionPresetSelect = (preset: Preset): ActionPresetSelect => ({
type: Action.SELECT_PRESET,
preset,
});
// Select Language
export interface ActionLanguageSelect {
type: Action.SELECT_LANGUAGE;
language: Language;
}
export const createActionLanguageSelect = (language: Language): ActionLanguageSelect => ({
type: Action.SELECT_LANGUAGE,
language,
});
// Select Version
export interface ActionVersionSelect {
type: Action.SELECT_VERSION;
version: Version;
}
export const createActionVersionSelect = (version: Version): ActionVersionSelect => ({
type: Action.SELECT_VERSION,
version,
});
// Toggle Description
export const createActionDescriptionsToggle = (): ActionToggle<Action.TOGGLE_DESCRIPTIONS> => ({
type: Action.TOGGLE_DESCRIPTIONS,
});
// Toggle Source
export const createActionSourceToggle = (): ActionToggle<Action.TOGGLE_SOURCE> => ({
type: Action.TOGGLE_SOURCE,
});
// Toggle JavaDoc
export const createActionJavadocToggle = (): ActionToggle<Action.TOGGLE_JAVADOC> => ({
type: Action.TOGGLE_JAVADOC,
});
// Toggle Include JSON
export const createActionIncludeJSONToggle = (): ActionToggle<Action.TOGGLE_INCLUDE_JSON> => ({
type: Action.TOGGLE_INCLUDE_JSON,
});
// Toggle OSGi
export const createActionOSGiToggle = (): ActionToggle<Action.TOGGLE_OSGI> => ({
type: Action.TOGGLE_OSGI,
});
// Toggle Compact
export const createActionCompactToggle = (): ActionToggle<Action.TOGGLE_COMPACT> => ({
type: Action.TOGGLE_COMPACT,
});
// Toggle Hardcoded
export const createActionHardcodedToggle = (): ActionToggle<Action.TOGGLE_HARDCODED> => ({
type: Action.TOGGLE_HARDCODED,
});
// Toggle Artifact
export interface ActionArtifactToggle {
type: Action.TOGGLE_ARTIFACT;
artifact: Binding;
}
export const createActionArtifactToggle = (artifact: Binding): ActionArtifactToggle => ({
type: Action.TOGGLE_ARTIFACT,
artifact,
});
// Toggle Platform
export interface ActionPlatformToggle {
type: Action.TOGGLE_PLATFORM;
platform: Native;
}
export const createActionPlatformToggle = (platform: Native): ActionPlatformToggle => ({
type: Action.TOGGLE_PLATFORM,
platform,
});
// Toggle Addon
export interface ActionAddonToggle {
type: Action.TOGGLE_ADDON;
addon: Addon;
}
export const createActionAddonToggle = (addon: Addon): ActionAddonToggle => ({ type: Action.TOGGLE_ADDON, addon });
// Selectors
// export const selectorStore = (state: BuildStore): BuildStore => state;
export const selectorDescriptions = (state: BuildStore): boolean => state.descriptions;
export const selectorHasLanguageOption = (state: BuildStore): boolean => state.mode === Mode.Gradle;
export const selectorBuild = (state: BuildStore) => state.build;
export const selectorBuilds = (state: BuildStore) => state.builds;
export const selectorIsBuildSelected = (state: BuildStore): boolean => state.build !== null;
export const selectorIsBuildRelease = (state: BuildStore): boolean => state.build === BuildType.Release;
export const selectorMode = (state: BuildStore) => state.mode;
export const selectorModes = (state: BuildStore) => state.modes;
const selectorSource = (state: BuildStore) => state.source;
const selectorJavaDoc = (state: BuildStore) => state.javadoc;
const selectorIncludeJSON = (state: BuildStore) => state.includeJSON;
const selectorPreset = (state: BuildStore) => state.preset;
const selectorHardcoded = (state: BuildStore) => state.hardcoded;
const selectorCompact = (state: BuildStore) => state.compact;
const selectorOSGi = (state: BuildStore) => state.osgi;
const selectorLanguage = (state: BuildStore) => state.language;
const selectorVersion = (state: BuildStore) => state.version;
const selectorHasCompactModeOption = (state: BuildStore): boolean =>
state.mode === Mode.Maven || state.mode === Mode.Ivy;
const selectorIsModeZip = (state: BuildStore): boolean => state.mode === Mode.Zip;
const selectorIsModeNotZip = (state: BuildStore): boolean => state.mode !== Mode.Zip;
const selectorShowOSGi = (state: BuildStore): boolean =>
state.mode !== Mode.Zip && state.build === BuildType.Release && checkOSGiVersion(state.version);
export const selectorNatives = (store: BuildStore) => store.natives;
export const selectorArtifactsVersion = (store: BuildStore) => store.artifacts.version;
export const selectorPlatformsSelected = (store: BuildStore) => store.platform;
export const selectorAddons = (store: BuildStore) => store.addons;
export const selectorAddonsSelected = (store: BuildStore) => store.selectedAddons;
export const selectorContents = (store: BuildStore) => store.contents;
export const selectorAvailability = (store: BuildStore) => store.availability;
export const selectorArtifacts = (store: BuildStore) => store.artifacts;
// Fields
export const fields = {
mode: {
name: 'mode',
value: selectorMode,
action: createActionModeSelect,
options: ({ modes: { allIds, byId }, build }: BuildStore): RadioOptions =>
allIds.map((mode) => ({
value: mode,
label: byId[mode].title,
})),
},
descriptions: {
children: 'Show descriptions',
checked: selectorDescriptions,
action: createActionDescriptionsToggle,
},
source: {
children: 'Include source',
checked: selectorSource,
hidden: selectorIsModeNotZip,
action: createActionSourceToggle,
},
javadoc: {
children: 'Include JavaDoc',
checked: selectorJavaDoc,
hidden: selectorIsModeNotZip,
action: createActionJavadocToggle,
},
includeJSON: {
children: 'Include build config',
checked: selectorIncludeJSON,
hidden: selectorIsModeNotZip,
action: createActionIncludeJSONToggle,
},
hardcoded: {
children: 'Do not use variables',
checked: selectorHardcoded,
hidden: selectorIsModeZip,
action: createActionHardcodedToggle,
},
compact: {
children: 'Compact Mode',
checked: selectorCompact,
hidden: (state: BuildStore) => !selectorHasCompactModeOption(state),
action: createActionCompactToggle,
},
osgi: {
children: 'OSGi Mode',
checked: selectorOSGi,
hidden: (state: BuildStore) => !selectorShowOSGi(state),
action: createActionOSGiToggle,
},
language: {
name: 'language',
value: selectorLanguage,
action: createActionLanguageSelect,
options: ({ languages: { allIds, byId } }: BuildStore): RadioOptions =>
allIds.map((lang: Language) => ({
value: lang,
label: byId[lang].title,
})),
},
preset: {
name: 'preset',
value: selectorPreset,
action: createActionPresetSelect,
options: ({ presets: { allIds, byId }, preset }: BuildStore): RadioOptions =>
allIds.map((presetId) => ({
value: presetId,
label: byId[presetId].title,
disabled: preset !== presetId && presetId === 'custom',
})),
},
version: {
name: 'version',
value: selectorVersion,
action: createActionVersionSelect,
options: ({ versions }: BuildStore): RadioOptions =>
versions.map((version) => ({
value: version,
label: version,
disabled: version === '3.0.0',
})),
},
};
// Reducer
export const reducer: React.Reducer<BuildStore, ActionMessage> = (
state: BuildStore = config,
action: ActionMessage
) => {
return produce(state, (draft: BuildStore) => {
switch (action.type) {
case Action.CONFIG_LOAD:
loadConfig(draft, action.payload);
break;
case Action.SELECT_TYPE:
selectBuild(draft, action.build !== state.build ? action.build : null);
break;
case Action.SELECT_MODE:
if (state.mode !== action.mode) {
selectMode(draft, action.mode);
}
break;
case Action.TOGGLE_DESCRIPTIONS:
draft.descriptions = !draft.descriptions;
break;
case Action.TOGGLE_COMPACT:
if (state.mode === Mode.Maven || state.mode === Mode.Ivy) {
draft.compact = !draft.compact;
}
break;
case Action.TOGGLE_HARDCODED:
if (state.mode !== Mode.Zip) {
draft.hardcoded = !draft.hardcoded;
}
break;
case Action.TOGGLE_JAVADOC:
if (state.mode === Mode.Zip) {
draft.javadoc = !draft.javadoc;
}
break;
case Action.TOGGLE_INCLUDE_JSON:
if (state.mode === Mode.Zip) {
draft.includeJSON = !draft.includeJSON;
}
break;
case Action.TOGGLE_SOURCE:
if (state.mode === Mode.Zip) {
draft.source = !draft.source;
}
break;
case Action.TOGGLE_OSGI:
if (state.mode !== Mode.Zip && state.build === BuildType.Release) {
if (draft.osgi) {
if (!checkOSGiVersion(state.version)) {
break;
}
}
draft.osgi = !draft.osgi;
}
break;
case Action.SELECT_PRESET:
if (state.preset !== action.preset) {
selectPreset(draft, action.preset);
}
break;
case Action.SELECT_LANGUAGE:
if (state.mode === Mode.Gradle) {
draft.language = action.language;
}
break;
case Action.TOGGLE_PLATFORM:
const selections = state.natives.allIds.reduce(
(previousValue, platform) => previousValue + (state.platform[platform] ? 1 : 0),
0
);
if (selections > 1 || state.platform[action.platform] === false) {
draft.platform[action.platform] = !state.platform[action.platform];
computeArtifacts(draft);
}
break;
case Action.SELECT_VERSION:
if (state.build === BuildType.Release && state.version !== action.version) {
selectVersion(draft, action.version);
}
break;
case Action.TOGGLE_ARTIFACT:
if (action.artifact !== 'lwjgl') {
doToggleArtifact(draft, action.artifact);
}
break;
case Action.TOGGLE_ADDON:
doToggleAddon(draft, action.addon);
break;
}
});
};
export function versionNum(version: Version) {
return parseInt(version.replace(/\./g, ''), 10);
}
export function checkOSGiVersion(version: Version) {
let vnum = versionNum(version);
return 312 <= vnum && vnum <= versionNum(OSGiVersionMax);
}
function selectBuild(state: BuildStore, build: BuildType | null) {
state.build = build;
computeArtifacts(state);
}
function selectMode(state: BuildStore, mode: Mode) {
state.mode = mode;
computeArtifacts(state);
}
function selectPreset(state: BuildStore, preset: Preset) {
// Make sure preset exists
if (state.presets.byId[preset] === undefined) {
return;
}
// Set preset
state.preset = preset;
if (preset === Preset.All) {
state.artifacts.allIds.forEach((artifact) => {
state.contents[artifact] = true;
});
} else if (preset !== Preset.Custom) {
state.artifacts.allIds.forEach((artifact) => {
state.contents[artifact] = false;
});
const configPreset = state.presets.byId[preset];
if (configPreset.artifacts !== undefined) {
configPreset.artifacts.forEach((artifact) => {
state.contents[artifact] = true;
});
}
}
}
function computeArtifacts(state: BuildStore) {
if (state.build === null) {
return;
}
state.artifacts = state.lwjgl[state.build === BuildType.Release ? state.version : state.build];
const vnum = versionNum(state.artifacts.version);
NATIVE_ALL.forEach((p) => {
if (state.platform[p] && vnum < versionNum(config.natives.byId[p].since)) {
state.platform[p] = false;
}
});
if (!NATIVE_ALL.some((p) => state.platform[p])) {
state.platform[getDefaultPlatform()] = true;
}
// reset state
state.availability = {} as BindingMapSelection;
state.presets.allIds.forEach((preset) => {
state.presets.byId[preset].artifacts = [];
});
state.artifacts.allIds.forEach((it) => {
const artifact = state.artifacts.byId[it] as BindingDefinition;
state.availability[it] =
artifact.natives === undefined ||
artifact.nativesOptional === true ||
artifact.natives.length === config.natives.allIds.length ||
artifact.natives.some((platform) => !!state.platform[platform]);
if (state.availability[it] && artifact.presets !== undefined) {
// Populate presets
artifact.presets.forEach((preset) => {
const statePreset = state.presets.byId[preset];
if (statePreset.artifacts !== undefined) {
statePreset.artifacts.push(it);
}
});
}
});
if (state.preset !== Preset.Custom) {
selectPreset(state, state.preset);
}
}
const selectVersion = (state: BuildStore, version: Version) => {
state.version = version;
computeArtifacts(state);
if (state.osgi && !checkOSGiVersion(version)) {
state.osgi = false;
}
};
const doToggleArtifact = (state: BuildStore, artifact: Binding) => {
state.contents[artifact] = !state.contents[artifact];
// MATCH PRESET
// collect selected artifacts in an Array
const selected = state.artifacts.allIds.filter((artifact) => state.contents[artifact]);
if (selected.length === state.artifacts.allIds.length) {
state.preset = Preset.All;
return;
} else if (selected.length === 1) {
state.preset = Preset.None;
return;
}
// match selected artifacts with a preset
const presetFoundMatch = state.presets.allIds.some((presetName: Preset) => {
// only check predefined presets
if (presetName === Preset.Custom || presetName === Preset.All || presetName === Preset.None) {
return false;
}
const preset = state.presets.byId[presetName];
// Get preset artifacts but keep only ones present in the current artifact collection
if (preset.artifacts !== undefined) {
const artifacts = preset.artifacts.filter((it) => !!state.artifacts.byId[it]);
// first check length for speed, then do deep comparison
if (artifacts.length === selected.length && artifacts.every((it, i) => it === selected[i])) {
state.preset = presetName;
return true;
}
}
return false;
});
// if we didn't get a match, set it to custom preset
if (!presetFoundMatch) {
state.preset = Preset.Custom;
}
};
const doToggleAddon = (state: BuildStore, addon: Addon) => {
if (state.selectedAddons.includes(addon)) {
state.selectedAddons = state.selectedAddons.filter((it) => it !== addon);
} else {
state.selectedAddons.push(addon);
}
};
const loadConfig = (state: BuildStore, config: BuildStoreSnapshot) => {
if (config.build === null) {
return;
}
state.build = config.build;
state.mode = config.mode;
state.selectedAddons = config.selectedAddons;
state.descriptions = config.descriptions;
state.compact = config.compact;
state.hardcoded = config.hardcoded;
state.javadoc = config.javadoc;
state.includeJSON = config.includeJSON;
state.source = config.source;
state.language = config.language;
state.osgi = !!config.osgi;
if (config.build === BuildType.Release && config.version !== undefined && config.versionLatest !== undefined) {
if (config.versionLatest === state.versions[1]) {
state.version = state.versions[0];
} else {
state.version = config.version;
}
}
if (config.mode === Mode.Zip) {
state.natives.allIds.forEach((platform) => {
state.platform[platform] = false;
});
config.platform.forEach((platform) => {
state.platform[platform] = true;
});
}
computeArtifacts(state);
if (config.preset !== undefined) {
selectPreset(state, config.preset);
} else if (config.contents !== undefined) {
state.preset = Preset.Custom;
state.contents = {} as BindingMapSelection;
config.contents.forEach((binding: Binding) => {
if (state.artifacts.byId[binding] !== undefined) {
state.contents[binding] = true;
}
});
} else {
selectPreset(state, Preset.GettingStarted);
}
}; | the_stack |
import { Component, Input, Output, EventEmitter, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core'; // tslint:disable-line
// RxJS
import { Observable } from "rxjs/Observable";
// Ionic
import { Platform, Events } from 'ionic-angular';
// Models
import { SideMenuOption } from './models/side-menu-option';
import { SideMenuSettings } from './models/side-menu-settings';
import { SideMenuOptionSelect, SideMenuOptionSelectData } from './models/side-menu-option-select-event';
// This class is defined in this file because
// we don't want to make it exportable
class InnerMenuOptionModel {
public id: number;
public iconName: string;
public displayText: string;
public badge?: Observable<any>;
public targetOption: SideMenuOption;
public parent: InnerMenuOptionModel;
public selected: boolean;
public expanded: boolean;
public suboptionsCount: number;
public subOptions: Array<InnerMenuOptionModel>;
private static counter = 1;
public static fromMenuOptionModel(option: SideMenuOption, parent?: InnerMenuOptionModel): InnerMenuOptionModel {
let innerMenuOptionModel = new InnerMenuOptionModel();
innerMenuOptionModel.id = this.counter++;
innerMenuOptionModel.iconName = option.iconName;
innerMenuOptionModel.displayText = option.displayText;
innerMenuOptionModel.badge = option.badge;
innerMenuOptionModel.targetOption = option;
innerMenuOptionModel.parent = parent || null;
innerMenuOptionModel.selected = option.selected;
if (option.suboptions) {
innerMenuOptionModel.expanded = false;
innerMenuOptionModel.suboptionsCount = option.suboptions.length;
innerMenuOptionModel.subOptions = [];
option.suboptions.forEach(subItem => {
let innerSubItem = InnerMenuOptionModel.fromMenuOptionModel(subItem, innerMenuOptionModel);
innerMenuOptionModel.subOptions.push(innerSubItem);
// Select the parent if any
// child option is selected
if (subItem.selected) {
innerSubItem.parent.selected = true;
innerSubItem.parent.expanded = true;
}
});
}
return innerMenuOptionModel;
}
}
@Component({
selector: 'side-menu-content',
templateUrl: 'side-menu-content.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class SideMenuContentComponent {
// Main inputs
public menuSettings: SideMenuSettings;
public menuOptions: Array<SideMenuOption>;
// Private properties
private selectedOption: InnerMenuOptionModel;
public collapsableItems: Array<InnerMenuOptionModel> = [];
@Input('options')
set options(value: Array<SideMenuOption>) {
if (value) {
// Keep a reference to the options
// sent to this component
this.menuOptions = value;
this.collapsableItems = new Array<InnerMenuOptionModel>();
// Map the options to our internal models
this.menuOptions.forEach(option => {
let innerMenuOption = InnerMenuOptionModel.fromMenuOptionModel(option);
this.collapsableItems.push(innerMenuOption);
// Check if there's any option marked as selected
if (option.selected) {
this.selectedOption = innerMenuOption;
} else if (innerMenuOption.suboptionsCount) {
innerMenuOption.subOptions.forEach(subItem => {
if (subItem.selected) {
this.selectedOption = subItem;
}
});
}
});
}
}
@Input('settings')
set settings(value: SideMenuSettings) {
if (value) {
this.menuSettings = value;
this.mergeSettings();
}
}
// Outputs: return the selected option to the caller
@Output() change = new EventEmitter<any>();
constructor(private platform: Platform,
private eventsCtrl: Events,
private cdRef: ChangeDetectorRef) {
// Handle the redirect event
this.eventsCtrl.subscribe(SideMenuOptionSelect, (data: SideMenuOptionSelectData) => {
this.updateSelectedOption(data);
});
}
ngOnDestroy() {
this.eventsCtrl.unsubscribe(SideMenuOptionSelect);
}
// ---------------------------------------------------
// PUBLIC methods
// ---------------------------------------------------
// Send the selected option to the caller component
public select(option: InnerMenuOptionModel): void {
if (this.menuSettings.showSelectedOption) {
this.setSelectedOption(option);
}
// Return the selected option (not our inner option)
this.change.emit(option.targetOption);
}
// Toggle the sub options of the selected item
public toggleItemOptions(targetOption: InnerMenuOptionModel): void {
if (!targetOption) return;
// If the accordion mode is set to true, we need
// to collapse all the other menu options
if (this.menuSettings.accordionMode) {
this.collapsableItems.forEach(option => {
if (option.id !== targetOption.id) {
option.expanded = false;
}
});
}
// Toggle the selected option
targetOption.expanded = !targetOption.expanded;
}
// Reset the entire menu
public collapseAllOptions(): void {
this.collapsableItems.forEach(option => {
if (!option.selected) {
option.expanded = false;
}
if (option.suboptionsCount) {
option.subOptions.forEach(subItem => {
if (subItem.selected) {
// Expand the parent if any of
// its childs is selected
subItem.parent.expanded = true;
}
});
}
});
// Update the view since there wasn't
// any user interaction with it
this.cdRef.detectChanges();
}
// Get the proper indentation of each option
public get subOptionIndentation(): number {
if (this.platform.is('ios')) return this.menuSettings.subOptionIndentation.ios;
if (this.platform.is('windows')) return this.menuSettings.subOptionIndentation.wp;
return this.menuSettings.subOptionIndentation.md;
}
// Get the proper height of each option
public get optionHeight(): number {
if (this.platform.is('ios')) return this.menuSettings.optionHeight.ios;
if (this.platform.is('windows')) return this.menuSettings.optionHeight.wp;
return this.menuSettings.optionHeight.md;
}
// ---------------------------------------------------
// PRIVATE methods
// ---------------------------------------------------
// Method that set the selected option and its parent
private setSelectedOption(option: InnerMenuOptionModel) {
if (!option.targetOption.component) return;
// Clean the current selected option if any
if (this.selectedOption) {
this.selectedOption.selected = false;
this.selectedOption.targetOption.selected = false;
if (this.selectedOption.parent) {
this.selectedOption.parent.selected = false;
this.selectedOption.parent.expanded = false;
}
this.selectedOption = null;
}
// Set this option to be the selected
option.selected = true;
option.targetOption.selected = true;
if (option.parent) {
option.parent.selected = true;
option.parent.expanded = true;
}
// Keep a reference to the selected option
this.selectedOption = option;
// Update the view if needed since we may have
// expanded or collapsed some options
this.cdRef.detectChanges();
}
// Update the selected option
private updateSelectedOption(data: SideMenuOptionSelectData): void {
if (!data.displayText) return;
let targetOption: InnerMenuOptionModel;
if (data.displayText.includes('>>')) {
// The display text includes the name of the parent
const parentDisplayText = data.displayText.split('>>')[0];
const childDisplayText = data.displayText.split('>>')[1];
let targetParent: InnerMenuOptionModel;
// First search the parent option
this.collapsableItems.forEach(option => {
if (this.compareOptionsName(option.displayText, parentDisplayText)) {
targetParent = option;
}
});
// Now try to find the child option within the parent
if (targetParent) {
targetParent.subOptions.forEach(subOption => {
if (this.compareOptionsName(subOption.displayText, childDisplayText)) {
targetOption = subOption;
}
});
}
} else {
// The display text does not include the name of the parent
this.collapsableItems.forEach(option => {
if (this.compareOptionsName(option.displayText, data.displayText)) {
targetOption = option;
} else if (option.suboptionsCount) {
option.subOptions.forEach(subOption => {
if (this.compareOptionsName(subOption.displayText, data.displayText)) {
targetOption = subOption;
}
});
}
});
}
if (targetOption) {
this.setSelectedOption(targetOption);
}
}
// Merge the settings received with the default settings
private mergeSettings(): void {
const defaultSettings: SideMenuSettings = {
accordionMode: false,
optionHeight: {
ios: 50,
md: 50,
wp: 50
},
arrowIcon: 'ios-arrow-down',
showSelectedOption: false,
selectedOptionClass: 'selected-option',
indentSubOptionsWithoutIcons: false,
subOptionIndentation: {
ios: 16,
md: 16,
wp: 16
}
}
if (!this.menuSettings) {
// Use the default values
this.menuSettings = defaultSettings;
return;
}
if (!this.menuSettings.optionHeight) {
this.menuSettings.optionHeight = defaultSettings.optionHeight;
} else {
this.menuSettings.optionHeight.ios = this.isDefinedAndPositive(this.menuSettings.optionHeight.ios) ? this.menuSettings.optionHeight.ios : defaultSettings.optionHeight.ios;
this.menuSettings.optionHeight.md = this.isDefinedAndPositive(this.menuSettings.optionHeight.md) ? this.menuSettings.optionHeight.md : defaultSettings.optionHeight.md;
this.menuSettings.optionHeight.wp = this.isDefinedAndPositive(this.menuSettings.optionHeight.wp) ? this.menuSettings.optionHeight.wp : defaultSettings.optionHeight.wp;
}
this.menuSettings.showSelectedOption = this.isDefined(this.menuSettings.showSelectedOption) ? this.menuSettings.showSelectedOption : defaultSettings.showSelectedOption;
this.menuSettings.accordionMode = this.isDefined(this.menuSettings.accordionMode) ? this.menuSettings.accordionMode : defaultSettings.accordionMode;
this.menuSettings.arrowIcon = this.isDefined(this.menuSettings.arrowIcon) ? this.menuSettings.arrowIcon : defaultSettings.arrowIcon;
this.menuSettings.selectedOptionClass = this.isDefined(this.menuSettings.selectedOptionClass) ? this.menuSettings.selectedOptionClass : defaultSettings.selectedOptionClass;
this.menuSettings.indentSubOptionsWithoutIcons = this.isDefined(this.menuSettings.indentSubOptionsWithoutIcons) ? this.menuSettings.indentSubOptionsWithoutIcons : defaultSettings.indentSubOptionsWithoutIcons;
if (!this.menuSettings.subOptionIndentation) {
this.menuSettings.subOptionIndentation = defaultSettings.subOptionIndentation;
} else {
this.menuSettings.subOptionIndentation.ios = this.isDefinedAndPositive(this.menuSettings.subOptionIndentation.ios) ? this.menuSettings.subOptionIndentation.ios : defaultSettings.subOptionIndentation.ios;
this.menuSettings.subOptionIndentation.md = this.isDefinedAndPositive(this.menuSettings.subOptionIndentation.md) ? this.menuSettings.subOptionIndentation.md : defaultSettings.subOptionIndentation.md;
this.menuSettings.subOptionIndentation.wp = this.isDefinedAndPositive(this.menuSettings.subOptionIndentation.wp) ? this.menuSettings.subOptionIndentation.wp : defaultSettings.subOptionIndentation.wp;
}
}
private isDefined(property: any): boolean {
return property !== null && property !== undefined;
}
private isDefinedAndPositive(property: any): boolean {
return this.isDefined(property) && !isNaN(property) && property > 0;
}
private compareOptionsName(name1: string, name2: string): boolean {
return name1.replace(/\s/g, '').toLowerCase() === name2.replace(/\s/g, '').toLowerCase();
}
} | the_stack |
import {Scene} from 'three/src/scenes/Scene';
import {WebGLRenderTarget} from 'three/src/renderers/WebGLRenderTarget';
import {HalfFloatType, FloatType} from 'three/src/constants';
import {MeshPhongMaterial} from 'three/src/materials/MeshPhongMaterial';
import {MeshBasicMaterial} from 'three/src/materials/MeshBasicMaterial';
import {Material} from 'three/src/materials/Material';
import {PlaneBufferGeometry} from 'three/src/geometries/PlaneGeometry';
import {Mesh} from 'three/src/objects/Mesh';
import {Object3D} from 'three/src/core/Object3D';
import {WebGLRenderer} from 'three/src/renderers/WebGLRenderer';
import {Camera} from 'three/src/cameras/Camera';
import {Light} from 'three/src/lights/Light';
import {Texture} from 'three/src/textures/Texture';
import {RenderTarget} from 'three/src/renderers/webgl/WebGLRenderLists';
import {Matrix4} from 'three/src/math/Matrix4';
import {Vector3} from 'three/src/math/Vector3';
import {Quaternion} from 'three/src/math/Quaternion';
import {CoreUserAgent} from '../../../../core/UserAgent';
//
// adapted from https://threejs.org/examples/?q=light#webgl_shadowmap_progressive
//
interface MeshPhongMaterialWithUniforms extends MeshPhongMaterial {
uniforms: {
previousShadowMap: {value: Texture | null};
iterationBlend: {value: number};
};
}
interface MeshBasicMaterialWithUniforms extends MeshBasicMaterial {
uniforms: {
previousShadowMap: {value: Texture | null};
pixelOffset: {value: number};
};
}
interface ObjectState {
material: Material | Material[];
frustumCulled: boolean;
parent: Object3D | null;
castShadow: boolean;
receiveShadow: boolean;
}
interface LightHierarchyState {
matrixAutoUpdate: boolean;
parent: Object3D | null;
}
interface LightMatrixState {
matrix: Matrix4;
position: Vector3;
}
interface Params {
lightRadius: number;
iterations: number;
iterationBlend: number;
blur: boolean;
blurAmount: number;
}
export const DEFAULT_ITERATION_BLEND = 1 / 200;
export class LightMapController {
private objectTargets: Mesh[] = [];
private lights: Light[] = [];
private scene = new Scene();
// private tinyTarget = new WebGLRenderTarget(1, 1);
private buffer1Active = false;
// private firstUpdate = false;
private progressiveLightMap1: WebGLRenderTarget;
private progressiveLightMap2: WebGLRenderTarget;
private uvMat: MeshPhongMaterialWithUniforms;
private blurMaterial: MeshBasicMaterialWithUniforms | undefined;
private blurringPlane: Mesh | undefined;
private _params: Params = {
lightRadius: 1,
iterations: 1,
iterationBlend: DEFAULT_ITERATION_BLEND,
blur: false,
blurAmount: 0,
};
constructor(private renderer: WebGLRenderer, private res: number = 1024) {
// Create the Progressive LightMap Texture
const isAndroidOriOS = CoreUserAgent.isAndroid() || CoreUserAgent.isiOS();
const format = isAndroidOriOS ? HalfFloatType : FloatType;
this.progressiveLightMap1 = new WebGLRenderTarget(this.res, this.res, {type: format});
this.progressiveLightMap2 = new WebGLRenderTarget(this.res, this.res, {type: format});
this.uvMat = this._createUVMat();
}
textureRenderTarget() {
return this.progressiveLightMap2;
}
texture() {
return this.textureRenderTarget().texture;
}
setParams(params: Params) {
this._params.lightRadius = params.lightRadius;
this._params.iterations = params.iterations;
this._params.iterationBlend = params.iterationBlend;
this._params.blur = params.blur;
this._params.blurAmount = params.blurAmount;
}
/**
* Sets these objects' materials' lightmaps and modifies their uv2's.
* @param {Object3D} objects An array of objects and lights to set up your lightmap.
*/
init(objects: Mesh[], lights: Light[]) {
// this._reset();
this._setObjects(objects);
this._setLights(lights);
}
private _setObjects(objects: Array<Mesh>) {
this.objectTargets = [];
for (let mesh of objects) {
if (this.blurringPlane == null) {
this._initializeBlurPlane(this.res, this.progressiveLightMap1);
}
this.objectTargets.push(mesh);
}
this._saveObjectsState();
}
private _setLights(lights: Array<Light>) {
this.lights = lights;
for (let light of lights) {
this._saveLightHierarchyState(light);
this.scene.attach(light);
this._saveLightMatrixState(light);
}
}
/**
* This function renders each mesh one at a time into their respective surface maps
* @param {Camera} camera Standard Rendering Camera
* @param {number} iterationBlend When >1, samples will accumulate over time.
* @param {boolean} blurEdges Whether to fix UV Edges via blurring
*/
private _objectStateByObject: WeakMap<Object3D, ObjectState> = new WeakMap();
private _previousRenderTarget: RenderTarget | null = null;
private _lightHierarchyStateByLight: WeakMap<Light, LightHierarchyState> = new WeakMap();
private _lightMatrixStateByLight: WeakMap<Light, LightMatrixState> = new WeakMap();
// private _reset() {
// this.firstUpdate = false;
// }
private _saveLightHierarchyState(light: Light) {
this._lightHierarchyStateByLight.set(light, {
parent: light.parent,
matrixAutoUpdate: light.matrixAutoUpdate,
});
light.matrixAutoUpdate = true;
}
private _t = new Vector3();
private _q = new Quaternion();
private _s = new Vector3();
private _saveLightMatrixState(light: Light) {
light.updateMatrix();
light.matrix.decompose(this._t, this._q, this._s);
this._lightMatrixStateByLight.set(light, {
matrix: light.matrix.clone(),
position: this._t.clone(),
});
}
private _saveObjectsState() {
let i = 0;
for (let object of this.objectTargets) {
this._objectStateByObject.set(object, {
frustumCulled: object.frustumCulled,
material: object.material,
parent: object.parent,
castShadow: object.castShadow,
receiveShadow: object.receiveShadow,
});
object.material = this.uvMat;
object.frustumCulled = false;
object.castShadow = true;
object.receiveShadow = true;
object.renderOrder = 1000 + i;
this.scene.attach(object);
i++;
}
this._previousRenderTarget = this.renderer.getRenderTarget();
}
private _moveLights() {
const lightRadius = this._params.lightRadius;
for (let light of this.lights) {
const state = this._lightMatrixStateByLight.get(light);
if (state) {
const position = state.position;
light.position.x = position.x + lightRadius * (Math.random() - 0.5);
light.position.y = position.y + lightRadius * (Math.random() - 0.5);
light.position.z = position.z + lightRadius * (Math.random() - 0.5);
}
}
}
restoreState() {
this._restoreObjectsState();
this._restoreLightsState();
this.renderer.setRenderTarget(this._previousRenderTarget);
}
private _restoreObjectsState() {
for (let object of this.objectTargets) {
const state = this._objectStateByObject.get(object);
if (state) {
object.frustumCulled = state.frustumCulled;
object.castShadow = state.castShadow;
object.receiveShadow = state.receiveShadow;
object.material = state.material;
const parent = state.parent;
if (parent) {
parent.add(object);
}
}
}
}
private _restoreLightsState() {
for (let light of this.lights) {
const stateH = this._lightHierarchyStateByLight.get(light);
const stateM = this._lightMatrixStateByLight.get(light);
if (stateH && stateM) {
light.matrixAutoUpdate = stateH.matrixAutoUpdate;
light.matrix.copy(stateM.matrix);
light.matrix.decompose(light.position, light.quaternion, light.scale);
light.updateMatrix();
stateH.parent?.attach(light);
}
}
}
runUpdates(camera: Camera) {
if (!this.blurMaterial) {
return;
}
if (this.blurringPlane == null) {
return;
}
const iterations = this._params.iterations;
this.blurMaterial.uniforms.pixelOffset.value = this._params.blurAmount / this.res;
this.blurringPlane.visible = this._params.blur;
this.uvMat.uniforms.iterationBlend.value = this._params.iterationBlend;
this._clear(camera);
for (let i = 0; i < iterations; i++) {
this._moveLights();
this._update(camera);
}
}
private _clear(camera: Camera) {
this.scene.visible = false;
this._update(camera);
this._update(camera);
this.scene.visible = true;
}
private _update(camera: Camera) {
if (!this.blurMaterial) {
return;
}
// Ping-pong two surface buffers for reading/writing
const activeMap = this.buffer1Active ? this.progressiveLightMap1 : this.progressiveLightMap2;
const inactiveMap = this.buffer1Active ? this.progressiveLightMap2 : this.progressiveLightMap1;
// Render the object's surface maps
this.renderer.setRenderTarget(activeMap);
this.uvMat.uniforms.previousShadowMap.value = inactiveMap.texture;
this.blurMaterial.uniforms.previousShadowMap.value = inactiveMap.texture;
this.buffer1Active = !this.buffer1Active;
this.renderer.render(this.scene, camera);
}
private _initializeBlurPlane(res: number, lightMap: WebGLRenderTarget) {
this.blurMaterial = this._createBlurPlaneMaterial(res, lightMap);
this.blurringPlane = new Mesh(new PlaneBufferGeometry(1, 1), this.blurMaterial);
this.blurringPlane.name = 'Blurring Plane';
this.blurringPlane.frustumCulled = false;
this.blurringPlane.renderOrder = 0;
this.blurMaterial.depthWrite = false;
this.scene.add(this.blurringPlane);
}
private _createBlurPlaneMaterial(res: number, lightMap: WebGLRenderTarget) {
const blurMaterial = new MeshBasicMaterial() as MeshBasicMaterialWithUniforms;
blurMaterial.uniforms = {
previousShadowMap: {value: null},
pixelOffset: {value: 1.0 / res},
// TODO: make sure this is not important
// polygonOffset: true,
// polygonOffsetFactor: -1,
// polygonOffsetUnits: 3.0,
};
blurMaterial.onBeforeCompile = (shader) => {
// Vertex Shader: Set Vertex Positions to the Unwrapped UV Positions
shader.vertexShader =
'#define USE_UV\n' +
shader.vertexShader.slice(0, -2) +
' gl_Position = vec4((uv - 0.5) * 2.0, 1.0, 1.0); }';
// Fragment Shader: Set Pixels to 9-tap box blur the current frame's Shadows
const bodyStart = shader.fragmentShader.indexOf('void main() {');
shader.fragmentShader =
'#define USE_UV\n' +
shader.fragmentShader.slice(0, bodyStart) +
' uniform sampler2D previousShadowMap;\n uniform float pixelOffset;\n' +
shader.fragmentShader.slice(bodyStart - 1, -2) +
` gl_FragColor.rgb = (
texture2D(previousShadowMap, vUv + vec2( pixelOffset, 0.0 )).rgb +
texture2D(previousShadowMap, vUv + vec2( 0.0 , pixelOffset)).rgb +
texture2D(previousShadowMap, vUv + vec2( 0.0 , -pixelOffset)).rgb +
texture2D(previousShadowMap, vUv + vec2(-pixelOffset, 0.0 )).rgb +
texture2D(previousShadowMap, vUv + vec2( pixelOffset, pixelOffset)).rgb +
texture2D(previousShadowMap, vUv + vec2(-pixelOffset, pixelOffset)).rgb +
texture2D(previousShadowMap, vUv + vec2( pixelOffset, -pixelOffset)).rgb +
texture2D(previousShadowMap, vUv + vec2(-pixelOffset, -pixelOffset)).rgb)/8.0;
}`;
// Set the LightMap Accumulation Buffer
const uniforms = {
previousShadowMap: {value: lightMap.texture},
pixelOffset: {value: 0.5 / res},
};
shader.uniforms.previousShadowMap = uniforms.previousShadowMap;
shader.uniforms.pixelOffset = uniforms.pixelOffset;
blurMaterial.uniforms.previousShadowMap = uniforms.previousShadowMap;
blurMaterial.uniforms.pixelOffset = uniforms.pixelOffset;
// Set the new Shader to this
blurMaterial.userData.shader = shader;
};
return blurMaterial;
}
private _createUVMat() {
const mat = new MeshPhongMaterial() as MeshPhongMaterialWithUniforms;
mat.uniforms = {
previousShadowMap: {value: null},
iterationBlend: {value: DEFAULT_ITERATION_BLEND},
};
mat.name = 'uvMat';
mat.onBeforeCompile = (shader) => {
// Vertex Shader: Set Vertex Positions to the Unwrapped UV Positions
shader.vertexShader =
'#define USE_LIGHTMAP\n' +
shader.vertexShader.slice(0, -2) +
' gl_Position = vec4((uv2 - 0.5) * 2.0, 1.0, 1.0); }';
// Fragment Shader: Set Pixels to average in the Previous frame's Shadows
const bodyStart = shader.fragmentShader.indexOf('void main() {');
shader.fragmentShader =
'varying vec2 vUv2;\n' +
shader.fragmentShader.slice(0, bodyStart) +
' uniform sampler2D previousShadowMap;\n uniform float iterationBlend;\n' +
shader.fragmentShader.slice(bodyStart - 1, -2) +
`\nvec3 texelOld = texture2D(previousShadowMap, vUv2).rgb;
gl_FragColor.rgb = mix(texelOld, gl_FragColor.rgb, iterationBlend);
// gl_FragColor.rgb = vec3(vUv2,1.0);
}`;
// Set the Previous Frame's Texture Buffer and Averaging Window
const uniforms = {
previousShadowMap: {value: this.progressiveLightMap1.texture},
iterationBlend: {value: DEFAULT_ITERATION_BLEND},
};
shader.uniforms.previousShadowMap = uniforms.previousShadowMap;
shader.uniforms.iterationBlend = uniforms.iterationBlend;
mat.uniforms.previousShadowMap = uniforms.previousShadowMap;
mat.uniforms.iterationBlend = uniforms.iterationBlend;
// Set the new Shader to this
mat.userData.shader = shader;
};
return mat;
}
} | the_stack |
import { inject, injectable } from 'inversify';
import * as apid from '../../../../../../api';
import IRuleApiModel from '../../../..//model/api/rule/IRuleApiModel';
import GenreUtil from '../../../../util/GenreUtil';
import IVideoApiModel from '../../..//api/video/IVideoApiModel';
import IRecordedApiModel from '../../../api/recorded/IRecordedApiModel';
import IChannelModel from '../../../channels/IChannelModel';
import IServerConfigModel from '../../../serverConfig/IServerConfigModel';
import { ISettingStorageModel } from '../../../storage/setting/ISettingStorageModel';
import IRecordedUploadState, { SelectorItem, UploadProgramOption, VideoFileItem } from './IRecordedUploadState';
@injectable()
class RecordedUploadState implements IRecordedUploadState {
public programOption: UploadProgramOption = {
ruleId: null,
channelId: undefined,
startAt: null,
duration: null,
name: null,
description: null,
extended: null,
genre1: undefined,
subGenre1: undefined,
};
public videoFileItems: VideoFileItem[] = [];
public ruleKeyword: string | null = null;
public ruleItems: apid.RuleKeywordItem[] = [];
public isShowPeriod: boolean = true;
private settingModel: ISettingStorageModel;
private channelModel: IChannelModel;
private serverConfig: IServerConfigModel;
private ruleApiModel: IRuleApiModel;
private recordedApiModel: IRecordedApiModel;
private videoApiModel: IVideoApiModel;
private channelItems: SelectorItem[] = [];
private genreItems: SelectorItem[] = [];
private subGemreItems: SelectorItem[][] = [];
private videoItemCnt: number = 0;
constructor(
@inject('IServerConfigModel') serverConfig: IServerConfigModel,
@inject('ISettingStorageModel') settingModel: ISettingStorageModel,
@inject('IChannelModel') channelModel: IChannelModel,
@inject('IRuleApiModel') ruleApiModel: IRuleApiModel,
@inject('IRecordedApiModel') recordedApiModel: IRecordedApiModel,
@inject('IVideoApiModel') videoApiModel: IVideoApiModel,
) {
this.serverConfig = serverConfig;
this.settingModel = settingModel;
this.channelModel = channelModel;
this.ruleApiModel = ruleApiModel;
this.recordedApiModel = recordedApiModel;
this.videoApiModel = videoApiModel;
this.genreItems = GenreUtil.getGenreListItems();
for (let i = 0; i < GenreUtil.GENRE_MAX_NUM; i++) {
this.subGemreItems.push(GenreUtil.getSubGenreListItems(i));
}
}
/**
* 各種変数初期化
*/
public init(): void {
this.programOption = {
ruleId: null,
channelId: undefined,
startAt: null,
duration: null,
name: null,
description: null,
extended: null,
genre1: undefined,
subGenre1: undefined,
};
this.videoItemCnt = 0;
this.videoFileItems = [];
this.addEmptyVideoFileItem();
if (this.channelItems.length === 0) {
const channels = this.channelModel.getChannels(this.settingModel.getSavedValue().isHalfWidthDisplayed);
for (const c of channels) {
this.channelItems.push({
text: c.name,
value: c.id,
});
}
}
}
/**
* 各種データ取得
* @return Promise<void>
*/
public async fetchData(): Promise<void> {
await this.updateRuleItems();
}
/**
* ルール item 更新
*/
public async updateRuleItems(): Promise<void> {
const keywordItems = await this.ruleApiModel.searchKeyword(this.createSearchKeywordOption());
this.ruleItems.splice(-this.ruleItems.length);
for (const k of keywordItems) {
this.ruleItems.push(k);
}
}
/**
* ルールのキーワード検索オプション生成
* @return apid.GetRuleOption
*/
private createSearchKeywordOption(): apid.GetRuleOption {
const option: apid.GetRuleOption = {
limit: RecordedUploadState.KEYWORD_SEARCH_LIMIT,
};
if (this.ruleKeyword !== null) {
option.keyword = this.ruleKeyword;
}
return option;
}
/**
* 放送局 item を返す
* @return SelectorItem[]
*/
public getChannelItems(): SelectorItem[] {
return this.channelItems;
}
/**
* 親ディレクトリ item を返す
* @return string[]
*/
public getPrentDirectoryItems(): string[] {
const config = this.serverConfig.getConfig();
return config === null ? [] : config.recorded;
}
/**
* ファイルタイプ item を返す
* @return apid.VideoFileType[]
*/
public getFileTypeItems(): apid.VideoFileType[] {
return ['ts', 'encoded'];
}
/**
* ジャンル item を返す
* @return SelectorItem[]
*/
public getGenreItems(): SelectorItem[] {
return this.genreItems;
}
/**
* サブジャンル items を返す
* @return SelectorItem[]
*/
public getSubGenreItems(): SelectorItem[] {
return typeof this.programOption.genre1 === 'undefined' || this.programOption.genre1 < 0 || this.programOption.genre1 > GenreUtil.GENRE_MAX_NUM
? []
: this.subGemreItems[this.programOption.genre1];
}
/**
* videoFileItems に空要素追加
*/
public addEmptyVideoFileItem(): void {
this.videoFileItems.push({
key: this.videoItemCnt,
parentDirectoryName: this.getPrentDirectoryItems()[0],
subDirectory: null,
viewName: null,
fileType: undefined,
file: null,
});
this.videoItemCnt++;
}
/**
* 入力値のチェック
* @return true 入力値に問題なければ true を返す
*/
public checkInput(): boolean {
if (typeof this.programOption.channelId !== 'number') {
return false;
}
if (this.programOption.startAt === null) {
return false;
}
if (typeof this.programOption.duration !== 'number' || this.programOption.duration <= 0) {
return false;
}
if (typeof this.programOption.name !== 'string') {
return false;
}
if (this.videoFileItems.length === 0 || this.checkVideoFileItemInput(this.videoFileItems[0]) === false) {
return false;
}
return true;
}
/**
* ビデオファイル入力チェック
* @param item: VideoFileItem
* @return boolean
*/
private checkVideoFileItemInput(item: VideoFileItem): boolean {
if (typeof item.viewName !== 'string') {
return false;
}
if (typeof item.fileType !== 'string') {
return false;
}
if (typeof item.parentDirectoryName !== 'string') {
return false;
}
if (typeof item.file === 'undefined' || item.file === null) {
return false;
}
return true;
}
/**
* ファイルアップロード処理
* @return Promise<void>
*/
public async upload(): Promise<void> {
if (this.checkInput() === false) {
throw new Error('InputError');
}
const recordedId = await this.recordedApiModel.createNewRecorded(this.createProgramOption());
for (const video of this.videoFileItems) {
if (
typeof video.parentDirectoryName !== 'string' ||
typeof video.viewName !== 'string' ||
video.viewName.length === 0 ||
typeof video.fileType !== 'string' ||
typeof video.file === 'undefined' ||
video.file === null
) {
continue;
}
const uploadVideoOption: apid.UploadVideoFileOption = {
recordedId: recordedId,
parentDirectoryName: video.parentDirectoryName,
viewName: video.viewName,
fileType: video.fileType as apid.VideoFileType,
file: video.file,
};
if (typeof video.subDirectory === 'string' && video.subDirectory.length > 0) {
uploadVideoOption.subDirectory = video.subDirectory;
}
try {
await this.videoApiModel.uploadedVideoFile(uploadVideoOption);
} catch (err) {
// アップロードに失敗したら番組情報を削除する
await this.recordedApiModel.delete(recordedId).catch(e => {
console.error(e);
});
throw err;
}
}
}
/**
* アップロードするビデオファイルの番組情報を生成する
* @return apid.CreateNewRecordedOption
*/
private createProgramOption(): apid.CreateNewRecordedOption {
if (
typeof this.programOption.channelId === 'undefined' ||
this.programOption.startAt === null ||
typeof this.programOption.duration !== 'number' ||
typeof this.programOption.name !== 'string'
) {
throw new Error('ProgramError');
}
const startAt = this.programOption.startAt.getTime();
const option: apid.CreateNewRecordedOption = {
channelId: this.programOption.channelId,
startAt: startAt,
endAt: startAt + this.programOption.duration * 60 * 1000,
name: this.programOption.name,
};
if (typeof this.programOption.ruleId === 'number') {
option.ruleId = this.programOption.ruleId;
}
if (typeof this.programOption.description === 'string') {
option.description = this.programOption.description;
}
if (typeof this.programOption.extended === 'string') {
option.extended = this.programOption.extended;
}
if (typeof this.programOption.genre1 === 'number') {
option.genre1 = this.programOption.genre1;
}
if (typeof this.programOption.subGenre1 === 'number') {
option.subGenre1 = this.programOption.subGenre1;
}
return option;
}
}
namespace RecordedUploadState {
export const KEYWORD_SEARCH_LIMIT = 1000;
}
export default RecordedUploadState; | the_stack |
import Editor = require('../editor/index');
import is = require('../is/index');
import selection = require('current-selection');
import range = require('current-range');
import split = require('split-at-range');
import position = require('./range-position');
import classes = require('component-classes');
import matches = require('matches-selector');
import DEBUG = require('debug');
import inlineElements = require('inline-elements');
import voidElements = require('void-elements');
import collapse = require('collapse');
import leafRange = require('./leaf-range');
/**
* debug
*/
var debug = DEBUG('editor:input-normalizer');
var NON_VOID_INLINE_ELEMENTS = inlineElements.filter((el) => voidElements.indexOf(el) == -1 ).join(', ');
/**
* Helper function to select an element
*/
function select(n: Node, around: boolean = false): void {
var s = selection(document);
var r = document.createRange();
if (around) {
r.selectNode(n);
} else {
r.selectNodeContents(n);
}
s.removeAllRanges();
s.addRange(r);
}
/**
* Helper function to create a newline paragraph
*/
function newline(): HTMLElement {
var p = document.createElement('p');
var n = document.createElement('br');
p.appendChild(n);
return p;
}
class InputNormalizer {
private editor: Editor;
constructor(editor: Editor) {
if (!(this instanceof InputNormalizer)) {
return new InputNormalizer(editor);
}
this.editor = editor;
document.addEventListener('keydown', this.normalize.bind(this), false);
document.addEventListener('keypress', this.normalizeOnKeyPress.bind(this), false);
document.addEventListener('compositionstart', this.normalizeOnCompositionStart.bind(this), false);
document.addEventListener('paste', this.normalizeOnPaste.bind(this), true);
}
public normalize(e: KeyboardEvent) {
// bail if a plugin has already cancelled this event
if (e.defaultPrevented) return debug('not normalizing, event already cancelled: %o', e);
// bail if the keyboard event happened outside of the Editor
if (this.editor.mousetrapStopCallback(e, <Node>e.target)) return;
var s = selection(document);
var r = range(s);
if (!r) return;
// Are both ends of the Range on the same container element?
// If they're not, leave default browser behavior alone.
// When necessary, a proper collapsed check is done on the
// more specific functions called below.
if (r.startContainer != r.endContainer) return;
var node = this.figureOutNodeForRange(r);
// Overlay reference interactions
if (is.overlayReference(node)) {
this.normalizeOnOverlayReference(e, s, r, node);
}
// Empty paragraph interactions
else if (is.emptyParagraph(node)) {
this.normalizeOnEmptyParagraph(e, s, r, node);
}
// General interactions
else {
this.normalizeGeneric(e, s, r, node);
}
// FIX: this is a fix for an IE bug where surprisingly
// text can end up inserted *inside* a BR tag
r = range(s);
// check if selection range lies within a BR element
if (r.startContainer.nodeName == 'BR') {
// move it to outside, after the BR element
select(r.startContainer, true);
collapse.toStart(s);
}
}
/**
* Normalizes input when a compositon starts
*/
private normalizeOnCompositionStart(e: CompositionEvent) {
var s = selection(document);
var r = range(s);
if (!r) return;
var node = this.figureOutNodeForRange(r);
// Overlay reference interactions
if (is.overlayReference(node)) {
var ref = <HTMLElement>node;
this.editor.transactions.run(() => {
var p = newline();
ref.parentNode.insertBefore(p, ref.nextSibling);
select(p);
collapse.toStart(s);
});
}
// Empty paragraph interactions
else if (is.emptyParagraph(node)) {
// nothing to normalize for now
}
// General interactions
else {
if (!r.collapsed) {
return;
}
var tcm;
if (tcm = this.topmostContainerMatching(r.startContainer, 'a')) {
this.normalizeOnAnchor(e, s, r, tcm);
} else if (tcm = this.topmostContainerMatching(r.startContainer, '.zwsp')) {
this.normalizeOnZwspSpan(e, s, r, tcm);
}
}
}
/**
* Normalizes input when a paste takes place
*/
private normalizeOnPaste(e: ClipboardEvent) {
var s = selection(document);
var r = range(s);
if (!r) return;
var node = this.figureOutNodeForRange(r);
// Overlay reference interactions
if (is.overlayReference(node)) {
// nothing to normalize for now
}
// Empty paragraph interactions
else if (is.emptyParagraph(node)) {
// nothing to normalize for now
}
// General interactions
else {
if (!r.collapsed) {
return;
}
var tcm;
if (tcm = this.topmostContainerMatching(r.startContainer, 'a')) {
this.normalizeOnAnchor(e, s, r, tcm);
} else if (tcm = this.topmostContainerMatching(r.startContainer, '.zwsp')) {
this.normalizeOnZwspSpan(e, s, r, tcm);
}
}
}
/**
* Normalizes input when a printable key gets pressed
*/
private normalizeOnKeyPress(e: KeyboardEvent) {
var s = selection(document);
var r = range(s);
if (!r) return;
var node = this.figureOutNodeForRange(r);
// Overlay reference interactions
if (is.overlayReference(node)) {
// nothing to normalize for now
}
// Empty paragraph interactions
else if (is.emptyParagraph(node)) {
// nothing to normalize for now
}
// General interactions
else {
if (!r.collapsed) {
return;
}
var tcm;
if (tcm = this.topmostContainerMatching(r.startContainer, 'a')) {
this.normalizeOnAnchor(e, s, r, tcm);
} else if (tcm = this.topmostContainerMatching(r.startContainer, '.zwsp')) {
this.normalizeOnZwspSpan(e, s, r, tcm);
}
}
}
/**
* Figures out the node the range lies on
*/
private figureOutNodeForRange(r: Range): Node {
var node = r.startContainer;
// Fixes a Firefox bug where the caret ends up outside of the
// paragraphs, and text nodes are added to the root when typing.
if (node == this.editor.el && r.startOffset == r.endOffset) {
var ctnr = node.childNodes[r.startOffset];
if (!ctnr) {
ctnr = node.lastChild;
var offset = (ctnr.nodeType == Node.ELEMENT_NODE) ? ctnr.childNodes.length : ctnr.textContent.length;
r.setStart(ctnr, offset);
r.setEnd(ctnr, offset);
} else {
r.setStart(ctnr, 0);
r.setEnd(ctnr, 0);
}
node = ctnr;
}
return node;
}
/**
* Find the topmost element that we can split
*/
private topmostSplittableNode(node: Node): Node {
for (;;) {
if (!node.parentNode) return;
if (node.parentNode == this.editor.el) break;
// Properly break list items
if (node.nodeName == 'LI' && node.parentNode.nodeName == 'UL') break;
if (node.nodeName == 'LI' && node.parentNode.nodeName == 'OL') break;
// Properly break elements inside block quotes
if (node.parentNode.nodeName == 'BLOCKQUOTE') break;
node = node.parentNode;
}
return node;
}
/**
* Find the topmost element that matches a given selector
*/
private topmostContainerMatching(node: Node, selector: string): HTMLElement {
var tcm: HTMLElement = null;
for (;;) {
if (node.nodeType == Node.ELEMENT_NODE) {
if (matches(<HTMLElement>node, selector)) {
tcm = <HTMLElement>node;
}
}
if ((!node.parentNode) || (node.parentNode == this.editor.el)) break;
node = node.parentNode;
}
return tcm;
}
/**
* Normalizes input when the caret is on an Overlay Reference
*/
private normalizeOnOverlayReference(e: KeyboardEvent, s: Selection, r: Range, node: Node): void {
var ref = <HTMLElement>node;
if (e.which == 13 /* Enter */) {
if (e.altKey || e.ctrlKey || e.metaKey) return;
if (e.shiftKey) {
this.editor.transactions.run(() => {
var p = newline();
ref.parentNode.insertBefore(p, ref);
select(p);
collapse.toStart(s);
});
} else {
this.editor.transactions.run(() => {
var p = newline();
ref.parentNode.insertBefore(p, ref.nextSibling);
select(p);
collapse.toStart(s);
});
}
e.preventDefault();
} else if (e.which == 37 /* Left */ || e.which == 38 /* Up */) {
if (e.shiftKey || e.altKey || e.ctrlKey || e.metaKey) return;
if (!ref.previousElementSibling) {
this.editor.transactions.run(() => {
var p = newline();
ref.parentNode.insertBefore(p, ref);
select(p);
collapse.toStart(s);
});
e.preventDefault();
}
} else if (e.which == 39 /* Right */ || e.which == 40 /* Down */) {
if (e.shiftKey || e.altKey || e.ctrlKey || e.metaKey) return;
if (!ref.nextElementSibling) {
this.editor.transactions.run(() => {
var p = newline();
ref.parentNode.appendChild(p);
select(p);
collapse.toStart(s);
});
e.preventDefault();
}
} else if (e.which == 8 /* Backwards delete ("Backspace") */) {
if (e.shiftKey || e.altKey || e.ctrlKey || e.metaKey) return;
this.editor.transactions.run(() => {
if (ref.previousElementSibling) {
select(ref.previousElementSibling);
collapse.toEnd(s);
} else if (ref.nextElementSibling) {
select(ref.nextElementSibling);
collapse.toStart(s);
} else {
var p = newline();
ref.parentNode.insertBefore(p, ref);
select(p);
collapse.toStart(s);
}
ref.parentNode.removeChild(ref);
});
e.preventDefault();
} else if (e.which == 46 /* Forward delete */) {
if (e.shiftKey || e.altKey || e.ctrlKey || e.metaKey) return;
this.editor.transactions.run(() => {
if (ref.nextElementSibling) {
select(ref.nextElementSibling);
collapse.toStart(s);
} else if (ref.previousElementSibling) {
select(ref.previousElementSibling);
collapse.toEnd(s);
} else {
var p = newline();
ref.parentNode.insertBefore(p, ref);
select(p);
collapse.toStart(s);
}
ref.parentNode.removeChild(ref);
});
e.preventDefault();
}
}
/**
* Normalizes input when the caret is on an empty paragraph
*/
private normalizeOnEmptyParagraph(e: KeyboardEvent, s: Selection, r: Range, node: Node): void {
debug('normalize empty paragraph');
var blank = <HTMLElement>node;
if (e.which == 8 /* Backward Delete ("Backspace") */) {
if (e.shiftKey || e.altKey || e.ctrlKey || e.metaKey) return;
if (blank.previousElementSibling) {
this.editor.transactions.run(() => {
var prev = blank.previousElementSibling;
while (is.list(prev) && prev.lastElementChild) {
prev = prev.lastElementChild;
}
select(prev);
var tr = s.getRangeAt(0);
collapse.toEnd(s);
tr = s.getRangeAt(0);
blank.parentNode.removeChild(blank);
});
e.preventDefault();
}
} else if (e.which == 46 /* Forward Delete */) {
if (e.shiftKey || e.altKey || e.ctrlKey || e.metaKey) return;
if (blank.nextElementSibling) {
this.editor.transactions.run(() => {
select(blank.nextElementSibling);
collapse.toStart(s);
blank.parentNode.removeChild(blank);
});
e.preventDefault();
}
} else if (e.which == 13 /* Enter */) {
if (e.altKey || e.ctrlKey || e.metaKey) return;
if (e.shiftKey) {
e.preventDefault();
var br = document.createElement('br');
node.appendChild(br);
select(br, true);
collapse.toEnd(s);
}
}
}
/**
* Normalize generic editor content
*/
private normalizeGeneric(e: KeyboardEvent, s: Selection, r: Range, node: Node): void {
// check for selected text
if (!r.collapsed) {
return;
}
// find the topmost element that we can split
node = this.topmostSplittableNode(node);
var p = position(r, node);
if (e.which == 13 /* Enter */) {
if (e.altKey || e.ctrlKey || e.metaKey) {
e.preventDefault();
return;
}
if (this.editor.tokens.handleEnter()) {
e.preventDefault();
return;
}
// elements
var el;
// are we at the end of the element?
if (p == position.END) {
debug('end of element');
this.editor.transactions.run(() => {
var name = node.nodeName;
if (name.match(/^H[1-6]$/)) {
name = 'p';
}
if (e.shiftKey) {
while (node.lastChild.nodeType == Node.ELEMENT_NODE &&
matches(<HTMLElement>node.lastChild, NON_VOID_INLINE_ELEMENTS)) {
node = node.lastChild;
}
// when inserting a line break after a text node we actually need to
// insert *two* BR elements to get the desired empty line. The first BR
// causes the existing line to break, and the second one creates an editable
// empty line. If we already have a BR element in place we
// don't need the second one.
if (node.lastChild.nodeName != 'BR') {
node.appendChild(document.createElement('br'));
}
var n = document.createElement('br');
node.appendChild(n);
select(n, true);
collapse.toStart(s);
} else {
el = document.createElement(name);
var styleAttr = (<HTMLElement>node).getAttribute('style');
if (styleAttr) {
el.setAttribute('style', styleAttr);
}
el.appendChild(document.createElement('br'));
node.parentNode.insertBefore(el, node.nextSibling);
select(el);
collapse.toStart(s);
}
});
}
// are we at the start of the element?
else if (p == position.START) {
debug('start of element');
if (is.emptyListItem(node)) {
e.preventDefault();
this.editor.transactions.run(() => {
var newList = document.createElement(node.parentNode.nodeName);
var newParagraph = document.createElement('p');
// move BR to paragraph
newParagraph.appendChild(node.firstChild);
while (node.nextSibling) {
newList.appendChild(node.nextSibling);
}
if (newList.childNodes.length > 0) {
node.parentNode.parentNode.insertBefore(newList, node.parentNode.nextSibling);
}
node.parentNode.parentNode.insertBefore(newParagraph, node.parentNode.nextSibling);
node.parentNode.removeChild(node);
select(newParagraph);
collapse.toStart(s);
});
return;
}
this.editor.transactions.run(() => {
var name = node.nodeName;
if (name.match(/^H[1-6]$/)) {
name = 'p';
}
if (e.shiftKey) {
var n = document.createElement('br');
r.insertNode(n);
select(n);
collapse.toEnd(s);
} else {
var el = document.createElement(name);
var styleAttr = (<HTMLElement>node).getAttribute('style');
if (styleAttr) {
el.setAttribute('style', styleAttr);
}
el.appendChild(document.createElement('br'));
node.parentNode.insertBefore(el, node);
}
});
}
// we're at the middle of the element.
else {
debug('middle of element');
r = leafRange(r);
var parts = split(node, r);
this.editor.transactions.run(() => {
if (e.shiftKey) {
var n = document.createElement('br');
r.insertNode(n);
select(n, true);
collapse.toEnd(s);
} else {
node.parentNode.insertBefore(parts[0], node);
node.parentNode.insertBefore(parts[1], node);
select(node.previousSibling);
node.parentNode.removeChild(node);
collapse.toStart(s);
}
});
}
e.preventDefault();
} else if (e.which == 8 /* Backward delete ("backspace") */) {
// are we at the start of the element
if (p == position.START) {
e.preventDefault();
if (is.listItem(node)) {
var parent = node.parentNode;
var parentName = parent.nodeName;
// first list item in a list, and another
// list of the same type right before
if (!node.previousSibling &&
parent.previousSibling &&
parent.previousSibling.nodeName == parentName) {
this.editor.transactions.run(() => {
while(parent.firstChild) {
parent.previousSibling.appendChild(parent.firstChild);
}
parent.parentNode.removeChild(parent);
select(node);
collapse.toStart(s);
});
return;
}
this.editor.transactions.run(() => {
var otherList = document.createElement(parentName);
while (node.nextSibling) {
otherList.appendChild(node.nextSibling);
}
var newParagraph = document.createElement('p');
while (node.firstChild) {
newParagraph.appendChild(node.firstChild);
}
parent.removeChild(node);
parent.parentNode.insertBefore(otherList, parent.nextSibling);
parent.parentNode.insertBefore(newParagraph, parent.nextSibling);
select(newParagraph);
collapse.toStart(s);
return;
});
}
var prev = node.previousSibling;
var first = node.firstChild;
if (!prev) {
return;
} else if (is.emptyParagraph(prev)) {
this.editor.transactions.run(() => {
prev.parentNode.removeChild(prev);
});
} else if (is.overlayReference(prev)) {
this.editor.transactions.run(() => {
select(prev);
collapse.toStart(s);
});
} else if (is.list(prev) && prev.lastChild) {
this.editor.transactions.run(() => {
var referencePoint = node.firstChild;
while (node.firstChild) {
prev.lastChild.appendChild(node.firstChild);
}
node.parentNode.removeChild(node);
select(referencePoint, true);
collapse.toStart(s);
});
} else {
this.editor.transactions.run(() => {
while (node.firstChild) {
prev.appendChild(node.firstChild);
}
select(first, true);
collapse.toStart(s);
node.parentNode.removeChild(node);
});
}
}
} else if (e.which == 46 /* Forward delete */) {
// are we at the end of the element?
if (p == position.END) {
e.preventDefault();
var next = node.nextSibling;
var last = node.lastChild;
if (!next) {
return;
} else if (is.emptyParagraph(next)) {
this.editor.transactions.run(() => {
next.parentNode.removeChild(next);
});
} else {
this.editor.transactions.run(() => {
while (next.firstChild) {
node.appendChild(next.firstChild);
}
select(last, true);
collapse.toEnd(s);
node.parentNode.removeChild(next);
});
}
}
} else if (e.which == 27 /* Escape */) {
if (this.editor.tokens.handleEsc()) {
e.preventDefault();
return;
}
}
}
/**
* Normalize input when inside anchors (repositions caret to fix Firefox bug
* where user would get "stuck" inside an anchor.)
*/
private normalizeOnAnchor(e: KeyboardEvent | CompositionEvent | ClipboardEvent, s: Selection, r: Range, tcm: HTMLElement): void {
// TODO: make sure this is 100% robust, interacts better with undo and that
// we absolutely never keep zwsps laying around.
var ptcm = position(r, tcm);
if (ptcm == position.END) {
this.editor.transactions.run(() => {
var zwsp = document.createTextNode('\u200b');
tcm.parentNode.insertBefore(zwsp, tcm.nextSibling);
select(zwsp);
});
} else if (ptcm == position.START) {
this.editor.transactions.run(() => {
var zwsp = document.createTextNode('\u200b');
tcm.parentNode.insertBefore(zwsp, tcm);
select(zwsp);
});
}
}
/**
* Normalize when the cursor is inside a `.zwsp` node, which by convention
* is assumed to contain a single TextNode with the '\u200b' 0-width space
* inside. This normalizer:
*
* 1) unwraps the .zwsp SPAN's child node(s) to be before the SPAN
* 2) remove the .zwsp SPAN from the DOM completely
* if keyCode is "space" (32), then:
* 3) removes the 0-width space, and manually inserts a space char TextNode
see: http://git.io/vfT5k
* else
* 3) selects the 0-width space, but *doesn't* cancel then native event
*
* What happens next is the native keyboard event happens, and the selected
* 0-width space is immediately removed by new contents input from the keyboard.
*/
private normalizeOnZwspSpan(e: KeyboardEvent | CompositionEvent | ClipboardEvent, s: Selection, r: Range, tcm: HTMLElement): void {
debug('normalizing zero width space span (span=%o)', tcm);
var parent: HTMLElement = <HTMLElement>tcm.parentNode;
var zwsp: Node = tcm.firstChild;
while (tcm.firstChild) parent.insertBefore(tcm.firstChild, tcm);
parent.removeChild(tcm);
if ((<KeyboardEvent>e).which == 32 /* Space */) {
debug('removing zero width TextNode %o, adding space char manually', zwsp);
e.preventDefault();
var space = document.createTextNode(' ');
r.deleteContents();
r.insertNode(space);
select(space);
collapse.toEnd(s);
// remove the 0-width space TextNode
parent.removeChild(zwsp);
} else {
debug('selecting zero width TextNode %o, not preventing default', zwsp);
select(zwsp, true);
}
}
}
export = InputNormalizer; | the_stack |
import nj from '../core';
import * as tools from '../utils/tools';
import * as tranData from '../transforms/transformData';
import { unescape } from '../utils/escape';
import { extensionConfig } from '../helpers/extension';
import { filterConfig } from '../helpers/filter';
const GLOBAL = 'g';
const CONTEXT = 'c';
const PARAMS = 'p';
function _buildFn(content, node, fns, no, newContext, level, useStringLocal?) {
let fnStr = '';
const useString = useStringLocal != null ? useStringLocal : fns.useString,
main = no === 0,
/* retType
1: single child node
2: multiple child nodes
object: not build function
*/
retType = content.length === 1 ? '1' : '2',
counter = {
_type: 0,
_params: 0,
_compParam: 0,
_children: 0,
_dataRefer: 0,
_ex: 0,
_value: 0,
_filter: 0,
_fnH: 0,
_tmp: 0,
newContext
};
if (!useString) {
counter._compParam = 0;
} else {
counter._children = 0;
}
if (!main && newContext) {
fnStr += `${CONTEXT} = ${GLOBAL}.n(${CONTEXT}, ${PARAMS});\n`;
}
if (retType === '2') {
if (!useString) {
fnStr += 'var ret = [];\n';
} else {
fnStr += `var ret = '';\n`;
}
}
fnStr += _buildContent(content, node, fns, counter, retType, level, useStringLocal);
if (retType === '2') {
fnStr += 'return ret;';
}
try {
/* build template functions
g: global configs
c: context
p: parameters
*/
fns[main ? 'main' : 'fn' + no] = new Function(GLOBAL, CONTEXT, PARAMS, fnStr);
} catch (err) {
tools.error('Failed to generate template function:\n\n' + err.toString() + ' in\n\n' + fnStr + '\n');
}
return no;
}
function _buildOptions(config, useStringLocal, node, fns, level, hashProps?, tagName?, tagProps?) {
let hashStr = ', useString: ' + (useStringLocal == null ? `${GLOBAL}.us` : useStringLocal ? 'true' : 'false');
const noConfig = !config,
no = fns._no;
if (node) {
//tags
const newContext = config ? config.newContext : true;
const isDirective = node.isDirective || (config && config.isDirective);
if (noConfig || config.hasName) {
hashStr += `, name: '${node.ex}'`;
}
if (tagName && isDirective && (noConfig || !config.noTagName)) {
hashStr += ', tagName: ' + tagName;
hashStr += `, setTagName: function(c) { ${tagName} = c }`;
}
if (tagProps && (noConfig || config.hasTagProps)) {
hashStr += ', tagProps: ' + tagProps;
}
if (hashProps != null) {
hashStr += ', props: ' + hashProps;
}
hashStr +=
', ' +
(isDirective ? 'value' : 'children') +
': ' +
(node.content
? `${GLOBAL}.r(${GLOBAL}, ${CONTEXT}, ${GLOBAL}.fn` +
_buildFn(node.content, node, fns, ++fns._no, newContext, level, useStringLocal) +
')'
: `${GLOBAL}.np`);
}
return (
'{ _njOpts: ' +
(no + 1) +
(noConfig || config.hasTmplCtx ? `, global: ${GLOBAL}, context: ${CONTEXT}` : '') +
(noConfig || config.hasOutputH ? ', outputH: ' + !fns.useString : '') +
hashStr +
(level != null && (noConfig || config.hasLevel) ? ', level: ' + level : '') +
' }'
);
}
const CUSTOM_VAR = 'nj_custom';
const OPERATORS = [
'+',
'-',
'*',
'/',
'%',
'===',
'!==',
'==',
'!=',
'<=',
'>=',
'=',
'+=',
'<',
'>',
'&&',
'||',
'?',
':'
];
const ASSIGN_OPERATORS = ['=', '+='];
const SP_FILTER_REPLACE = {
or: '||'
};
function _buildDataValue(ast, escape, fns, level) {
let dataValueStr,
special: any = false;
const { isBasicType, isAccessor, hasSet } = ast;
if (isBasicType) {
dataValueStr = ast.name;
} else {
const { name, parentNum } = ast;
let data = '',
specialP = false;
switch (name) {
case '@index':
data = 'index';
special = true;
break;
case '@item':
data = 'item';
special = true;
break;
case 'this':
data = 'data';
special = data => `${data}[${data}.length - 1]`;
break;
case '@data':
data = 'data';
special = true;
break;
case '@g':
data = `${GLOBAL}.g`;
special = CUSTOM_VAR;
break;
case '@context':
data = CONTEXT;
special = CUSTOM_VAR;
break;
case '@lt':
data = `'<'`;
special = CUSTOM_VAR;
break;
case '@gt':
data = `'>'`;
special = CUSTOM_VAR;
break;
case '@lb':
data = `'{'`;
special = CUSTOM_VAR;
break;
case '@rb':
data = `'}'`;
special = CUSTOM_VAR;
break;
case '@q':
data = `'"'`;
special = CUSTOM_VAR;
break;
case '@sq':
data = `"'"`;
special = CUSTOM_VAR;
break;
}
if (parentNum) {
if (!data) {
data = 'data';
}
const isCtx = data == CONTEXT;
for (let i = 0; i < parentNum; i++) {
data = !isCtx ? 'parent.' + data : data + '.parent';
}
if (!special) {
specialP = true;
}
}
if (!special && !specialP) {
dataValueStr =
(isAccessor ? `${GLOBAL}.c(` : '') +
`${CONTEXT}.d('` +
name +
`'` +
(hasSet ? ', 0, true' : '') +
')' +
(isAccessor ? `, ${CONTEXT}` + ')' : '');
} else {
const isCustomVar = special === CUSTOM_VAR;
let dataStr = isCustomVar ? data : `${CONTEXT}.` + data;
if (tools.isObject(special)) {
dataStr = special(dataStr);
}
dataValueStr = special
? isCustomVar || !hasSet
? dataStr
: `{ source: c, value: ${dataStr}, prop: '${data}', _njSrc: true }`
: (isAccessor ? `${GLOBAL}.c(` : '') +
`${CONTEXT}.d('` +
name +
`', ` +
dataStr +
(hasSet ? ', true' : '') +
')' +
(isAccessor ? `, ${CONTEXT}` + ')' : '');
}
}
if (dataValueStr) {
dataValueStr = _replaceBackslash(dataValueStr);
}
return _buildEscape(dataValueStr, fns, isBasicType || isAccessor ? false : escape, special);
}
function replaceFilterName(name) {
const nameR = SP_FILTER_REPLACE[name];
return nameR != null ? nameR : name;
}
export function buildExpression(ast, inObj, escape, fns, useStringLocal, level) {
let codeStr =
ast.filters && OPERATORS.indexOf(replaceFilterName(ast.filters[0].name)) < 0
? ''
: !inObj
? _buildDataValue(ast, escape, fns, level)
: ast.name;
let lastCodeStr = '';
ast.filters &&
ast.filters.forEach((filter, i) => {
const hasFilterNext = ast.filters[i + 1] && OPERATORS.indexOf(replaceFilterName(ast.filters[i + 1].name)) < 0;
const filterName = replaceFilterName(filter.name);
if (OPERATORS.indexOf(filterName) >= 0) {
//Native operator
if (ASSIGN_OPERATORS.indexOf(filterName) >= 0) {
codeStr += `.source.${i == 0 ? ast.name : tools.clearQuot(ast.filters[i - 1].params[0].name)} ${filterName} `;
} else {
codeStr += ` ${filterName} `;
}
if (!ast.filters[i + 1] || OPERATORS.indexOf(replaceFilterName(ast.filters[i + 1].name)) >= 0) {
if (filter.params[0].filters) {
codeStr += '(';
codeStr += buildExpression(filter.params[0], null, escape, fns, useStringLocal, level);
codeStr += ')';
} else {
codeStr += _buildDataValue(filter.params[0], escape, fns, level);
}
}
} else if (filterName === '_') {
//Call function
let _codeStr = `${GLOBAL}.f['${filterName}'](${lastCodeStr}`;
if (filter.params.length) {
_codeStr += ', [';
filter.params.forEach((param, j) => {
_codeStr += buildExpression(param, null, escape, fns, useStringLocal, level);
if (j < filter.params.length - 1) {
_codeStr += ', ';
}
});
_codeStr += ']';
}
_codeStr += ')';
if (hasFilterNext) {
lastCodeStr = _codeStr;
} else {
codeStr += _codeStr;
lastCodeStr = '';
}
} else {
//Custom filter
let startStr, endStr, isObj, configF;
const isMethod = ast.isEmpty && i == 0;
if (filterName === 'bracket') {
startStr = '(';
endStr = ')';
} else if (filterName === 'list') {
startStr = '[';
endStr = ']';
} else if (filterName === 'obj') {
startStr = '{ ';
endStr = ' }';
isObj = true;
} else {
if (filterName == 'require') {
startStr = 'require';
} else {
const filterStr = `${GLOBAL}.f['${filterName}']`,
warnStr = `${GLOBAL}.wn('${filterName}', 'f')`,
isDev = process.env.NODE_ENV !== 'production';
configF = filterConfig[filterName];
if (configF && configF.onlyGlobal) {
startStr = isDev ? `(${filterStr} || ${warnStr})` : filterStr;
} else {
startStr = `${GLOBAL}.cf(${CONTEXT}.d('${filterName}', 0, true) || ${filterStr}${
isDev ? ` || ${warnStr}` : ''
})`;
}
}
startStr += '(';
endStr = ')';
}
let _codeStr = startStr;
if (isMethod) {
//Method
filter.params.forEach((param, j) => {
_codeStr += buildExpression(param, isObj, escape, fns, useStringLocal, level);
if (j < filter.params.length - 1) {
_codeStr += ', ';
}
});
} else {
//Operator
if (i == 0) {
_codeStr += _buildDataValue(ast, escape, fns, level);
} else if (lastCodeStr !== '') {
_codeStr += lastCodeStr;
} else {
if (ast.filters[i - 1].params[0].filters) {
_codeStr += buildExpression(ast.filters[i - 1].params[0], null, escape, fns, useStringLocal, level);
} else {
_codeStr += _buildDataValue(ast.filters[i - 1].params[0], escape, fns, level);
}
}
filter.params &&
filter.params.forEach((param, j) => {
_codeStr += ', ';
if (param.filters) {
_codeStr += buildExpression(param, null, escape, fns, useStringLocal, level);
} else {
_codeStr += _buildDataValue(param, escape, fns, level);
}
});
const nextFilter = ast.filters[i + 1];
if (filterName === '.' && nextFilter && replaceFilterName(nextFilter.name) === '_') {
_codeStr += ', true';
}
//if (!configF || configF.hasOptions) {
if (configF && configF.hasOptions) {
_codeStr += `, ${_buildOptions(configF, useStringLocal, null, fns, level)}`;
}
}
_codeStr += endStr;
if (hasFilterNext) {
lastCodeStr = _codeStr;
} else {
codeStr += _codeStr;
lastCodeStr = '';
}
}
});
return codeStr;
}
function _buildEscape(valueStr, fns, escape, special) {
if (fns.useString) {
if (escape && special !== CUSTOM_VAR) {
return `${GLOBAL}.es(` + valueStr + ')';
} else {
return valueStr;
}
} else {
//文本中的特殊字符需转义
return unescape(valueStr);
}
}
function _replaceStrs(str) {
return _replaceBackslash(str)
.replace(/_njNl_/g, '\\n')
.replace(/'/g, `\\'`);
}
function _replaceBackslash(str) {
return (str = str.replace(/\\/g, '\\\\'));
}
function _buildProps(obj, fns, useStringLocal, level?) {
const str0 = obj.strs[0];
let valueStr = '';
if (tools.isString(str0)) {
//常规属性
valueStr = !obj.isAll && str0 !== '' ? `'${_replaceStrs(str0)}'` : '';
tools.each(
obj.props,
function(o, i) {
let dataValueStr = buildExpression(o.prop, null, o.escape, fns, useStringLocal, level);
if (!obj.isAll) {
const strI = obj.strs[i + 1],
prefixStr = str0 === '' && i == 0 ? '' : ' + ';
// if (strI.trim() === '\\n') { //如果只包含换行符号则忽略
// valueStr += prefixStr + dataValueStr;
// return;
// }
dataValueStr = prefixStr + '(' + dataValueStr + ')' + (strI !== '' ? ` + '${_replaceStrs(strI)}'` : '');
} else {
dataValueStr = '(' + dataValueStr + ')';
}
valueStr += dataValueStr;
if (obj.isAll) {
return false;
}
},
true
);
}
return valueStr;
}
function _buildParams(node, fns, counter, useString, level, tagName) {
//节点参数
const { params, paramsEx } = node;
const useStringF = fns.useString,
hasPropsEx = paramsEx;
let paramsStr = '',
_paramsC,
_tagProps;
if (params || hasPropsEx) {
_paramsC = counter._params++;
_tagProps = '_params' + _paramsC;
paramsStr = 'var ' + _tagProps + ' = ';
if (params) {
const paramKeys = Object.keys(params),
len = paramKeys.length;
paramsStr += '{\n';
tools.each(
paramKeys,
function(k, i) {
let valueStr = _buildProps(params[k], fns, useString, level);
if (!useStringF && k === 'style') {
//将style字符串转换为对象
valueStr = `${GLOBAL}.sp(` + valueStr + ')';
}
let key = _replaceStrs(k);
const onlyKey = params[k].onlyKey;
if (!useStringF) {
key = tranData.fixPropName(key);
}
paramsStr +=
` '` + key + `': ` + (!onlyKey ? valueStr : !useString ? 'true' : `'${key}'`) + (i < len - 1 ? ',\n' : '');
},
false
);
paramsStr += '\n};\n';
}
if (hasPropsEx) {
if (!params) {
paramsStr += '{};\n';
}
if (paramsEx) {
paramsStr += _buildContent(
paramsEx.content,
paramsEx,
fns,
counter,
{ _paramsE: true },
null,
useString,
tagName,
_tagProps
);
}
if (useString) {
paramsStr += '\n' + _tagProps + ` = ${GLOBAL}.ans(` + _tagProps + ');\n';
}
} else if (useString) {
paramsStr += '\n' + _tagProps + ` = ${GLOBAL}.ans({}, ` + _tagProps + ');\n';
}
}
return [paramsStr, _paramsC];
}
function _buildNode(node, parent, fns, counter, retType, level, useStringLocal, isFirst, tagName, tagProps) {
let fnStr = '';
const useStringF = fns.useString;
if (node.type === 'nj_plaintext') {
//文本节点
const valueStr = _buildProps(node.content[0], fns, useStringLocal, level);
if (valueStr === '') {
return fnStr;
}
const textStr = _buildRender(
node,
parent,
1,
retType,
{ text: valueStr },
fns,
level,
useStringLocal,
node.allowNewline,
isFirst
);
if (useStringF) {
fnStr += textStr;
} else {
//文本中的特殊字符需转义
fnStr += unescape(textStr);
}
} else if (node.type === 'nj_ex') {
//扩展标签节点
const _exC = counter._ex++,
_dataReferC = counter._dataRefer++,
configE = extensionConfig[node.ex],
exVarStr = '_ex' + _exC,
globalExStr = `${GLOBAL}.x['${node.ex}']`;
let dataReferStr = '',
fnHVarStr;
if (configE && configE.onlyGlobal) {
//只能从全局获取
fnStr += '\nvar ' + exVarStr + ' = ' + globalExStr + ';\n';
} else {
//优先从context.data中获取
fnHVarStr = '_fnH' + counter._fnH++;
fnStr += '\nvar ' + exVarStr + ';\n';
fnStr += 'var ' + fnHVarStr + ` = ${CONTEXT}.d('${node.ex}', 0, true);\n`;
fnStr += 'if (' + fnHVarStr + ') {\n';
fnStr += ' ' + exVarStr + ' = ' + fnHVarStr + '.value;\n';
fnStr += '} else {\n';
fnStr += ' ' + exVarStr + ' = ' + globalExStr + ';\n';
fnStr += '}\n';
}
dataReferStr += 'var _dataRefer' + _dataReferC + ' = [\n';
if (node.args) {
//构建匿名参数
tools.each(
node.args,
function(arg, i) {
const valueStr = _buildProps(arg, fns, useStringLocal, level);
dataReferStr += ' ' + valueStr + ',';
},
true
);
}
//hash参数
const retP = _buildParams(node, fns, counter, useStringLocal, level, tagName),
paramsStr = retP[0],
_paramsC = retP[1];
dataReferStr += _buildOptions(
configE,
useStringLocal,
node,
fns,
level,
paramsStr !== '' ? '_params' + _paramsC : null,
tagName,
tagProps
);
dataReferStr += '\n];\n';
//添加匿名参数
if (paramsStr !== '') {
dataReferStr += `${GLOBAL}.aa(_params` + _paramsC + ', _dataRefer' + _dataReferC + ');\n';
}
fnStr += paramsStr + dataReferStr;
if (process.env.NODE_ENV !== 'production') {
//如果扩展标签不存在则打印警告信息
fnStr += `${GLOBAL}.tf(_ex${_exC}, '${node.ex}', 'ex');\n`;
}
//渲染
fnStr += _buildRender(
node,
parent,
2,
retType,
{
_ex: _exC,
_dataRefer: _dataReferC,
fnH: fnHVarStr
},
fns,
level,
useStringLocal,
node.allowNewline,
isFirst
);
} else {
//元素节点
//节点类型和typeRefer
const _typeC = counter._type++,
_tagName = '_type' + _typeC;
let _type, _typeRefer;
if (node.typeRefer) {
const valueStrT = _buildProps(node.typeRefer, fns, level);
_typeRefer = valueStrT;
_type = node.typeRefer.props[0].prop.name;
} else {
_type = node.type;
}
let typeStr;
if (!useStringF) {
let _typeL = _type.toLowerCase(),
subName = '';
if (!_typeRefer && _typeL.indexOf('.') > -1) {
const typeS = _type.split('.');
_typeL = _typeL.split('.')[0];
_type = typeS[0];
subName = `, '${typeS[1]}'`;
}
typeStr = _typeRefer
? `${GLOBAL}.er(` + _typeRefer + `, '` + _typeL + `', ${GLOBAL}, '` + _type + `', ${CONTEXT})`
: `${GLOBAL}.e('` + _typeL + `', ${GLOBAL}, '` + _type + `', ${CONTEXT}` + subName + ')';
} else {
typeStr = _typeRefer ? `${GLOBAL}.en(` + _typeRefer + `, '` + _type + `')` : `'${_type}'`;
}
fnStr += '\nvar _type' + _typeC + ' = ' + typeStr + ';\n';
//节点参数
const retP = _buildParams(node, fns, counter, useStringF, level, _tagName),
paramsStr = retP[0],
_paramsC = retP[1];
fnStr += paramsStr;
let _compParamC, _childrenC;
if (!useStringF) {
//组件参数
_compParamC = counter._compParam++;
fnStr +=
'var _compParam' +
_compParamC +
' = [_type' +
_typeC +
', ' +
(paramsStr !== '' ? '_params' + _paramsC : 'null') +
'];\n';
} else {
//子节点字符串
_childrenC = counter._children++;
fnStr += 'var _children' + _childrenC + ` = '';\n`;
}
//子节点
fnStr += _buildContent(
node.content,
node,
fns,
counter,
!useStringF ? { _compParam: '_compParam' + _compParamC } : { _children: '_children' + _childrenC },
useStringF && node.type === nj.noWsTag ? null : level != null ? level + 1 : level,
useStringLocal,
_tagName
);
//渲染
fnStr += _buildRender(
node,
parent,
3,
retType,
!useStringF
? { _compParam: _compParamC }
: {
_type: _typeC,
_typeS: _type,
_typeR: _typeRefer,
_params: paramsStr !== '' ? _paramsC : null,
_children: _childrenC,
_selfClose: node.selfCloseTag
},
fns,
level,
useStringLocal,
node.allowNewline,
isFirst
);
}
return fnStr;
}
function _buildContent(content, parent, fns, counter, retType, level, useStringLocal, tagName?, tagProps?) {
let fnStr = '';
if (!content) {
return fnStr;
}
tools.each(
content,
node => {
const { useString } = node;
fnStr += _buildNode(
node,
parent,
fns,
counter,
retType,
level,
useString != null ? useString : useStringLocal,
fns._firstNode && level == 0,
tagName,
tagProps
);
if (fns._firstNode) {
//输出字符串时模板第一个节点前面不加换行符
fns._firstNode = false;
}
},
true
);
return fnStr;
}
function _buildRender(node, parent, nodeType, retType, params, fns, level, useStringLocal, allowNewline, isFirst) {
let retStr;
const useStringF = fns.useString,
useString = useStringLocal != null ? useStringLocal : useStringF,
noLevel = level == null;
switch (nodeType) {
case 1: //文本节点
retStr =
(!useStringF || allowNewline || noLevel
? ''
: isFirst
? parent.type !== 'nj_root'
? `${GLOBAL}.fl(${CONTEXT}) + `
: ''
: `'\\n' + `) +
_buildLevelSpace(level, fns, allowNewline) +
_buildLevelSpaceRt(useStringF, isFirst || noLevel) +
params.text;
break;
case 2: //扩展标签
retStr =
'_ex' +
params._ex +
'.apply(' +
(params.fnH ? params.fnH + ' ? ' + params.fnH + `.source : ${CONTEXT}` : CONTEXT) +
', _dataRefer' +
params._dataRefer +
')';
break;
case 3: //元素节点
if (!useStringF) {
retStr = `${GLOBAL}.H(_compParam` + params._compParam + ')';
} else {
if ((allowNewline && allowNewline !== 'nlElem') || noLevel) {
retStr = '';
} else if (isFirst) {
retStr = parent.type !== 'nj_root' ? `${GLOBAL}.fl(${CONTEXT}) + ` : '';
} else {
retStr = `'\\n' + `;
}
if (node.type !== nj.textTag && node.type !== nj.noWsTag) {
const levelSpace = _buildLevelSpace(level, fns, allowNewline),
content = node.content,
hasTypeR = params._typeR,
hasParams = params._params != null;
retStr +=
levelSpace +
_buildLevelSpaceRt(useStringF, isFirst || noLevel) +
`'<` +
(hasTypeR ? `' + _type` + params._type : params._typeS) +
(hasParams ? (!hasTypeR ? `'` : '') + ' + _params' + params._params : '') +
(hasTypeR || hasParams ? ` + '` : '');
if (!params._selfClose) {
retStr += `>'`;
retStr += ' + _children' + params._children + ' + ';
retStr +=
(!content || allowNewline || noLevel ? '' : `'\\n' + `) +
(content ? levelSpace : '') + //如果子节点为空则不输出缩进空格和换行符
_buildLevelSpaceRt(useStringF, noLevel) +
`'</` +
(hasTypeR ? `' + _type` + params._type + ` + '` : params._typeS) +
`>'`;
} else {
retStr += ` />'`;
}
} else {
retStr += '_children' + params._children;
}
}
break;
}
//保存方式
if (retType === '1') {
return '\nreturn ' + retStr + ';';
} else if (retType === '2') {
if (!useString) {
return '\nret.push(' + retStr + ');\n';
} else {
return '\nret += ' + retStr + ';\n';
}
} else if (retType._paramsE) {
return '\n' + retStr + ';\n';
} else {
if (!useStringF) {
return '\n' + retType._compParam + '.push(' + retStr + ');\n';
} else {
return '\n' + retType._children + ' += ' + retStr + ';\n';
}
}
}
function _buildLevelSpace(level, fns, allowNewline) {
let ret = '';
if (allowNewline && allowNewline !== 'nlElem') {
return ret;
}
if (fns.useString && level != null && level > 0) {
ret += `'`;
for (let i = 0; i < level; i++) {
ret += ' ';
}
ret += `' + `;
}
return ret;
}
function _buildLevelSpaceRt(useString, noSpace) {
if (useString && !noSpace) {
return `${GLOBAL}.ls(${CONTEXT}) + `;
}
return '';
}
export function buildRuntime(astContent, ast, useString) {
const fns = {
useString,
_no: 0, //扩展标签函数计数
_firstNode: true
};
_buildFn(astContent, ast, fns, fns._no, null, 0);
return fns;
} | the_stack |
import {
Logger,
LoggerProvider,
LogLevelDesc,
} from "@hyperledger/cactus-common";
const logLevel: LogLevelDesc = "TRACE";
const logger: Logger = LoggerProvider.getOrCreate({
label: "test-check-connection-to-ethereum-ledger",
level: logLevel,
});
const http = require("http");
const net = require("net");
const fs = require("fs");
const yaml = require("js-yaml");
function getConfigData(): any {
const config: any = yaml.safeLoad(
fs.readFileSync("/etc/cactus/usersetting.yaml", "utf8"),
);
const hostName: string = config.applicationHostInfo.hostName.replace(
"http://",
"",
);
const hostPort: string = config.applicationHostInfo.hostPort;
logger.info(`BLP hostname from usersetting file in /etc/cactus: ${hostName}`);
logger.info(`BLP port from usersetting file in /etc/cactus: ${hostPort}`);
return { hostname: hostName, port: hostPort };
}
function createOptionObj(
path: string,
method: string,
postData: string,
): Record<string, unknown> {
const configData = getConfigData();
const options = {
hostname: configData.hostname,
port: configData.port,
path: path,
method: method,
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(postData),
},
};
return options;
}
function pingService(hostName: string, port: number): Promise<boolean> {
return new Promise((resolve) => {
const sock = new net.Socket();
sock.setTimeout(120);
sock.on("connect", function () {
logger.debug(`${hostName}:${port} is up.`);
sock.destroy();
resolve(true);
});
sock.on("error", function (error: any) {
logger.error(`${hostName}:${port} is down: ${error.message}`);
resolve(false);
});
sock.connect(port, hostName);
});
}
function sendRequest(
options: Record<string, unknown>,
postData: string,
): Promise<any> {
return new Promise((resolve, reject) => {
const request = http
.request(options, (response: any) => {
response.setEncoding("utf8");
let body = "";
const statusCode = response.statusCode;
response.on("data", (chunk: any) => (body += chunk));
response.on("end", () => resolve([body, statusCode]));
})
.on("error", reject);
request.write(postData);
request.end();
});
}
function checkContainerStatus(containerName: string): Promise<boolean> {
const { exec } = require("child_process");
const checkRunningCmd = "docker container inspect -f '{{.State.Running}}'";
return new Promise((resolve) => {
exec(`${checkRunningCmd} ${containerName}`, (err: any, out: any) => {
logger.debug(`Output from docker command: err: ${err}, out: ${out}`);
if (out.replace("\n", "") == "true") {
logger.info(`Container: ${containerName} is up and running!`);
resolve(true);
} else {
logger.error(`Container: ${containerName} is down!`);
resolve(false);
}
});
});
}
describe("Environment check tests", () => {
test("Check if all required services are accessible", async () => {
const config = getConfigData();
const ethereumLedgerPort = 8545;
const ethereumConnectorPort = 5050;
logger.debug(`Check connection to BLP (${config.hostname}:${config.port})`);
expect(await pingService(config.hostname, config.port)).toBeTrue();
logger.debug(
`Check connection to Ethereum Connector (${config.hostname}:${ethereumConnectorPort})`,
);
expect(
await pingService(config.hostname, ethereumConnectorPort),
).toBeTrue();
logger.debug(
`Check connection to Ethereum Ledger (${config.hostname}:${ethereumLedgerPort})`,
);
expect(await pingService(config.hostname, ethereumLedgerPort)).toBeTrue();
});
test("Check if containers started successfully", async () => {
logger.debug(`Check ethereum ledger container`);
const ethereumLedgerContainerName = "geth1";
expect(await checkContainerStatus(ethereumLedgerContainerName)).toBeTrue();
logger.debug(`Check ethereum connector container`);
const ethereumConnectorContainerName =
"hyperledger-cactus-plugin-ledger-connector-go-ethereum-socketio";
expect(
await checkContainerStatus(ethereumConnectorContainerName),
).toBeTrue();
});
test("Check connection to BLP and validate response", async () => {
const postData = JSON.stringify({
businessLogicID: "jLn76rgB",
});
const path = "/api/v1/bl/check-ethereum-validator";
const options = createOptionObj(path, "POST", postData);
const response = await sendRequest(options, postData);
logger.debug(`Received response: [${response}]`);
logger.debug(`Check status code from API`);
expect(response[1]).toBe(200);
logger.debug(`Check if response is not empty`);
expect(response[0]).not.toBe("");
let jsonResponse: any;
try {
jsonResponse = JSON.parse(response[0]);
} catch (error) {
logger.error(`There was a problem with parsing response`);
}
logger.debug(`Check if parsed response contains proper keys`);
expect(Object.keys(jsonResponse)).toContain("tradeID");
logger.debug(`Check if value assigned to tradeID key is not empty`);
expect(jsonResponse.tradeID).not.toEqual("");
});
});
describe("Ledger operation tests", () => {
test("Get balance from ledger (read test <sync, async>)", async () => {
const account = "06fc56347d91c6ad2dae0c3ba38eb12ab0d72e97";
const path = "/api/v1/bl/check-ethereum-validator/getBalance";
logger.info("Checking ASYNC request...");
let postData = JSON.stringify({
account: account,
requestType: "async",
});
let options = createOptionObj(path, "POST", postData);
let response = await sendRequest(options, postData);
logger.debug(`Received response: [${response}]`);
// check status code
logger.debug(`Check status code from API`);
expect(response[1]).toBe(200);
// check response content
logger.debug(`Check response content`);
expect(response[0]).toBe("true");
logger.info("Checking SYNC request");
postData = JSON.stringify({
account: account,
requestType: "sync",
});
options = createOptionObj(path, "POST", postData);
response = await sendRequest(options, postData);
logger.debug(`Received response: [${response}]`);
// check status code from API
logger.debug(`Check status code from API`);
expect(response[1]).toBe(200);
// check if response is not empty
expect(response[0]).not.toBe("");
let jsonResponse: any;
try {
jsonResponse = JSON.parse(response[0]);
} catch (error) {
logger.error(`There was a problem with parsing response`);
}
logger.debug(`Check if parsed response contains proper keys`);
expect(Object.keys(jsonResponse)).toContain("status");
expect(Object.keys(jsonResponse)).toContain("amount");
logger.debug(`Check if values assigned keys are not empty`);
expect(jsonResponse.status).not.toEqual("");
expect(jsonResponse.amount).not.toEqual("");
logger.debug(
`Check if status code retrieved from connector is between 200-300`,
);
expect(jsonResponse.status >= 200).toBeTruthy();
expect(jsonResponse.status).toBeLessThan(300);
logger.debug(`Check if balance is not negative number`);
expect(jsonResponse.amount >= 0).toBeTruthy();
});
async function getCurrentBalanceOnAccount(account: string): Promise<number> {
const getCurrentBalancePath =
"/api/v1/bl/check-ethereum-validator/getBalance";
const postData = JSON.stringify({
account: account,
requestType: "sync",
});
const options = createOptionObj(getCurrentBalancePath, "POST", postData);
const srcCheckBalanceResponse = await sendRequest(options, postData);
let srcCheckBalanceJsonResponse: any;
try {
srcCheckBalanceJsonResponse = JSON.parse(srcCheckBalanceResponse[0]);
} catch (error) {
logger.error(`There was a problem with parsing response`);
}
return srcCheckBalanceJsonResponse.amount;
}
test("Make sample transaction (write test <sync, async>)", async () => {
const srcAccount = "06fc56347d91c6ad2dae0c3ba38eb12ab0d72e97";
const destAccount = "9d624f7995e8bd70251f8265f2f9f2b49f169c55";
const transferAmount = "150";
const path = "/api/v1/bl/check-ethereum-validator/transferAssets";
logger.info("Checking ASYNC request...");
let postData = JSON.stringify({
srcAccount: srcAccount,
destAccount: destAccount,
amount: transferAmount,
requestType: "async",
});
let options = createOptionObj(path, "POST", postData);
// Get current balances on accounts before sending request
let srcBalanceBeforeTransaction = await getCurrentBalanceOnAccount(
srcAccount,
);
let destBalanceBeforeTransaction = await getCurrentBalanceOnAccount(
destAccount,
);
logger.debug(`Balances before transaction:\nsource account:${srcBalanceBeforeTransaction}
\ndestination account: ${destBalanceBeforeTransaction}`);
// Make request
let response = await sendRequest(options, postData);
logger.debug(`Received response: [${response}]`);
// Check status code
logger.debug(`Check status code from API`);
expect(response[1]).toBe(200);
// Check response content
logger.debug(`Check response content`);
expect(response[0]).toBe("true");
// Wait for 20s to complete transfer
const foo = true;
await new Promise((r) => setTimeout(r, 60000));
expect(foo).toBeDefined();
// Check balances after transaction
let srcBalanceAfterTransaction = await getCurrentBalanceOnAccount(
srcAccount,
);
let destBalanceAfterTransaction = await getCurrentBalanceOnAccount(
destAccount,
);
// Check if differences from before and after transaction are correct
expect(srcBalanceBeforeTransaction - srcBalanceAfterTransaction).toBe(
parseInt(transferAmount),
);
expect(destBalanceAfterTransaction - destBalanceBeforeTransaction).toBe(
parseInt(transferAmount),
);
logger.debug("Assets have been successfully moved between accounts");
logger.info("Checking SYNC request...");
postData = JSON.stringify({
srcAccount: srcAccount,
destAccount: destAccount,
amount: transferAmount,
requestType: "sync",
});
options = createOptionObj(path, "POST", postData);
// Get current balances on accounts before sending request
srcBalanceBeforeTransaction = await getCurrentBalanceOnAccount(srcAccount);
destBalanceBeforeTransaction = await getCurrentBalanceOnAccount(
destAccount,
);
logger.debug(`Balances before transaction:\nsource account:${srcBalanceBeforeTransaction}
destination account: ${destBalanceBeforeTransaction}`);
// Make request
response = await sendRequest(options, postData);
logger.debug(`Received response: [${response}]`);
// Check status code
logger.debug(`Check status code from API`);
expect(response[1]).toBe(200);
// Check response content
logger.debug(`Check response content`);
let jsonResponse: any;
try {
jsonResponse = JSON.parse(response[0]);
} catch (error) {
logger.error(`There was a problem with parsing response`);
}
logger.debug(`Check if parsed response contains proper keys`);
expect(Object.keys(jsonResponse)).toContain("status");
expect(Object.keys(jsonResponse)).toContain("data");
logger.debug("Check content of response");
logger.debug(`Check if values assigned keys are not empty`);
expect(jsonResponse.status).not.toEqual("");
expect(jsonResponse.data).not.toEqual("");
logger.debug(
`Check if status code retrieved from connector is between 200-300`,
);
expect(jsonResponse.status >= 200).toBeTruthy();
expect(jsonResponse.status).toBeLessThan(300);
// Wait for 20s to complete transfer
await new Promise((r) => setTimeout(r, 60000));
expect(foo).toBeDefined();
// Check balances after transaction
srcBalanceAfterTransaction = await getCurrentBalanceOnAccount(srcAccount);
destBalanceAfterTransaction = await getCurrentBalanceOnAccount(destAccount);
// Check if differences from before and after transaction are correct
expect(srcBalanceBeforeTransaction - srcBalanceAfterTransaction).toBe(
parseInt(transferAmount),
);
expect(destBalanceAfterTransaction - destBalanceBeforeTransaction).toBe(
parseInt(transferAmount),
);
logger.debug("Assets have been successfully moved between accounts");
});
}); | the_stack |
import { BlockRegData, BlockPortRegData } from "../Define/BlockDef";
import { Block } from "../Define/Block";
import { BlockPort, BlockPortDirection } from "../Define/Port";
import CommonUtils from "../../utils/CommonUtils";
import { BlockEditor } from "../Editor/BlockEditor";
export default {
register,
packageName: 'Logic',
version: 1,
}
function register() {
let And = new BlockRegData("F839DDA4-B666-74B6-E8B7-836D63708B65", "与", '逻辑与运算');
let Or = new BlockRegData("29D1D2D3-47E1-2B67-C527-9E9274E6C582", "或", '逻辑或运算');
let Not = new BlockRegData("E0D54F96-611E-C8AB-E347-5DEA1E9C227F", "非", '逻辑非运算');
let ExclusiveOr = new BlockRegData("ED238520-58E6-AA7B-8787-26F2853D1248", "异或", '逻辑异或与运算');
let Equal = new BlockRegData("B3D85366-FE65-1F1E-BAC8-F896668AD87C", "相等", '判断两个数是否相等');
let NotEqual = new BlockRegData("6BE62EF6-A031-6D24-6720-99ABF1BBE5C1", "不相等", '判断两个数是否不相等');
let Less = new BlockRegData("CFFCEB53-B68C-98AE-3363-455BDE728F88", "小于", '判断一个数是小于另一个数');
let Greater = new BlockRegData("1FF0A894-C51E-F2ED-AEC8-9156ED490895", "大于", '判断一个数是大于另一个数');
let LessOrEqual = new BlockRegData("57F7A1F6-51AE-6071-0926-5420877B9E20", "小于或等于", '判断一个数是小于或等于另一个数');
let GreaterOrEqual = new BlockRegData("97DAB36F-B83F-9473-8B56-6FDB422E6D4F", "大于或等于", '判断一个数是大于或等于另一个数');
let LeftMove = new BlockRegData("E9E8B9CD-3C86-081C-A46C-DE325062CD87", "左移", '按位左移');
let RightMove = new BlockRegData("3B3AB761-33B9-3CC6-45B0-AE9F6B300458", "右移", '按位右移');
let LogicBase_onCreate = (block : Block) => {
if(typeof block.options['opType'] == 'undefined')
block.options['opType'] = block.data['requireNumber'] ? 'number' : 'any';
//更换数据类型
block.allPorts.forEach((port) => {
if(port.paramType.isExecute())
block.changePortParamType(port, block.options['opType']);
});
};
let LogicBase_onUserAddPort = (block : Block, dirction : BlockPortDirection, type : 'execute'|'param') => {
block.data['portCount'] = typeof block.data['portCount'] == 'number' ? block.data['portCount'] + 1 : block.inputPortCount;
return {
guid: 'PI' + block.data['portCount'],
paramType: type == 'execute' ? 'execute' : block.options['opType'],
direction: dirction,
portAnyFlexable: { flexable: true }
};
};
let LogicBase_onPortConnectCheck = (block : BlockEditor, port : BlockPort, portSource : BlockPort) => {
if(portSource.paramType.baseType == 'number' || portSource.paramType.baseType == 'boolean' || portSource.paramType.baseType == 'bigint')
return null;
return '与 ' + portSource.getTypeFriendlyString() + ' 不兼容,无法连接';
};
let LogicBase_portAnyFlexables = { flexable: { setResultToOptions: 'opType' } };
let LogicBase_cm_ports : Array<BlockPortRegData> = [
{
direction: 'input',
guid: 'PI0',
paramType: 'any',
portAnyFlexable: { flexable: true }
},
{
description: '',
direction: 'input',
guid: 'PI1',
paramType: 'any',
portAnyFlexable: { flexable: true }
},
{
description: '',
direction: 'output',
guid: 'PO1',
paramType: 'any',
portAnyFlexable: { flexable: true }
},
];
let LogicBase_compare_ports : Array<BlockPortRegData> = [
{
direction: 'input',
guid: 'PI1',
paramType: 'any',
portAnyFlexable: { flexable: true }
},
{
direction: 'input',
guid: 'PI2',
paramType: 'any',
portAnyFlexable: { flexable: true }
},
{
direction: 'output',
guid: 'PO',
paramType: 'boolean'
},
]
//#region And
And.baseInfo.author = 'imengyu';
And.baseInfo.category = '逻辑';
And.baseInfo.version = '2.0';
And.baseInfo.logo = require('../../assets/images/BlockIcon/and.svg');
And.settings.parametersChangeSettings.userCanAddInputParameter = true;
And.blockStyle.noTitle = true;
And.blockStyle.logoBackground = And.baseInfo.logo;
And.ports = LogicBase_cm_ports;
And.callbacks.onCreate = LogicBase_onCreate;
And.callbacks.onUserAddPort = LogicBase_onUserAddPort;
And.callbacks.onPortConnectCheck = LogicBase_onPortConnectCheck;
And.callbacks.onPortParamRequest = (block, port, context) => {
let rs : any = null;
Object.keys(block.inputPorts).forEach(guid => {
let v = block.getInputParamValue(guid, context);
if(!CommonUtils.isDefinedAndNotNull(v))
return;
if(block.options['opType'] == 'boolean') {
if(rs == null) rs = v
else rs = rs && v;
} else {
if(rs == null) rs = v
else rs = rs & v;
}
});
return rs;
};
And.portAnyFlexables = LogicBase_portAnyFlexables;
//#endregion
//#region Or
Or.baseInfo.author = 'imengyu';
Or.baseInfo.category = '逻辑';
Or.baseInfo.version = '2.0';
Or.baseInfo.logo = require('../../assets/images/BlockIcon/or.svg');
Or.blockStyle.noTitle = true;
Or.blockStyle.logoBackground = Or.baseInfo.logo;
Or.settings.parametersChangeSettings.userCanAddInputParameter = true;
Or.ports = LogicBase_cm_ports;
Or.callbacks.onCreate =LogicBase_onCreate;
Or.callbacks.onUserAddPort = LogicBase_onUserAddPort;
Or.callbacks.onPortConnectCheck = LogicBase_onPortConnectCheck;
Or.callbacks.onPortParamRequest = (block, port, context) => {
let rs : any = null;
Object.keys(block.inputPorts).forEach(guid => {
let v = block.getInputParamValue(guid, context);
if(!CommonUtils.isDefinedAndNotNull(v))
return;
if(block.options['opType'] == 'boolean') {
if(rs == null) rs = v
else rs = rs || v;
} else {
if(rs == null) rs = v
else rs = rs | v;
}
});
return rs;
};
Or.portAnyFlexables = LogicBase_portAnyFlexables;
//#endregion
//#region Not
Not.baseInfo.author = 'imengyu';
Not.baseInfo.category = '逻辑';
Not.baseInfo.version = '2.0';
Not.baseInfo.logo = require('../../assets/images/BlockIcon/not.svg');
Not.blockStyle.noTitle = true;
Not.blockStyle.logoBackground = Not.baseInfo.logo;
Not.blockStyle.minWidth = '111px';
Not.blockStyle.minHeight = '50px';
Not.portAnyFlexables = LogicBase_portAnyFlexables;
Not.ports = [
{
direction: 'input',
guid: 'PI1',
paramType: 'any',
portAnyFlexable: { flexable: true }
},
{
description: '',
direction: 'output',
guid: 'PO1',
paramType: 'any',
portAnyFlexable: { flexable: true }
},
];
Not.callbacks.onCreate = LogicBase_onCreate;
Not.callbacks.onPortConnectCheck = LogicBase_onPortConnectCheck;
Not.callbacks.onPortParamRequest = (block, port, context) => {
let v = block.getInputParamValue('PI1', context);
if(CommonUtils.isDefinedAndNotNull(v))
return (block.options['opType'] == 'boolean' ? !v : ~v);
return false;
};
//#endregion
//#region ExclusiveOr
ExclusiveOr.baseInfo.author = 'imengyu';
ExclusiveOr.baseInfo.category = '逻辑';
ExclusiveOr.baseInfo.version = '2.0';
ExclusiveOr.baseInfo.logo = require('../../assets/images/BlockIcon/xor.svg');
ExclusiveOr.blockStyle.noTitle = true;
ExclusiveOr.blockStyle.logoBackground = ExclusiveOr.baseInfo.logo;
ExclusiveOr.blockStyle.minWidth = '111px';
ExclusiveOr.portAnyFlexables = LogicBase_portAnyFlexables;
ExclusiveOr.ports = [
{
direction: 'input',
guid: 'PI1',
paramType: 'any',
portAnyFlexable: { flexable: true }
},
{
direction: 'input',
guid: 'PI2',
paramType: 'any',
portAnyFlexable: { flexable: true }
},
{
direction: 'output',
guid: 'PO1',
paramType: 'any',
portAnyFlexable: { flexable: true }
},
];
ExclusiveOr.callbacks.onCreate = LogicBase_onCreate;
ExclusiveOr.callbacks.onPortConnectCheck = LogicBase_onPortConnectCheck;
ExclusiveOr.callbacks.onPortParamRequest = (block, port, context) => {
let v1 = block.getInputParamValue('PI1', context);
let v2 = block.getInputParamValue('PI2', context);
if(CommonUtils.isDefinedAndNotNull(v1) && CommonUtils.isDefinedAndNotNull(v2))
return v1 ^ v2;
return null;
};
//#endregion
//#region Equal
Equal.baseInfo.author = 'imengyu';
Equal.baseInfo.category = '逻辑';
Equal.baseInfo.version = '2.0';
Equal.baseInfo.logo = require('../../assets/images/BlockIcon/equal.svg');
Equal.blockStyle.noTitle = true;
Equal.blockStyle.logoBackground = Equal.baseInfo.logo;
Equal.ports = LogicBase_compare_ports;
Equal.portAnyFlexables = LogicBase_portAnyFlexables;
Equal.callbacks.onCreate = LogicBase_onCreate;
Equal.callbacks.onPortParamRequest = (block, port, context) => {
let v1 = block.getInputParamValue('PI1', context), v2 = block.getInputParamValue('PI2', context);
if(CommonUtils.isDefinedAndNotNull(v1) && CommonUtils.isDefinedAndNotNull(v2))
return v1 === v2;
return false;
};
//#endregion
//#region NotEqual
NotEqual.baseInfo.author = 'imengyu';
NotEqual.baseInfo.category = '逻辑';
NotEqual.baseInfo.version = '2.0';
NotEqual.baseInfo.logo = require('../../assets/images/BlockIcon/not_equal.svg');
NotEqual.blockStyle.noTitle = true;
NotEqual.blockStyle.logoBackground = NotEqual.baseInfo.logo;
NotEqual.portAnyFlexables = LogicBase_portAnyFlexables;
NotEqual.ports = LogicBase_compare_ports;
NotEqual.callbacks.onCreate = LogicBase_onCreate;
NotEqual.callbacks.onPortParamRequest = (block, port, context) => {
let v1 = block.getInputParamValue('PI1', context), v2 = block.getInputParamValue('PI2', context);
if(CommonUtils.isDefinedAndNotNull(v1) && CommonUtils.isDefinedAndNotNull(v2))
return v1 !== v2;
return false;
};
//#endregion
//#region Less
Less.baseInfo.author = 'imengyu';
Less.baseInfo.category = '逻辑';
Less.baseInfo.version = '2.0';
Less.baseInfo.logo = require('../../assets/images/BlockIcon/less.svg');
Less.blockStyle.noTitle = true;
Less.blockStyle.logoBackground = Less.baseInfo.logo;
Less.portAnyFlexables = LogicBase_portAnyFlexables;
Less.ports = LogicBase_compare_ports;
Less.callbacks.onCreate = LogicBase_onCreate;
Less.callbacks.onPortConnectCheck = LogicBase_onPortConnectCheck;
Less.callbacks.onPortParamRequest = (block, port, context) => {
let v1 = block.getInputParamValue('PI1', context), v2 = block.getInputParamValue('PI2', context);
if(CommonUtils.isDefinedAndNotNull(v1) && CommonUtils.isDefinedAndNotNull(v2))
return v1 < v2;
return false;
};
//#endregion
//#region Greater
Greater.baseInfo.author = 'imengyu';
Greater.baseInfo.category = '逻辑';
Greater.baseInfo.version = '2.0';
Greater.baseInfo.logo = require('../../assets/images/BlockIcon/greater.svg');
Greater.blockStyle.noTitle = true;
Greater.blockStyle.logoBackground = Greater.baseInfo.logo;
Greater.portAnyFlexables = LogicBase_portAnyFlexables;
Greater.ports = LogicBase_compare_ports;
Greater.callbacks.onCreate = LogicBase_onCreate;
Greater.callbacks.onPortConnectCheck = LogicBase_onPortConnectCheck;
Greater.callbacks.onPortParamRequest = (block, port, context) => {
let v1 = block.getInputParamValue('PI1', context), v2 = block.getInputParamValue('PI2', context);
if(CommonUtils.isDefinedAndNotNull(v1) && CommonUtils.isDefinedAndNotNull(v2))
return v1 > v2;
return false;
};
//#endregion
//#region LessOrEqual
LessOrEqual.baseInfo.author = 'imengyu';
LessOrEqual.baseInfo.category = '逻辑';
LessOrEqual.baseInfo.version = '2.0';
LessOrEqual.baseInfo.logo = require('../../assets/images/BlockIcon/less_or_equal.svg');
LessOrEqual.blockStyle.noTitle = true;
LessOrEqual.blockStyle.logoBackground = LessOrEqual.baseInfo.logo;
LessOrEqual.portAnyFlexables = LogicBase_portAnyFlexables;
LessOrEqual.ports = LogicBase_compare_ports;
LessOrEqual.callbacks.onCreate = LogicBase_onCreate;
LessOrEqual.callbacks.onPortConnectCheck = LogicBase_onPortConnectCheck;
LessOrEqual.callbacks.onPortParamRequest = (block, port, context) => {
let v1 = block.getInputParamValue('PI1', context), v2 = block.getInputParamValue('PI2', context);
if(CommonUtils.isDefinedAndNotNull(v1) && CommonUtils.isDefinedAndNotNull(v2))
return v1 <= v2;
return false;
};
//#endregion
//#region GreaterOrEqual
GreaterOrEqual.baseInfo.author = 'imengyu';
GreaterOrEqual.baseInfo.category = '逻辑';
GreaterOrEqual.baseInfo.version = '2.0';
GreaterOrEqual.baseInfo.logo = require('../../assets/images/BlockIcon/greater_or_equal.svg');
GreaterOrEqual.blockStyle.noTitle = true;
GreaterOrEqual.blockStyle.logoBackground = GreaterOrEqual.baseInfo.logo;
GreaterOrEqual.portAnyFlexables = LogicBase_portAnyFlexables;
GreaterOrEqual.ports = LogicBase_compare_ports;
GreaterOrEqual.callbacks.onCreate = LogicBase_onCreate;
GreaterOrEqual.callbacks.onPortConnectCheck = LogicBase_onPortConnectCheck;
GreaterOrEqual.callbacks.onPortParamRequest = (block, port, context) => {
let v1 = block.getInputParamValue('PI1', context), v2 = block.getInputParamValue('PI2', context);
if(CommonUtils.isDefinedAndNotNull(v1) && CommonUtils.isDefinedAndNotNull(v2))
return v1 >= v2;
return false;
};
//#endregion
//#region LeftMove
LeftMove.baseInfo.author = 'imengyu';
LeftMove.baseInfo.category = '逻辑';
LeftMove.baseInfo.version = '2.0';
LeftMove.baseInfo.logo = require('../../assets/images/BlockIcon/left_move.svg');
LeftMove.blockStyle.noTitle = true;
LeftMove.blockStyle.logoBackground = LeftMove.baseInfo.logo;
LeftMove.portAnyFlexables = LogicBase_portAnyFlexables;
LeftMove.ports = LogicBase_compare_ports;
LeftMove.callbacks.onCreate = LogicBase_onCreate;
LeftMove.callbacks.onPortConnectCheck = LogicBase_onPortConnectCheck;
LeftMove.callbacks.onPortParamRequest = (block, port, context) => {
let v1 = block.getInputParamValue('PI1', context), v2 = block.getInputParamValue('PI2', context);
if(CommonUtils.isDefinedAndNotNull(v1) && CommonUtils.isDefinedAndNotNull(v2))
return v1 << v2;
return null;
};
//#endregion
//#region RightMove
RightMove.baseInfo.author = 'imengyu';
RightMove.baseInfo.category = '逻辑';
RightMove.baseInfo.version = '2.0';
RightMove.baseInfo.logo = require('../../assets/images/BlockIcon/right_move.svg');
RightMove.blockStyle.noTitle = true;
RightMove.blockStyle.logoBackground = RightMove.baseInfo.logo;
RightMove.portAnyFlexables = LogicBase_portAnyFlexables;
RightMove.ports = LogicBase_compare_ports;
RightMove.callbacks.onCreate = LogicBase_onCreate;
RightMove.callbacks.onPortConnectCheck = LogicBase_onPortConnectCheck;
RightMove.callbacks.onPortParamRequest = (block, port, context) => {
let v1 = block.getInputParamValue('PI1', context), v2 = block.getInputParamValue('PI2', context);
if(CommonUtils.isDefinedAndNotNull(v1) && CommonUtils.isDefinedAndNotNull(v2))
return v1 >> v2;
return null;
};
//#endregion
return [
And,
Or,
Not,
ExclusiveOr,
Equal,
NotEqual,
Less,
Greater,
LessOrEqual,
GreaterOrEqual,
LeftMove,
RightMove,
];
} | the_stack |
import * as IR from "../ir";
import { unreachable, zip } from "../utils/utils";
import { XorShift } from "../utils/xorshift";
import { Namespace, PassthroughNamespace } from "./namespaces";
// Only imported so callbacks get the correct type here
import type { Pattern } from "./logic/unification";
import type { CrochetTrace } from "./tracing/trace";
import { hash, isImmutable } from "immutable";
export type Primitive = boolean | null | bigint | number;
//#region Base values
export enum Tag {
NOTHING = 0,
INTEGER,
FLOAT_64,
TEXT,
TRUE,
FALSE,
INTERPOLATION,
LIST,
RECORD,
INSTANCE,
LAMBDA,
NATIVE_LAMBDA,
PARTIAL,
THUNK,
CELL,
TYPE,
ACTION,
ACTION_CHOICE,
UNKNOWN,
PROTECTED,
}
export type PayloadType = {
[Tag.NOTHING]: null;
[Tag.INTEGER]: bigint;
[Tag.FLOAT_64]: number;
[Tag.TEXT]: string;
[Tag.TRUE]: null;
[Tag.FALSE]: null;
[Tag.INTERPOLATION]: (string | CrochetValue)[];
[Tag.LIST]: CrochetValue[];
[Tag.RECORD]: Map<string, CrochetValue>;
[Tag.INSTANCE]: CrochetValue[];
[Tag.PARTIAL]: CrochetPartial;
[Tag.LAMBDA]: CrochetLambda;
[Tag.NATIVE_LAMBDA]: CrochetNativeLambda;
[Tag.THUNK]: CrochetThunk;
[Tag.CELL]: CrochetCell;
[Tag.TYPE]: CrochetType;
[Tag.ACTION]: BoundAction;
[Tag.ACTION_CHOICE]: ActionChoice;
[Tag.UNKNOWN]: unknown;
[Tag.PROTECTED]: CrochetProtectedValue;
};
export interface ActionChoice {
score: number;
action: Action;
env: Environment;
}
export interface BoundAction {
action: Action;
env: Environment;
}
export class CrochetValue<T extends Tag = Tag> {
constructor(
readonly tag: T,
readonly type: CrochetType,
readonly payload: PayloadType[T]
) {}
equals(that: CrochetValue<Tag>): boolean {
return equals(this, that);
}
hashCode() {
return 0; // FIXME: implement proper hash codes here
}
}
export class CrochetLambda {
constructor(
readonly env: Environment,
readonly parameters: string[],
readonly body: IR.BasicBlock
) {}
}
export class CrochetNativeLambda {
constructor(
readonly arity: number,
readonly handlers: HandlerStack,
readonly fn: (...args: CrochetValue[]) => Machine<CrochetValue>
) {}
}
export class CrochetPartial {
constructor(
readonly module: CrochetModule,
readonly name: string,
readonly arity: number
) {}
}
export class CrochetCell {
constructor(public value: CrochetValue) {}
}
export class CrochetCapturedContext {
constructor(readonly state: State) {}
}
export class CrochetThunk {
public value: CrochetValue | null = null;
constructor(readonly env: Environment, readonly body: IR.BasicBlock) {}
}
export class CrochetProtectedValue {
public protected_by = new Set<CrochetCapability>();
constructor(readonly value: CrochetValue) {}
}
export class CrochetTrait {
readonly implemented_by = new Set<CrochetType>();
readonly protected_by = new Set<CrochetCapability>();
constructor(
readonly module: CrochetModule | null,
readonly name: string,
readonly documentation: string,
readonly meta: IR.Metadata | null
) {}
}
export class CrochetType {
public sealed = false;
readonly layout: Map<string, number>;
readonly sub_types: CrochetType[] = [];
readonly traits = new Set<CrochetTrait>();
readonly protected_by = new Set<CrochetCapability>();
constructor(
readonly module: CrochetModule | null,
readonly name: string,
readonly documentation: string,
readonly parent: CrochetType | null,
readonly fields: string[],
readonly types: CrochetTypeConstraint[],
readonly is_static: boolean,
readonly meta: IR.Metadata | null
) {
this.layout = new Map(this.fields.map((k, i) => [k, i]));
}
}
export class CrochetTypeConstraint {
constructor(readonly type: CrochetType, readonly traits: CrochetTrait[]) {}
}
export class CrochetCapability {
readonly protecting = new Set<any>();
constructor(
readonly module: CrochetModule | null,
readonly name: string,
readonly documentation: string,
readonly meta: IR.Metadata | null
) {}
get full_name() {
const pkg = this.module?.pkg;
if (!pkg) {
return this.name;
} else {
return `${pkg.name}/${this.name}`;
}
}
}
//#endregion
//#region Core operations
export function equals(left: CrochetValue, right: CrochetValue): boolean {
if (left.tag !== right.tag) {
return false;
}
switch (left.tag) {
case Tag.NOTHING:
case Tag.TRUE:
case Tag.FALSE:
return left.tag === right.tag;
case Tag.INTEGER: {
return left.payload === right.payload;
}
case Tag.FLOAT_64: {
return left.payload === right.payload;
}
case Tag.PARTIAL: {
const l = left as CrochetValue<Tag.PARTIAL>;
const r = right as CrochetValue<Tag.PARTIAL>;
return (
l.payload.module === r.payload.module &&
l.payload.name === r.payload.name
);
}
case Tag.TEXT: {
return left.payload === right.payload;
}
case Tag.INTERPOLATION: {
const l = left as CrochetValue<Tag.INTERPOLATION>;
const r = right as CrochetValue<Tag.INTERPOLATION>;
if (l.payload.length !== r.payload.length) {
return false;
}
for (const [a, b] of zip(l.payload, r.payload)) {
if (typeof a === "string" && typeof b === "string") {
if (a !== b) return false;
} else if (a instanceof CrochetValue && b instanceof CrochetValue) {
if (!equals(a, b)) return false;
} else {
return false;
}
}
return true;
}
case Tag.LIST: {
const l = left as CrochetValue<Tag.LIST>;
const r = right as CrochetValue<Tag.LIST>;
if (l.payload.length !== r.payload.length) {
return false;
}
for (const [a, b] of zip(l.payload, r.payload)) {
if (!equals(a, b)) return false;
}
return true;
}
case Tag.RECORD: {
const l = left as CrochetValue<Tag.RECORD>;
const r = right as CrochetValue<Tag.RECORD>;
if (l.payload.size !== r.payload.size) {
return false;
}
for (const [k, v] of l.payload.entries()) {
const rv = r.payload.get(k);
if (rv == null || !equals(v, rv)) {
return false;
}
}
return true;
}
default:
return left === right;
}
}
//#endregion
//#region Commands
export class CrochetCommand {
readonly branches: CrochetCommandBranch[] = [];
readonly versions: CrochetCommandBranch[][] = [];
constructor(readonly name: string, readonly arity: number) {}
}
export class CrochetCommandBranch {
constructor(
readonly module: CrochetModule,
readonly env: Environment,
readonly name: string,
readonly documentation: string,
readonly parameters: string[],
readonly types: CrochetTypeConstraint[],
readonly body: IR.BasicBlock,
readonly meta: IR.Metadata | null
) {}
get arity() {
return this.types.length;
}
}
export enum NativeTag {
NATIVE_SYNCHRONOUS,
NATIVE_MACHINE,
}
export type Machine<T> = Generator<NativeSignal, T, CrochetValue>;
export type NativePayload = {
[NativeTag.NATIVE_SYNCHRONOUS]: (...args: CrochetValue[]) => CrochetValue;
[NativeTag.NATIVE_MACHINE]: (
...args: CrochetValue[]
) => Machine<CrochetValue>;
};
export class NativeFunction<T extends NativeTag = NativeTag> {
constructor(
readonly tag: T,
readonly name: string,
readonly pkg: CrochetPackage,
readonly payload: NativePayload[T]
) {}
}
//#endregion
//#region Metadata
export class Metadata {
constructor(
readonly source: string,
readonly table: Map<number, IR.Interval>
) {}
}
//#endregion
//#region World
export class CrochetTest {
constructor(
readonly module: CrochetModule,
readonly env: Environment,
readonly title: string,
readonly body: IR.BasicBlock
) {}
}
export class CrochetPrelude {
constructor(readonly env: Environment, readonly body: IR.BasicBlock) {}
}
export class CrochetWorld {
readonly commands = new Namespace<CrochetCommand>(null, null);
readonly types = new Namespace<CrochetType>(null, null);
readonly traits = new Namespace<CrochetTrait>(null, null);
readonly definitions = new Namespace<CrochetValue>(null, null);
readonly relations = new Namespace<CrochetRelation>(null, null);
readonly native_types = new Namespace<CrochetType>(null, null);
readonly native_functions = new Namespace<NativeFunction>(null, null);
readonly actions = new Namespace<Action>(null, null);
readonly contexts = new Namespace<CrochetContext>(null, null);
readonly capabilities = new Namespace<CrochetCapability>(null, null);
readonly global_context = new GlobalContext();
readonly prelude: CrochetPrelude[] = [];
readonly tests: CrochetTest[] = [];
readonly packages = new Map<string, CrochetPackage>();
}
export class CrochetPackage {
readonly types: PassthroughNamespace<CrochetType>;
readonly traits: PassthroughNamespace<CrochetTrait>;
readonly definitions: PassthroughNamespace<CrochetValue>;
readonly relations: PassthroughNamespace<CrochetRelation>;
readonly native_functions: Namespace<NativeFunction>;
readonly actions: PassthroughNamespace<Action>;
readonly contexts: PassthroughNamespace<CrochetContext>;
readonly capabilities: PassthroughNamespace<CrochetCapability>;
readonly dependencies = new Set<string>();
readonly granted_capabilities = new Set<CrochetCapability>();
constructor(
readonly world: CrochetWorld,
readonly name: string,
readonly filename: string
) {
this.types = new PassthroughNamespace(world.types, name);
this.traits = new PassthroughNamespace(world.traits, name);
this.definitions = new PassthroughNamespace(world.definitions, name);
this.native_functions = new Namespace(world.native_functions, name);
this.relations = new PassthroughNamespace(world.relations, name);
this.actions = new PassthroughNamespace(world.actions, name);
this.contexts = new PassthroughNamespace(world.contexts, name);
this.capabilities = new PassthroughNamespace(world.capabilities, name);
}
}
export class CrochetModule {
readonly types: Namespace<CrochetType>;
readonly definitions: Namespace<CrochetValue>;
readonly relations: Namespace<CrochetRelation>;
readonly actions: Namespace<Action>;
readonly contexts: Namespace<CrochetContext>;
readonly traits: Namespace<CrochetTrait>;
readonly open_prefixes: Set<string>;
constructor(
readonly pkg: CrochetPackage,
readonly filename: string,
readonly metadata: Metadata | null
) {
this.open_prefixes = new Set();
this.open_prefixes.add("crochet.core");
this.types = new Namespace(pkg.types, pkg.name, this.open_prefixes);
this.definitions = new Namespace(
pkg.definitions,
pkg.name,
this.open_prefixes
);
this.relations = new Namespace(pkg.relations, pkg.name, this.open_prefixes);
this.actions = new Namespace(pkg.actions, pkg.name, this.open_prefixes);
this.contexts = new Namespace(pkg.contexts, pkg.name, this.open_prefixes);
this.traits = new Namespace(pkg.traits, pkg.name, this.open_prefixes);
}
}
//#endregion
//#region Relations
export enum RelationTag {
CONCRETE,
PROCEDURAL,
}
export type RelationPayload = {
[RelationTag.CONCRETE]: ConcreteRelation;
[RelationTag.PROCEDURAL]: ProceduralRelation;
};
export class CrochetRelation<T extends RelationTag = RelationTag> {
constructor(
readonly tag: T,
readonly name: string,
readonly documentation: string,
readonly payload: RelationPayload[T]
) {}
}
export class ConcreteRelation {
constructor(
readonly module: CrochetModule,
readonly meta: number,
readonly type: TreeType,
public tree: Tree
) {}
}
export class ProceduralRelation {
constructor(
readonly search: (env: Environment, patterns: Pattern[]) => Environment[],
readonly sample:
| null
| ((env: Environment, patterns: Pattern[], size: number) => Environment[])
) {}
}
export class Pair {
constructor(readonly value: CrochetValue, public tree: Tree) {}
}
export enum TreeTag {
ONE,
MANY,
END,
}
export type TreeType = TTOne | TTMany | TTEnd;
export class TTOne {
readonly tag = TreeTag.ONE;
constructor(readonly next: TreeType) {}
}
export class TTMany {
readonly tag = TreeTag.MANY;
constructor(readonly next: TreeType) {}
}
export class TTEnd {
readonly tag = TreeTag.END;
}
export const type_end = new TTEnd();
export type Tree = TreeOne | TreeMany | TreeEnd;
export abstract class TreeBase {
abstract tag: TreeTag;
}
export class TreeOne extends TreeBase {
readonly tag = TreeTag.ONE;
public value: Pair | null = null;
constructor(readonly type: TreeType) {
super();
}
}
export class TreeMany extends TreeBase {
readonly tag = TreeTag.MANY;
public table = new CMap<Tree>();
constructor(readonly type: TreeType) {
super();
}
}
export class TreeEnd extends TreeBase {
readonly tag = TreeTag.END;
constructor() {
super();
}
}
export const tree_end = new TreeEnd();
//#endregion
//#region Simulation
export class Action {
readonly fired = new Set<CrochetValue>();
constructor(
readonly type: CrochetType,
readonly meta: number,
readonly module: CrochetModule,
readonly name: string,
readonly documentation: string,
readonly actor_type: CrochetTypeConstraint,
readonly self_parameter: string,
readonly predicate: IR.Predicate,
readonly rank_function: IR.BasicBlock,
readonly body: IR.BasicBlock
) {}
}
export class When {
constructor(
readonly meta: number,
readonly module: CrochetModule,
readonly documentation: string,
readonly predicate: IR.Predicate,
readonly body: IR.BasicBlock
) {}
}
export type Context = CrochetContext | GlobalContext;
export enum ContextTag {
LOCAL,
GLOBAL,
}
export class GlobalContext {
readonly tag = ContextTag.GLOBAL;
readonly actions: Action[] = [];
readonly events: When[] = [];
}
export class CrochetContext {
readonly tag = ContextTag.LOCAL;
readonly actions: Action[] = [];
readonly events: When[] = [];
constructor(
readonly meta: number,
readonly module: CrochetModule,
readonly name: string,
readonly documentation: string
) {}
}
export class SimulationSignal {
constructor(
readonly meta: number,
readonly name: string,
readonly parameters: string[],
readonly body: IR.BasicBlock,
readonly module: CrochetModule
) {}
}
export class SimulationState {
public rounds: bigint = 0n;
public acted = new Set<CrochetValue>();
public turn: CrochetValue | null = null;
constructor(
readonly state: State,
readonly module: CrochetModule,
readonly env: Environment,
readonly random: XorShift,
readonly actors: CrochetValue[],
readonly context: Context,
readonly goal: IR.SimulationGoal,
readonly signals: Namespace<SimulationSignal>
) {}
}
//#endregion
//#region Evaluation
export class Environment {
readonly bindings = new Map<string, CrochetValue>();
constructor(
readonly parent: Environment | null,
readonly raw_receiver: CrochetValue | null,
readonly raw_module: CrochetModule | null,
readonly raw_continuation: CrochetActivation | null
) {}
define(name: string, value: CrochetValue): boolean {
if (this.bindings.has(name)) {
return false;
}
this.bindings.set(name, value);
return true;
}
has(name: string) {
return this.bindings.has(name);
}
try_lookup(name: string): CrochetValue | null {
const value = this.bindings.get(name);
if (value != null) {
return value;
} else if (this.parent != null) {
return this.parent.try_lookup(name);
} else {
return null;
}
}
}
export class State {
constructor(
readonly universe: Universe,
public activation: Activation,
readonly random: XorShift
) {}
}
export class HandlerStack {
public activation: CrochetActivation | null = null;
constructor(
readonly parent: HandlerStack | null,
readonly handlers: Handler[]
) {}
}
export class Handler {
constructor(
readonly guard: CrochetType,
readonly parameters: string[],
readonly env: Environment,
readonly body: IR.BasicBlock
) {}
}
export enum ContinuationTag {
RETURN,
DONE,
TAP,
}
export type Continuation =
| ContinuationDone
| ContinuationReturn
| ContinuationTap;
export class ContinuationReturn {
readonly tag = ContinuationTag.RETURN;
}
export class ContinuationDone {
readonly tag = ContinuationTag.DONE;
}
export class ContinuationTap {
readonly tag = ContinuationTag.TAP;
constructor(
readonly saved_state: State,
readonly continuation: (
previous: State,
state: State,
value: CrochetValue
) => State
) {}
}
export const _done = new ContinuationDone();
export const _return = new ContinuationReturn();
export enum ActivationTag {
CROCHET_ACTIVATION,
NATIVE_ACTIVATION,
}
export type Activation = CrochetActivation | NativeActivation;
export interface IActivation {
tag: ActivationTag;
parent: Activation | null;
continuation: Continuation;
handlers: HandlerStack;
}
export type ActivationLocation =
| CrochetLambda
| CrochetCommandBranch
| CrochetThunk
| CrochetPrelude
| CrochetTest
| NativeFunction
| SimulationSignal
| null;
export class CrochetActivation implements IActivation {
readonly tag = ActivationTag.CROCHET_ACTIVATION;
public stack: CrochetValue[] = [];
public block_stack: [number, IR.BasicBlock][] = [];
private _return: CrochetValue | null = null;
public instruction: number = 0;
constructor(
readonly parent: Activation | null,
readonly location: ActivationLocation,
readonly env: Environment,
readonly continuation: Continuation,
readonly handlers: HandlerStack,
public block: IR.BasicBlock
) {}
get current(): IR.Op | null {
if (this.instruction < 0 || this.instruction > this.block.ops.length) {
return null;
}
return this.block.ops[this.instruction];
}
next() {
this.instruction += 1;
}
get return_value() {
return this._return;
}
set_return_value(value: CrochetValue) {
this._return = value;
}
push_block(b: IR.BasicBlock) {
this.block_stack.push([this.instruction, this.block]);
this.block = b;
this.instruction = 0;
}
pop_block() {
if (this.block_stack.length === 0) {
throw new Error(`internal: pop_block() on empty stack`);
}
const [pc, block] = this.block_stack.pop()!;
this.block = block;
this.instruction = pc;
}
}
export enum NativeSignalTag {
INVOKE,
APPLY,
AWAIT,
EVALUATE,
JUMP,
TRANSCRIPT_WRITE,
MAKE_CLOSURE,
CURRENT_ACTIVATION,
CURRENT_UNIVERSE,
}
export type NativeSignal =
| NSInvoke
| NSApply
| NSAwait
| NSEvaluate
| NSJump
| NSTranscriptWrite
| NSMakeClosure
| NSCurrentActivation
| NSCurrentUniverse;
export abstract class NSBase {}
export class NSInvoke extends NSBase {
readonly tag = NativeSignalTag.INVOKE;
constructor(readonly name: string, readonly args: CrochetValue[]) {
super();
}
}
export class NSApply extends NSBase {
readonly tag = NativeSignalTag.APPLY;
constructor(readonly fn: CrochetValue, readonly args: CrochetValue[]) {
super();
}
}
export class NSMakeClosure extends NSBase {
readonly tag = NativeSignalTag.MAKE_CLOSURE;
constructor(
readonly arity: number,
readonly fn: (...args: CrochetValue[]) => Machine<CrochetValue>
) {
super();
}
}
export class NSCurrentActivation extends NSBase {
readonly tag = NativeSignalTag.CURRENT_ACTIVATION;
}
export class NSCurrentUniverse extends NSBase {
readonly tag = NativeSignalTag.CURRENT_UNIVERSE;
}
export class NSAwait extends NSBase {
readonly tag = NativeSignalTag.AWAIT;
constructor(readonly promise: Promise<CrochetValue>) {
super();
}
}
export class NSEvaluate extends NSBase {
readonly tag = NativeSignalTag.EVALUATE;
constructor(readonly env: Environment, readonly block: IR.BasicBlock) {
super();
}
}
export class NSJump extends NSBase {
readonly tag = NativeSignalTag.JUMP;
constructor(readonly activation: (parent: Activation) => Activation) {
super();
}
}
export class NSTranscriptWrite extends NSBase {
readonly tag = NativeSignalTag.TRANSCRIPT_WRITE;
constructor(
readonly tag_name: string,
readonly message: CrochetValue | string
) {
super();
}
}
export type NativeLocation = NativeFunction | null;
export class NativeActivation implements IActivation {
readonly tag = ActivationTag.NATIVE_ACTIVATION;
constructor(
readonly parent: Activation | null,
readonly location: NativeLocation,
readonly env: Environment,
readonly routine: Machine<CrochetValue>,
readonly handlers: HandlerStack,
readonly continuation: Continuation
) {}
}
export class Universe {
readonly type_cache = new Map<CrochetType, CrochetType>();
readonly static_type_cache = new Map<CrochetType, CrochetValue>();
readonly registered_instances = new Map<CrochetType, CrochetValue[]>();
readonly nothing: CrochetValue;
readonly true: CrochetValue;
readonly false: CrochetValue;
readonly integer_cache: CrochetValue[];
readonly float_cache: CrochetValue[];
readonly trusted_base = new Set<CrochetPackage>();
constructor(
readonly trace: CrochetTrace,
readonly world: CrochetWorld,
readonly random: XorShift,
readonly types: {
Any: CrochetType;
Unknown: CrochetType;
Protected: CrochetType;
Nothing: CrochetType;
True: CrochetType;
False: CrochetType;
Integer: CrochetType;
Float: CrochetType;
UnsafeArbitraryText: CrochetType;
UntrustedText: CrochetType;
Text: CrochetType;
StaticText: CrochetType;
DynamicText: CrochetType;
Interpolation: CrochetType;
Function: CrochetType[];
NativeFunctions: CrochetType[];
Thunk: CrochetType;
Record: CrochetType;
List: CrochetType;
Enum: CrochetType;
Type: CrochetType;
Cell: CrochetType;
Action: CrochetType;
ActionChoice: CrochetType;
Effect: CrochetType;
Skeleton: {
Node: CrochetType;
Name: CrochetType;
Literal: CrochetType;
Dynamic: CrochetType;
List: CrochetType;
Interpolation: CrochetType;
};
}
) {
this.nothing = new CrochetValue(Tag.NOTHING, types.Nothing, null);
this.true = new CrochetValue(Tag.TRUE, types.True, null);
this.false = new CrochetValue(Tag.FALSE, types.False, null);
this.integer_cache = [];
this.float_cache = [];
for (let i = 0; i < 256; ++i) {
this.integer_cache[i] = new CrochetValue(
Tag.INTEGER,
types.Integer,
BigInt(i)
);
this.float_cache[i] = new CrochetValue(Tag.FLOAT_64, types.Float, i);
}
}
make_integer(x: bigint) {
if (x >= 0 && x < this.integer_cache.length) {
return this.integer_cache[Number(x)];
} else {
return new CrochetValue(Tag.INTEGER, this.types.Integer, x);
}
}
make_float(x: number) {
if (Number.isInteger(x) && x >= 0 && x < this.float_cache.length) {
return this.float_cache[x];
} else {
return new CrochetValue(Tag.FLOAT_64, this.types.Float, x);
}
}
make_text(x: string) {
return new CrochetValue(Tag.TEXT, this.types.Text, x);
}
}
//#endregion
//#region Intrinsic supporting data structures
class CMapEntry<V> {
constructor(readonly key: CrochetValue, public value: V) {}
}
function cmap_is_slow(v: CrochetValue) {
switch (v.tag) {
case Tag.INTERPOLATION:
case Tag.LIST:
case Tag.RECORD:
case Tag.TEXT:
return true;
default:
return false;
}
}
function cmap_is_primitive(v: CrochetValue) {
switch (v.tag) {
case Tag.NOTHING:
case Tag.INTEGER:
case Tag.FLOAT_64:
case Tag.TRUE:
case Tag.FALSE:
return true;
default:
return false;
}
}
function cmap_get_primitive(v: CrochetValue): Primitive {
switch (v.tag) {
case Tag.TRUE:
return true;
case Tag.FALSE:
return false;
case Tag.NOTHING:
return null;
case Tag.INTEGER:
case Tag.FLOAT_64:
return v.payload as any;
default:
throw new Error(`Unsupported`);
}
}
export class CMap<V> {
private _types: {
integer: CrochetType;
float: CrochetType;
true: CrochetValue;
false: CrochetValue;
nothing: CrochetValue;
} = Object.create(null)!;
private slow_entries: CMapEntry<V>[] = [];
private table = new Map<CrochetValue | Primitive, V>();
get(key: CrochetValue): V | undefined {
if (cmap_is_slow(key)) {
return this.get_slow(key);
} else if (cmap_is_primitive(key)) {
return this.table.get(cmap_get_primitive(key));
} else {
return this.table.get(key);
}
}
private get_slow(key: CrochetValue): V | undefined {
for (const entry of this.slow_entries) {
if (equals(entry.key, key)) {
return entry.value;
}
}
return undefined;
}
has(key: CrochetValue): boolean {
return this.get(key) !== undefined;
}
set(key: CrochetValue, value: V) {
if (cmap_is_slow(key)) {
this.set_slow(key, value);
} else if (cmap_is_primitive(key)) {
const prim = cmap_get_primitive(key);
this.remember_type(prim, key);
this.table.set(cmap_get_primitive(key), value);
} else {
this.table.set(key, value);
}
}
private set_slow(key: CrochetValue, value: V) {
for (const entry of this.slow_entries) {
if (equals(entry.key, key)) {
entry.value = value;
}
}
this.slow_entries.push(new CMapEntry(key, value));
}
delete(key: CrochetValue) {
if (cmap_is_slow(key)) {
this.delete_slow(key);
} else if (cmap_is_primitive(key)) {
this.table.delete(cmap_get_primitive(key));
} else {
this.table.delete(key);
}
}
private delete_slow(key: CrochetValue) {
const new_entries = [];
for (const entry of this.slow_entries) {
if (!equals(entry.key, key)) {
new_entries.push(entry);
}
}
this.slow_entries = new_entries;
}
*entries(): Generator<[CrochetValue, V]> {
for (const [k, v] of this.table.entries()) {
yield [this.materialise_key(k), v];
}
for (const entry of this.slow_entries) {
yield [entry.key, entry.value];
}
}
*values() {
for (const value of this.table.values()) {
yield value;
}
for (const entry of this.slow_entries) {
yield entry.value;
}
}
*keys() {
for (const key of this.table.keys()) {
yield this.materialise_key(key);
}
for (const entry of this.slow_entries) {
yield entry.key;
}
}
private remember_type(primitive: Primitive, value: CrochetValue) {
if (primitive === null) {
if (this._types.nothing) return;
this._types.nothing = value;
return;
}
switch (typeof primitive) {
case "bigint":
if (this._types.integer) break;
this._types.integer = value.type;
break;
case "number":
if (this._types.float) break;
this._types.float = value.type;
break;
case "boolean":
if (primitive) {
if (this._types.true) break;
this._types.true = value;
break;
} else {
if (this._types.false) break;
this._types.false = value;
break;
}
default:
throw unreachable(primitive, "unreachable");
}
}
private materialise_key(key: CrochetValue | Primitive) {
if (key instanceof CrochetValue) {
return key;
} else if (key === null) {
return this._types.nothing;
} else {
switch (typeof key) {
case "number":
return new CrochetValue(Tag.FLOAT_64, this._types.float, key);
case "bigint":
return new CrochetValue(Tag.INTEGER, this._types.integer, key);
case "boolean": {
if (key) {
return this._types.true;
} else {
return this._types.false;
}
}
default:
throw unreachable(key, "unreachable");
}
}
}
get size() {
return this.table.size + this.slow_entries.length;
}
}
//#endregion | the_stack |
import {Oas20Document} from "../src/models/2.0/document.model";
import {OasLibraryUtils} from "../src/library.utils";
import {OasNode, OasValidationProblem} from "../src/models/node.model";
import {Oas30Document} from "../src/models/3.0/document.model";
import * as JsDiff from "diff";
import {IOasValidationSeverityRegistry, OasValidationProblemSeverity} from "../src/validation/validation";
import {ValidationRuleMetaData} from "../src/validation/ruleset";
class CustomSeverities implements IOasValidationSeverityRegistry {
constructor(private severity: OasValidationProblemSeverity) {}
public lookupSeverity(rule: ValidationRuleMetaData): OasValidationProblemSeverity {
return this.severity;
}
}
function errorsAsString(errors: OasValidationProblem[]): string {
let es: string[] = [];
for (let error of errors) {
es.push(`[${error.errorCode}] |${error.severity}| {${error.nodePath}->${error.property}} :: ${error.message}`);
}
return es.join("\n");
};
function assertValidationOutput(actual: string, expected: string): void {
console.info("========== EXPECTED ==========");
console.info(expected);
console.info("==============================")
console.info("========== ACTUAL ==========");
console.info(actual);
console.info("==============================")
let theDiff: any[] = JsDiff.diffLines(actual, expected);
let hasDiff: boolean = false;
theDiff.forEach( change => {
if (change.added) {
console.info("--- EXPECTED BUT MISSING ---\n" + change.value);
console.info("----------------------------");
hasDiff = true;
}
if (change.removed) {
console.info("--- FOUND EXTRA ---\n" + change.value);
console.info("-------------------");
hasDiff = true;
}
});
expect(hasDiff).toBeFalsy();
}
describe("Validation (2.0)", () => {
let library: OasLibraryUtils;
beforeEach(() => {
library = new OasLibraryUtils();
});
it("Valid Pet Store Document", () => {
let json: any = readJSON('tests/fixtures/validation/2.0/valid-pet-store.json');
let document: Oas20Document = library.createDocument(json) as Oas20Document;
let node: OasNode = document;
let errors: OasValidationProblem[] = library.validate(node);
expect(errors).toEqual([]);
});
it("Document (Required Properties)", () => {
let json: any = readJSON('tests/fixtures/validation/2.0/document-required-properties.json');
let document: Oas20Document = library.createDocument(json) as Oas20Document;
let node: OasNode = document;
let errors: OasValidationProblem[] = library.validate(node);
let actual: string = errorsAsString(errors);
let expected: string =
`[R-002] |2| {/->info} :: API is missing the 'info' property.
[R-003] |2| {/->paths} :: API is missing the 'paths' property.`;
assertValidationOutput(actual, expected);
});
it("Document (Invalid Property Format)", () => {
let json: any = readJSON('tests/fixtures/validation/2.0/document-invalid-property-format.json');
let document: Oas20Document = library.createDocument(json) as Oas20Document;
let node: OasNode = document;
let errors: OasValidationProblem[] = library.validate(node);
let actual: string = errorsAsString(errors);
let expected: string =
`[R-004] |2| {/->host} :: Host not properly formatted - only the host name (and optionally port) should be specified.
[R-005] |2| {/->basePath} :: Base Path should being with a '/' character.`;
assertValidationOutput(actual, expected);
});
it("Info (Required Properties)", () => {
let json: any = readJSON('tests/fixtures/validation/2.0/info-required-properties.json');
let document: Oas20Document = library.createDocument(json) as Oas20Document;
let node: OasNode = document;
let errors: OasValidationProblem[] = library.validate(node);
let actual: string = errorsAsString(errors);
let expected: string =
`[INF-001] |2| {/info->title} :: API is missing a title.
[INF-002] |2| {/info->version} :: API is missing a version.`
assertValidationOutput(actual, expected);
});
it("Info (Invalid Property Value)", () => {
let json: any = readJSON('tests/fixtures/validation/2.0/info-invalid-property-format.json');
let document: Oas20Document = library.createDocument(json) as Oas20Document;
let node: OasNode = document;
let errors: OasValidationProblem[] = library.validate(node);
let actual: string = errorsAsString(errors);
let expected: string =
`[CTC-002] |2| {/info/contact->email} :: Contact Email is an incorrect format.
[LIC-002] |2| {/info/license->url} :: License URL is an incorrect format.`;
assertValidationOutput(actual, expected);
});
it("Security Scheme (Required Properties)", () => {
let json: any = readJSON('tests/fixtures/validation/2.0/security-scheme-required-properties.json');
let document: Oas20Document = library.createDocument(json) as Oas20Document;
let node: OasNode = document;
let errors: OasValidationProblem[] = library.validate(node);
let actual: string = errorsAsString(errors);
// console.info("+++++");
// console.info(actual);
// console.info("+++++");
let expected: string =
`[SS-001] |2| {/securityDefinitions[notype_auth]->type} :: Security Scheme is missing a type.
[SS-002] |2| {/securityDefinitions[apikey_auth_1]->name} :: API Key Security Scheme is missing a parameter name (e.g. name of a header or query param).
[SS-003] |2| {/securityDefinitions[apikey_auth_1]->in} :: API Key Security Scheme must describe where the Key can be found (e.g. header, query param, etc).
[SS-004] |2| {/securityDefinitions[oauth2_auth_1]->flow} :: OAuth Security Scheme is missing a flow type.
[SS-007] |2| {/securityDefinitions[oauth2_auth_1]->scopes} :: OAuth Security Scheme is missing defined scopes.
[SS-005] |2| {/securityDefinitions[oauth2_auth_2]->authorizationUrl} :: OAuth Security Scheme is missing an Authorization URL.
[SS-007] |2| {/securityDefinitions[oauth2_auth_2]->scopes} :: OAuth Security Scheme is missing defined scopes.
[SS-005] |2| {/securityDefinitions[oauth2_auth_3]->authorizationUrl} :: OAuth Security Scheme is missing an Authorization URL.
[SS-006] |2| {/securityDefinitions[oauth2_auth_3]->tokenUrl} :: OAuth Security Scheme is missing a Token URL.
[SS-007] |2| {/securityDefinitions[oauth2_auth_3]->scopes} :: OAuth Security Scheme is missing defined scopes.
[SS-006] |2| {/securityDefinitions[oauth2_auth_4]->tokenUrl} :: OAuth Security Scheme is missing a Token URL.
[SS-007] |2| {/securityDefinitions[oauth2_auth_4]->scopes} :: OAuth Security Scheme is missing defined scopes.
[SS-006] |2| {/securityDefinitions[oauth2_auth_5]->tokenUrl} :: OAuth Security Scheme is missing a Token URL.
[SS-007] |2| {/securityDefinitions[oauth2_auth_5]->scopes} :: OAuth Security Scheme is missing defined scopes.`;
assertValidationOutput(actual, expected);
});
it("Security Scheme (Invalid Property Format)", () => {
let json: any = readJSON('tests/fixtures/validation/2.0/security-scheme-invalid-property-format.json');
let document: Oas20Document = library.createDocument(json) as Oas20Document;
let node: OasNode = document;
let errors: OasValidationProblem[] = library.validate(node);
let actual: string = errorsAsString(errors);
let expected: string =
`[SS-011] |2| {/securityDefinitions[petstore_auth]->authorizationUrl} :: Security Scheme Authorization URL is an incorrect format.
[SS-011] |2| {/securityDefinitions[petstore_auth_accessCode]->authorizationUrl} :: Security Scheme Authorization URL is an incorrect format.
[SS-012] |2| {/securityDefinitions[petstore_auth_accessCode]->tokenUrl} :: Security Scheme Token URL is an incorrect format.`;
assertValidationOutput(actual, expected);
});
it("Invalid Property Name (All)", () => {
let json: any = readJSON('tests/fixtures/validation/2.0/invalid-property-name.json');
let document: Oas20Document = library.createDocument(json) as Oas20Document;
let node: OasNode = document;
let errors: OasValidationProblem[] = library.validate(node);
let actual: string = errorsAsString(errors);
let expected: string =
`[PATH-005] |2| {/paths[pet]->null} :: Path template "pet" is not valid.
[PATH-005] |2| {/paths[pet/findByStatus]->null} :: Path template "pet/findByStatus" is not valid.
[RES-003] |2| {/paths[/pet/findByTags]/get/responses[487]->statusCode} :: "487" is not a valid HTTP response status code.
[RES-003] |2| {/paths[/pet/findByTags]/get/responses[822]->statusCode} :: "822" is not a valid HTTP response status code.
[EX-001] |2| {/paths[/pet/findByTags]/get/responses[822]/examples->produces} :: Example 'text/plain' must match one of the "produces" mime-types.
[PATH-006] |2| {/paths[//pathstest11]->null} :: Path template "//pathstest11" contains one or more empty segment.
[PATH-005] |2| {/paths[pathstest12]->null} :: Path template "pathstest12" is not valid.
[PATH-005] |2| {/paths[{pathstest13}]->null} :: Path template "{pathstest13}" is not valid.
[PATH-005] |2| {/paths[/{{pathstest14}}]->null} :: Path template "/{{pathstest14}}" is not valid.
[PATH-005] |2| {/paths[/pathstest15/{var1}{var2}]->null} :: Path template "/pathstest15/{var1}{var2}" is not valid.
[PATH-005] |2| {/paths[/pathstest16/{var]->null} :: Path template "/pathstest16/{var" is not valid.
[PATH-005] |2| {/paths[/pathstest17/var}]->null} :: Path template "/pathstest17/var}" is not valid.
[PATH-005] |2| {/paths[/pathstest19/{1var}]->null} :: Path template "/pathstest19/{1var}" is not valid.
[PATH-007] |2| {/paths[/pathstest22/{var}/{var}]->null} :: Path template "/pathstest22/{var}/{var}" contains duplicate variable names (var).
[PATH-007] |2| {/paths[/pathstest23/{var1}/{var2}/a{var2}/{var1}]->null} :: Path template "/pathstest23/{var1}/{var2}/a{var2}/{var1}" contains duplicate variable names (var1, var2).
[PATH-009] |2| {/paths[/pathstest25/]->null} :: Path template "/pathstest25/" is semantically identical to at least one other path.
[PATH-009] |2| {/paths[/pathstest25]->null} :: Path template "/pathstest25/" is semantically identical to at least one other path.
[PATH-009] |2| {/paths[/pathstest26/{var}/]->null} :: Path template "/pathstest26/{var}/" is semantically identical to at least one other path.
[PATH-009] |2| {/paths[/pathstest26/{var}]->null} :: Path template "/pathstest26/{var}/" is semantically identical to at least one other path.
[PATH-009] |2| {/paths[/pathstest27/{var2}/]->null} :: Path template "/pathstest27/{var2}/" is semantically identical to at least one other path.
[PATH-009] |2| {/paths[/pathstest27/{var1}]->null} :: Path template "/pathstest27/{var2}/" is semantically identical to at least one other path.`;
assertValidationOutput(actual, expected);
});
it("Uniqueness (All)", () => {
let json: any = readJSON('tests/fixtures/validation/2.0/uniqueness.json');
let document: Oas20Document = library.createDocument(json) as Oas20Document;
let node: OasNode = document;
let errors: OasValidationProblem[] = library.validate(node);
let actual: string = errorsAsString(errors);
let expected: string =
`[OP-003] |2| {/paths[/pet]/put->operationId} :: Duplicate operationId 'addPet' found (operation IDs must be unique across all operations in the API).
[OP-003] |2| {/paths[/pet]/post->operationId} :: Duplicate operationId 'addPet' found (operation IDs must be unique across all operations in the API).
[PAR-019] |2| {/paths[/pet/findByStatus]/get/parameters[0]->in} :: Duplicate query parameter named 'status' found (parameters must be unique by name and location).
[PAR-019] |2| {/paths[/pet/findByStatus]/get/parameters[1]->in} :: Duplicate query parameter named 'status' found (parameters must be unique by name and location).
[PAR-019] |2| {/paths[/pet/findByTags]/get/parameters[0]->in} :: Duplicate query parameter named 'tags' found (parameters must be unique by name and location).
[PAR-019] |2| {/paths[/pet/findByTags]/get/parameters[1]->in} :: Duplicate query parameter named 'tags' found (parameters must be unique by name and location).
[PAR-019] |2| {/paths[/pet/findByTags]/get/parameters[2]->in} :: Duplicate query parameter named 'tags' found (parameters must be unique by name and location).
[OP-003] |2| {/paths[/pet/{petId}]/get->operationId} :: Duplicate operationId 'getPetById' found (operation IDs must be unique across all operations in the API).
[OP-003] |2| {/paths[/pet/{petId}]/post->operationId} :: Duplicate operationId 'getPetById' found (operation IDs must be unique across all operations in the API).
[OP-003] |2| {/paths[/pet/{petId}]/delete->operationId} :: Duplicate operationId 'getPetById' found (operation IDs must be unique across all operations in the API).
[PAR-020] |2| {/paths[/store/order]/post/parameters[0]->in} :: Operation has multiple "body" parameters.
[PAR-020] |2| {/paths[/store/order]/post/parameters[1]->in} :: Operation has multiple "body" parameters.
[TAG-003] |2| {/tags[1]->store} :: Duplicate tag 'store' found (every tag must have a unique name).
[TAG-003] |2| {/tags[2]->store} :: Duplicate tag 'store' found (every tag must have a unique name).`;
assertValidationOutput(actual, expected);
});
it("Mutually Exclusive (All)", () => {
let json: any = readJSON('tests/fixtures/validation/2.0/mutually-exclusive.json');
let document: Oas20Document = library.createDocument(json) as Oas20Document;
let node: OasNode = document;
let errors: OasValidationProblem[] = library.validate(node);
let actual: string = errorsAsString(errors);
let expected: string = `[PATH-002] |2| {/paths[/pet]/post->body} :: Operation may not have both Body and Form Data parameters.`;
assertValidationOutput(actual, expected);
});
it("Invalid Reference (All)", () => {
let json: any = readJSON('tests/fixtures/validation/2.0/invalid-reference.json');
let document: Oas20Document = library.createDocument(json) as Oas20Document;
let node: OasNode = document;
let errors: OasValidationProblem[] = library.validate(node);
let actual: string = errorsAsString(errors);
let expected: string =
`[PAR-018] |2| {/paths[/pet]/put/parameters[1]->$ref} :: Parameter Reference must refer to a valid Parameter Definition.
[SCH-001] |2| {/paths[/pet]/post/parameters[0]/schema->$ref} :: Schema Reference must refer to a valid Schema Definition.
[SCH-001] |2| {/paths[/pet/findByStatus]/get/responses[200]/schema/items->$ref} :: Schema Reference must refer to a valid Schema Definition.
[SREQ-001] |2| {/paths[/pet/findByStatus]/get/security[0]->null} :: Security Requirement 'petstore_auth_notfound' must refer to a valid Security Scheme.
[RES-002] |2| {/paths[/pet/findByTags]/get/responses[404]->$ref} :: Response Reference must refer to a valid Response Definition.`;
assertValidationOutput(actual, expected);
});
it("Pet Store (Extra Properties)", () => {
let json: any = readJSON('tests/fixtures/validation/2.0/pet-store-extra-properties.json');
let document: Oas20Document = library.createDocument(json) as Oas20Document;
let node: OasNode = document;
let errors: OasValidationProblem[] = library.validate(node);
let actual: string = errorsAsString(errors);
let expected: string =
`[UNKNOWN-001] |2| {/info->extra-info-property} :: An unexpected property "extra-info-property" was found. Extension properties should begin with "x-".
[UNKNOWN-001] |2| {/info/license->extra-license-property-1} :: An unexpected property "extra-license-property-1" was found. Extension properties should begin with "x-".
[UNKNOWN-001] |2| {/info/license->extra-license-property-2} :: An unexpected property "extra-license-property-2" was found. Extension properties should begin with "x-".`;
assertValidationOutput(actual, expected);
});
it("Required operationId if un-ignored", () => {
let json: any = readJSON('tests/fixtures/validation/2.0/operation-id.json');
let document: Oas20Document = library.createDocument(json) as Oas20Document;
let node: OasNode = document;
let errors: OasValidationProblem[] = library.validate(node, true, new CustomSeverities(OasValidationProblemSeverity.high));
let actual: string = errorsAsString(errors);
let expected: string = `[OP-008] |3| {/paths[/path]/post->operationId} :: Operation is missing a operation id.`;
assertValidationOutput(actual, expected);
});
});
describe("Validation (3.0)", () => {
let library: OasLibraryUtils;
beforeEach(() => {
library = new OasLibraryUtils();
});
it("Valid Pet Store Document", () => {
let json: any = readJSON('tests/fixtures/validation/3.0/valid-pet-store.json');
let document: Oas30Document = library.createDocument(json) as Oas30Document;
let node: OasNode = document;
let errors: OasValidationProblem[] = library.validate(node);
let actual: string = errorsAsString(errors);
let expected: string = "";
assertValidationOutput(actual, expected);
});
it("Invalid Property Format", () => {
let json: any = readJSON('tests/fixtures/validation/3.0/invalid-property-format.json');
let document: Oas30Document = library.createDocument(json) as Oas30Document;
let node: OasNode = document;
let errors: OasValidationProblem[] = library.validate(node);
let actual: string = errorsAsString(errors);
let expected: string =
`[INF-004] |2| {/info->termsOfService} :: Terms of Service URL is an incorrect format.
[CTC-001] |2| {/info/contact->url} :: Contact URL is an incorrect format.
[CTC-002] |2| {/info/contact->email} :: Contact Email is an incorrect format.
[LIC-002] |2| {/info/license->url} :: License URL is an incorrect format.`;
assertValidationOutput(actual, expected);
});
it("Ignored Property Name", () => {
let json: any = readJSON('tests/fixtures/validation/3.0/ignored-property-name.json');
let document: Oas30Document = library.createDocument(json) as Oas30Document;
let node: OasNode = document;
let errors: OasValidationProblem[] = library.validate(node);
let actual: string = errorsAsString(errors);
let expected: string =
`[PAR-021] |2| {/paths[/pets]/get/parameters[2]->name} :: The "Authorization" header parameter will be ignored.
[HEAD-008] |2| {/paths[/pets]/get/responses[200]/content[multipart/form-data]/encoding[id]/headers[Content-Type]->null} :: The "Content-Type" header will be ignored.`;
assertValidationOutput(actual, expected);
});
it("Invalid Property Type", () => {
let json: any = readJSON('tests/fixtures/validation/3.0/invalid-property-type.json');
let document: Oas30Document = library.createDocument(json) as Oas30Document;
let node: OasNode = document;
let errors: OasValidationProblem[] = library.validate(node);
let actual: string = errorsAsString(errors);
let expected: string = [
`[SCH-004] |2| {/paths[/pets]/get/responses[200]/content[application/json]/schema->items} :: Schema items must be present only for schemas of type 'array'.`,
`[SCH-003] |2| {/components/schemas[NewPet]/properties[name]->type} :: Schema type value of "invalid" is not allowed. Must be one of: [string, number, integer, boolean, array, object]`,
`[SCH-005] |2| {/components/schemas[NewPet]/properties[tags]->items} :: Schema is missing array type information.`,
`[SCH-003] |2| {/components/schemas[NewPet]/properties[nickNames]/items->type} :: Schema type value of "invalid" is not allowed. Must be one of: [string, number, integer, boolean, array, object]`
].join('\n')
assertValidationOutput(actual, expected);
});
it("Invalid Property Name", () => {
let json: any = readJSON('tests/fixtures/validation/3.0/invalid-property-name.json');
let document: Oas30Document = library.createDocument(json) as Oas30Document;
let node: OasNode = document;
let errors: OasValidationProblem[] = library.validate(node);
let actual: string = errorsAsString(errors);
let expected: string =
`[ENC-006] |2| {/paths[/enc-006]/post/requestBody/content[multipart/mixed]/encoding[missingProperty]->missingProperty} :: Encoding Property "missingProperty" not found in the associated schema.
[RES-003] |2| {/paths[/pets]/get/responses[Success]->statusCode} :: "Success" is not a valid HTTP response status code.
[PATH-005] |2| {/paths[pets/{id}]->null} :: Path template "pets/{id}" is not valid.
[PATH-006] |2| {/paths[//pathstest11]->null} :: Path template "//pathstest11" contains one or more empty segment.
[PATH-005] |2| {/paths[pathstest12]->null} :: Path template "pathstest12" is not valid.
[PATH-005] |2| {/paths[{pathstest13}]->null} :: Path template "{pathstest13}" is not valid.
[PATH-005] |2| {/paths[/{{pathstest14}}]->null} :: Path template "/{{pathstest14}}" is not valid.
[PATH-005] |2| {/paths[/pathstest15/{var1}{var2}]->null} :: Path template "/pathstest15/{var1}{var2}" is not valid.
[PAR-007] |2| {/paths[/pathstest15/{var1}{var2}]/get/parameters[1]->name} :: Path Parameter "var2" not found in path template.
[PATH-005] |2| {/paths[/pathstest16/{var]->null} :: Path template "/pathstest16/{var" is not valid.
[PATH-005] |2| {/paths[/pathstest17/var}]->null} :: Path template "/pathstest17/var}" is not valid.
[PATH-005] |2| {/paths[/pathstest19/{1var}]->null} :: Path template "/pathstest19/{1var}" is not valid.
[PATH-007] |2| {/paths[/pathstest22/{var}/{var}]->null} :: Path template "/pathstest22/{var}/{var}" contains duplicate variable names (var).
[PATH-007] |2| {/paths[/pathstest23/{var1}/{var2}/a{var2}/{var1}]->null} :: Path template "/pathstest23/{var1}/{var2}/a{var2}/{var1}" contains duplicate variable names (var1, var2).
[PATH-009] |2| {/paths[/pathstest25/]->null} :: Path template "/pathstest25/" is semantically identical to at least one other path.
[PATH-009] |2| {/paths[/pathstest25]->null} :: Path template "/pathstest25/" is semantically identical to at least one other path.
[PATH-009] |2| {/paths[/pathstest26/{var}/]->null} :: Path template "/pathstest26/{var}/" is semantically identical to at least one other path.
[PATH-009] |2| {/paths[/pathstest26/{var}]->null} :: Path template "/pathstest26/{var}/" is semantically identical to at least one other path.
[PATH-009] |2| {/paths[/pathstest27/{var2}/]->null} :: Path template "/pathstest27/{var2}/" is semantically identical to at least one other path.
[PATH-009] |2| {/paths[/pathstest27/{var1}]->null} :: Path template "/pathstest27/{var2}/" is semantically identical to at least one other path.
[SDEF-001] |2| {/components/schemas[Pet+Foo]->name} :: Schema Definition Name is not valid.
[RDEF-001] |2| {/components/responses[The Response]->name} :: Response Definition Name is not valid.
[PDEF-001] |2| {/components/parameters[Some$Parameter]->parameterName} :: Parameter Definition Name is not valid.
[EDEF-001] |2| {/components/examples[Example|1]->name} :: Example Definition Name is not valid.
[RBDEF-001] |2| {/components/requestBodies[Request Body]->name} :: Request Body Definition Name is not valid.
[HDEF-001] |2| {/components/headers[[Header]]->name} :: Header Definition Name is not valid.
[SS-013] |2| {/components/securitySchemes[Security%Scheme]->schemeName} :: Security Scheme Name is not valid.
[LDEF-001] |2| {/components/links[Link*Twelve]->name} :: Link Definition Name is not valid.
[CDEF-001] |2| {/components/callbacks[Invalid Callback Name]->name} :: Callback Definition Name is not valid.
[SREQ-001] |2| {/security[1]->null} :: Security Requirement 'MissingAuth' must refer to a valid Security Scheme.`;
assertValidationOutput(actual, expected);
});
it("Invalid Property Value", () => {
let json: any = readJSON('tests/fixtures/validation/3.0/invalid-property-value.json');
let document: Oas30Document = library.createDocument(json) as Oas30Document;
let node: OasNode = document;
let errors: OasValidationProblem[] = library.validate(node);
let actual: string = errorsAsString(errors);
let expected: string =
`[SVAR-003] |2| {/servers[0]/variables[missingProperty]->null} :: Server Variable "missingProperty" is not found in the server url template.
[ENC-001] |2| {/paths[/enc-001]/post/requestBody/content[application/x-www-form-urlencoded]/encoding[profileImage]->headers} :: Headers are not allowed for "application/x-www-form-urlencoded" media types.
[ENC-002] |2| {/paths[/enc-002]/post/requestBody/content[multipart/form-data]/encoding[historyMetadata]->style} :: Encoding Style is not allowed for "multipart/form-data" media types.
[ENC-003] |2| {/paths[/enc-003]/post/requestBody/content[multipart/form-data]/encoding[historyMetadata]->explode} :: "Explode" is not allowed for "multipart/form-data" media types.
[ENC-004] |2| {/paths[/enc-004]/post/requestBody/content[multipart/form-data]/encoding[historyMetadata]->allowReserved} :: "Allow Reserved" is not allowed for "multipart/form-data" media types.
[ENC-005] |2| {/paths[/enc-005]/post/requestBody/content[application/x-www-form-urlencoded]/encoding[historyMetadata]->style} :: Encoding Style is an invalid value.
[HEAD-010] |2| {/paths[/head-010]/post/requestBody/content[multipart/form-data]/encoding[historyMetadata]/headers[X-Header-1]->style} :: Header Style must be "simple".
[HEAD-011] |2| {/paths[/head-011]/post/requestBody/content[multipart/form-data]/encoding[historyMetadata]/headers[X-Header-1]->content} :: Header content cannot have multiple media types.
[LINK-002] |2| {/paths[/link-002]/get/responses[200]/links[address]->operationId} :: The Operation ID does not refer to an existing Operation.
[MT-003] |2| {/paths[/mt-003]/post/requestBody/content[application/json]->encoding} :: Encoding is not allowed for "application/json" media types.
[OP-009] |2| {/paths[/op-009]/get->requestBody} :: Request Body is not supported for GET operations.
[OP-013] |2| {/paths[/op-013]/get->null} :: Operation must have at least one Response.
[PAR-022] |2| {/paths[/par-022]/parameters[0]->style} :: Parameter Style must be one of: ["matrix", "label", "form", "simple", "spaceDelimited", "pipeDelimited", "deepObject"] (Found "shallowObject").
[PAR-023] |2| {/paths[/par-022]/parameters[0]->style} :: Query Parameter Style must be one of: ["form", "spaceDelimited", "pipeDelimited", "deepObject"] (Found "shallowObject").
[PAR-003] |2| {/paths[/par-003/{id}]/parameters[0]->required} :: Path Parameter "id" must be marked as required.
[PAR-013] |2| {/paths[/par-013/{id}]/parameters[0]->allowEmptyValue} :: Allow Empty Value is not allowed (only for Query params).
[PAR-027] |2| {/paths[/par-027/{id}]/parameters[0]->style} :: Path Parameter Style must be one of: ["matrix", "label", "simple"] (Found "form").
[PAR-023] |2| {/paths[/par-023]/parameters[0]->style} :: Query Parameter Style must be one of: ["form", "spaceDelimited", "pipeDelimited", "deepObject"] (Found "label").
[PAR-024] |2| {/paths[/par-024]/parameters[0]->style} :: Cookie Parameter style must be "form". (Found "label")
[PAR-025] |2| {/paths[/par-025]/parameters[0]->style} :: Header Parameter Style must be "simple". (Found "label").
[PAR-028] |2| {/paths[/par-028]/parameters[0]->allowReserved} :: Allow Reserved is only allowed for Query Parameters.
[PAR-029] |2| {/paths[/par-029]/parameters[0]->content} :: Parameter content cannot have multiple media types.
[PAR-019] |2| {/paths[/dupesWithinPathItemInlined]/parameters[0]->in} :: Duplicate query parameter named 'status' found (parameters must be unique by name and location).
[PAR-019] |2| {/paths[/dupesWithinPathItemInlined]/parameters[1]->in} :: Duplicate query parameter named 'status' found (parameters must be unique by name and location).
[PAR-019] |2| {/paths[/dupesWithinPathItemInlineAndRefCombo]/parameters[0]->in} :: Duplicate query parameter named 'status' found (parameters must be unique by name and location).
[PAR-019] |2| {/paths[/dupesWithinPathItemInlineAndRefCombo]/parameters[1]->in} :: Duplicate query parameter named 'status' found (parameters must be unique by name and location).
[PAR-019] |2| {/paths[/dupesWithinPathItemIndirectReference]/parameters[0]->in} :: Duplicate query parameter named 'status' found (parameters must be unique by name and location).
[PAR-019] |2| {/paths[/dupesWithinPathItemIndirectReference]/parameters[1]->in} :: Duplicate query parameter named 'status' found (parameters must be unique by name and location).
[PAR-018] |2| {/paths[/incorrectReferenceWithinPathItem]/parameters[1]->$ref} :: Parameter Reference must refer to a valid Parameter Definition.
[PAR-019] |2| {/paths[/dupesWithinOpInlined]/get/parameters[0]->in} :: Duplicate query parameter named 'status' found (parameters must be unique by name and location).
[PAR-019] |2| {/paths[/dupesWithinOpInlined]/get/parameters[1]->in} :: Duplicate query parameter named 'status' found (parameters must be unique by name and location).
[PAR-019] |2| {/paths[/dupesWithinOpInlineAndRefCombo]/get/parameters[0]->in} :: Duplicate query parameter named 'status' found (parameters must be unique by name and location).
[PAR-019] |2| {/paths[/dupesWithinOpInlineAndRefCombo]/get/parameters[1]->in} :: Duplicate query parameter named 'status' found (parameters must be unique by name and location).
[PAR-007] |2| {/paths[/par-007/operation/{id}]/get/parameters[1]->name} :: Path Parameter "missing" not found in path template.
[PAR-007] |2| {/paths[/par-007/pathItem/{id}]/parameters[0]->name} :: Path Parameter "missing" not found in path template.
[OP-011] |2| {/paths[/op-011/{id}/{sub}]/get->null} :: No definition found for path variable "sub" for path '/op-011/{id}/{sub}' and method 'GET'.
[PAR-021] |2| {/paths[/par-021]/parameters[0]->name} :: The "Content-Type" header parameter will be ignored.
[SCH-002] |2| {/paths[/sch-002]/get/responses[200]/content[application/json]/schema/discriminator->discriminator} :: Schema Discriminator is only allowed when using one of: ["oneOf", "anyOf", "allOf"]
[SREQ-002] |2| {/paths[/sreq-002]/get/security[0]->null} :: Security Requirement 'api_key' scopes must be an empty array because the referenced Security Definition not "oauth2" or "openIdConnect".
[XML-002] |2| {/components/schemas[xml-002]/properties[name]/xml->wrapped} :: XML Wrapped elements can only be used for "array" properties.
[SS-008] |2| {/components/securitySchemes[ss-008]->type} :: Security Scheme Type must be one of: http, apiKey, oauth2, openIdConnect
[SS-009] |2| {/components/securitySchemes[ss-009]->in} :: API Key Security Scheme must be located "in" one of: query, header, cookie
[SS-017] |2| {/components/securitySchemes[ss-017]->bearerFormat} :: Security Scheme "Bearer Format" only allowed for HTTP Bearer auth scheme.
[SS-016] |2| {/components/securitySchemes[ss-016]->scheme} :: HTTP Security Scheme must be one of: ["basic", "bearer", "digest", "hoba", "mutual", "negotiate", "oauth", "vapid", "scram-sha-1", "scram-sha-256"] (Found: 'leveraged')`;
assertValidationOutput(actual, expected);
});
it("Invalid Reference", () => {
let json: any = readJSON('tests/fixtures/validation/3.0/invalid-reference.json');
let document: Oas30Document = library.createDocument(json) as Oas30Document;
let node: OasNode = document;
let errors: OasValidationProblem[] = library.validate(node);
let actual: string = errorsAsString(errors);
let expected: string =
`[CALL-001] |2| {/paths[/call-001]/get/callbacks[myRefCallback]->$ref} :: Callback Reference must refer to a valid Callback Definition.
[EX-003] |2| {/paths[/ex-003]/put/requestBody/content[application/json]/examples[bar]->$ref} :: Example Reference must refer to a valid Example Definition.
[HEAD-012] |2| {/paths[/head-005]/get/responses[200]/headers[X-Rate-Limit-Reset]->$ref} :: Header Reference must refer to a valid Header Definition.
[LINK-003] |2| {/paths[/link-003]/get/responses[200]/links[MissingLink]->operationRef} :: Link "Operation Reference" must refer to a valid Operation Definition.
[LINK-005] |2| {/paths[/link-005]/get/responses[200]/links[MissingLink]->$ref} :: Link Reference must refer to a valid Link Definition.
[PAR-018] |2| {/paths[/par-018]/parameters[1]->$ref} :: Parameter Reference must refer to a valid Parameter Definition.
[RB-003] |2| {/paths[/rb-003]/post/requestBody->$ref} :: Request Body Reference must refer to a valid Request Body Definition.
[RES-002] |2| {/paths[/res-002]/get/responses[200]->$ref} :: Response Reference must refer to a valid Response Definition.
[SCH-001] |2| {/paths[/sch-001]/parameters[0]/schema->$ref} :: Schema Reference must refer to a valid Schema Definition.
[SCH-001] |2| {/paths[/ref-loop]/parameters[0]/schema->$ref} :: Schema Reference must refer to a valid Schema Definition.
[SCH-001] |2| {/paths[/missing-indirect-ref]/parameters[0]/schema->$ref} :: Schema Reference must refer to a valid Schema Definition.
[SCH-001] |2| {/components/schemas[SchemaRef1]->$ref} :: Schema Reference must refer to a valid Schema Definition.
[SCH-001] |2| {/components/schemas[SchemaRef2]->$ref} :: Schema Reference must refer to a valid Schema Definition.
[SCH-001] |2| {/components/schemas[MissingIndirectSchemaRef]->$ref} :: Schema Reference must refer to a valid Schema Definition.
[SS-018] |2| {/components/securitySchemes[BASIC]->$ref} :: Security Scheme Reference must refer to a valid Security Scheme Definition.`;
assertValidationOutput(actual, expected);
});
it("Mutually Exclusive", () => {
let json: any = readJSON('tests/fixtures/validation/3.0/mutually-exclusive.json');
let document: Oas30Document = library.createDocument(json) as Oas30Document;
let node: OasNode = document;
let errors: OasValidationProblem[] = library.validate(node);
let actual: string = errorsAsString(errors);
let expected: string =
`[MT-001] |2| {/components/parameters[mt-001]/content[text/plain]->example} :: Media Type "Example" and "Examples" are mutually exclusive.
[PAR-030] |2| {/components/parameters[par-030]->schema} :: Parameter cannot have both a Schema and Content.
[PAR-031] |2| {/components/parameters[par-031]->example} :: Parameter "Example" and "Examples" are mutually exclusive.
[EX-004] |2| {/components/examples[ex-004]->value} :: Example "Value" and "External Value" are mutually exclusive.
[HEAD-014] |2| {/components/headers[head-014]->schema} :: Header cannot have both a Schema and Content.
[HEAD-013] |2| {/components/headers[head-013]->example} :: Header "Example" and "Examples" are mutually exclusive.
[LINK-001] |2| {/components/links[link-001]->operationId} :: Link Operation Reference and Operation ID cannot both be used.`;
assertValidationOutput(actual, expected);
});
it("Required Property", () => {
let json: any = readJSON('tests/fixtures/validation/3.0/required-property.json');
let document: Oas30Document = library.createDocument(json) as Oas30Document;
let node: OasNode = document;
let errors: OasValidationProblem[] = library.validate(node);
let actual: string = errorsAsString(errors);
let expected: string =
`[INF-001] |2| {/info->title} :: API is missing a title.
[INF-002] |2| {/info->version} :: API is missing a version.
[LIC-001] |2| {/info/license->name} :: License is missing a name.
[SRV-001] |2| {/servers[0]->url} :: Server is missing a template URL.
[SVAR-001] |2| {/servers[1]/variables[username]->default} :: Server Variable "username" is missing a default value.
[OP-007] |2| {/paths[/op-007]/get->responses} :: Operation must have at least one response.
[PAR-001] |2| {/paths[/par-001]/parameters[0]->name} :: Parameter is missing a name.
[PAR-002] |2| {/paths[/par-002]/parameters[0]->in} :: Parameter is missing a location (Query, Header, etc).
[RES-001] |2| {/paths[/res-001]/get/responses[200]->description} :: Response (code 200) is missing a description.
[DISC-001] |2| {/components/schemas[disc-001]/discriminator->propertyName} :: Discriminator must indicate a property (by name).
[ED-001] |2| {/components/schemas[ed-001]/externalDocs->url} :: External Documentation is missing a URL.
[FLOW-001] |2| {/components/securitySchemes[flow-001]/flows/implicit->authorizationUrl} :: Implicit OAuth Flow is missing an Authorization URL.
[FLOW-001] |2| {/components/securitySchemes[flow-001]/flows/authorizationCode->authorizationUrl} :: Auth Code OAuth Flow is missing an Authorization URL.
[FLOW-002] |2| {/components/securitySchemes[flow-002]/flows/clientCredentials->tokenUrl} :: Client Credentials OAuth Flow is missing a Token URL.
[FLOW-002] |2| {/components/securitySchemes[flow-002]/flows/authorizationCode->tokenUrl} :: Auth Code OAuth Flow is missing a Token URL.
[FLOW-006] |2| {/components/securitySchemes[flow-006]/flows/implicit->scopes} :: OAuth Flow is missing defined scopes.
[SS-001] |2| {/components/securitySchemes[ss-001]->type} :: Security Scheme is missing a type.
[SS-002] |2| {/components/securitySchemes[ss-002]->name} :: API Key Security Scheme is missing a parameter name (e.g. name of a header or query param).
[SS-003] |2| {/components/securitySchemes[ss-003]->in} :: API Key Security Scheme must describe where the Key can be found (e.g. header, query param, etc).
[SS-019] |2| {/components/securitySchemes[ss-019]->scheme} :: HTTP Security Scheme is missing a scheme (Basic, Digest, etc).
[SS-020] |2| {/components/securitySchemes[ss-020]->flows} :: OAuth Security Scheme does not define any OAuth flows.
[SS-021] |2| {/components/securitySchemes[ss-021]->openIdConnectUrl} :: OpenID Connect Security Scheme is missing a Connect URL.
[TAG-001] |2| {/tags[0]->name} :: Tag is missing a name.`;
assertValidationOutput(actual, expected);
// Now test re-validating just the Info node
errors = library.validate(document.info);
actual = errorsAsString(errors);
expected =
`[INF-001] |2| {/info->title} :: API is missing a title.
[INF-002] |2| {/info->version} :: API is missing a version.
[LIC-001] |2| {/info/license->name} :: License is missing a name.`
assertValidationOutput(actual, expected);
});
it("Required Property (Root)", () => {
let json: any = readJSON('tests/fixtures/validation/3.0/required-property-root.json');
let document: Oas30Document = library.createDocument(json) as Oas30Document;
let node: OasNode = document;
let errors: OasValidationProblem[] = library.validate(node);
let actual: string = errorsAsString(errors);
let expected: string =
`[R-002] |2| {/->info} :: API is missing the 'info' property.
[R-003] |2| {/->paths} :: API is missing the 'paths' property.`;
assertValidationOutput(actual, expected);
});
it("Uniqueness", () => {
let json: any = readJSON('tests/fixtures/validation/3.0/uniqueness.json');
let document: Oas30Document = library.createDocument(json) as Oas30Document;
let node: OasNode = document;
let errors: OasValidationProblem[] = library.validate(node);
let actual: string = errorsAsString(errors);
let expected: string =
`[OP-003] |2| {/paths[/foo]/get->operationId} :: Duplicate operationId 'fooId' found (operation IDs must be unique across all operations in the API).
[OP-003] |2| {/paths[/bar]/get->operationId} :: Duplicate operationId 'fooId' found (operation IDs must be unique across all operations in the API).
[TAG-003] |2| {/tags[0]->MyTag} :: Duplicate tag 'MyTag' found (every tag must have a unique name).
[TAG-003] |2| {/tags[2]->MyTag} :: Duplicate tag 'MyTag' found (every tag must have a unique name).`;
assertValidationOutput(actual, expected);
});
it("Uniqueness (Re-Validate)", () => {
let json: any = readJSON('tests/fixtures/validation/3.0/uniqueness.json');
let document: Oas30Document = library.createDocument(json) as Oas30Document;
let node: OasNode = document;
let errors1: OasValidationProblem[] = library.validate(node);
let errors2: OasValidationProblem[] = library.validate(node);
// If we validate twice, the output should be the same!
expect(errorsAsString(errors1)).toEqual(errorsAsString(errors2));
let actual: string = errorsAsString(errors2);
let expected: string =
`[OP-003] |2| {/paths[/foo]/get->operationId} :: Duplicate operationId 'fooId' found (operation IDs must be unique across all operations in the API).
[OP-003] |2| {/paths[/bar]/get->operationId} :: Duplicate operationId 'fooId' found (operation IDs must be unique across all operations in the API).
[TAG-003] |2| {/tags[0]->MyTag} :: Duplicate tag 'MyTag' found (every tag must have a unique name).
[TAG-003] |2| {/tags[2]->MyTag} :: Duplicate tag 'MyTag' found (every tag must have a unique name).`;
assertValidationOutput(actual, expected);
});
it("Custom Severities", () => {
let json: any = readJSON('tests/fixtures/validation/3.0/mutually-exclusive.json');
let document: Oas30Document = library.createDocument(json) as Oas30Document;
let node: OasNode = document;
let errors: OasValidationProblem[] = library.validate(node, true, new CustomSeverities(OasValidationProblemSeverity.low));
let actual: string = errorsAsString(errors);
let expected: string =
`[MT-001] |1| {/components/parameters[mt-001]/content[text/plain]->example} :: Media Type "Example" and "Examples" are mutually exclusive.
[PAR-030] |1| {/components/parameters[par-030]->schema} :: Parameter cannot have both a Schema and Content.
[PAR-031] |1| {/components/parameters[par-031]->example} :: Parameter "Example" and "Examples" are mutually exclusive.
[EX-004] |1| {/components/examples[ex-004]->value} :: Example "Value" and "External Value" are mutually exclusive.
[HEAD-014] |1| {/components/headers[head-014]->schema} :: Header cannot have both a Schema and Content.
[HEAD-013] |1| {/components/headers[head-013]->example} :: Header "Example" and "Examples" are mutually exclusive.
[LINK-001] |1| {/components/links[link-001]->operationId} :: Link Operation Reference and Operation ID cannot both be used.`;
assertValidationOutput(actual, expected);
// Test @Ignore of problems.
errors = library.validate(node, true, new CustomSeverities(OasValidationProblemSeverity.ignore));
actual = errorsAsString(errors);
expected = ``;
assertValidationOutput(actual, expected);
});
it("Validation Problem List", () => {
let json: any = readJSON('tests/fixtures/validation/3.0/invalid-property-value.json');
let document: Oas30Document = library.createDocument(json) as Oas30Document;
let node: OasNode = document;
library.validate(node);
let enode: OasNode = document.paths.pathItem("/par-022").parameters[0];
let errors: OasValidationProblem[] = enode.validationProblems();
let actual: string = errorsAsString(errors);
let expected: string =
`[PAR-022] |2| {/paths[/par-022]/parameters[0]->style} :: Parameter Style must be one of: ["matrix", "label", "form", "simple", "spaceDelimited", "pipeDelimited", "deepObject"] (Found "shallowObject").
[PAR-023] |2| {/paths[/par-022]/parameters[0]->style} :: Query Parameter Style must be one of: ["form", "spaceDelimited", "pipeDelimited", "deepObject"] (Found "shallowObject").`;
assertValidationOutput(actual, expected);
let codes: string[] = enode.validationProblemCodes();
expect(codes).toEqual([ "PAR-022", "PAR-023" ]);
errors = enode.validationProblemsFor("style");
actual = errorsAsString(errors);
expected =
`[PAR-022] |2| {/paths[/par-022]/parameters[0]->style} :: Parameter Style must be one of: ["matrix", "label", "form", "simple", "spaceDelimited", "pipeDelimited", "deepObject"] (Found "shallowObject").
[PAR-023] |2| {/paths[/par-022]/parameters[0]->style} :: Query Parameter Style must be one of: ["form", "spaceDelimited", "pipeDelimited", "deepObject"] (Found "shallowObject").`;
assertValidationOutput(actual, expected);
errors = enode.validationProblemsFor("in");
expect(errors).toEqual([]);
});
it("Unknown Properties", () => {
let json: any = readJSON('tests/fixtures/validation/3.0/unknown-properties.json');
let document: Oas30Document = library.createDocument(json) as Oas30Document;
let node: OasNode = document;
let errors: OasValidationProblem[] = library.validate(node);
let actual: string = errorsAsString(errors);
let expected: string =
`[UNKNOWN-001] |2| {/info/license->unknown-license-property} :: An unexpected property "unknown-license-property" was found. Extension properties should begin with "x-".
[UNKNOWN-001] |2| {/components/schemas[Error]->unexpected-property-datatype} :: An unexpected property "unexpected-property-datatype" was found. Extension properties should begin with "x-".`;
assertValidationOutput(actual, expected);
});
it("Required operationId if un-ignored", () => {
let json: any = readJSON('tests/fixtures/validation/3.0/operation-id.json');
let document: Oas30Document = library.createDocument(json) as Oas30Document;
let node: OasNode = document;
let errors: OasValidationProblem[] = library.validate(node, true, new CustomSeverities(OasValidationProblemSeverity.high));
let actual: string = errorsAsString(errors);
let expected: string = `[OP-008] |3| {/paths[/path]/post->operationId} :: Operation is missing a operation id.`;
assertValidationOutput(actual, expected);
});
}); | the_stack |
import { AddChildFromBuilder, CSSType, Color, CoreTypes, Image, Label, PropertyChangeData, PseudoClassHandler, View, ViewBase } from '@nativescript/core';
import { backgroundColorProperty, backgroundInternalProperty } from '@nativescript/core/ui/styling/style-properties';
import { textTransformProperty } from '@nativescript/core/ui/text-base';
import { TabStripItem as TabStripItemDefinition } from '.';
import { TabNavigationBase } from '../tab-navigation-base';
import { TabStrip } from '../tab-strip';
@CSSType('MDTabStripItem')
export class TabStripItem extends View implements TabStripItemDefinition, AddChildFromBuilder {
public static tapEvent = 'tap';
public static selectEvent = 'select';
public static unselectEvent = 'unselect';
public image: Image;
public label: Label;
private mIndex: number;
private mTitle: string;
private mIconSource: string;
private mIconClass: string;
private mHighlightedHandler: () => void;
private mNormalHandler: () => void;
private mLabelColorHandler: (args: PropertyChangeData) => void;
private mLabelFontHandler: (args: PropertyChangeData) => void;
private mLabelTextTransformHandler: (args: PropertyChangeData) => void;
private _labelTextHandler: (args: PropertyChangeData) => void;
private mImageColorHandler: (args: PropertyChangeData) => void;
private mImageFontHandler: (args: PropertyChangeData) => void;
private mImageSrcHandler: (args: PropertyChangeData) => void;
get index() {
return this.mIndex;
}
set index(value) {
this.mIndex = value;
}
get title() {
if (this.isLoaded) {
return this.label.text;
}
return this.mTitle;
}
set title(value: string) {
this.mTitle = value;
if (this.isLoaded) {
this.label.text = value;
}
}
get iconClass() {
if (this.isLoaded) {
return this.image.className;
}
return this.mIconClass;
}
set iconClass(value: string) {
this.mIconClass = value;
if (this.isLoaded) {
this.image.className = value;
}
}
get iconSource() {
if (this.isLoaded) {
return this.image.src;
}
return this.mIconSource;
}
set iconSource(value: string) {
this.mIconSource = value;
if (this.isLoaded) {
this.image.src = value;
}
}
public onLoaded() {
if (!this.image) {
const image = new Image();
image.src = this.iconSource;
image.className = this.iconClass;
this.image = image;
this._addView(this.image);
}
if (!this.label) {
const label = new Label();
label.text = this.title;
this.label = label;
this._addView(this.label);
}
super.onLoaded();
this.mLabelColorHandler =
this.mLabelColorHandler ||
((args: PropertyChangeData) => {
const parent = this.parent as TabStrip;
const tabStripParent = parent && (parent.parent as TabNavigationBase);
return tabStripParent && tabStripParent.setTabBarItemColor(this, args.value);
});
this.label.style.on('colorChange', this.mLabelColorHandler);
this.mLabelFontHandler =
this.mLabelFontHandler ||
((args: PropertyChangeData) => {
const parent = this.parent as TabStrip;
const tabStripParent = parent && (parent.parent as TabNavigationBase);
return tabStripParent && tabStripParent.setTabBarItemFontInternal(this, args.value);
});
this.label.style.on('fontInternalChange', this.mLabelFontHandler);
this.mLabelTextTransformHandler =
this.mLabelTextTransformHandler ||
((args: PropertyChangeData) => {
const parent = this.parent as TabStrip;
const tabStripParent = parent && (parent.parent as TabNavigationBase);
return tabStripParent && tabStripParent.setTabBarItemTextTransform(this, args.value);
});
this.label.style.on('textTransformChange', this.mLabelTextTransformHandler);
this._labelTextHandler =
this._labelTextHandler ||
((args: PropertyChangeData) => {
const parent = this.parent as TabStrip;
const tabStripParent = parent && (parent.parent as TabNavigationBase);
return tabStripParent && tabStripParent.setTabBarItemTitle(this, args.value);
});
this.label.on('textChange', this._labelTextHandler);
this.mImageColorHandler =
this.mImageColorHandler ||
((args: PropertyChangeData) => {
const parent = this.parent as TabStrip;
const tabStripParent = parent && (parent.parent as TabNavigationBase);
return tabStripParent && tabStripParent.setTabBarIconColor(this, args.value);
});
this.image.style.on('colorChange', this.mImageColorHandler);
this.mImageFontHandler =
this.mImageFontHandler ||
((args: PropertyChangeData) => {
const parent = this.parent as TabStrip;
const tabStripParent = parent && (parent.parent as TabNavigationBase);
return tabStripParent && tabStripParent.setTabBarItemFontInternal(this, args.value);
});
this.image.style.on('fontInternalChange', this.mImageFontHandler);
this.mImageSrcHandler =
this.mImageSrcHandler ||
((args: PropertyChangeData) => {
const parent = this.parent as TabStrip;
const tabStripParent = parent && (parent.parent as TabNavigationBase);
return tabStripParent && tabStripParent.setTabBarIconSource(this, args.value);
});
this.image.on('srcChange', this.mImageSrcHandler);
}
public onUnloaded() {
super.onUnloaded();
this.label.style.off('colorChange', this.mLabelColorHandler);
this.label.style.off('fontInternalChange', this.mLabelFontHandler);
this.label.style.off('textTransformChange', this.mLabelTextTransformHandler);
this.label.style.off('textChange', this._labelTextHandler);
this.image.style.off('colorChange', this.mImageColorHandler);
this.image.style.off('fontInternalChange', this.mImageFontHandler);
this.image.style.off('srcChange', this.mImageSrcHandler);
}
public eachChild(callback: (child: ViewBase) => boolean) {
if (this.label) {
callback(this.label);
}
if (this.image) {
callback(this.image);
}
}
public _addChildFromBuilder(name: string, value: any): void {
if (value instanceof Image) {
this.image = value;
this.iconSource = value.src;
this.iconClass = value.className;
this._addView(value);
// selectedIndexProperty.coerce(this);
}
if (value instanceof Label) {
this.label = value;
this.title = value.text;
this._addView(value);
// selectedIndexProperty.coerce(this);
}
}
public requestLayout(): void {
// Default implementation for non View instances (like TabViewItem).
const parent = this.parent;
if (parent) {
parent.requestLayout();
}
}
@PseudoClassHandler('normal', 'highlighted', 'pressed', 'active')
_updateTabStateChangeHandler(subscribe: boolean) {
if (subscribe) {
this.mHighlightedHandler =
this.mHighlightedHandler ||
(() => {
this._goToVisualState('highlighted');
});
this.mNormalHandler =
this.mNormalHandler ||
(() => {
this._goToVisualState('normal');
});
this.on(TabStripItem.selectEvent, this.mHighlightedHandler);
this.on(TabStripItem.unselectEvent, this.mNormalHandler);
const parent = this.parent as TabStrip;
const tabStripParent = parent && (parent.parent as TabNavigationBase);
if (this.mIndex === tabStripParent.selectedIndex && !(global.isIOS && tabStripParent.cssType.toLowerCase() === 'tabs')) {
// HACK: tabStripParent instanceof Tabs creates a circular dependency
// HACK: tabStripParent.cssType === "Tabs" is a hacky workaround
this._goToVisualState('highlighted');
}
} else {
this.off(TabStripItem.selectEvent, this.mHighlightedHandler);
this.off(TabStripItem.unselectEvent, this.mNormalHandler);
}
}
[backgroundColorProperty.getDefault](): Color {
const parent = this.parent as TabStrip;
const tabStripParent = parent && (parent.parent as TabNavigationBase);
return tabStripParent && tabStripParent.getTabBarBackgroundColor();
}
[backgroundColorProperty.setNative](value: Color) {
const parent = this.parent as TabStrip;
const tabStripParent = parent && (parent.parent as TabNavigationBase);
return tabStripParent && tabStripParent.setTabBarItemBackgroundColor(this, value);
}
[textTransformProperty.getDefault](): CoreTypes.TextTransformType {
const parent = this.parent as TabStrip;
const tabStripParent = parent && (parent.parent as TabNavigationBase);
return tabStripParent && tabStripParent.getTabBarItemTextTransform(this);
}
[textTransformProperty.setNative](value: CoreTypes.TextTransformType) {
const parent = this.parent as TabStrip;
const tabStripParent = parent && (parent.parent as TabNavigationBase);
return tabStripParent && tabStripParent.setTabBarItemTextTransform(this, value);
}
[backgroundInternalProperty.getDefault](): any {
return null;
}
[backgroundInternalProperty.setNative](value: any) {
// disable the background CSS properties
}
} | the_stack |
import {Reducer} from 'redux';
import {
RCRE_ASYNC_LOAD_DATA_FAIL,
RCRE_ASYNC_LOAD_DATA_PROGRESS,
RCRE_ASYNC_LOAD_DATA_SUCCESS,
RCRE_RESET_CONTAINER_STORE,
RCRE_DATA_CUSTOMER_PASS,
IContainerAction,
RCRE_SET_DATA,
RCRE_SET_MULTI_DATA,
RCRE_SYNC_LOAD_DATA_FAIL,
RCRE_SYNC_LOAD_DATA_SUCCESS,
RCRE_CLEAR_DATA,
RCRE_DELETE_DATA, RCRE_INIT_CONTAINER
} from './action';
import {clone, each, get} from 'lodash';
import {
syncExportContainerState,
syncDeleteContainerState, syncPropsContainerState, ContainerNode
} from '../Service/ContainerDepGraph';
import {setWith, deleteWith, combineKeys} from '../util/util';
export const TMP_MODEL = '__TMP_MODEL__DO_NO_USE_IT';
export type IContainerState = {
[key: string]: any;
};
export let containerInitState: IContainerState = Object.freeze({
[TMP_MODEL]: {}
});
export const containerReducer: Reducer<IContainerState> =
(state: IContainerState = containerInitState, actions: IContainerAction): IContainerState => {
switch (actions.type) {
case RCRE_INIT_CONTAINER: {
let model = actions.payload.model;
let data = actions.payload.data;
let context = actions.context;
if (!state[model]) {
state = setWith(state, model, data);
} else {
state = setWith(state, model, {
...state[model],
...data
});
}
let container = context.rcre.containerGraph.get(model);
if (!container) {
return state;
}
// 初次挂载的时候,继承父级的数据
if (container.parent) {
let affectNode: ContainerNode[] = [container.parent];
state = syncPropsContainerState(state, actions.context, container.parent);
state = syncExportContainerState(state, affectNode, actions.context, container);
affectNode.forEach(node => {
state = syncPropsContainerState(state, actions.context, node);
});
}
return state;
}
case RCRE_SET_DATA: {
let name = actions.payload.name;
let newValue = actions.payload.value;
let context = actions.context;
let options = actions.payload.options || {};
let model = actions.model;
if (!(model in state)) {
state = setWith(state, model, {});
}
let paginationCacheKey = `${TMP_MODEL}.${model}.pagination`;
if (options.pagination) {
let cache = {};
options.pagination.paginationQueryParams.forEach(param => {
cache[param] = state[model][param];
});
state = setWith(state, paginationCacheKey, {
key: name,
value: newValue,
cache: cache
});
}
// 在当前分页器不在第一页的情况下,选择新的选项要重置分页的值
let oldPaginationCache = get(state, paginationCacheKey);
if (!options.pagination &&
oldPaginationCache &&
oldPaginationCache.value.current !== 1 &&
oldPaginationCache.cache.hasOwnProperty(name) &&
oldPaginationCache.cache[name] !== newValue) {
let newPaginationValue = clone(oldPaginationCache.value);
let paginationKey = oldPaginationCache.key;
newPaginationValue.current = 1;
state = setWith(state, combineKeys(model, paginationKey), newPaginationValue);
}
state = setWith(state, combineKeys(model, name), newValue);
let container = context.rcre.containerGraph.get(model);
let affectNode: ContainerNode[] = [];
state = syncExportContainerState(state, affectNode, actions.context, container);
affectNode.forEach(node => {
state = syncPropsContainerState(state, actions.context, node);
});
return state;
}
case RCRE_SET_MULTI_DATA: {
let payload = actions.payload;
let model = actions.model;
let context = actions.context;
if (!(model in state)) {
state = setWith(state, model, {});
}
payload.forEach(item => {
let name = item.name;
let value = item.value;
model = actions.model;
state = setWith(state, combineKeys(model, name), value);
});
let container = context.rcre.containerGraph.get(model);
let affectNode: ContainerNode[] = [];
state = syncExportContainerState(state, affectNode, actions.context, container);
affectNode.forEach(node => {
state = syncPropsContainerState(state, actions.context, node);
});
return state;
}
case RCRE_ASYNC_LOAD_DATA_PROGRESS: {
let payload = actions.payload;
let model = payload.model;
if (!(model in state)) {
state = setWith(state, model, {
$loading: true
});
}
state = setWith(state, combineKeys(model, '$loading'), true);
return state;
}
case RCRE_ASYNC_LOAD_DATA_SUCCESS: {
let payload = actions.payload;
let model = payload.model;
let context = payload.context;
let data = payload.data;
if (!state[model]) {
state = setWith(state, model, {});
}
state = setWith(state, combineKeys(model, '$loading'), false);
state = setWith(state, combineKeys(model, '$error'), null);
each(data, (value, name) => {
state = setWith(state, combineKeys(model, name), value);
});
let container = context.rcre.containerGraph.get(model);
let affectNode: ContainerNode[] = [];
// 初次挂载的时候,继承父级的数据
if (container && container.parent) {
affectNode.push(container.parent);
}
state = syncExportContainerState(state, affectNode, payload.context, container);
affectNode.forEach(node => {
state = syncPropsContainerState(state, payload.context, node);
});
return state;
}
case RCRE_ASYNC_LOAD_DATA_FAIL: {
let payload = actions.payload;
let model = payload.model;
let error = payload.error;
if (!(model in state)) {
state = setWith(state, model, {});
}
state = setWith(state, combineKeys(model, '$loading'), false);
state = setWith(state, combineKeys(model, '$error'), error);
return state;
}
case RCRE_SYNC_LOAD_DATA_SUCCESS: {
let payload = actions.payload;
let model = payload.model;
let data = payload.data;
let context = payload.context;
if (!(model in state)) {
state = setWith(state, model, {});
}
each(data, (val, key) => {
state = setWith(state, combineKeys(model, key), val);
});
let container = context.rcre.containerGraph.get(model);
let affectNode: ContainerNode[] = [];
// 初次挂载的时候,继承父级的数据
if (container && container.parent) {
affectNode.push(container.parent);
state = syncPropsContainerState(state, payload.context, container.parent);
}
state = syncExportContainerState(state, affectNode, payload.context, container);
affectNode.forEach(node => {
state = syncPropsContainerState(state, payload.context, node);
});
return state;
}
case RCRE_SYNC_LOAD_DATA_FAIL: {
let payload = actions.payload;
let model = payload.model;
let error = payload.error;
if (!(model in state)) {
state = setWith(state, model, {});
}
state = setWith(state, combineKeys(model, '$error'), error);
return state;
}
case RCRE_DATA_CUSTOMER_PASS: {
let payload = actions.payload;
let model = payload.model;
let data = payload.data;
let context = actions.context;
if (!(model in state)) {
console.error(`DataCustomerPass: ${model} is not exist`);
return state;
}
each(data, (val, key) => {
state = setWith(state, combineKeys(model, key), val);
});
let container = context.rcre.containerGraph.get(model);
let affectNode: ContainerNode[] = [];
state = syncExportContainerState(state, affectNode, actions.context, container);
affectNode.forEach(node => {
state = syncPropsContainerState(state, actions.context, node);
});
return state;
}
case RCRE_CLEAR_DATA: {
let delKey = actions.payload.model;
let context = actions.payload.context;
let node = context.rcre.containerGraph.get(delKey);
if (node && node.options.clearDataToParentsWhenDestroy) {
state = syncDeleteContainerState(state, actions.payload.context, node);
}
state = deleteWith(state, delKey);
return state;
}
case RCRE_RESET_CONTAINER_STORE:
state = {
[TMP_MODEL]: {}
};
Object.freeze(state);
return state;
case RCRE_DELETE_DATA: {
let payload = actions.payload;
let name = payload.name;
let model = actions.model;
let context = actions.context;
let container = context.rcre.containerGraph.get(model);
if (!(model in state)) {
return state;
}
if (container && container.options.syncDelete) {
state = syncDeleteContainerState(state, context, container, name);
state = deleteWith(state, combineKeys(model, name));
} else {
state = deleteWith(state, combineKeys(model, name));
state = syncExportContainerState(state, [], actions.context, container);
}
return state;
}
default:
return state;
}
}; | the_stack |
import { CAParser } from "./CAParser";
/*
* Date: 2021-05-01 17:41:46
* LastEditors: GT<caogtaa@gmail.com>
* LastEditTime: 2021-05-01 17:42:33
*/
const {ccclass, property} = cc._decorator;
type CARawConfig = {
name: string,
str: string
};
@ccclass
export default class SceneCellularAutomata extends cc.Component {
@property(cc.Button)
btnRandom: cc.Button = null;
@property(cc.Button)
btnRun: cc.Button = null;
@property(cc.Button)
btnTest: cc.Button = null;
@property([cc.Sprite])
images: cc.Sprite[] = [];
@property(cc.Sprite)
imageDisplay: cc.Sprite = null;
@property(cc.Label)
lblFPS: cc.Label = null;
protected _originFPS: number = 60; // 保存进入场景前的fps,退出场景时恢复
protected _originEnableMultiTouch: boolean;
protected _paused: boolean = false;
protected _srcIndex: number = 0;
protected _viewCenter: cc.Vec2 = cc.v2(0, 0); // 视图中心相对与纹理的位置,单位: 设计分辨率像素
protected _viewScale: number = 1.0; // 视图缩放
protected _textureSize = cc.size(1024, 1024); // 目前先固定纹理大小,后续如果支持其他途径加载纹理,需要调整大小
protected _configs: CARawConfig[] = [];
onLoad() {
let that = this;
cc.resources.load("ca", cc.JsonAsset, (err: Error, data: cc.JsonAsset) => {
let json = data?.json;
if (json) {
for (let key in json) {
that._configs.push({
name: key,
str: json[key]
});
}
}
});
}
onEnable() {
this._originFPS = cc.game.getFrameRate();
this._originEnableMultiTouch = cc.macro.ENABLE_MULTI_TOUCH;
this.SetFrameRate(20);
cc.macro.ENABLE_MULTI_TOUCH = true;
}
onDisable() {
cc.game.setFrameRate(this._originFPS);
cc.macro.ENABLE_MULTI_TOUCH = this._originEnableMultiTouch;
}
protected SetFrameRate(fps: number) {
cc.game.setFrameRate(fps);
this.lblFPS.string = `${fps}`;
}
start () {
let imageDisplay = this.imageDisplay;
// this.images[this._srcIndex].spriteFrame = imageDisplay.spriteFrame;
for (let image of this.images)
this.UpdateRenderTextureMatProperties(image);
// 初始化视图区域
this._viewCenter.x = this._textureSize.width / 2;
this._viewCenter.y = this._textureSize.height / 2;
this._viewScale = 4.0;
this.UpdateDisplayMatProperties();
imageDisplay.node.on(cc.Node.EventType.TOUCH_START, this.OnDisplayTouchStart, this);
imageDisplay.node.on(cc.Node.EventType.TOUCH_MOVE, this.OnDisplayTouchMove, this);
imageDisplay.node.on(cc.Node.EventType.TOUCH_END, this.OnDisplayTouchEnd, this);
imageDisplay.node.on(cc.Node.EventType.TOUCH_CANCEL, this.OnDisplayTouchEnd, this);
imageDisplay.node.on(cc.Node.EventType.MOUSE_WHEEL, this.OnDisplayMouseWheel, this);
let that = this;
this.btnRandom.node.on("click", () => {
let configs = that._configs;
if (!configs)
return;
let index = this.RandomRangeInt(0, configs.length);
let rInfo = CAParser.Parse(configs[index].str);
let texture = CAParser.Merge(rInfo, null, null, null, that._textureSize.width, that._textureSize.height);
that.SetCATexture(texture);
});
this.btnRun.node.on("click", () => {
that._paused = !that._paused;
});
this.btnTest.node.on("click", () => {
let configs = that._configs;
if (!configs)
return;
let rInfo = CAParser.Parse(configs[this.RandomRangeInt(0, configs.length)].str);
let gInfo = CAParser.Parse(configs[this.RandomRangeInt(0, configs.length)].str);
let bInfo = CAParser.Parse(configs[this.RandomRangeInt(0, configs.length)].str);
let texture = CAParser.Merge(rInfo, gInfo, bInfo, null, that._textureSize.width, that._textureSize.height);
that.SetCATexture(texture);
});
}
protected SetCATexture(texture: cc.RenderTexture) {
this._srcIndex = 0;
this.images[this._srcIndex].spriteFrame = new cc.SpriteFrame(texture);
}
protected UpdateRenderTextureMatProperties(sprite: cc.Sprite) {
let mat = sprite.getMaterial(0);
if (!mat)
return;
let sf = sprite.spriteFrame;
let dx: number, dy: number;
if (sf) {
// 获取纹素大小
let sz = sf.getOriginalSize();
dx = 1.0 / sz.width;
dy = 1.0 / sz.height;
} else {
// 纹理为空时,以设计分辨率像素为纹素大小。这里要求节点大小和期望的游戏区大小相同
dx = 1.0 / sprite.node.width;
dy = 1.0 / sprite.node.height;
}
mat.setProperty("dx", dx);
mat.setProperty("dy", dy);
}
protected UpdateDisplayMatProperties() {
let sprite = this.imageDisplay;
let mat = sprite.getMaterial(0);
if (!mat)
return;
// let viewOffset = this._viewOffset;
let width = sprite.node.width;
let height = sprite.node.height;
let viewCenter = this._viewCenter;
let viewScale = this._viewScale;
let tw = this._textureSize.width;
let th = this._textureSize.height;
// let left = 0.5 - width / 1024 + viewCenter.x / 1024;
let left = viewCenter.x / tw - width / (tw * 2 * viewScale);
let right = viewCenter.x / tw + width / (tw * 2 * viewScale);
let bottom = viewCenter.y / th - height / (th * 2 * viewScale);
let top = viewCenter.y / th + height / (th * 2 * viewScale);
// mat.setProperty("left", left);
// mat.setProperty("right", right);
// mat.setProperty("bottom", bottom);
// mat.setProperty("top", top);
// shader内Remap()简化为MAD
mat.setProperty("p", [right-left, top-bottom]);
mat.setProperty("q", [left, bottom]);
}
protected Tick() {
if (this._paused)
return;
let order = this._srcIndex;
let from = this.images[order];
let to = this.images[1-order];
let imageDisplay = this.imageDisplay;
from.enabled = true;
this.RenderToMemory(from.node, [], to.node);
from.enabled = false;
imageDisplay.spriteFrame = to.spriteFrame;
if (to.node.scaleY * imageDisplay.node.scaleY < 0) {
// 如果scaleY符号不相等,则imageDisplay上下翻转
imageDisplay.node.scaleY *= -1.0;
}
// 切换RenderTexture
this._srcIndex = 1 - this._srcIndex;
}
update(dt: number) {
this.Tick();
}
public OnFPSSliderChanged(sender: cc.Slider) {
let fps = Math.floor(120 * sender.progress);
fps = Math.max(fps, 2);
fps = Math.min(fps, 120);
this.SetFrameRate(fps);
}
public RenderToMemory(root: cc.Node, others: cc.Node[], target: cc.Node, extend: number = 0): cc.RenderTexture {
// 使截屏处于被截屏对象中心(两者有同样的父节点)
let node = new cc.Node;
node.parent = root;
node.x = (0.5 - root.anchorX) * root.width;
node.y = (0.5 - root.anchorY) * root.height;
let camera = node.addComponent(cc.Camera);
camera.backgroundColor = new cc.Color(255, 255, 255, 0); // 透明区域仍然保持透明,半透明区域和白色混合
camera.clearFlags = cc.Camera.ClearFlags.DEPTH | cc.Camera.ClearFlags.STENCIL | cc.Camera.ClearFlags.COLOR;
// 设置你想要的截图内容的 cullingMask
camera.cullingMask = 0xffffffff;
let success: boolean = false;
try {
let scaleX = 1.0; //this.fitArea.scaleX;
let scaleY = 1.0; //this.fitArea.scaleY;
let gl = cc.game._renderContext;
let targetWidth = Math.floor(root.width * scaleX + extend * 2); // texture's width/height must be integer
let targetHeight = Math.floor(root.height * scaleY + extend * 2);
// 内存纹理创建后缓存在目标节点上
// 如果尺寸和上次不一样也重新创建
let texture: cc.RenderTexture = target["__gt_texture"];
if (!texture || texture.width != targetWidth || texture.height != target.height) {
texture = target["__gt_texture"] = new cc.RenderTexture();
texture.initWithSize(targetWidth, targetHeight, gl.STENCIL_INDEX8);
texture.packable = false;
// texture.setFlipY(false);
// 采样坐标周期循环
//@ts-ignore
texture.setWrapMode(cc.Texture2D.WrapMode.REPEAT, cc.Texture2D.WrapMode.REPEAT);
// 像素化
texture.setFilters(cc.Texture2D.Filter.NEAREST, cc.Texture2D.Filter.NEAREST);
}
camera.alignWithScreen = false;
// camera.orthoSize = root.height / 2;
camera.orthoSize = targetHeight / 2;
camera.targetTexture = texture;
// 渲染一次摄像机,即更新一次内容到 RenderTexture 中
camera.render(root);
if (others) {
for (let o of others) {
camera.render(o);
}
}
let screenShot = target;
screenShot.active = true;
screenShot.opacity = 255;
// screenShot.parent = root.parent;
// screenShot.position = root.position;
screenShot.width = targetWidth; // root.width;
screenShot.height = targetHeight; // root.height;
screenShot.angle = root.angle;
// fitArea有可能被缩放,截图的实际尺寸是缩放后的
screenShot.scaleX = 1.0 / scaleX;
screenShot.scaleY = -1.0 / scaleY;
let sprite = screenShot.getComponent(cc.Sprite);
if (!sprite) {
sprite = screenShot.addComponent(cc.Sprite);
// sprite.srcBlendFactor = cc.macro.BlendFactor.ONE;
}
// 如果没有sf或者一开始设置过其他sf,则替换为renderTexture
if (!sprite.spriteFrame || sprite.spriteFrame.getTexture() != texture) {
sprite.sizeMode = cc.Sprite.SizeMode.CUSTOM;
sprite.spriteFrame = new cc.SpriteFrame(texture);
}
success = true;
} finally {
camera.targetTexture = null;
node.removeFromParent();
if (!success) {
target.active = false;
}
}
return target["__gt_texture"];
}
protected OnDisplayTouchStart(e: cc.Event.EventTouch) {
}
protected OnDisplayTouchMove(e: cc.Event.EventTouch) {
let touches = e.getTouches();
if (touches.length === 1) {
// simple drag
let touch = touches[0] as cc.Touch;
let offset = touch.getDelta();
offset.mulSelf(1.0 / this._viewScale);
this._viewCenter.subSelf(offset);
this.UpdateDisplayMatProperties();
} else if (touches.length >= 2) {
// simple zoom
let t0 = touches[0] as cc.Touch;
let t1 = touches[1] as cc.Touch;
let p0 = t0.getLocation();
let p1 = t1.getLocation();
let newLength = p0.sub(p1).len();
let oldLength = p0.sub(t0.getDelta()).sub(p1).add(t1.getDelta()).len();
let scale = newLength / oldLength;
this.DisplayScaleBy(scale);
}
}
protected OnDisplayTouchEnd(e: cc.Event.EventTouch) {
// do nothing
}
// 用鼠标滚轮进行缩放
// 简单起见目前只支持视图中心固定的缩放
protected OnDisplayMouseWheel(e: cc.Event.EventMouse) {
let scrollY = e.getScrollY();
if (!scrollY)
return;
if (scrollY > 0) {
this.DisplayScaleBy(1.1);
} else {
this.DisplayScaleBy(0.9);
}
}
protected DisplayScaleBy(scale: number) {
if (scale > 0)
this._viewScale = Math.min(this._viewScale * scale, 1e3);
else
this._viewScale = Math.max(this._viewScale * scale, 1e-3);
this.UpdateDisplayMatProperties();
}
protected RandomRange(min: number, max: number) {
return Math.random() * (max - min) + min;
}
protected RandomRangeInt(min: number, max: number) {
return Math.floor(this.RandomRange(min, max));
}
} | the_stack |
import { Event, EventEmitter } from 'vscode';
import '../../../../common/extensions';
import { createDeferred, Deferred } from '../../../../common/utils/async';
import { StopWatch } from '../../../../common/utils/stopWatch';
import { traceError } from '../../../../logging';
import { sendTelemetryEvent } from '../../../../telemetry';
import { EventName } from '../../../../telemetry/constants';
import { normalizePath } from '../../../common/externalDependencies';
import { PythonEnvInfo } from '../../info';
import { getEnvPath } from '../../info/env';
import {
GetRefreshEnvironmentsOptions,
IDiscoveryAPI,
IResolvingLocator,
isProgressEvent,
ProgressNotificationEvent,
ProgressReportStage,
PythonLocatorQuery,
TriggerRefreshOptions,
} from '../../locator';
import { getQueryFilter } from '../../locatorUtils';
import { PythonEnvCollectionChangedEvent, PythonEnvsWatcher } from '../../watcher';
import { IEnvsCollectionCache } from './envsCollectionCache';
/**
* A service which maintains the collection of known environments.
*/
export class EnvsCollectionService extends PythonEnvsWatcher<PythonEnvCollectionChangedEvent> implements IDiscoveryAPI {
/** Keeps track of ongoing refreshes for various queries. */
private refreshesPerQuery = new Map<PythonLocatorQuery | undefined, Deferred<void>>();
/** Keeps track of scheduled refreshes other than the ongoing one for various queries. */
private scheduledRefreshesPerQuery = new Map<PythonLocatorQuery | undefined, Promise<void>>();
/** Keeps track of promises which resolves when a stage has been reached */
private progressPromises = new Map<ProgressReportStage, Deferred<void>>();
/** Keeps track of whether a refresh has been triggered for various queries. */
private wasRefreshTriggeredForQuery = new Map<PythonLocatorQuery | undefined, boolean>();
private readonly progress = new EventEmitter<ProgressNotificationEvent>();
public get onProgress(): Event<ProgressNotificationEvent> {
return this.progress.event;
}
public getRefreshPromise(options?: GetRefreshEnvironmentsOptions): Promise<void> | undefined {
const stage = options?.stage ?? ProgressReportStage.discoveryFinished;
return this.progressPromises.get(stage)?.promise;
}
constructor(private readonly cache: IEnvsCollectionCache, private readonly locator: IResolvingLocator) {
super();
this.locator.onChanged((event) => {
const query = undefined; // We can also form a query based on the event, but skip that for simplicity.
let scheduledRefresh = this.scheduledRefreshesPerQuery.get(query);
// If there is no refresh scheduled for the query, start a new one.
if (!scheduledRefresh) {
scheduledRefresh = this.scheduleNewRefresh(query);
}
scheduledRefresh.then(() => {
// Once refresh of cache is complete, notify changes.
this.fire(event);
});
});
this.cache.onChanged((e) => {
this.fire(e);
});
this.onProgress((event) => {
// Resolve progress promise indicating the stage has been reached.
this.progressPromises.get(event.stage)?.resolve();
this.progressPromises.delete(event.stage);
});
}
public async resolveEnv(path: string): Promise<PythonEnvInfo | undefined> {
path = normalizePath(path);
// Note cache may have incomplete info when a refresh is happening.
// This API is supposed to return complete info by definition, so
// only use cache if it has complete info on an environment.
const cachedEnv = await this.cache.getLatestInfo(path);
if (cachedEnv) {
return cachedEnv;
}
const resolved = await this.locator.resolveEnv(path).catch((ex) => {
traceError(`Failed to resolve ${path}`, ex);
return undefined;
});
if (resolved) {
this.cache.addEnv(resolved, true);
}
return resolved;
}
public getEnvs(query?: PythonLocatorQuery): PythonEnvInfo[] {
const cachedEnvs = this.cache.getAllEnvs();
return query ? cachedEnvs.filter(getQueryFilter(query)) : cachedEnvs;
}
public triggerRefresh(query?: PythonLocatorQuery, options?: TriggerRefreshOptions): Promise<void> {
const stopWatch = new StopWatch();
if (options?.ifNotTriggerredAlready) {
if (this.wasRefreshTriggered(query)) {
return Promise.resolve(); // Refresh was already triggered, return.
}
}
let refreshPromise = this.getRefreshPromiseForQuery(query);
if (!refreshPromise) {
refreshPromise = this.startRefresh(query, options);
}
return refreshPromise.then(() => this.sendTelemetry(query, stopWatch));
}
private startRefresh(query: PythonLocatorQuery | undefined, options?: TriggerRefreshOptions): Promise<void> {
if (options?.clearCache) {
this.cache.clearCache();
}
this.createProgressStates(query);
const promise = this.addEnvsToCacheForQuery(query);
return promise
.then(async () => {
this.resolveProgressStates(query);
})
.catch((ex) => {
this.rejectProgressStates(query, ex);
});
}
private async addEnvsToCacheForQuery(query: PythonLocatorQuery | undefined) {
const iterator = this.locator.iterEnvs(query);
const seen: PythonEnvInfo[] = [];
const state = {
done: false,
pending: 0,
};
const updatesDone = createDeferred<void>();
if (iterator.onUpdated !== undefined) {
const listener = iterator.onUpdated(async (event) => {
if (isProgressEvent(event)) {
switch (event.stage) {
case ProgressReportStage.discoveryFinished:
state.done = true;
listener.dispose();
break;
case ProgressReportStage.allPathsDiscovered:
if (!query) {
// Only mark as all paths discovered when querying for all envs.
this.progress.fire(event);
}
break;
default:
this.progress.fire(event);
}
} else {
state.pending += 1;
this.cache.updateEnv(seen[event.index], event.update);
if (event.update) {
seen[event.index] = event.update;
}
state.pending -= 1;
}
if (state.done && state.pending === 0) {
updatesDone.resolve();
}
});
} else {
this.progress.fire({ stage: ProgressReportStage.discoveryStarted });
updatesDone.resolve();
}
for await (const env of iterator) {
seen.push(env);
this.cache.addEnv(env);
}
await updatesDone.promise;
await this.cache.validateCache();
this.cache.flush().ignoreErrors();
}
/**
* See if we already have a refresh promise for the query going on and return it.
*/
private getRefreshPromiseForQuery(query?: PythonLocatorQuery) {
// Even if no refresh is running for this exact query, there might be other
// refreshes running for a superset of this query. For eg. the `undefined` query
// is a superset for every other query, only consider that for simplicity.
return this.refreshesPerQuery.get(query)?.promise ?? this.refreshesPerQuery.get(undefined)?.promise;
}
private wasRefreshTriggered(query?: PythonLocatorQuery) {
return this.wasRefreshTriggeredForQuery.get(query) ?? this.wasRefreshTriggeredForQuery.get(undefined);
}
/**
* Ensure we trigger a fresh refresh for the query after the current refresh (if any) is done.
*/
private async scheduleNewRefresh(query?: PythonLocatorQuery): Promise<void> {
const refreshPromise = this.getRefreshPromiseForQuery(query);
let nextRefreshPromise: Promise<void>;
if (!refreshPromise) {
nextRefreshPromise = this.startRefresh(query);
} else {
nextRefreshPromise = refreshPromise.then(() => {
// No more scheduled refreshes for this query as we're about to start the scheduled one.
this.scheduledRefreshesPerQuery.delete(query);
this.startRefresh(query);
});
this.scheduledRefreshesPerQuery.set(query, nextRefreshPromise);
}
return nextRefreshPromise;
}
private createProgressStates(query: PythonLocatorQuery | undefined) {
this.refreshesPerQuery.set(query, createDeferred<void>());
this.wasRefreshTriggeredForQuery.set(query, true);
Object.values(ProgressReportStage).forEach((stage) => {
this.progressPromises.set(stage, createDeferred<void>());
});
if (ProgressReportStage.allPathsDiscovered && query) {
// Only mark as all paths discovered when querying for all envs.
this.progressPromises.delete(ProgressReportStage.allPathsDiscovered);
}
}
private rejectProgressStates(query: PythonLocatorQuery | undefined, ex: Error) {
this.refreshesPerQuery.get(query)?.reject(ex);
this.refreshesPerQuery.delete(query);
Object.values(ProgressReportStage).forEach((stage) => {
this.progressPromises.get(stage)?.reject(ex);
this.progressPromises.delete(stage);
});
}
private resolveProgressStates(query: PythonLocatorQuery | undefined) {
this.refreshesPerQuery.get(query)?.resolve();
this.refreshesPerQuery.delete(query);
// Refreshes per stage are resolved using progress events instead.
const isRefreshComplete = Array.from(this.refreshesPerQuery.values()).every((d) => d.completed);
if (isRefreshComplete) {
this.progress.fire({ stage: ProgressReportStage.discoveryFinished });
}
}
private sendTelemetry(query: PythonLocatorQuery | undefined, stopWatch: StopWatch) {
if (!query && !this.wasRefreshTriggered(query)) {
// Intent is to capture time taken for discovery of all envs to complete the first time.
sendTelemetryEvent(EventName.PYTHON_INTERPRETER_DISCOVERY, stopWatch.elapsedTime, {
interpreters: this.cache.getAllEnvs().length,
environmentsWithoutPython: this.cache
.getAllEnvs()
.filter((e) => getEnvPath(e.executable.filename, e.location).pathType === 'envFolderPath').length,
});
}
}
} | the_stack |
import {
ConnectionOptions,
Browser,
JSONType,
DataChannelConfiguration,
DataChannelMessageEvent,
PreKeyBundle,
SignalingConnectMessage,
SignalingConnectDataChannel,
SignalingEvent,
SignalingNotifyMetadata,
SignalingNotifyConnectionCreated,
SignalingNotifyConnectionDestroyed,
TimelineEvent,
TimelineEventLogType,
TransportType,
} from "./types";
function browser(): Browser {
const ua = window.navigator.userAgent.toLocaleLowerCase();
if (ua.indexOf("edge") !== -1) {
return "edge";
} else if (ua.indexOf("chrome") !== -1 && ua.indexOf("edge") === -1) {
return "chrome";
} else if (ua.indexOf("safari") !== -1 && ua.indexOf("chrome") === -1) {
return "safari";
} else if (ua.indexOf("opera") !== -1) {
return "opera";
} else if (ua.indexOf("firefox") !== -1) {
return "firefox";
}
return null;
}
function enabledSimulcast(): boolean {
const REQUIRED_HEADER_EXTEMSIONS = [
"urn:ietf:params:rtp-hdrext:sdes:mid",
"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id",
"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id",
];
if (!window.RTCRtpSender) {
return false;
}
if (!RTCRtpSender.getCapabilities) {
return false;
}
const capabilities = RTCRtpSender.getCapabilities("video");
if (!capabilities) {
return false;
}
const headerExtensions = capabilities.headerExtensions.map((h) => h.uri);
const hasAllRequiredHeaderExtensions = REQUIRED_HEADER_EXTEMSIONS.every((h) => headerExtensions.includes(h));
return hasAllRequiredHeaderExtensions;
}
function parseDataChannelConfiguration(dataChannelConfiguration: unknown): SignalingConnectDataChannel {
if (typeof dataChannelConfiguration !== "object" || dataChannelConfiguration === null) {
throw new Error("Failed to parse options dataChannels. Options dataChannels element must be type 'object'");
}
const configuration = dataChannelConfiguration as DataChannelConfiguration;
const result: SignalingConnectDataChannel = {};
if (typeof configuration.label === "string") {
result.label = configuration.label;
}
if (typeof configuration.direction === "string") {
result.direction = configuration.direction;
}
if (typeof configuration.ordered === "boolean") {
result.ordered = configuration.ordered;
}
if (typeof configuration.compress === "boolean") {
result.compress = configuration.compress;
}
if (typeof configuration.maxPacketLifeTime === "number") {
result.max_packet_life_time = configuration.maxPacketLifeTime;
}
if (typeof configuration.maxRetransmits === "number") {
result.max_retransmits = configuration.maxRetransmits;
}
if (typeof configuration.protocol === "string") {
result.protocol = configuration.protocol;
}
return result;
}
function parseDataChannelConfigurations(dataChannelConfigurations: unknown[]): SignalingConnectDataChannel[] {
const result: SignalingConnectDataChannel[] = [];
for (const dataChannelConfiguration of dataChannelConfigurations) {
result.push(parseDataChannelConfiguration(dataChannelConfiguration));
}
return result;
}
export function isSafari(): boolean {
return browser() === "safari";
}
export function isChrome(): boolean {
return browser() === "chrome";
}
export function createSignalingMessage(
offerSDP: string,
role: string,
channelId: string | null | undefined,
metadata: JSONType | undefined,
options: ConnectionOptions,
redirect: boolean
): SignalingConnectMessage {
if (role !== "sendrecv" && role !== "sendonly" && role !== "recvonly") {
throw new Error("Unknown role type");
}
if (channelId === null || channelId === undefined) {
throw new Error("channelId can not be null or undefined");
}
const message: SignalingConnectMessage = {
type: "connect",
sora_client: "Sora JavaScript SDK __SORA_JS_SDK_VERSION__",
environment: window.navigator.userAgent,
role: role,
channel_id: channelId,
sdp: offerSDP,
audio: true,
video: true,
};
if (metadata !== undefined) {
message.metadata = metadata;
}
if (redirect) {
message.redirect = true;
}
if ("signalingNotifyMetadata" in options) {
message.signaling_notify_metadata = options.signalingNotifyMetadata;
}
if ("multistream" in options && options.multistream === true) {
// multistream
message.multistream = true;
// spotlight
if ("spotlight" in options) {
message.spotlight = options.spotlight;
if ("spotlightNumber" in options) {
message.spotlight_number = options.spotlightNumber;
}
}
if (message.spotlight === true) {
const spotlightFocusRids = ["none", "r0", "r1", "r2"];
if (options.spotlightFocusRid !== undefined && 0 <= spotlightFocusRids.indexOf(options.spotlightFocusRid)) {
message.spotlight_focus_rid = options.spotlightFocusRid;
}
if (options.spotlightUnfocusRid !== undefined && 0 <= spotlightFocusRids.indexOf(options.spotlightUnfocusRid)) {
message.spotlight_unfocus_rid = options.spotlightUnfocusRid;
}
}
}
if ("simulcast" in options || "simulcastRid" in options) {
// simulcast
if ("simulcast" in options && options.simulcast === true) {
message.simulcast = true;
}
const simalcastRids = ["r0", "r1", "r2"];
if (options.simulcastRid !== undefined && 0 <= simalcastRids.indexOf(options.simulcastRid)) {
message.simulcast_rid = options.simulcastRid;
}
}
// client_id
if ("clientId" in options && options.clientId !== undefined) {
message.client_id = options.clientId;
}
if ("dataChannelSignaling" in options && typeof options.dataChannelSignaling === "boolean") {
message.data_channel_signaling = options.dataChannelSignaling;
}
if ("ignoreDisconnectWebSocket" in options && typeof options.ignoreDisconnectWebSocket === "boolean") {
message.ignore_disconnect_websocket = options.ignoreDisconnectWebSocket;
}
// parse options
const audioPropertyKeys = ["audioCodecType", "audioBitRate"];
const audioOpusParamsPropertyKeys = [
"audioOpusParamsChannels",
"audioOpusParamsClockRate",
"audioOpusParamsMaxplaybackrate",
"audioOpusParamsStereo",
"audioOpusParamsSpropStereo",
"audioOpusParamsMinptime",
"audioOpusParamsPtime",
"audioOpusParamsUseinbandfec",
"audioOpusParamsUsedtx",
];
const videoPropertyKeys = ["videoCodecType", "videoBitRate"];
const copyOptions = Object.assign({}, options);
(Object.keys(copyOptions) as (keyof ConnectionOptions)[]).forEach((key) => {
if (key === "audio" && typeof copyOptions[key] === "boolean") {
return;
}
if (key === "video" && typeof copyOptions[key] === "boolean") {
return;
}
if (0 <= audioPropertyKeys.indexOf(key) && copyOptions[key] !== null) {
return;
}
if (0 <= audioOpusParamsPropertyKeys.indexOf(key) && copyOptions[key] !== null) {
return;
}
if (0 <= videoPropertyKeys.indexOf(key) && copyOptions[key] !== null) {
return;
}
delete copyOptions[key];
});
if (copyOptions.audio !== undefined) {
message.audio = copyOptions.audio;
}
const hasAudioProperty = Object.keys(copyOptions).some((key) => {
return 0 <= audioPropertyKeys.indexOf(key);
});
if (message.audio && hasAudioProperty) {
message.audio = {};
if ("audioCodecType" in copyOptions) {
message.audio["codec_type"] = copyOptions.audioCodecType;
}
if ("audioBitRate" in copyOptions) {
message.audio["bit_rate"] = copyOptions.audioBitRate;
}
}
const hasAudioOpusParamsProperty = Object.keys(copyOptions).some((key) => {
return 0 <= audioOpusParamsPropertyKeys.indexOf(key);
});
if (message.audio && hasAudioOpusParamsProperty) {
if (typeof message.audio != "object") {
message.audio = {};
}
message.audio.opus_params = {};
if ("audioOpusParamsChannels" in copyOptions) {
message.audio.opus_params.channels = copyOptions.audioOpusParamsChannels;
}
if ("audioOpusParamsClockRate" in copyOptions) {
message.audio.opus_params.clock_rate = copyOptions.audioOpusParamsClockRate;
}
if ("audioOpusParamsMaxplaybackrate" in copyOptions) {
message.audio.opus_params.maxplaybackrate = copyOptions.audioOpusParamsMaxplaybackrate;
}
if ("audioOpusParamsStereo" in copyOptions) {
message.audio.opus_params.stereo = copyOptions.audioOpusParamsStereo;
}
if ("audioOpusParamsSpropStereo" in copyOptions) {
message.audio.opus_params.sprop_stereo = copyOptions.audioOpusParamsSpropStereo;
}
if ("audioOpusParamsMinptime" in copyOptions) {
message.audio.opus_params.minptime = copyOptions.audioOpusParamsMinptime;
}
if ("audioOpusParamsPtime" in copyOptions) {
message.audio.opus_params.ptime = copyOptions.audioOpusParamsPtime;
}
if ("audioOpusParamsUseinbandfec" in copyOptions) {
message.audio.opus_params.useinbandfec = copyOptions.audioOpusParamsUseinbandfec;
}
if ("audioOpusParamsUsedtx" in copyOptions) {
message.audio.opus_params.usedtx = copyOptions.audioOpusParamsUsedtx;
}
}
if (copyOptions.video !== undefined) {
message.video = copyOptions.video;
}
const hasVideoProperty = Object.keys(copyOptions).some((key) => {
return 0 <= videoPropertyKeys.indexOf(key);
});
if (message.video && hasVideoProperty) {
message.video = {};
if ("videoCodecType" in copyOptions) {
message.video["codec_type"] = copyOptions.videoCodecType;
}
if ("videoBitRate" in copyOptions) {
message.video["bit_rate"] = copyOptions.videoBitRate;
}
}
if (message.simulcast && !enabledSimulcast() && role !== "recvonly") {
throw new Error("Simulcast can not be used with this browser");
}
if (options.e2ee === true) {
if (message.signaling_notify_metadata === undefined) {
message.signaling_notify_metadata = {};
}
if (message.signaling_notify_metadata === null || typeof message.signaling_notify_metadata !== "object") {
throw new Error("E2EE failed. Options signalingNotifyMetadata must be type 'object'");
}
if (message.video === true) {
message.video = {};
}
if (message.video) {
message.video["codec_type"] = "VP8";
}
message.e2ee = true;
}
if (Array.isArray(options.dataChannels) && 0 < options.dataChannels.length) {
message.data_channels = parseDataChannelConfigurations(options.dataChannels);
}
return message;
}
export function getSignalingNotifyAuthnMetadata(
message: SignalingNotifyConnectionCreated | SignalingNotifyConnectionDestroyed | SignalingNotifyMetadata
): JSONType {
if (message.authn_metadata !== undefined) {
return message.authn_metadata;
} else if (message.metadata !== undefined) {
return message.metadata;
}
return null;
}
export function getSignalingNotifyData(message: SignalingNotifyConnectionCreated): SignalingNotifyMetadata[] {
if (message.data && Array.isArray(message.data)) {
return message.data;
} else if (message.metadata_list && Array.isArray(message.metadata_list)) {
return message.metadata_list;
}
return [];
}
export function getPreKeyBundle(message: JSONType): PreKeyBundle | null {
if (typeof message === "object" && message !== null && "pre_key_bundle" in message) {
return message.pre_key_bundle as PreKeyBundle;
}
return null;
}
export function trace(clientId: string | null, title: string, value: unknown): void {
const dump = (record: unknown) => {
if (record && typeof record === "object") {
let keys = null;
try {
keys = Object.keys(JSON.parse(JSON.stringify(record)));
} catch (_) {
// 何もしない
}
if (keys && Array.isArray(keys)) {
keys.forEach((key) => {
console.group(key);
dump((record as Record<string, unknown>)[key]);
console.groupEnd();
});
} else {
console.info(record);
}
} else {
console.info(record);
}
};
let prefix = "";
if (window.performance) {
prefix = "[" + (window.performance.now() / 1000).toFixed(3) + "]";
}
if (clientId) {
prefix = prefix + "[" + clientId + "]";
}
if (console.info !== undefined && console.group !== undefined) {
console.group(prefix + " " + title);
dump(value);
console.groupEnd();
} else {
console.log(prefix + " " + title + "\n", value);
}
}
export class ConnectError extends Error {
code?: number;
reason?: string;
}
export function createSignalingEvent(eventType: string, data: unknown, transportType: TransportType): SignalingEvent {
const event = new Event(eventType) as SignalingEvent;
// data をコピーする
try {
event.data = JSON.parse(JSON.stringify(data)) as unknown;
} catch (_) {
event.data = data;
}
event.transportType = transportType;
return event;
}
export function createDataChannelData(channel: RTCDataChannel): Record<string, unknown> {
return {
binaryType: channel.binaryType,
bufferedAmount: channel.bufferedAmount,
bufferedAmountLowThreshold: channel.bufferedAmountLowThreshold,
id: channel.id,
label: channel.label,
maxPacketLifeTime: channel.maxPacketLifeTime,
maxRetransmits: channel.maxRetransmits,
negotiated: channel.negotiated,
ordered: channel.ordered,
protocol: channel.protocol,
readyState: channel.readyState,
// @ts-ignore w3c 仕様には存在しない property
reliable: channel.reliable,
};
}
export function createTimelineEvent(
eventType: string,
data: unknown,
logType: TimelineEventLogType,
dataChannelId?: number | null,
dataChannelLabel?: string
): TimelineEvent {
const event = new Event(eventType) as TimelineEvent;
// data をコピーする
try {
event.data = JSON.parse(JSON.stringify(data)) as unknown;
} catch (_) {
event.data = data;
}
event.logType = logType;
event.dataChannelId = dataChannelId;
event.dataChannelLabel = dataChannelLabel;
return event;
}
export function createDataChannelMessageEvent(label: string, data: JSONType): DataChannelMessageEvent {
const event = new Event("message") as DataChannelMessageEvent;
event.label = label;
event.data = data;
return event;
} | the_stack |
import { Component, AfterViewInit, ElementRef, EventEmitter, HostListener,
Input, OnChanges, Output, SimpleChanges, ViewChild, ViewChildren } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { MatIconRegistry } from '@angular/material/icon';
import { MatTabGroup } from '@angular/material/tabs';
import { ChromeMessageService } from './chrome_message.service';
import { SettingsPage } from './settings_page.component';
import { TuneSettingsManagerService } from './tune_settings_manager.service';
import { LOW_THRESHOLD, MEDIUM_THRESHOLD, LOUD_THRESHOLD, BLARING_THRESHOLD,
colorGradient } from '../scores';
import { ChromeMessageEnum, GetCurrentWebsiteResponse } from '../messages';
import { EnabledWebsites, DEFAULT_WEBSITES, WEBSITE_NAME_MAP, WEBSITE_NAMES,
WebsiteSettingName } from '../tune_settings';
import { GoogleAnalyticsService, Page, EventAction,
EventCategory, OutgoingLinkName } from './google_analytics.service';
import * as throttle from 'lodash/throttle';
const THRESHOLD_CHANGE_THROTTLE = 200;
const DIAL_CONTAINER_HEIGHT_PX = 265;
// Note: this click target size covers the full extent of the dial container, so
// the user can click anywhere in the container and the dial rotates to the
// closest point. We could just remove the distance check completely, but
// leaving for now.
const DIAL_CLICK_TARGET_PX = 200;
const DIAL_TAIL_TARGET_PX = 50;
const DIAL_RADIUS_PX = 87.5;
// Must match the width for 'knobDescription' defined in CSS.
const KNOB_DESCRIPTION_WIDTH = 250;
// Must match the width for 'knobSubDescriptionWordChoice' defined in CSS.
const TEXT_CHOICE_WIDTH = 152;
const ARROW_ICON = 'tune-arrow';
const ARROW_ICON_LOCATION = 'ic_arrow.svg';
// How much the dial position/threshold changes on increment/decrement input
// events.
const INPUT_DELTA_AMOUNT = 0.10;
const OPENING_TRANSITION_TIME_MS = 2300;
// The error message returned in chrome.runtime.lastError when a connection
// could not be established when sending a message. One way this can happen is
// if there is no content script with a message handler for the message that was
// requested.
const NO_CONTENT_SCRIPT_ERROR_MESSAGE =
'Could not establish connection. Receiving end does not exist.';
interface Point {
x: number;
y: number;
}
// Array of pairs ordered by increasing threshold. Each pair has icons for when
// Tune is enabled and disabled.
const TUNE_ICONS = [
{enabled: 'ic_tune_quiet.png', disabled: 'ic_tune_quiet_off.png'},
{enabled: 'ic_tune_low.png', disabled: 'ic_tune_low_off.png'},
{enabled: 'ic_tune_medium.png', disabled: 'ic_tune_medium_off.png'},
{enabled: 'ic_tune_loud.png', disabled: 'ic_tune_loud_off.png'},
{enabled: 'ic_tune_blaring.png', disabled: 'ic_tune_blaring_off.png'},
];
const YOUTUBE_ICON_LOCATION = 'ic_youtube.svg';
const TWITTER_ICON_LOCATION = 'ic_twitter.svg';
const FACEBOOK_ICON_LOCATION = 'ic_facebook.svg';
const REDDIT_ICON_LOCATION = 'ic_reddit.svg';
type MouseEventType = 'drag' | 'click';
// A "radial" drag is a drag along the knob radius/perimeter. A "directional"
// drag is an up-down/left-right drag.
type DragType = 'radialDrag' | 'directionalDrag';
function getDegrees(radians: number): number {
return radians * 180 / Math.PI;
}
function getDistance(a: Point, b: Point): number {
return Math.sqrt(Math.pow(b.x - a.x, 2) + Math.pow(b.y - a.y, 2));
}
// Use polar coordinates to find the point on the circle with the given angle.
function getClosestDialPoint(angleRadians: number) {
// Our dial starts at 3pi / 2 radians.
const theta = angleRadians - Math.PI / 2;
return {
x: DIAL_RADIUS_PX * -Math.cos(theta), // Use negative because our dial goes in reverse.
y: DIAL_RADIUS_PX * Math.sin(theta)
};
}
// Using the border between the 3rd and 4th quadrants as 0 degrees, gets the
// clockwise angle of the point.
function getAngleRadians(p: Point): number {
return Math.PI + Math.atan2(p.x, p.y);
}
function getElementCenter(element: Element): Point {
const rect = element.getBoundingClientRect();
return {
x: rect.left + (rect.right - rect.left) / 2,
y: rect.top + (rect.bottom - rect.top) / 2,
};
}
export interface OpenSettingsEvent {
// The tab on the settings page to navigate to.
tab?: SettingsPage;
}
@Component({
selector: 'tune-knob-page',
templateUrl: './knob_page.component.html',
styleUrls: ['./knob_page.component.css']
})
export class KnobPageComponent implements AfterViewInit, OnChanges {
// TODO: This default causes some minor glitching. Because it takes some time
// for the true state to be determined, the popup is always initialized
// assuming that Tune is enabled. If it's actually disabled, then there's a
// small glitch where the popup background is purple and then turns black
// (same issue with the extension icon).
@Input() tuneDisabled = false;
@Input() interactionDisabled = false;
@Input() navigationTabs: MatTabGroup;
@Output() settingsButtonClicked = new EventEmitter<OpenSettingsEvent>();
currentWebsite: WebsiteSettingName|null = null;
enabledWebsites: EnabledWebsites = DEFAULT_WEBSITES;
readonly websiteNameMap = WEBSITE_NAME_MAP;
readonly settingsPage = SettingsPage;
// Value from [0.0, 1.0] corresponding to the current dial position/threshold
// setting.
dialPosition: number;
// Throttled version of setThreshold to avoid excessive updates when dragging
// knob.
updateSettingsThreshold: (threshold: number) => void;
// Whether the settings page is currently visible.
@Input() settingsVisible = false;
knobDragType: DragType;
knobDragStartMousePosition: MouseEvent;
knobDragStartDialPosition: number;
dialCenter: Point;
applyAnimateInAnimationClass = false;
waitingForAnimateIn = false;
iconPath = '';
// Min/max degree positions of the dial tail.
readonly rotMin = 25;
readonly rotMax = 335;
readonly svgMin = 1176;
readonly svgMax = 694;
readonly overallWidth = 340;
readonly knobSubDescriptionOptions = ['quiet', 'low', 'medium', 'loud', 'blaring'];
// Note: this value isn't used by the knob page template; it's used by the
// top-level app component since the entire background should change, not just
// the background of the knob page component.
bgChoice = '';
// Top-level description, which shows "Hide/Show it all" at the dial
// endpoints, and "keep it X" otherwise.
knobDescriptionIndex = 0;
// Index into 'knobSubDescriptionOptions'.
knobSubDescriptionIndex = 0;
svgProgressValue = 200;
@ViewChild('dial') dial: ElementRef;
@ViewChild('tail') dialTail: ElementRef;
@ViewChild('bg') bg: ElementRef;
@ViewChild('dragZone') dragZone: ElementRef;
@ViewChild('circle') circle: ElementRef;
@ViewChild('dialContainer') dialContainer: ElementRef;
// Used for top-level description, including special "Hide it all" and "Show
// it all" options at endpoints of the dial.
@ViewChild('knobDescriptionCarousel') knobDescriptionCarousel: ElementRef;
// When we aren't at the endpoints, we the knob description is "Keep it X".
// This element is used to control which option is displayed.
// TODO: maybe we should translate the sub-carousel along y instead of x?
@ViewChild('knobSubDescriptionCarousel') knobSubDescriptionCarousel: ElementRef;
constructor(private sanitizer: DomSanitizer,
private matIconRegistry: MatIconRegistry,
private tuneSettingsManagerService: TuneSettingsManagerService,
private chromeMessageService: ChromeMessageService,
private googleAnalyticsService: GoogleAnalyticsService) {
this.updateSettingsThreshold = throttle(threshold => {
this.tuneSettingsManagerService.setThreshold(threshold);
}, THRESHOLD_CHANGE_THROTTLE);
// Note: The bypassSecurity function is required to register svg files with
// the icon registry. Alternate options are not currently available. This is
// safe because it is pointing to a static file that is packaged with the
// extension.
matIconRegistry
.addSvgIcon(ARROW_ICON, sanitizer.bypassSecurityTrustResourceUrl(ARROW_ICON_LOCATION))
.addSvgIcon('youtube', sanitizer.bypassSecurityTrustResourceUrl(YOUTUBE_ICON_LOCATION))
.addSvgIcon('twitter', sanitizer.bypassSecurityTrustResourceUrl(TWITTER_ICON_LOCATION))
.addSvgIcon('facebook', sanitizer.bypassSecurityTrustResourceUrl(FACEBOOK_ICON_LOCATION))
.addSvgIcon('reddit', sanitizer.bypassSecurityTrustResourceUrl(REDDIT_ICON_LOCATION));
tuneSettingsManagerService.websites.subscribe((websites: EnabledWebsites) => {
this.enabledWebsites = websites;
});
chromeMessageService.sendMessage({action: ChromeMessageEnum.GET_CURRENT_WEBSITE}).then(
(response: GetCurrentWebsiteResponse) => {
console.log('Current website', response.siteName);
this.currentWebsite = response.siteName;
}).catch((error) => {
this.currentWebsite = null;
// If there is no content script for the webpage, then the response
// will be an error indicating that a connection could not be made.
if (error.message === NO_CONTENT_SCRIPT_ERROR_MESSAGE) {
console.log('Unsupported website');
} else {
console.error('Error fetching current website', error);
}
});
}
ngAfterViewInit() {
this.calculateDialCenter();
this.tuneSettingsManagerService.threshold.subscribe((threshold: number) => {
console.log('initializing threshold:', threshold);
if (this.applyAnimateInAnimationClass) {
this.resetToZero().then(() => {
this.setDialPosition(
threshold, true /* animated */, false /* logEvent*/);
});
} else {
// Wrap this in a Promise.resolve because any changes to state made here
// that are referenced in data binding (several state variables are
// updated when changing the dial position) can result in an
// ExpressionChangedAfterItHasBeenCheckedError. For some reason this
// error only seems to be happening in tests, possibly due to something
// lifecycle-related that's specific to the test enviroment? Wrapping it
// in a Promise.resolve forces the next change detection cycle and
// prevents this error.
// TODO: Find out if there is a way to fix the bug in the tests without
// this workaround.
Promise.resolve().then(() => {
this.setDialPosition(
threshold, false /* animated */, false /* logEvent*/);
});
}
});
}
ngOnChanges(changes: SimpleChanges) {
if (changes['tuneDisabled'] !== undefined) {
// Update icon for different disable/enabled state.
this.setIcon();
}
}
resetToZero(): Promise<void> {
this.dial.nativeElement.style.transition = 'none';
this.circle.nativeElement.style.transition = 'none';
// Turn off transitions for the carousel when setting to zero. For some
// reason this doesn't work when using a flag and ngClass to update the CSS
// class, probably because the transform is applied before change detection
// gets called and updates the template.
// TODO: We should rethink the way that we handle animations/transitions in
// this component, because right now it's a mixture of manually setting
// things and using CSS properties, and it's out of sync with the typical
// Angular change detection cycle. We should look into Angular animations as
// an alternative.
const knobDescriptionCarouselTransition =
window.getComputedStyle(this.knobDescriptionCarousel.nativeElement).transition;
const knobSubDescriptionCarouselTransition =
window.getComputedStyle(this.knobDescriptionCarousel.nativeElement).transition;
this.knobDescriptionCarousel.nativeElement.style.transition = 'none';
this.knobSubDescriptionCarousel.nativeElement.style.transition = 'none';
this.setDialPosition(0, false /* animated */, false /* logEvent */);
return new Promise((resolve, reject) => {
// Without this setTimeout, the knob will immediately jump to the
// threshold instead of animating from zero.
// TODO: Investigate this further, and simplify this if possible.
setTimeout(() => {
// Reset the transition values of the carousel from before we reset to zero.
this.knobDescriptionCarousel.nativeElement.style.transition =
knobDescriptionCarouselTransition;
this.knobSubDescriptionCarousel.nativeElement.style.transition =
knobSubDescriptionCarouselTransition;
resolve();
}, 100);
});
}
// Updates the state before animating in, which allows us to hide UI elements.
// This is necessary to avoid a "flicker" in the animation that is caused by a
// race between change detection in the parent component that makes this
// component visible, and the call to animateInt(), which applies the styling
// that hides everything.
setPreAnimationState() {
this.waitingForAnimateIn = true;
}
animateIn(): void {
this.applyAnimateInAnimationClass = true;
this.waitingForAnimateIn = false;
setTimeout(() => {
this.applyAnimateInAnimationClass = false;
}, OPENING_TRANSITION_TIME_MS);
}
calculateDialCenter() {
this.dialCenter = getElementCenter(this.dial.nativeElement);
}
handleDialMouseEvent(event: MouseEvent, eventType: MouseEventType): void {
const dialRelativePoint = {x: event.x - this.dialCenter.x,
y: this.dialCenter.y - event.y};
const angleRadians = getAngleRadians(dialRelativePoint);
let animated: boolean;
// For clicks, we only adjust the dial position if the click is close enough
// to the dial perimeter. We don't do this check for drags to avoid sudden
// interruptions in the middle of a drag.
switch (eventType) {
case 'click':
const closestCirclePoint = getClosestDialPoint(angleRadians);
const distanceFromDialEdge = getDistance(closestCirclePoint, dialRelativePoint);
if (distanceFromDialEdge > DIAL_CLICK_TARGET_PX) {
return;
}
animated = true;
break;
case 'drag':
animated = false;
break;
default:
throw new Error('BUG: unhandled eventType: ' + eventType);
}
const threshold =
this.getThresholdFromKnobRotationDegrees(getDegrees(angleRadians));
const logEvent = eventType === 'click';
this.setDialPosition(threshold, animated, logEvent);
}
onDialClick(event: MouseEvent): void {
if (this.shouldIgnoreKnobInteractionEvents()) {
return;
}
console.log('handling dial click');
this.handleDialMouseEvent(event, 'click');
}
closeToDialTail(event: MouseEvent): boolean {
const tailCenter = getElementCenter(this.dialTail.nativeElement);
return getDistance(tailCenter, event) < DIAL_TAIL_TARGET_PX;
}
shouldUseDisabledUIStyle(): boolean {
return this.tuneDisabled
|| !this.enabledWebsites[this.currentWebsite];
}
shouldIgnoreKnobInteractionEvents(): boolean {
return this.interactionDisabled
|| this.settingsVisible
|| this.currentWebsite === null
|| !this.enabledWebsites[this.currentWebsite];
}
onKnobDragStart(event: MouseEvent): void {
if (this.shouldIgnoreKnobInteractionEvents()) {
return;
}
this.knobDragType = this.closeToDialTail(event) ? 'radialDrag' : 'directionalDrag';
console.log('handling drag:', this.knobDragType);
this.knobDragStartMousePosition = event;
this.knobDragStartDialPosition = this.dialPosition;
}
onKnobDragEnd(event: MouseEvent): void {
this.googleAnalyticsService.emitEvent(
EventCategory.DIAL,
EventAction.DIAL_MOVE,
null /* eventLabel */,
this.dialPosition);
}
// Handles left-right and up-down mouse dragging.
handleDirectionalDrag(event: MouseEvent): void {
const dragDeltaX = event.x - this.knobDragStartMousePosition.x;
// Flip delta Y because dragging up should increase the dial value (and vice
// versa).
const dragDeltaY = (event.y - this.knobDragStartMousePosition.y) * -1;
const maxDelta = (Math.abs(dragDeltaX) > Math.abs(dragDeltaY)) ? dragDeltaX : dragDeltaY;
// This controls how much the dial moves for a given drag distance. If 1,
// the user needs to drag the entire window length to traverse the entire
// dial range. 2 means teh user only needs to drag half the window length to
// change from 0->1 or vice versa.
const changeMultiplier = 2;
const positionChange = maxDelta / this.overallWidth * changeMultiplier;
this.setDialPosition(
this.knobDragStartDialPosition + positionChange,
false /* animated */,
false /* logEvent */
);
}
onKnobDrag(event: MouseEvent): void {
if (this.shouldIgnoreKnobInteractionEvents()) {
return;
}
// We get this on the final drag event with x and y = 0, oddly.
if (event.x === 0 && event.y === 0) {
return;
}
switch (this.knobDragType) {
case 'radialDrag':
this.handleDialMouseEvent(event, 'drag');
break;
case 'directionalDrag':
this.handleDirectionalDrag(event);
break;
default:
throw new Error('BUG: unhandled drag type: ' + this.knobDragType);
}
}
@HostListener('window:keydown', ['$event'])
onKey(event: KeyboardEvent): void {
if (this.shouldIgnoreKnobInteractionEvents()) {
return;
}
// If a tab has focus, the arrow keys are reserved for keyboard navigation
// for accessibility purposes, so we don't move the dial.
if (this.navTabsHaveFocus()) {
return;
}
console.log('handling keydown:', event);
switch (event.code) {
case 'ArrowLeft':
case 'ArrowDown':
this.decrementDialPosition();
break;
case 'ArrowRight':
case 'ArrowUp':
this.incrementDialPosition();
break;
default:
break;
}
}
@HostListener('window:wheel', ['$event'])
onScroll(event: WheelEvent): void {
if (this.shouldIgnoreKnobInteractionEvents()) {
return;
}
console.log('handling scroll:', event);
const [left, right] = [event.deltaX < 0, event.deltaX > 0];
const [down, up] = [event.deltaY > 0, event.deltaY < 0];
// If anyone happens to have a fancy mouse with z-axis scrolling, this will
// also work for them :-).
const [in_, out] = [event.deltaZ < 0, event.deltaZ > 0];
if (left || down || in_) {
this.decrementDialPosition();
} else if (right || up || out) {
this.incrementDialPosition();
}
}
// TODO: Not animating makes these a little abrupt, but animating makes them
// feel too sluggish. Maybe have adjustable animation speed?
decrementDialPosition(): void {
this.setDialPosition(
this.dialPosition - INPUT_DELTA_AMOUNT,
false /* animated */,
true /* logEvent */);
}
incrementDialPosition(): void {
this.setDialPosition(
this.dialPosition + INPUT_DELTA_AMOUNT,
false /* animated */,
true /* logEvent */);
}
setDialPosition(value: number, animated: boolean, logEvent: boolean): void {
value = Math.min(Math.max(value, 0.0), 1.0);
if (logEvent) {
this.googleAnalyticsService.emitEvent(
EventCategory.DIAL,
EventAction.DIAL_MOVE,
null /* eventLabel */,
value);
}
this.updateSettingsThreshold(value);
this.dialPosition = value;
if (animated) {
this.turnOnTransitions();
}
this.setTextDescription(value);
this.setKnobRotation(value);
this.setProgressSVG(value);
this.setBackgroundColor(value);
this.setIcon();
}
setIcon() {
if (this.dialPosition === undefined || this.tuneDisabled === undefined) {
// This can happen due to setIcon being called after tuneDisabled changes
// but before the dial position is initialized.
return;
}
const iconIndex = Math.min(Math.floor(this.dialPosition * TUNE_ICONS.length),
TUNE_ICONS.length - 1);
const iconPair = TUNE_ICONS[iconIndex];
const iconPath = this.tuneDisabled ? iconPair.disabled : iconPair.enabled;
if (iconPath !== this.iconPath) {
chrome.browserAction.setIcon({path: iconPath});
this.iconPath = iconPath;
}
}
// Note: we don't always use these long transitions because when dragging,
// scrolling, or using arrow keys, the long transition makes the UI feel like
// it's lagging (e.g., the dial posiiton trails behind the user's mouse
// pointer).
//
// This causes issues with the background color transition. The background
// color change happens via the top-level app.component template, and we can't
// easily change the transition style from this contained component.
// Currently, we hack around this by always using a compromise 0.5s transition
// value.
turnOnTransitions(): void {
this.dial.nativeElement.style.transition = 'transform 1s ease-in-out';
this.circle.nativeElement.style.transition = 'all 1s ease-in-out';
}
transitionEnd(e: Event): void {
this.dial.nativeElement.style.transition = 'transform .2s linear';
this.circle.nativeElement.style.transition = 'all .2s linear';
}
setTextDescription(threshold: number): void {
// The text description elements are already laid out on the page. Changing
// the visible description involves calculating the translation needed to
// make the correct element visible through the "window" masks.
// Set the position of the top-level carousel.
if (threshold === 0.0) {
this.knobDescriptionIndex = 0; // hide it all
} else if (threshold === 1.0) {
this.knobDescriptionIndex = 2; // show it all
} else {
this.knobDescriptionIndex = 1; // keep it X
}
this.knobDescriptionCarousel.nativeElement.style.transform = 'translate('
+ String(this.knobDescriptionIndex * -1 * KNOB_DESCRIPTION_WIDTH) + 'px, 0)';
// Set the position of the secondary carousel for the "keep it" choice.
if (threshold >= BLARING_THRESHOLD) {
this.knobSubDescriptionIndex = 4;
} else if (threshold >= LOUD_THRESHOLD) {
this.knobSubDescriptionIndex = 3;
} else if (threshold >= MEDIUM_THRESHOLD) {
this.knobSubDescriptionIndex = 2;
} else if (threshold >= LOW_THRESHOLD) {
this.knobSubDescriptionIndex = 1;
} else {
this.knobSubDescriptionIndex = 0;
}
this.knobSubDescriptionCarousel.nativeElement.style.transform = 'translate('
+ String(this.knobSubDescriptionIndex * -1 * TEXT_CHOICE_WIDTH) + 'px, 0)';
}
setKnobRotation(threshold: number): void {
this.dial.nativeElement.style.transform =
'rotate(' + this.getRotationDegreesFromThreshold(threshold) + 'deg)';
}
getRotationDegreesFromThreshold(threshold: number): number {
return threshold * (this.rotMax - this.rotMin) + this.rotMin;
}
getThresholdFromKnobRotationDegrees(rotationDeg: number): number {
return (rotationDeg - this.rotMin) / (this.rotMax - this.rotMin);
}
setProgressSVG(threshold: number): void {
this.svgProgressValue = threshold * (this.svgMax - this.svgMin) + this.svgMin;
}
setBackgroundColor(threshold: number): void {
this.bgChoice = colorGradient(threshold);
}
openSettings(tab?: SettingsPage): void {
const openSettingsEvent: OpenSettingsEvent = {};
if (tab) {
openSettingsEvent.tab = tab;
}
this.settingsButtonClicked.emit(openSettingsEvent);
}
openDisabledPageLink(url: OutgoingLinkName) {
chrome.tabs.create({url: url, active: false});
this.googleAnalyticsService.emitEvent(
EventCategory.DISABLED_PAGE_OUTGOING_LINK, EventAction.CLICK, url);
}
round(value: number): number {
return Math.round(value);
}
getKnobA11yAnnouncement(): string {
let message = 'Dial position: ' + this.round(this.dialPosition * 100) + ' percent.';
switch (this.knobDescriptionIndex) {
case 0:
message += 'Hide it all';
break;
case 1:
message += 'Keep it ' + this.knobSubDescriptionOptions[this.knobSubDescriptionIndex];
break;
case 2:
message += 'Show it all';
break;
default:
break;
}
return message;
}
/** Queries the MatTabGroup to see if any of the tabs have focus. */
navTabsHaveFocus(): boolean {
// Technically the more *correct* thing to do here would be to pass the
// ElementRef directly from the parent rather than access the _elementRef
// property, but that would require adding a duplicate ViewChild on the
// parent, which seemed unnecessary.
//
// This overall solution is a hack, since calling querySelector is outside
// the Angular pattern. We should look into alternative solutions.
return this.navigationTabs._elementRef.nativeElement.querySelector(
'.mat-tab-label.cdk-keyboard-focused') !== null;
}
onHideAllClicked() {
this.googleAnalyticsService.emitEvent(
EventCategory.HIDE_ALL, EventAction.CLICK);
}
onShowAllClicked() {
this.googleAnalyticsService.emitEvent(
EventCategory.SHOW_ALL, EventAction.CLICK);
}
onSettingsButtonClicked() {
this.googleAnalyticsService.emitEvent(
EventCategory.SETTINGS_BUTTON, EventAction.CLICK);
}
} | the_stack |
import * as arraybuffers from '../lib/arraybuffers/arraybuffers';
import * as bridge from '../lib/bridge/bridge';
import * as consent from './consent';
import * as crypto from './crypto';
import * as globals from './globals';
import * as key_verify from './key-verify';
import * as _ from 'lodash';
import * as logging from '../lib/logging/logging';
import * as net from '../lib/net/net.types';
import Persistent from '../interfaces/persistent';
import * as remote_connection from './remote-connection';
import * as remote_user from './remote-user';
import * as signals from '../lib/webrtc/signals';
import * as social from '../interfaces/social';
import * as ui_connector from './ui_connector';
import * as user_interface from '../interfaces/ui';
import * as uproxy_core_api from '../interfaces/uproxy_core_api';
import storage = globals.storage;
import ui = ui_connector.connector;
// Keep track of the current remote instance who is acting as a proxy server
// for us.
// module Core {
var log :logging.Log = new logging.Log('remote-instance');
const VERIFY_TIMEOUT = 120000;
/**
* RemoteInstance - represents a remote uProxy installation.
*
* These remote instances are semi-permanent, and belong only to one user.
* They can be online or offline depending on if they are associated with a
* client. Interface-wise, this class is only aware of its parent User, and
* does not have any direct interaction with the network it belongs to.
*
* There are two pathways to modifying the consent of this remote instance.
* - Locally, via a user command from the UI.
* - Remotely, via consent bits sent over the wire by a friend.
*/
export class RemoteInstance implements Persistent {
public publicKey :string;
public keyVerified :boolean = false;
public description :string;
// Client version of the remote peer.
public messageVersion :number;
// Current proxy access activity of the remote instance with respect to the
// local instance of uProxy.
public wireConsentFromRemote :social.ConsentWireState = {
isRequesting: false,
isOffering: false
};
// Used to prevent saving state while we have not yet loaded the state
// from storage.
private fulfillStorageLoad_ : () => void;
// Any key-verify session state.
// - In-progress protocol session.
private keyVerifySession_ :key_verify.KeyVerify = null;
// - The Short Authentication String (SAS) if we're in the middle of
// verification.
private verifySAS_ :string = null;
// - The Verification-State-machine state. See the type for
// details -- mostly used for the UI.
private verifyState_ = social.VerifyState.VERIFY_NONE;
// - Promise resolution callback for user SAS verification.
private resolvedVerifySAS_ :(v:boolean) => void = null;
public onceLoaded : Promise<void> = new Promise<void>((F, R) => {
this.fulfillStorageLoad_ = F;
});
// Whether or not there is a UI update (triggered by this.user.notifyUI())
// scheduled to run in the next second.
// Used by SocksToRtc & RtcToNet Handlers to make sure bytes sent and
// received are only forwarded to the UI once every second.
private isUIUpdatePending = false;
private connection_ :remote_connection.RemoteConnection = null;
// Permission token that we have received from this instance, but have not
// yet sent back to the remote user (e.g. because they were offline when
// we accepted their invite).
public unusedPermissionToken :string;
/**
* Construct a Remote Instance as the result of receiving an instance
* handshake, or loadig from storage. Typically, instances are initialized
* with the lowest consent values.
* Users of RemoteInstance should call the static .create method
* rather than directly calling this, in order to get a RemoteInstance
* that has been loaded from storage.
*/
constructor(
// The User which this instance belongs to.
public user :remote_user.User,
public instanceId :string) {
this.connection_ = remote_connection.getOrCreateRemoteConnection(
this.handleConnectionUpdate_, this.instanceId, this.user.userId,
globals.portControl);
storage.load<RemoteInstanceState>(this.getStorePath())
.then((state:RemoteInstanceState) => {
this.restoreState(state);
this.fulfillStorageLoad_();
}).catch((e:Error) => {
// Instance not found in storage - we should fulfill the create
// promise anyway as this is not an error.
log.info('No stored state for instance', instanceId);
this.fulfillStorageLoad_();
});
}
public handleKeyVerifyMessage = (msg:any) => {
if (this.keyVerifySession_ !== null) {
log.debug('handleKeyVerifyMessage(%1): going to existing session',
msg);
this.keyVerifySession_.readMessage(msg);
} else {
log.debug('handleKeyVerifyMessage(%1): creating new session.', msg);
// Create a key verify session and give it this message.
this.verifyUser(msg);
}
};
private handleConnectionUpdate_ = (update :uproxy_core_api.Update,
data?:any) => {
log.debug('connection update: %1', uproxy_core_api.Update[update]);
switch (update) {
case uproxy_core_api.Update.SIGNALLING_MESSAGE:
var clientId = this.user.instanceToClient(this.instanceId);
if (!clientId) {
log.error('Could not find clientId for instance', this.instanceId);
return;
}
if (typeof this.publicKey !== 'undefined' &&
typeof globals.publicKey !== 'undefined' &&
// No need to encrypt again for networks like Quiver
!this.user.network.isEncrypted() &&
// Disable crypto for ios
globals.settings.crypto) {
crypto.signEncrypt(JSON.stringify(data.data), this.publicKey)
.then((cipherText :string) => {
data.data = cipherText;
this.user.network.send(this.user, clientId, data);
});
} else {
this.user.network.send(this.user, clientId, data);
}
break;
case uproxy_core_api.Update.STOP_GIVING:
ui.update(uproxy_core_api.Update.STOP_GIVING_TO_FRIEND, this.instanceId);
break;
case uproxy_core_api.Update.START_GIVING:
ui.update(uproxy_core_api.Update.START_GIVING_TO_FRIEND, this.instanceId);
break;
case uproxy_core_api.Update.STATE:
this.user.notifyUI();
break;
case uproxy_core_api.Update.REPROXY_ERROR:
case uproxy_core_api.Update.REPROXY_WORKING:
ui.update(update, data);
break;
default:
log.warn('Received unexpected update from remote connection', {
update: update,
data: data
});
}
}
/**
* Obtain the prefix for all storage keys associated with this Instance.
* Since the parent User's userId may change, only store the userId.
*/
public getStorePath = () => {
return this.user.getLocalInstanceId() + '/' + this.instanceId;
}
public isSharing = () => {
return this.connection_.localSharingWithRemote ===
social.SharingState.SHARING_ACCESS;
}
/**
* Handle signals sent along the signalling channel from the remote
* instance, and pass it along to the relevant socks-rtc module.
* TODO: spec
* TODO: assuming that signal is valid, should we remove signal?
* TODO: return a boolean on success/failure
*/
public handleSignal = (msg :social.VersionedPeerMessage) :Promise<void> => {
if (typeof this.publicKey !== 'undefined' &&
typeof globals.publicKey !== 'undefined' &&
// signal data is not encrypted for Quiver, because entire message
// is encrypted over the network and already decrypted by this point
!this.user.network.isEncrypted() &&
// Disable crypto for ios
globals.settings.crypto) {
return crypto.verifyDecrypt(<string>msg.data, this.publicKey)
.then((plainText :string) => {
return this.handleDecryptedSignal_(
msg.type, msg.version, JSON.parse(plainText));
}).catch((e) => {
log.error('Error decrypting message ', e);
});
} else {
return this.handleDecryptedSignal_(msg.type, msg.version, msg.data);
}
}
private handleDecryptedSignal_ = (
type:social.PeerMessageType,
messageVersion:number,
signalFromRemote:bridge.SignallingMessage) : Promise<void> => {
log.debug('handleDecryptedSignal_(%1, %2, %3)', type, messageVersion,
signalFromRemote);
if (social.PeerMessageType.SIGNAL_FROM_CLIENT_PEER === type) {
// If the remote peer sent signal as the client, we act as server.
if (!this.user.consent.localGrantsAccessToRemote) {
log.warn('Remote side attempted access without permission');
return Promise.resolve();
}
// Create a new RtcToNet instance each time a new round of client peer
// messages begins. The type field check is so pre-bridge,
// MESSAGE_VERSION = 1, clients can initiate.
// TODO: have RemoteConnection do this, based on SignallingMetadata
if (signalFromRemote.first ||
((<signals.Message>signalFromRemote).type === signals.Type.OFFER)) {
this.connection_.resetSharerCreated();
this.startShare_();
}
// Wait for the new rtcToNet instance to be created before you handle
// additional messages from a client peer.
return this.connection_.onceSharerCreated.then(() => {
this.connection_.handleSignal({
type: type,
data: signalFromRemote
});
});
/*
TODO: Uncomment when getter sends a cancel signal if socksToRtc closes while
trying to connect. Something like:
https://github.com/uProxy/uproxy-lib/tree/lucyhe-emitcancelsignal
Issue: https://github.com/uProxy/uproxy/issues/1256
else if (signalFromRemote['type'] == signals.Type.CANCEL_OFFER) {
this.stopShare();
return;
}
*/
}
this.connection_.handleSignal({
type: type,
data: signalFromRemote
});
return Promise.resolve();
}
public verifyUser = (firstMsg ?:any) : void => {
log.debug('verifyUser(%1)', firstMsg);
// The only time you'd want to do a second key verification is
// if an attacker is trying to kill an existing trust
// relationship.
if (this.verifyState_ === social.VerifyState.VERIFY_COMPLETE) {
log.debug('verifyUser(%1): ALREADY VERIFIED.', firstMsg);
return;
}
let inst = this;
let clientId = this.user.instanceToClient(this.instanceId);
let delegate :key_verify.Delegate = {
sendMessage : (msg:any) :Promise<void> => {
let verifyMessage :social.PeerMessage = {
type: social.PeerMessageType.KEY_VERIFY_MESSAGE,
data: msg
};
return inst.user.network.send(inst.user, clientId, verifyMessage);
},
showSAS : (sas:string) :Promise<boolean> => {
log.debug('verifyUser: Got SAS ' + sas);
if (sas) {
inst.verifySAS_ = sas;
}
let result = new Promise<boolean>((resolve:any) => {
// Send UPDATE message with SAS.
this.resolvedVerifySAS_ = resolve;
// The UI's now showing the SAS with a YES/NO prompt. The
// user will hit one of those buttons and we'll send a
// command back that'll cause a resolution of the Promise
// from start() below.
inst.user.notifyUI();
});
return result;
}
};
if (firstMsg !== undefined) {
this.keyVerifySession_ = key_verify.RespondToVerify(
this.publicKey, delegate, firstMsg);
if (this.keyVerifySession_ === null) {
// Immediately fail - bad initial message from peer.
log.error('verifyUser: peer-initiated session had bad message: ',
firstMsg);
return;
}
} else {
this.keyVerifySession_ = key_verify.InitiateVerify(this.publicKey,
delegate);
}
this.verifyState_ = social.VerifyState.VERIFY_BEGIN;
this.user.notifyUI();
this.keyVerifySession_.start(VERIFY_TIMEOUT).then(() => {
log.debug('verifyUser: succeeded.');
inst.keyVerified = true;
inst.keyVerifySession_ = null
inst.verifySAS_ = null;
inst.verifyState_ = social.VerifyState.VERIFY_COMPLETE;
inst.user.notifyUI();
}, () => {
log.debug('verifyUser: failed.');
inst.keyVerified = false;
inst.verifyState_ = social.VerifyState.VERIFY_FAILED;
inst.keyVerifySession_ = null
inst.verifySAS_ = null;
inst.user.notifyUI();
});
};
public finishVerifyUser = (result :boolean) => {
console.log('finishVerifyuser: ', result, ' promise resolution is ',
this.resolvedVerifySAS_);
if (this.resolvedVerifySAS_ !== null) {
this.resolvedVerifySAS_(result);
} else {
log.error('Getting a completed verification result when no session ' +
'is open.');
}
}
/**
* When our peer sends us a signal that they'd like to be a client,
* we should try to start sharing.
*/
private startShare_ = () : void => {
var sharingStopped :Promise<void>;
log.debug('startShare_');
if (this.connection_.localSharingWithRemote === social.SharingState.NONE) {
// Stop any existing sharing attempts with this instance.
sharingStopped = Promise.resolve();
} else {
// Implies that the SharingState is TRYING_TO_SHARE_ACCESS because
// the client peer should never be able to try to get if they are
// already getting (and this sharer is already sharing).
sharingStopped = this.stopShare();
}
// Start sharing only after an existing connection is stopped.
sharingStopped.then(() => {
log.debug('sharingStopped.then()');
this.connection_.startShare(this.messageVersion).then(() => {
log.debug('this.connection_.startShare().then()');
}, () => {
log.warn('Could not start sharing.');
// Tell the UI that sharing failed. It will show a toast.
// TODO: Send this update from remote-connection.ts
// https://github.com/uProxy/uproxy/issues/1861
ui.update(uproxy_core_api.Update.FAILED_TO_GIVE, {
name: this.user.name,
proxyingId: this.connection_.getProxyingId()
});
});
});
}
public stopShare = () :Promise<void> => {
log.debug('stopShare()');
if (this.connection_.localSharingWithRemote === social.SharingState.NONE) {
log.warn('Cannot stop sharing while currently not sharing.');
return Promise.resolve();
}
return this.connection_.stopShare();
}
/**
* Begin to use this remote instance as a proxy server, if permission is
* currently granted.
*/
public start = () :Promise<net.Endpoint> => {
log.debug('start()');
if (!this.wireConsentFromRemote.isOffering) {
log.warn('Lacking permission to proxy');
return Promise.reject(Error('Lacking permission to proxy'));
}
return this.connection_.startGet(this.messageVersion);
}
/**
* Stop using this remote instance as a proxy server.
*/
public stop = () :Promise<void> => {
log.debug('stop()');
return this.connection_.stopGet();
}
/**
* Update the information about this remote instance as a result of its
* Instance Message.
* Assumes that |data| actually belongs to this instance.
*/
public update = (data:social.InstanceHandshake,
messageVersion:number) :Promise<void> => {
log.debug('update(%1, %2)', data, messageVersion);
return this.onceLoaded.then(() => {
log.debug('update(%1, %2).onceLoaded.then()', data, messageVersion);
if (data.publicKey &&
(typeof this.publicKey === 'undefined' || !this.keyVerified)) {
this.publicKey = data.publicKey;
}
this.description = data.description;
this.updateConsentFromWire_(data.consent);
this.messageVersion = messageVersion;
this.saveToStorage();
});
}
private updateConsentFromWire_ = (bits :social.ConsentWireState) => {
log.debug('updateConsentFromWire_(%1)', bits);
var userConsent = this.user.consent;
if (!bits.isOffering &&
this.connection_.localGettingFromRemote === social.GettingState.TRYING_TO_GET_ACCESS) {
this.connection_.stopGet();
}
// Update this remoteInstance.
this.wireConsentFromRemote = bits;
this.user.updateRemoteRequestsAccessFromLocal();
}
public saveToStorage = () => {
log.debug('saveToStorage()');
return this.onceLoaded.then(() => {
log.debug('saveToStorage() this.onceLoaded.then()');
var state = this.currentState();
return storage.save(this.getStorePath(), state)
.then(() => {
log.debug('Saved instance to storage', this.instanceId);
}).catch((e) => {
log.error('Failed saving instance to storage', this.instanceId, e.stack);
});
});
}
/**
* Get the raw attributes of the instance to be sent over to the UI or saved
* to storage.
*/
public currentState = () :RemoteInstanceState => {
return _.cloneDeep({
wireConsentFromRemote: this.wireConsentFromRemote,
description: this.description,
publicKey: this.publicKey,
keyVerified: this.keyVerified,
unusedPermissionToken: this.unusedPermissionToken
});
}
/**
* Restore state from storage
* if remote instance state was set, only overwrite fields
* that correspond to local user action.
*/
public restoreState = (state :RemoteInstanceState) => {
this.description = state.description;
if (typeof state.publicKey !== 'undefined') {
this.publicKey = state.publicKey;
}
if (typeof state.keyVerified !== 'undefined') {
this.keyVerified = state.keyVerified;
if (state.keyVerified) {
// There's an open question here on how to handle
// verification failures - do we remember them as explicit
// failures, or do we just treat them as not having
// succeeded? So far, treat as the latter.
this.verifyState_ = social.VerifyState.VERIFY_COMPLETE;
}
}
if (state.wireConsentFromRemote) {
this.wireConsentFromRemote = state.wireConsentFromRemote
} else {
log.error('Failed to load wireConsentFromRemote for instance ' +
this.instanceId);
}
if (typeof state.unusedPermissionToken !== 'undefined') {
this.unusedPermissionToken = state.unusedPermissionToken;
}
}
/**
* Returns a snapshot of a RemoteInstance's state for the UI. This includes
* fields like isCurrentProxyClient that we don't want to save to storage.
*/
// TODO: bad smell: remote-instance should not need to know the structure of
// UI message data. Maybe rename to |getInstanceData|?
public currentStateForUi = () :social.InstanceData => {
var connectionState = this.connection_.getCurrentState();
return {
instanceId: this.instanceId,
description: this.description,
isOnline: this.user.isInstanceOnline(this.instanceId),
verifyState: this.verifyState_,
verifySAS: this.verifySAS_,
localGettingFromRemote: connectionState.localGettingFromRemote,
localSharingWithRemote: connectionState.localSharingWithRemote,
bytesSent: connectionState.bytesSent,
bytesReceived: connectionState.bytesReceived,
activeEndpoint: connectionState.activeEndpoint,
proxyingId: connectionState.proxyingId,
};
}
public handleLogout = () => {
log.debug('handleLogout()');
if (this.connection_.localSharingWithRemote !== social.SharingState.NONE) {
log.info('Closing rtcToNet_ for logout');
this.connection_.stopShare();
}
if (this.connection_.localGettingFromRemote !== social.GettingState.NONE) {
log.info('Stopping socksToRtc_ for logout');
this.connection_.stopGet();
}
}
} // class remote_instance.RemoteInstance
export interface RemoteInstanceState {
wireConsentFromRemote :social.ConsentWireState;
description :string;
publicKey :string;
keyVerified :boolean;
unusedPermissionToken :string;
}
// TODO: Implement obfuscation.
export enum ObfuscationType {NONE, RANDOM1 }
// } // module Core | the_stack |
// Credit: A majority of this code was taken from the Visual Studio Code Arduino extension with some modifications to suit our purposes.
import * as vscode from "vscode";
import CONSTANTS, { DialogResponses, STATUS_BAR_PRIORITY } from "./constants";
import { DeviceContext } from "./deviceContext";
import { outChannel } from "./extension";
import { logToOutputChannel } from "./extension_utils/utils";
import { SerialPortControl } from "./serialPortControl";
export interface ISerialPortDetail {
path: string;
manufacturer: string;
vendorId: string;
productId: string;
}
export class SerialMonitor implements vscode.Disposable {
public static DEFAULT_BAUD_RATE: number = 115200;
public static listBaudRates(): number[] {
return [
300,
1200,
2400,
4800,
9600,
19200,
38400,
57600,
74880,
115200,
230400,
250000,
];
}
public static getInstance(): SerialMonitor {
if (SerialMonitor._serialMonitor === null) {
SerialMonitor._serialMonitor = new SerialMonitor();
}
return SerialMonitor._serialMonitor;
}
private static _serialMonitor: SerialMonitor | null = null;
private _currentPort!: string;
private _currentBaudRate!: number;
private _outputChannel!: vscode.OutputChannel;
private _serialPortControl: SerialPortControl | null = null;
private _baudRateStatusBar!: vscode.StatusBarItem;
private _openPortStatusBar!: vscode.StatusBarItem;
private _portsStatusBar!: vscode.StatusBarItem;
private constructor() {
const deviceContext = DeviceContext.getInstance();
deviceContext.onDidChange(() => {
if (deviceContext.port) {
if (!this.initialized) {
this.initialize();
}
this.updatePortListStatus(null);
}
});
}
public initialize() {
const defaultBaudRate: number = SerialMonitor.DEFAULT_BAUD_RATE;
this._outputChannel = vscode.window.createOutputChannel(
CONSTANTS.MISC.SERIAL_MONITOR_NAME
);
this._currentBaudRate = defaultBaudRate;
this._portsStatusBar = vscode.window.createStatusBarItem(
vscode.StatusBarAlignment.Right,
STATUS_BAR_PRIORITY.PORT
);
this._portsStatusBar.command =
"deviceSimulatorExpress.common.selectSerialPort";
this._portsStatusBar.tooltip = "Select Serial Port";
this._portsStatusBar.show();
this._openPortStatusBar = vscode.window.createStatusBarItem(
vscode.StatusBarAlignment.Right,
STATUS_BAR_PRIORITY.OPEN_PORT
);
this._openPortStatusBar.command =
"deviceSimulatorExpress.common.openSerialMonitor";
this._openPortStatusBar.text = `$(plug)`;
this._openPortStatusBar.tooltip = "Open Serial Monitor";
this._openPortStatusBar.show();
this._baudRateStatusBar = vscode.window.createStatusBarItem(
vscode.StatusBarAlignment.Right,
STATUS_BAR_PRIORITY.BAUD_RATE
);
this._baudRateStatusBar.command =
"deviceSimulatorExpress.common.changeBaudRate";
this._baudRateStatusBar.tooltip = "Baud Rate";
this._baudRateStatusBar.text = defaultBaudRate.toString();
this.updatePortListStatus(null);
}
public async selectSerialPort(vid: string | null, pid: string | null) {
const lists = await SerialPortControl.list();
if (!lists.length) {
vscode.window.showInformationMessage(
"No serial message is available."
);
return;
}
if (vid && pid) {
const valueOfVid = parseInt(vid, 16);
const valueOfPid = parseInt(pid, 16);
const foundPort = lists.find(port => {
if (port.productId && port.vendorId) {
return (
parseInt(port.productId, 16) === valueOfPid &&
parseInt(port.vendorId, 16) === valueOfVid
);
}
return false;
});
if (
foundPort &&
!(this._serialPortControl && this._serialPortControl.isActive)
) {
this.updatePortListStatus(foundPort.path);
}
} else {
const chosen = await vscode.window.showQuickPick(
lists
.map(
(port: ISerialPortDetail): vscode.QuickPickItem => {
return {
description: port.manufacturer,
label: port.path,
};
}
)
.sort((a, b): number => {
return a.label === b.label
? 0
: a.label > b.label
? 1
: -1;
}) as vscode.QuickPickItem[],
{ placeHolder: CONSTANTS.MISC.SELECT_PORT_PLACEHOLDER }
);
if (chosen && chosen.label) {
this.updatePortListStatus(chosen.label);
}
}
}
public async openSerialMonitor() {
if (!this._currentPort) {
const ans = await vscode.window.showInformationMessage(
CONSTANTS.WARNING.NO_SERIAL_PORT_SELECTED,
DialogResponses.SELECT,
DialogResponses.CANCEL
);
if (ans === DialogResponses.SELECT) {
await this.selectSerialPort(null, null);
}
if (!this._currentPort) {
return;
}
}
if (this._serialPortControl) {
if (this._currentPort !== this._serialPortControl.currentPort) {
await this._serialPortControl.changePort(this._currentPort);
} else if (this._serialPortControl.isActive) {
vscode.window.showWarningMessage(
`Serial Monitor is already opened for ${this._currentPort}`
);
return;
}
} else {
this._serialPortControl = new SerialPortControl(
this._currentPort,
this._currentBaudRate,
this._outputChannel
);
}
if (!this._serialPortControl.currentPort) {
console.error(
CONSTANTS.ERROR.FAILED_TO_OPEN_SERIAL_PORT(this._currentPort)
);
return;
}
try {
await this._serialPortControl.open();
this.updatePortStatus(true);
} catch (error) {
logToOutputChannel(
outChannel,
CONSTANTS.ERROR.FAILED_TO_OPEN_SERIAL_PORT_DUE_TO(
this._currentPort,
error
),
true
);
}
}
public get initialized(): boolean {
return !!this._outputChannel;
}
public dispose() {
if (this._serialPortControl && this._serialPortControl.isActive) {
return this._serialPortControl.stop();
}
}
public async changeBaudRate() {
const baudRates = SerialMonitor.listBaudRates();
const chosen = await vscode.window.showQuickPick(
baudRates.map(baudRate => baudRate.toString())
);
if (!chosen) {
logToOutputChannel(
outChannel,
CONSTANTS.WARNING.NO_RATE_SELECTED,
true
);
return;
}
if (!parseInt(chosen, 10)) {
logToOutputChannel(
outChannel,
CONSTANTS.WARNING.INVALID_BAUD_RATE,
true
);
return;
}
if (!this._serialPortControl) {
logToOutputChannel(
outChannel,
CONSTANTS.WARNING.SERIAL_MONITOR_NOT_STARTED,
true
);
return;
}
const selectedRate: number = parseInt(chosen, 10);
await this._serialPortControl.changeBaudRate(selectedRate);
this._currentBaudRate = selectedRate;
this._baudRateStatusBar.text = chosen;
}
public async closeSerialMonitor(port: string, showWarning: boolean = true) {
if (this._serialPortControl) {
if (port && port !== this._serialPortControl.currentPort) {
// Port is not opened
return false;
}
const result = await this._serialPortControl.stop();
this.updatePortStatus(false);
return result;
} else if (!port && showWarning) {
logToOutputChannel(
outChannel,
CONSTANTS.WARNING.SERIAL_PORT_NOT_STARTED,
true
);
return false;
}
}
private updatePortStatus(isOpened: boolean) {
if (isOpened) {
this._openPortStatusBar.command =
"deviceSimulatorExpress.common.closeSerialMonitor";
this._openPortStatusBar.text = `$(x)`;
this._openPortStatusBar.tooltip = "Close Serial Monitor";
this._baudRateStatusBar.show();
} else {
this._openPortStatusBar.command =
"deviceSimulatorExpress.common.openSerialMonitor";
this._openPortStatusBar.text = `$(plug)`;
this._openPortStatusBar.tooltip = "Open Serial Monitor";
this._baudRateStatusBar.hide();
}
}
private updatePortListStatus(port: string | null) {
const deviceContext = DeviceContext.getInstance();
if (port) {
deviceContext.port = port;
}
this._currentPort = deviceContext.port;
if (deviceContext.port) {
this._portsStatusBar.text = deviceContext.port;
} else {
this._portsStatusBar.text = "<Select Serial Port>";
}
}
} | the_stack |
import BigNumber from "bignumber.js";
import { cloneDeep } from "lodash";
import { FrozenFunds, FrozenFundsParams, getFrozenFundsAfterEventForOneOutcome, Trade } from "../../../../../src/blockchain/log-processors/profit-loss/frozen-funds";
import { ZERO } from "../../../../../src/constants";
function bn(n: number): BigNumber {
return new BigNumber(n, 10);
}
interface TestCase extends FrozenFundsParams {
name: string;
expectedFrozenFunds: FrozenFunds;
}
const testClaims: Array<TestCase> = [
{
name: "ClaimProceeds keeps frozen funds to zero",
frozenFundsBeforeEvent: {
frozenFunds: ZERO,
},
event: "ClaimProceeds",
expectedFrozenFunds: {
frozenFunds: ZERO,
},
},
{
name: "ClaimProceeds sets frozen funds to zero",
frozenFundsBeforeEvent: {
frozenFunds: bn(29),
},
event: "ClaimProceeds",
expectedFrozenFunds: {
frozenFunds: ZERO,
},
},
];
const testTrades: Array<TestCase> = [
{
name: "Binary State 1",
frozenFundsBeforeEvent: {
frozenFunds: ZERO,
},
event: {
minPrice: bn(0),
maxPrice: bn(1),
price: bn(0.65),
numCreatorTokens: bn(3.5),
numCreatorShares: bn(0),
numFillerTokens: bn(0),
numFillerShares: bn(0),
longOrShort: "short",
creatorOrFiller: "creator",
realizedProfitDelta: bn(0),
},
expectedFrozenFunds: {
frozenFunds: bn(3.5),
},
},
// skip Binary State 2 which is a price change
{
name: "Binary State 3",
frozenFundsBeforeEvent: {
frozenFunds: bn(3.5),
},
event: {
minPrice: bn(0),
maxPrice: bn(1),
price: bn(0.58),
numCreatorTokens: bn(0),
numCreatorShares: bn(3),
numFillerTokens: bn(0),
numFillerShares: bn(0),
longOrShort: "long",
creatorOrFiller: "creator",
realizedProfitDelta: bn(0.21),
},
expectedFrozenFunds: {
frozenFunds: bn(2.45),
},
},
// skip Binary State 4 which is a price change
{
name: "Binary State 5",
frozenFundsBeforeEvent: {
frozenFunds: bn(2.45),
},
event: {
minPrice: bn(0),
maxPrice: bn(1),
price: bn(0.62),
numCreatorTokens: bn(4.94),
numCreatorShares: bn(0),
numFillerTokens: bn(0),
numFillerShares: bn(0),
longOrShort: "short",
creatorOrFiller: "creator",
realizedProfitDelta: bn(0),
},
expectedFrozenFunds: {
frozenFunds: bn(7.39),
},
},
{
name: "Binary State 6",
frozenFundsBeforeEvent: {
frozenFunds: bn(7.39),
},
event: {
minPrice: bn(0),
maxPrice: bn(1),
price: bn(0.5),
numCreatorTokens: bn(0),
numCreatorShares: bn(10),
numFillerTokens: bn(0),
numFillerShares: bn(0),
longOrShort: "long",
creatorOrFiller: "creator",
realizedProfitDelta: bn(1.515 - 0.21),
},
expectedFrozenFunds: {
frozenFunds: bn(3.695),
},
},
// skip Binary State 7 which is a price change
{
name: "Binary State 8",
frozenFundsBeforeEvent: {
frozenFunds: bn(3.695),
},
event: {
minPrice: bn(0),
maxPrice: bn(1),
price: bn(0.15),
numCreatorTokens: bn(0),
numCreatorShares: bn(7),
numFillerTokens: bn(0),
numFillerShares: bn(0),
longOrShort: "long",
creatorOrFiller: "creator",
realizedProfitDelta: bn(4.8785 - 1.515),
},
expectedFrozenFunds: {
frozenFunds: bn(1.1085),
},
},
{
name: "Cat3-Tr1 State 1",
frozenFundsBeforeEvent: {
frozenFunds: ZERO,
},
event: {
minPrice: bn(0),
maxPrice: bn(1),
price: bn(0.4),
numCreatorTokens: bn(0.4),
numCreatorShares: bn(0),
numFillerTokens: bn(0),
numFillerShares: bn(0),
longOrShort: "long",
creatorOrFiller: "creator",
realizedProfitDelta: bn(0),
},
expectedFrozenFunds: {
frozenFunds: bn(0.4),
},
},
{
name: "Cat3-Tr1 State 2",
frozenFundsBeforeEvent: {
frozenFunds: ZERO,
},
event: {
minPrice: bn(0),
maxPrice: bn(1),
price: bn(0.2),
numCreatorTokens: bn(1.6),
numCreatorShares: bn(0),
numFillerTokens: bn(0),
numFillerShares: bn(0),
longOrShort: "short",
creatorOrFiller: "creator",
realizedProfitDelta: bn(0),
},
expectedFrozenFunds: {
frozenFunds: bn(1.6),
},
},
{
name: "Cat3-Tr1 State 3",
frozenFundsBeforeEvent: {
frozenFunds: ZERO,
},
event: {
minPrice: bn(0),
maxPrice: bn(1),
price: bn(0.3),
numCreatorTokens: bn(0.15),
numCreatorShares: bn(0),
numFillerTokens: bn(0),
numFillerShares: bn(0),
longOrShort: "long",
creatorOrFiller: "creator",
realizedProfitDelta: bn(0),
},
expectedFrozenFunds: {
frozenFunds: bn(0.15),
},
},
// skip "Cat3-Tr1 State 4" which is a price change
{
name: "Cat3-Tr1 State 5",
frozenFundsBeforeEvent: {
frozenFunds: bn(0.4),
},
event: {
minPrice: bn(0),
maxPrice: bn(1),
price: bn(0.7),
numCreatorTokens: bn(0),
numCreatorShares: bn(1),
numFillerTokens: bn(0),
numFillerShares: bn(0),
longOrShort: "short",
creatorOrFiller: "creator",
realizedProfitDelta: bn(0.3),
},
expectedFrozenFunds: {
frozenFunds: bn(0),
},
},
{
name: "Cat3-Tr2 State 1",
frozenFundsBeforeEvent: {
frozenFunds: ZERO,
},
event: {
minPrice: bn(0),
maxPrice: bn(1),
price: bn(0.4),
numCreatorTokens: bn(3),
numCreatorShares: bn(0),
numFillerTokens: bn(0),
numFillerShares: bn(0),
longOrShort: "short",
creatorOrFiller: "creator",
realizedProfitDelta: bn(0),
},
expectedFrozenFunds: {
frozenFunds: bn(3),
},
},
{
name: "Cat3-Tr2 State 2",
frozenFundsBeforeEvent: {
frozenFunds: ZERO,
},
event: {
minPrice: bn(0),
maxPrice: bn(1),
price: bn(0.35),
numCreatorTokens: bn(0),
numCreatorShares: bn(3),
numFillerTokens: bn(0),
numFillerShares: bn(0),
longOrShort: "short",
creatorOrFiller: "creator",
realizedProfitDelta: bn(0),
},
expectedFrozenFunds: {
frozenFunds: bn(-1.05),
},
},
{
name: "Cat3-Tr2 State 3",
frozenFundsBeforeEvent: {
frozenFunds: ZERO,
},
event: {
minPrice: bn(0),
maxPrice: bn(1),
price: bn(0.3),
numCreatorTokens: bn(3.5),
numCreatorShares: bn(5),
numFillerTokens: bn(3),
numFillerShares: bn(0),
longOrShort: "short",
creatorOrFiller: "creator",
realizedProfitDelta: bn(0),
},
expectedFrozenFunds: {
frozenFunds: bn(2),
},
},
{
name: "Cat3-Tr2 State 4",
frozenFundsBeforeEvent: {
frozenFunds: bn(2),
},
event: {
minPrice: bn(0),
maxPrice: bn(1),
price: bn(0.1),
numCreatorTokens: bn(0.3),
numCreatorShares: bn(5),
numFillerTokens: bn(0),
numFillerShares: bn(0),
longOrShort: "long",
creatorOrFiller: "creator",
realizedProfitDelta: bn(1.6),
},
expectedFrozenFunds: {
frozenFunds: bn(-0.6),
},
},
{
name: "Cat3-Tr3 State 1",
frozenFundsBeforeEvent: {
frozenFunds: bn(0),
},
event: {
minPrice: bn(0),
maxPrice: bn(1),
price: bn(0.15),
numCreatorTokens: bn(1.5),
numCreatorShares: bn(0),
numFillerTokens: bn(0),
numFillerShares: bn(0),
longOrShort: "long",
creatorOrFiller: "creator",
realizedProfitDelta: bn(0),
},
expectedFrozenFunds: {
frozenFunds: bn(1.5),
},
},
{
name: "Cat3-Tr3 State 2",
frozenFundsBeforeEvent: {
frozenFunds: bn(0),
},
event: {
minPrice: bn(0),
maxPrice: bn(1),
price: bn(0.1),
numCreatorTokens: bn(2.5),
numCreatorShares: bn(0),
numFillerTokens: bn(0),
numFillerShares: bn(0),
longOrShort: "long",
creatorOrFiller: "creator",
realizedProfitDelta: bn(0),
},
expectedFrozenFunds: {
frozenFunds: bn(2.5),
},
},
{
name: "Cat3-Tr3 State 3",
frozenFundsBeforeEvent: {
frozenFunds: bn(0),
},
event: {
minPrice: bn(0),
maxPrice: bn(1),
price: bn(0.6),
numCreatorTokens: bn(0),
numCreatorShares: bn(5),
numFillerTokens: bn(0),
numFillerShares: bn(0),
longOrShort: "long",
creatorOrFiller: "creator",
realizedProfitDelta: bn(0),
},
expectedFrozenFunds: {
frozenFunds: bn(-2),
},
},
{
name: "Cat3-Tr3 State 4",
frozenFundsBeforeEvent: {
frozenFunds: bn(2.5),
},
event: {
minPrice: bn(0),
maxPrice: bn(1),
price: bn(0.2),
numCreatorTokens: bn(0),
numCreatorShares: bn(13),
numFillerTokens: bn(0),
numFillerShares: bn(0),
longOrShort: "short",
creatorOrFiller: "creator",
realizedProfitDelta: bn(1.3),
},
expectedFrozenFunds: {
frozenFunds: bn(1.2),
},
},
// skip Cat3-Tr3 State 5 which is price change
{
name: "Cat3-Tr3 State 6",
frozenFundsBeforeEvent: {
frozenFunds: bn(-2),
},
event: {
minPrice: bn(0),
maxPrice: bn(1),
price: bn(0.8),
numCreatorTokens: bn(0.6),
numCreatorShares: bn(0),
numFillerTokens: bn(0),
numFillerShares: bn(0),
longOrShort: "short",
creatorOrFiller: "creator",
realizedProfitDelta: bn(0.6),
},
expectedFrozenFunds: {
frozenFunds: bn(-0.8),
},
},
{
name: "Cat3-Tr3 State 7",
frozenFundsBeforeEvent: {
frozenFunds: bn(1.5),
},
event: {
minPrice: bn(0),
maxPrice: bn(1),
price: bn(0.1),
numCreatorTokens: bn(1.8),
numCreatorShares: bn(8),
numFillerTokens: bn(0),
numFillerShares: bn(0),
longOrShort: "short",
creatorOrFiller: "creator",
realizedProfitDelta: bn(-0.5),
},
expectedFrozenFunds: {
frozenFunds: bn(2),
},
},
{
name: "Scalar State 1",
frozenFundsBeforeEvent: {
frozenFunds: bn(0),
},
event: {
minPrice: bn(50),
maxPrice: bn(250),
price: bn(200),
numCreatorTokens: bn(300),
numCreatorShares: bn(0),
numFillerTokens: bn(0),
numFillerShares: bn(0),
longOrShort: "long",
creatorOrFiller: "creator",
realizedProfitDelta: bn(0),
},
expectedFrozenFunds: {
frozenFunds: bn(300),
},
},
{
name: "Scalar State 2",
frozenFundsBeforeEvent: {
frozenFunds: bn(300),
},
event: {
minPrice: bn(50),
maxPrice: bn(250),
price: bn(180),
numCreatorTokens: bn(390),
numCreatorShares: bn(0),
numFillerTokens: bn(0),
numFillerShares: bn(0),
longOrShort: "long",
creatorOrFiller: "creator",
realizedProfitDelta: bn(0),
},
expectedFrozenFunds: {
frozenFunds: bn(690),
},
},
// skip Scalar State 3 which is price change
{
name: "Scalar State 4",
frozenFundsBeforeEvent: {
frozenFunds: bn(690),
},
event: {
minPrice: bn(50),
maxPrice: bn(250),
price: bn(202),
numCreatorTokens: bn(0),
numCreatorShares: bn(4),
numFillerTokens: bn(0),
numFillerShares: bn(0),
longOrShort: "short",
creatorOrFiller: "creator",
realizedProfitDelta: bn(56),
},
expectedFrozenFunds: {
frozenFunds: bn(138),
},
},
{
name: "Scalar State 5",
frozenFundsBeforeEvent: {
frozenFunds: bn(138),
},
event: {
minPrice: bn(50),
maxPrice: bn(250),
price: bn(205),
numCreatorTokens: bn(450),
numCreatorShares: bn(1),
numFillerTokens: bn(0),
numFillerShares: bn(0),
longOrShort: "short",
creatorOrFiller: "creator",
realizedProfitDelta: bn(73 - 56),
},
expectedFrozenFunds: {
frozenFunds: bn(450),
},
},
// skip Scalar State 6 which is price change
// skip Scalar State 7 which is price change
{
name: "Scalar State 8",
frozenFundsBeforeEvent: {
frozenFunds: bn(450),
},
event: {
minPrice: bn(50),
maxPrice: bn(250),
price: bn(150),
numCreatorTokens: bn(0),
numCreatorShares: bn(7),
numFillerTokens: bn(0),
numFillerShares: bn(0),
longOrShort: "long",
creatorOrFiller: "creator",
realizedProfitDelta: bn(458 - 73),
},
expectedFrozenFunds: {
frozenFunds: bn(135),
},
},
];
const testData: Array<TestCase> = [
...testClaims,
...testTrades,
// Autogenerate test cases to ensure algorithm correctly handles
// dual of each trade. Each trade has a natural dual/symmetric
// opposite: a creator who was long could instead be a filler that
// was short (given symmetric price, share, and token amounts).
...testTrades.map((tc) => {
const tc2 = cloneDeep(tc);
tc2.name = "auto-generated dual of: " + tc.name;
const trade = tc2.event as Trade;
trade.price = trade.minPrice.plus(trade.maxPrice.minus(trade.price));
trade.longOrShort = trade.longOrShort === "long" ? "short" : "long";
trade.creatorOrFiller = trade.creatorOrFiller === "creator" ? "filler" : "creator";
let tmp: BigNumber = trade.numCreatorShares;
trade.numCreatorShares = trade.numFillerShares;
trade.numFillerShares = tmp;
tmp = trade.numCreatorTokens;
trade.numCreatorTokens = trade.numFillerTokens;
trade.numFillerTokens = tmp;
return tc2;
}),
];
testData.forEach((tc) => {
test(tc.name, () => {
expect(getFrozenFundsAfterEventForOneOutcome(tc)
.frozenFunds).toEqual(tc.expectedFrozenFunds.frozenFunds);
});
}); | the_stack |
import { Components, registerComponent, } from '../../lib/vulcan-lib';
import React, { useState, useEffect } from 'react';
import { useUserLocation } from '../../lib/collections/users/helpers';
import { useCurrentUser } from '../common/withUser';
import { createStyles } from '@material-ui/core/styles';
import * as _ from 'underscore';
import FilterIcon from '@material-ui/icons/FilterList';
import NotificationsIcon from '@material-ui/icons/Notifications';
import NotificationsNoneIcon from '@material-ui/icons/NotificationsNone';
import { useDialog } from '../common/withDialog'
import {AnalyticsContext} from "../../lib/analyticsEvents";
import { useUpdate } from '../../lib/crud/withUpdate';
import { pickBestReverseGeocodingResult } from '../../server/mapsUtils';
import { useGoogleMaps, geoSuggestStyles } from '../form-components/LocationFormComponent';
import Select from '@material-ui/core/Select';
import MenuItem from '@material-ui/core/MenuItem';
import { useMulti } from '../../lib/crud/withMulti';
import { getBrowserLocalStorage } from '../async/localStorageHandlers';
import Geosuggest from 'react-geosuggest';
import Button from '@material-ui/core/Button';
import { forumTypeSetting } from '../../lib/instanceSettings';
import { EVENT_TYPES } from '../../lib/collections/posts/custom_fields';
import Input from '@material-ui/core/Input';
import OutlinedInput from '@material-ui/core/OutlinedInput';
import Checkbox from '@material-ui/core/Checkbox';
import ListItemText from '@material-ui/core/ListItemText';
import classNames from 'classnames';
const styles = createStyles((theme: ThemeType): JssStyles => ({
section: {
maxWidth: 1200,
padding: 20,
margin: 'auto',
},
sectionHeadingRow: {
display: 'flex',
justifyContent: 'space-between',
maxWidth: 700,
margin: '40px auto',
'@media (max-width: 812px)': {
flexDirection: 'column',
margin: '30px auto',
}
},
sectionHeading: {
flex: 'none',
...theme.typography.headline,
fontSize: 34,
margin: 0
},
sectionDescription: {
...theme.typography.commentStyle,
textAlign: 'left',
fontSize: 15,
lineHeight: '1.8em',
marginLeft: 60,
'@media (max-width: 812px)': {
marginTop: 10,
marginLeft: 0
}
},
filters: {
gridColumnStart: 1,
gridColumnEnd: -1,
display: 'flex',
alignItems: 'baseline',
columnGap: 10,
...theme.typography.commentStyle,
fontSize: 13,
},
where: {
flex: '1 0 0',
color: theme.palette.text.dim60,
paddingLeft: 3
},
geoSuggest: {
...geoSuggestStyles(theme),
display: 'inline-block',
minWidth: 200,
marginLeft: 6
},
filterIcon: {
alignSelf: 'center',
fontSize: 20
},
filter: {
'& .MuiOutlinedInput-input': {
paddingRight: 30
},
'@media (max-width: 812px)': {
display: 'none'
}
},
distanceFilter: {
display: 'flex',
alignItems: 'center',
color: theme.palette.text.dim60,
},
distanceInput: {
width: 68,
color: theme.palette.primary.main,
margin: '0 6px'
},
formatFilter: {
[theme.breakpoints.down('md')]: {
display: 'none'
}
},
placeholder: {
color: theme.palette.text.dim40,
},
notifications: {
flex: '1 0 0',
textAlign: 'right'
},
notificationsBtn: {
textTransform: 'none',
fontSize: 14,
[theme.breakpoints.down('xs')]: {
fontSize: 12,
padding: '8px 8px'
}
},
notificationsIcon: {
fontSize: 18,
marginRight: 6,
[theme.breakpoints.down('xs')]: {
fontSize: 16,
marginRight: 4
}
},
eventCards: {
display: 'grid',
gridTemplateColumns: 'repeat(3, 373px)',
gridGap: '20px',
justifyContent: 'center',
marginTop: 16,
[theme.breakpoints.down('md')]: {
gridTemplateColumns: 'repeat(2, 373px)',
},
'@media (max-width: 812px)': {
gridTemplateColumns: 'auto',
}
},
loadMoreRow: {
gridColumnStart: 1,
gridColumnEnd: -1,
},
loadMore: {
...theme.typography.commentStyle,
background: 'none',
color: theme.palette.primary.main,
fontSize: 16,
padding: 0,
'&:hover': {
color: theme.palette.eventsHomeLoadMoreHover,
}
},
loading: {
display: 'inline-block'
},
}))
const EventsHome = ({classes}: {
classes: ClassesType,
}) => {
const currentUser = useCurrentUser();
const { openDialog } = useDialog();
// in-person, online, or all
const [modeFilter, setModeFilter] = useState('all')
// ex. presentation, discussion, course, etc. (see EVENT_TYPES for full list)
const [formatFilter, setFormatFilter] = useState<Array<string>>([])
// used to set the user's location if they did not already have one
const { mutate: updateUser } = useUpdate({
collectionName: "Users",
fragmentName: 'UsersProfile',
});
// used to set the cutoff distance for the query (default to 160 km / 100 mi)
const [distance, setDistance] = useState(160)
const [distanceUnit, setDistanceUnit] = useState<"km"|"mi">('km')
useEffect(() => {
const ls = getBrowserLocalStorage()
const savedDistance = ls?.getItem('eventsDistanceFilter')
if (savedDistance) {
setDistance(savedDistance)
}
// only US and UK default to miles - everyone else defaults to km
// (this is checked here to allow SSR to work properly)
if (['en-US', 'en-GB'].some(lang => lang === window?.navigator?.language)) {
setDistanceUnit('mi')
setDistance(Math.round((savedDistance || distance) * 0.621371))
}
//No exhaustive deps because this is supposed to run only on mount
//eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
/**
* Given a location, update the page query to use that location,
* then save it to the user's settings (if they are logged in)
* or to the browser's local storage (if they are logged out).
*
* @param {Object} location - The location to save for the user.
* @param {number} location.lat - The location's latitude.
* @param {number} location.lng - The location's longitude.
* @param {Object} location.gmaps - The Google Maps location data.
* @param {string} location.gmaps.formatted_address - The user-facing address (ex: Cambridge, MA, USA).
*/
const saveUserLocation = ({lat, lng, gmaps}) => {
// save it in the page state
userLocation.setLocationData({lat, lng, loading: false, known: true, label: gmaps.formatted_address})
if (currentUser) {
// save it on the user document
void updateUser({
selector: {_id: currentUser._id},
data: {
location: gmaps.formatted_address,
googleLocation: gmaps
}
})
} else {
// save it in local storage
const ls = getBrowserLocalStorage()
try {
ls?.setItem('userlocation', JSON.stringify({lat, lng, known: true, label: gmaps.formatted_address}))
} catch(e) {
// eslint-disable-next-line no-console
console.error(e);
}
}
}
// if the current user provides their browser location and we don't have a location saved for them,
// save it accordingly
const [mapsLoaded, googleMaps] = useGoogleMaps()
const [geocodeError, setGeocodeError] = useState(false)
const saveReverseGeocodedLocation = async ({lat, lng, known}) => {
if (
mapsLoaded && // we need Google Maps to be loaded before we can call the Geocoder
!geocodeError && // if we've ever gotten a geocoding error, don't try again
known // skip if we've received the default location
) {
try {
// get a list of matching Google locations for the current lat/lng (reverse geocoding)
const geocoder = new googleMaps.Geocoder();
const geocodingResponse = await geocoder.geocode({
location: {lat, lng}
});
const results = geocodingResponse?.results;
if (results?.length) {
const location = pickBestReverseGeocodingResult(results)
saveUserLocation({lat, lng, gmaps: location})
} else {
// update the page state to indicate that we're not waiting on a location name
userLocation.setLocationData({...userLocation, label: null})
}
} catch (e) {
setGeocodeError(true)
// eslint-disable-next-line no-console
console.error(e?.message)
// update the page state to indicate that we're not waiting on a location name
userLocation.setLocationData({...userLocation, label: null})
}
}
}
// on page load, try to get the user's location from:
// 1. (logged in user) user settings
// 2. (logged out user) browser's local storage
// 3. failing those, browser's geolocation API (which we then try to save in #1 or #2)
const userLocation = useUserLocation(currentUser)
useEffect(() => {
// if we've gotten a location from the browser's geolocation API, save it
if (!userLocation.loading && userLocation.known && userLocation.label === '') {
void saveReverseGeocodedLocation(userLocation)
}
//eslint-disable-next-line react-hooks/exhaustive-deps
}, [userLocation])
const openEventNotificationsForm = () => {
openDialog({
componentName: currentUser ? "EventNotificationsDialog" : "LoginPopup",
});
}
const handleChangeDistance = (e) => {
const distance = parseInt(e.target.value)
setDistance(distance)
// save it in local storage in km
const ls = getBrowserLocalStorage()
ls?.setItem('eventsDistanceFilter', distanceUnit === 'mi' ? Math.round(distance / 0.621371) : distance)
}
const handleChangeDistanceUnit = (unit) => {
setDistanceUnit(unit)
// when changing between miles and km, we convert the distance to the new unit
setDistance(unit === 'mi' ? Math.round(distance * 0.621371) : Math.round(distance / 0.621371))
}
const { HighlightedEventCard, EventCards, Loading, DistanceUnitToggle } = Components
// on the EA Forum, we insert some special event cards (ex. Intro VP card)
let numSpecialCards = currentUser ? 1 : 2
// hide them on other forums, and when certain filters are set
if (forumTypeSetting.get() !== 'EAForum' || modeFilter === 'in-person' || (formatFilter.length > 0 && !formatFilter.includes('course'))) {
numSpecialCards = 0
}
const filters: PostsViewTerms = {}
if (modeFilter === 'in-person') {
filters.onlineEvent = false
} else if (modeFilter === 'online') {
filters.onlineEvent = true
}
if (formatFilter.length) {
filters.eventType = formatFilter
}
if (distance) {
// convert distance to miles if necessary
filters.distance = (distanceUnit === 'mi') ? distance : (distance * 0.621371)
}
const eventsListTerms: PostsViewTerms = userLocation.known ? {
view: 'nearbyEvents',
lat: userLocation.lat,
lng: userLocation.lng,
...filters,
} : {
view: 'globalEvents',
...filters,
}
const { results, loading, showLoadMore, loadMore } = useMulti({
terms: eventsListTerms,
collectionName: "Posts",
fragmentName: 'PostsList',
fetchPolicy: 'cache-and-network',
nextFetchPolicy: "cache-first",
limit: 12 - numSpecialCards,
itemsPerPage: 12,
skip: userLocation.loading
});
// we try to highlight the event most relevant to you
let highlightedEvent: PostsList|undefined;
if (results && results.length > 0) {
// first, try to find the next in-person event near you
results.forEach(result => {
if (!highlightedEvent && !result.onlineEvent) {
highlightedEvent = result
}
})
// if none, then try to find the next "local" online event near you
results.forEach(result => {
if (!highlightedEvent && !result.globalEvent) {
highlightedEvent = result
}
})
// otherwise, just show the first event in the list
if (!highlightedEvent) highlightedEvent = results[0]
}
let loadMoreButton = showLoadMore && <button className={classes.loadMore} onClick={() => loadMore(null)}>
Load More
</button>
if (loading && results?.length) {
loadMoreButton = <div className={classes.loading}><Loading /></div>
}
return (
<AnalyticsContext pageContext="EventsHome">
<div>
<HighlightedEventCard event={highlightedEvent} loading={loading || userLocation.loading} />
</div>
<div className={classes.section}>
<div className={classes.sectionHeadingRow}>
<h1 className={classes.sectionHeading}>
Events
</h1>
<div className={classes.sectionDescription}>
Join people from around the world for discussions, talks, and other events on how we can tackle
the world's biggest problems.
</div>
</div>
<div className={classes.eventCards}>
<div className={classes.filters}>
<div className={classes.where}>
Showing events near {mapsLoaded
&& <div className={classes.geoSuggest}>
<Geosuggest
placeholder="search for a location"
onSuggestSelect={(suggestion) => {
if (suggestion?.location) {
saveUserLocation({
...suggestion.location,
gmaps: suggestion.gmaps
})
}
}}
initialValue={userLocation?.label}
/>
</div>
}
</div>
</div>
<div className={classes.filters}>
<FilterIcon className={classes.filterIcon} />
<div className={classes.distanceFilter}>
Within
<Input type="number"
value={distance}
placeholder="distance"
onChange={handleChangeDistance}
className={classes.distanceInput}
/>
<DistanceUnitToggle distanceUnit={distanceUnit} onChange={handleChangeDistanceUnit} skipDefaultEffect />
</div>
<Select
className={classes.filter}
value={modeFilter}
input={<OutlinedInput labelWidth={0} />}
onChange={(e) => setModeFilter(e.target.value)}>
<MenuItem key="all" value="all">In-person and online</MenuItem>
<MenuItem key="in-person" value="in-person">In-person only</MenuItem>
<MenuItem key="online" value="online">Online only</MenuItem>
</Select>
<Select
className={classNames(classes.filter, classes.formatFilter)}
value={formatFilter}
input={<OutlinedInput labelWidth={0} />}
onChange={e => {
// MUI documentation says e.target.value is always an array: https://mui.com/components/selects/#multiple-select
// @ts-ignore
setFormatFilter(e.target.value)
}}
multiple
displayEmpty
renderValue={(selected: Array<string>) => {
if (selected.length === 0) {
return <em className={classes.placeholder}>Filter by format</em>
}
// if any options are selected, display them separated by commas
return selected.map(type => EVENT_TYPES.find(t => t.value === type)?.label).join(', ')
}}>
{EVENT_TYPES.map(type => {
return <MenuItem key={type.value} value={type.value}>
<Checkbox checked={formatFilter.some(format => format === type.value)} />
<ListItemText primary={type.label} />
</MenuItem>
})}
</Select>
<div className={classes.notifications}>
<Button variant="text" color="primary" onClick={openEventNotificationsForm} className={classes.notificationsBtn}>
{currentUser?.nearbyEventsNotifications ? <NotificationsIcon className={classes.notificationsIcon} /> : <NotificationsNoneIcon className={classes.notificationsIcon} />} Notify me
</Button>
</div>
</div>
<EventCards events={results || []} loading={loading || userLocation.loading} numDefaultCards={6} hideSpecialCards={!numSpecialCards} />
<div className={classes.loadMoreRow}>
{loadMoreButton}
</div>
</div>
</div>
</AnalyticsContext>
)
}
const EventsHomeComponent = registerComponent('EventsHome', EventsHome, {styles});
declare global {
interface ComponentTypes {
EventsHome: typeof EventsHomeComponent
}
} | the_stack |
* Standard WebGL and WebGL2 constants
* These constants are also defined on the WebGLRenderingContext interface.
*/
export enum GL {
// Clearing buffers
// Constants passed to clear() to clear buffer masks.
DEPTH_BUFFER_BIT = 0x00000100,
STENCIL_BUFFER_BIT = 0x00000400,
COLOR_BUFFER_BIT = 0x00004000,
// Rendering primitives
// Constants passed to drawElements() or drawArrays() to specify what kind of primitive to render.
POINTS = 0x0000,
LINES = 0x0001,
LINE_LOOP = 0x0002,
LINE_STRIP = 0x0003,
TRIANGLES = 0x0004,
TRIANGLE_STRIP = 0x0005,
TRIANGLE_FAN = 0x0006,
// Blending modes
// Constants passed to blendFunc() or blendFuncSeparate() to specify the blending mode (for both, RBG and alpha, or separately).
ZERO = 0,
ONE = 1,
SRC_COLOR = 0x0300,
ONE_MINUS_SRC_COLOR = 0x0301,
SRC_ALPHA = 0x0302,
ONE_MINUS_SRC_ALPHA = 0x0303,
DST_ALPHA = 0x0304,
ONE_MINUS_DST_ALPHA = 0x0305,
DST_COLOR = 0x0306,
ONE_MINUS_DST_COLOR = 0x0307,
SRC_ALPHA_SATURATE = 0x0308,
CONSTANT_COLOR = 0x8001,
ONE_MINUS_CONSTANT_COLOR = 0x8002,
CONSTANT_ALPHA = 0x8003,
ONE_MINUS_CONSTANT_ALPHA = 0x8004,
// Blending equations
// Constants passed to blendEquation() or blendEquationSeparate() to control
// how the blending is calculated (for both, RBG and alpha, or separately).
FUNC_ADD = 0x8006,
FUNC_SUBTRACT = 0x800a,
FUNC_REVERSE_SUBTRACT = 0x800b,
// Getting GL parameter information
// Constants passed to getParameter() to specify what information to return.
BLEND_EQUATION = 0x8009,
BLEND_EQUATION_RGB = 0x8009,
BLEND_EQUATION_ALPHA = 0x883d,
BLEND_DST_RGB = 0x80c8,
BLEND_SRC_RGB = 0x80c9,
BLEND_DST_ALPHA = 0x80ca,
BLEND_SRC_ALPHA = 0x80cb,
BLEND_COLOR = 0x8005,
ARRAY_BUFFER_BINDING = 0x8894,
ELEMENT_ARRAY_BUFFER_BINDING = 0x8895,
LINE_WIDTH = 0x0b21,
ALIASED_POINT_SIZE_RANGE = 0x846d,
ALIASED_LINE_WIDTH_RANGE = 0x846e,
CULL_FACE_MODE = 0x0b45,
FRONT_FACE = 0x0b46,
DEPTH_RANGE = 0x0b70,
DEPTH_WRITEMASK = 0x0b72,
DEPTH_CLEAR_VALUE = 0x0b73,
DEPTH_FUNC = 0x0b74,
STENCIL_CLEAR_VALUE = 0x0b91,
STENCIL_FUNC = 0x0b92,
STENCIL_FAIL = 0x0b94,
STENCIL_PASS_DEPTH_FAIL = 0x0b95,
STENCIL_PASS_DEPTH_PASS = 0x0b96,
STENCIL_REF = 0x0b97,
STENCIL_VALUE_MASK = 0x0b93,
STENCIL_WRITEMASK = 0x0b98,
STENCIL_BACK_FUNC = 0x8800,
STENCIL_BACK_FAIL = 0x8801,
STENCIL_BACK_PASS_DEPTH_FAIL = 0x8802,
STENCIL_BACK_PASS_DEPTH_PASS = 0x8803,
STENCIL_BACK_REF = 0x8ca3,
STENCIL_BACK_VALUE_MASK = 0x8ca4,
STENCIL_BACK_WRITEMASK = 0x8ca5,
VIEWPORT = 0x0ba2,
SCISSOR_BOX = 0x0c10,
COLOR_CLEAR_VALUE = 0x0c22,
COLOR_WRITEMASK = 0x0c23,
UNPACK_ALIGNMENT = 0x0cf5,
PACK_ALIGNMENT = 0x0d05,
MAX_TEXTURE_SIZE = 0x0d33,
MAX_VIEWPORT_DIMS = 0x0d3a,
SUBPIXEL_BITS = 0x0d50,
RED_BITS = 0x0d52,
GREEN_BITS = 0x0d53,
BLUE_BITS = 0x0d54,
ALPHA_BITS = 0x0d55,
DEPTH_BITS = 0x0d56,
STENCIL_BITS = 0x0d57,
POLYGON_OFFSET_UNITS = 0x2a00,
POLYGON_OFFSET_FACTOR = 0x8038,
TEXTURE_BINDING_2D = 0x8069,
SAMPLE_BUFFERS = 0x80a8,
SAMPLES = 0x80a9,
SAMPLE_COVERAGE_VALUE = 0x80aa,
SAMPLE_COVERAGE_INVERT = 0x80ab,
COMPRESSED_TEXTURE_FORMATS = 0x86a3,
VENDOR = 0x1f00,
RENDERER = 0x1f01,
VERSION = 0x1f02,
IMPLEMENTATION_COLOR_READ_TYPE = 0x8b9a,
IMPLEMENTATION_COLOR_READ_FORMAT = 0x8b9b,
BROWSER_DEFAULT_WEBGL = 0x9244,
// Buffers
// Constants passed to bufferData(), bufferSubData(), bindBuffer(), or
// getBufferParameter().
STATIC_DRAW = 0x88e4,
STREAM_DRAW = 0x88e0,
DYNAMIC_DRAW = 0x88e8,
ARRAY_BUFFER = 0x8892,
ELEMENT_ARRAY_BUFFER = 0x8893,
BUFFER_SIZE = 0x8764,
BUFFER_USAGE = 0x8765,
// Vertex attributes
// Constants passed to getVertexAttrib().
CURRENT_VERTEX_ATTRIB = 0x8626,
VERTEX_ATTRIB_ARRAY_ENABLED = 0x8622,
VERTEX_ATTRIB_ARRAY_SIZE = 0x8623,
VERTEX_ATTRIB_ARRAY_STRIDE = 0x8624,
VERTEX_ATTRIB_ARRAY_TYPE = 0x8625,
VERTEX_ATTRIB_ARRAY_NORMALIZED = 0x886a,
VERTEX_ATTRIB_ARRAY_POINTER = 0x8645,
VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = 0x889f,
// Culling
// Constants passed to cullFace().
CULL_FACE = 0x0b44,
FRONT = 0x0404,
BACK = 0x0405,
FRONT_AND_BACK = 0x0408,
// Enabling and disabling
// Constants passed to enable() or disable().
BLEND = 0x0be2,
DEPTH_TEST = 0x0b71,
DITHER = 0x0bd0,
POLYGON_OFFSET_FILL = 0x8037,
SAMPLE_ALPHA_TO_COVERAGE = 0x809e,
SAMPLE_COVERAGE = 0x80a0,
SCISSOR_TEST = 0x0c11,
STENCIL_TEST = 0x0b90,
// Errors
// Constants returned from getError().
NO_ERROR = 0,
INVALID_ENUM = 0x0500,
INVALID_VALUE = 0x0501,
INVALID_OPERATION = 0x0502,
OUT_OF_MEMORY = 0x0505,
CONTEXT_LOST_WEBGL = 0x9242,
// Front face directions
// Constants passed to frontFace().
CW = 0x0900,
CCW = 0x0901,
// Hints
// Constants passed to hint()
DONT_CARE = 0x1100,
FASTEST = 0x1101,
NICEST = 0x1102,
GENERATE_MIPMAP_HINT = 0x8192,
// Data types
BYTE = 0x1400,
UNSIGNED_BYTE = 0x1401,
SHORT = 0x1402,
UNSIGNED_SHORT = 0x1403,
INT = 0x1404,
UNSIGNED_INT = 0x1405,
FLOAT = 0x1406,
DOUBLE = 0x140a,
// Pixel formats
DEPTH_COMPONENT = 0x1902,
ALPHA = 0x1906,
RGB = 0x1907,
RGBA = 0x1908,
LUMINANCE = 0x1909,
LUMINANCE_ALPHA = 0x190a,
// Pixel types
// UNSIGNED_BYTE = 0x1401,
UNSIGNED_SHORT_4_4_4_4 = 0x8033,
UNSIGNED_SHORT_5_5_5_1 = 0x8034,
UNSIGNED_SHORT_5_6_5 = 0x8363,
// Shaders
// Constants passed to createShader() or getShaderParameter()
FRAGMENT_SHADER = 0x8b30,
VERTEX_SHADER = 0x8b31,
COMPILE_STATUS = 0x8b81,
DELETE_STATUS = 0x8b80,
LINK_STATUS = 0x8b82,
VALIDATE_STATUS = 0x8b83,
ATTACHED_SHADERS = 0x8b85,
ACTIVE_ATTRIBUTES = 0x8b89,
ACTIVE_UNIFORMS = 0x8b86,
MAX_VERTEX_ATTRIBS = 0x8869,
MAX_VERTEX_UNIFORM_VECTORS = 0x8dfb,
MAX_VARYING_VECTORS = 0x8dfc,
MAX_COMBINED_TEXTURE_IMAGE_UNITS = 0x8b4d,
MAX_VERTEX_TEXTURE_IMAGE_UNITS = 0x8b4c,
MAX_TEXTURE_IMAGE_UNITS = 0x8872,
MAX_FRAGMENT_UNIFORM_VECTORS = 0x8dfd,
SHADER_TYPE = 0x8b4f,
SHADING_LANGUAGE_VERSION = 0x8b8c,
CURRENT_PROGRAM = 0x8b8d,
// Depth or stencil tests
// Constants passed to depthFunc() or stencilFunc().
NEVER = 0x0200,
ALWAYS = 0x0207,
LESS = 0x0201,
EQUAL = 0x0202,
LEQUAL = 0x0203,
GREATER = 0x0204,
GEQUAL = 0x0206,
NOTEQUAL = 0x0205,
// Stencil actions
// Constants passed to stencilOp().
KEEP = 0x1e00,
REPLACE = 0x1e01,
INCR = 0x1e02,
DECR = 0x1e03,
INVERT = 0x150a,
INCR_WRAP = 0x8507,
DECR_WRAP = 0x8508,
// Textures
// Constants passed to texParameteri(),
// texParameterf(), bindTexture(), texImage2D(), and others.
NEAREST = 0x2600,
LINEAR = 0x2601,
NEAREST_MIPMAP_NEAREST = 0x2700,
LINEAR_MIPMAP_NEAREST = 0x2701,
NEAREST_MIPMAP_LINEAR = 0x2702,
LINEAR_MIPMAP_LINEAR = 0x2703,
TEXTURE_MAG_FILTER = 0x2800,
TEXTURE_MIN_FILTER = 0x2801,
TEXTURE_WRAP_S = 0x2802,
TEXTURE_WRAP_T = 0x2803,
TEXTURE_2D = 0x0de1,
TEXTURE = 0x1702,
TEXTURE_CUBE_MAP = 0x8513,
TEXTURE_BINDING_CUBE_MAP = 0x8514,
TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515,
TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516,
TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517,
TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518,
TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519,
TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851a,
MAX_CUBE_MAP_TEXTURE_SIZE = 0x851c,
// TEXTURE0 - 31 0x84C0 - 0x84DF A texture unit.
TEXTURE0 = 0x84c0,
ACTIVE_TEXTURE = 0x84e0,
REPEAT = 0x2901,
CLAMP_TO_EDGE = 0x812f,
MIRRORED_REPEAT = 0x8370,
// Emulation
TEXTURE_WIDTH = 0x1000,
TEXTURE_HEIGHT = 0x1001,
// Uniform types
FLOAT_VEC2 = 0x8b50,
FLOAT_VEC3 = 0x8b51,
FLOAT_VEC4 = 0x8b52,
INT_VEC2 = 0x8b53,
INT_VEC3 = 0x8b54,
INT_VEC4 = 0x8b55,
BOOL = 0x8b56,
BOOL_VEC2 = 0x8b57,
BOOL_VEC3 = 0x8b58,
BOOL_VEC4 = 0x8b59,
FLOAT_MAT2 = 0x8b5a,
FLOAT_MAT3 = 0x8b5b,
FLOAT_MAT4 = 0x8b5c,
SAMPLER_2D = 0x8b5e,
SAMPLER_CUBE = 0x8b60,
// Shader precision-specified types
LOW_FLOAT = 0x8df0,
MEDIUM_FLOAT = 0x8df1,
HIGH_FLOAT = 0x8df2,
LOW_INT = 0x8df3,
MEDIUM_INT = 0x8df4,
HIGH_INT = 0x8df5,
// Framebuffers and renderbuffers
FRAMEBUFFER = 0x8d40,
RENDERBUFFER = 0x8d41,
RGBA4 = 0x8056,
RGB5_A1 = 0x8057,
RGB565 = 0x8d62,
DEPTH_COMPONENT16 = 0x81a5,
STENCIL_INDEX = 0x1901,
STENCIL_INDEX8 = 0x8d48,
DEPTH_STENCIL = 0x84f9,
RENDERBUFFER_WIDTH = 0x8d42,
RENDERBUFFER_HEIGHT = 0x8d43,
RENDERBUFFER_INTERNAL_FORMAT = 0x8d44,
RENDERBUFFER_RED_SIZE = 0x8d50,
RENDERBUFFER_GREEN_SIZE = 0x8d51,
RENDERBUFFER_BLUE_SIZE = 0x8d52,
RENDERBUFFER_ALPHA_SIZE = 0x8d53,
RENDERBUFFER_DEPTH_SIZE = 0x8d54,
RENDERBUFFER_STENCIL_SIZE = 0x8d55,
FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = 0x8cd0,
FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = 0x8cd1,
FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = 0x8cd2,
FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = 0x8cd3,
COLOR_ATTACHMENT0 = 0x8ce0,
DEPTH_ATTACHMENT = 0x8d00,
STENCIL_ATTACHMENT = 0x8d20,
DEPTH_STENCIL_ATTACHMENT = 0x821a,
NONE = 0,
FRAMEBUFFER_COMPLETE = 0x8cd5,
FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 0x8cd6,
FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 0x8cd7,
FRAMEBUFFER_INCOMPLETE_DIMENSIONS = 0x8cd9,
FRAMEBUFFER_UNSUPPORTED = 0x8cdd,
FRAMEBUFFER_BINDING = 0x8ca6,
RENDERBUFFER_BINDING = 0x8ca7,
READ_FRAMEBUFFER = 0x8ca8,
DRAW_FRAMEBUFFER = 0x8ca9,
MAX_RENDERBUFFER_SIZE = 0x84e8,
INVALID_FRAMEBUFFER_OPERATION = 0x0506,
// Pixel storage modes
// Constants passed to pixelStorei().
UNPACK_FLIP_Y_WEBGL = 0x9240,
UNPACK_PREMULTIPLY_ALPHA_WEBGL = 0x9241,
UNPACK_COLORSPACE_CONVERSION_WEBGL = 0x9243,
// Additional constants defined WebGL 2
// These constants are defined on the WebGL2RenderingContext interface.
// All WebGL 1 constants are also available in a WebGL 2 context.
// Getting GL parameter information
// Constants passed to getParameter()
// to specify what information to return.
READ_BUFFER = 0x0c02,
UNPACK_ROW_LENGTH = 0x0cf2,
UNPACK_SKIP_ROWS = 0x0cf3,
UNPACK_SKIP_PIXELS = 0x0cf4,
PACK_ROW_LENGTH = 0x0d02,
PACK_SKIP_ROWS = 0x0d03,
PACK_SKIP_PIXELS = 0x0d04,
TEXTURE_BINDING_3D = 0x806a,
UNPACK_SKIP_IMAGES = 0x806d,
UNPACK_IMAGE_HEIGHT = 0x806e,
MAX_3D_TEXTURE_SIZE = 0x8073,
MAX_ELEMENTS_VERTICES = 0x80e8,
MAX_ELEMENTS_INDICES = 0x80e9,
MAX_TEXTURE_LOD_BIAS = 0x84fd,
MAX_FRAGMENT_UNIFORM_COMPONENTS = 0x8b49,
MAX_VERTEX_UNIFORM_COMPONENTS = 0x8b4a,
MAX_ARRAY_TEXTURE_LAYERS = 0x88ff,
MIN_PROGRAM_TEXEL_OFFSET = 0x8904,
MAX_PROGRAM_TEXEL_OFFSET = 0x8905,
MAX_VARYING_COMPONENTS = 0x8b4b,
FRAGMENT_SHADER_DERIVATIVE_HINT = 0x8b8b,
RASTERIZER_DISCARD = 0x8c89,
VERTEX_ARRAY_BINDING = 0x85b5,
MAX_VERTEX_OUTPUT_COMPONENTS = 0x9122,
MAX_FRAGMENT_INPUT_COMPONENTS = 0x9125,
MAX_SERVER_WAIT_TIMEOUT = 0x9111,
MAX_ELEMENT_INDEX = 0x8d6b,
// Textures
// Constants passed to texParameteri(),
// texParameterf(), bindTexture(), texImage2D(), and others.
RED = 0x1903,
RGB8 = 0x8051,
RGBA8 = 0x8058,
RGB10_A2 = 0x8059,
TEXTURE_3D = 0x806f,
TEXTURE_WRAP_R = 0x8072,
TEXTURE_MIN_LOD = 0x813a,
TEXTURE_MAX_LOD = 0x813b,
TEXTURE_BASE_LEVEL = 0x813c,
TEXTURE_MAX_LEVEL = 0x813d,
TEXTURE_COMPARE_MODE = 0x884c,
TEXTURE_COMPARE_FUNC = 0x884d,
SRGB = 0x8c40,
SRGB8 = 0x8c41,
SRGB8_ALPHA8 = 0x8c43,
COMPARE_REF_TO_TEXTURE = 0x884e,
RGBA32F = 0x8814,
RGB32F = 0x8815,
RGBA16F = 0x881a,
RGB16F = 0x881b,
TEXTURE_2D_ARRAY = 0x8c1a,
TEXTURE_BINDING_2D_ARRAY = 0x8c1d,
R11F_G11F_B10F = 0x8c3a,
RGB9_E5 = 0x8c3d,
RGBA32UI = 0x8d70,
RGB32UI = 0x8d71,
RGBA16UI = 0x8d76,
RGB16UI = 0x8d77,
RGBA8UI = 0x8d7c,
RGB8UI = 0x8d7d,
RGBA32I = 0x8d82,
RGB32I = 0x8d83,
RGBA16I = 0x8d88,
RGB16I = 0x8d89,
RGBA8I = 0x8d8e,
RGB8I = 0x8d8f,
RED_INTEGER = 0x8d94,
RGB_INTEGER = 0x8d98,
RGBA_INTEGER = 0x8d99,
R8 = 0x8229,
RG8 = 0x822b,
R16F = 0x822d,
R32F = 0x822e,
RG16F = 0x822f,
RG32F = 0x8230,
R8I = 0x8231,
R8UI = 0x8232,
R16I = 0x8233,
R16UI = 0x8234,
R32I = 0x8235,
R32UI = 0x8236,
RG8I = 0x8237,
RG8UI = 0x8238,
RG16I = 0x8239,
RG16UI = 0x823a,
RG32I = 0x823b,
RG32UI = 0x823c,
R8_SNORM = 0x8f94,
RG8_SNORM = 0x8f95,
RGB8_SNORM = 0x8f96,
RGBA8_SNORM = 0x8f97,
RGB10_A2UI = 0x906f,
/* covered by extension
COMPRESSED_R11_EAC = 0x9270,
COMPRESSED_SIGNED_R11_EAC = 0x9271,
COMPRESSED_RG11_EAC = 0x9272,
COMPRESSED_SIGNED_RG11_EAC = 0x9273,
COMPRESSED_RGB8_ETC2 = 0x9274,
COMPRESSED_SRGB8_ETC2 = 0x9275,
COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9276,
COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC = 0x9277,
COMPRESSED_RGBA8_ETC2_EAC = 0x9278,
COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 0x9279,
*/
TEXTURE_IMMUTABLE_FORMAT = 0x912f,
TEXTURE_IMMUTABLE_LEVELS = 0x82df,
// Pixel types
UNSIGNED_INT_2_10_10_10_REV = 0x8368,
UNSIGNED_INT_10F_11F_11F_REV = 0x8c3b,
UNSIGNED_INT_5_9_9_9_REV = 0x8c3e,
FLOAT_32_UNSIGNED_INT_24_8_REV = 0x8dad,
UNSIGNED_INT_24_8 = 0x84fa,
HALF_FLOAT = 0x140b,
RG = 0x8227,
RG_INTEGER = 0x8228,
INT_2_10_10_10_REV = 0x8d9f,
// Queries
CURRENT_QUERY = 0x8865,
QUERY_RESULT = 0x8866,
QUERY_RESULT_AVAILABLE = 0x8867,
ANY_SAMPLES_PASSED = 0x8c2f,
ANY_SAMPLES_PASSED_CONSERVATIVE = 0x8d6a,
// Draw buffers
MAX_DRAW_BUFFERS = 0x8824,
DRAW_BUFFER0 = 0x8825,
DRAW_BUFFER1 = 0x8826,
DRAW_BUFFER2 = 0x8827,
DRAW_BUFFER3 = 0x8828,
DRAW_BUFFER4 = 0x8829,
DRAW_BUFFER5 = 0x882a,
DRAW_BUFFER6 = 0x882b,
DRAW_BUFFER7 = 0x882c,
DRAW_BUFFER8 = 0x882d,
DRAW_BUFFER9 = 0x882e,
DRAW_BUFFER10 = 0x882f,
DRAW_BUFFER11 = 0x8830,
DRAW_BUFFER12 = 0x8831,
DRAW_BUFFER13 = 0x8832,
DRAW_BUFFER14 = 0x8833,
DRAW_BUFFER15 = 0x8834,
MAX_COLOR_ATTACHMENTS = 0x8cdf,
COLOR_ATTACHMENT1 = 0x8ce1,
COLOR_ATTACHMENT2 = 0x8ce2,
COLOR_ATTACHMENT3 = 0x8ce3,
COLOR_ATTACHMENT4 = 0x8ce4,
COLOR_ATTACHMENT5 = 0x8ce5,
COLOR_ATTACHMENT6 = 0x8ce6,
COLOR_ATTACHMENT7 = 0x8ce7,
COLOR_ATTACHMENT8 = 0x8ce8,
COLOR_ATTACHMENT9 = 0x8ce9,
COLOR_ATTACHMENT10 = 0x8cea,
COLOR_ATTACHMENT11 = 0x8ceb,
COLOR_ATTACHMENT12 = 0x8cec,
COLOR_ATTACHMENT13 = 0x8ced,
COLOR_ATTACHMENT14 = 0x8cee,
COLOR_ATTACHMENT15 = 0x8cef,
// Samplers
SAMPLER_3D = 0x8b5f,
SAMPLER_2D_SHADOW = 0x8b62,
SAMPLER_2D_ARRAY = 0x8dc1,
SAMPLER_2D_ARRAY_SHADOW = 0x8dc4,
SAMPLER_CUBE_SHADOW = 0x8dc5,
INT_SAMPLER_2D = 0x8dca,
INT_SAMPLER_3D = 0x8dcb,
INT_SAMPLER_CUBE = 0x8dcc,
INT_SAMPLER_2D_ARRAY = 0x8dcf,
UNSIGNED_INT_SAMPLER_2D = 0x8dd2,
UNSIGNED_INT_SAMPLER_3D = 0x8dd3,
UNSIGNED_INT_SAMPLER_CUBE = 0x8dd4,
UNSIGNED_INT_SAMPLER_2D_ARRAY = 0x8dd7,
MAX_SAMPLES = 0x8d57,
SAMPLER_BINDING = 0x8919,
// Buffers
PIXEL_PACK_BUFFER = 0x88eb,
PIXEL_UNPACK_BUFFER = 0x88ec,
PIXEL_PACK_BUFFER_BINDING = 0x88ed,
PIXEL_UNPACK_BUFFER_BINDING = 0x88ef,
COPY_READ_BUFFER = 0x8f36,
COPY_WRITE_BUFFER = 0x8f37,
COPY_READ_BUFFER_BINDING = 0x8f36,
COPY_WRITE_BUFFER_BINDING = 0x8f37,
// Data types
FLOAT_MAT2x3 = 0x8b65,
FLOAT_MAT2x4 = 0x8b66,
FLOAT_MAT3x2 = 0x8b67,
FLOAT_MAT3x4 = 0x8b68,
FLOAT_MAT4x2 = 0x8b69,
FLOAT_MAT4x3 = 0x8b6a,
UNSIGNED_INT_VEC2 = 0x8dc6,
UNSIGNED_INT_VEC3 = 0x8dc7,
UNSIGNED_INT_VEC4 = 0x8dc8,
UNSIGNED_NORMALIZED = 0x8c17,
SIGNED_NORMALIZED = 0x8f9c,
// Vertex attributes
VERTEX_ATTRIB_ARRAY_INTEGER = 0x88fd,
VERTEX_ATTRIB_ARRAY_DIVISOR = 0x88fe,
// Transform feedback
TRANSFORM_FEEDBACK_BUFFER_MODE = 0x8c7f,
MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS = 0x8c80,
TRANSFORM_FEEDBACK_VARYINGS = 0x8c83,
TRANSFORM_FEEDBACK_BUFFER_START = 0x8c84,
TRANSFORM_FEEDBACK_BUFFER_SIZE = 0x8c85,
TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN = 0x8c88,
MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS = 0x8c8a,
MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS = 0x8c8b,
INTERLEAVED_ATTRIBS = 0x8c8c,
SEPARATE_ATTRIBS = 0x8c8d,
TRANSFORM_FEEDBACK_BUFFER = 0x8c8e,
TRANSFORM_FEEDBACK_BUFFER_BINDING = 0x8c8f,
TRANSFORM_FEEDBACK = 0x8e22,
TRANSFORM_FEEDBACK_PAUSED = 0x8e23,
TRANSFORM_FEEDBACK_ACTIVE = 0x8e24,
TRANSFORM_FEEDBACK_BINDING = 0x8e25,
// Framebuffers and renderbuffers
FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING = 0x8210,
FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE = 0x8211,
FRAMEBUFFER_ATTACHMENT_RED_SIZE = 0x8212,
FRAMEBUFFER_ATTACHMENT_GREEN_SIZE = 0x8213,
FRAMEBUFFER_ATTACHMENT_BLUE_SIZE = 0x8214,
FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE = 0x8215,
FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE = 0x8216,
FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE = 0x8217,
FRAMEBUFFER_DEFAULT = 0x8218,
// DEPTH_STENCIL_ATTACHMENT = 0x821A,
// DEPTH_STENCIL = 0x84F9,
DEPTH24_STENCIL8 = 0x88f0,
DRAW_FRAMEBUFFER_BINDING = 0x8ca6,
READ_FRAMEBUFFER_BINDING = 0x8caa,
RENDERBUFFER_SAMPLES = 0x8cab,
FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER = 0x8cd4,
FRAMEBUFFER_INCOMPLETE_MULTISAMPLE = 0x8d56,
// Uniforms
UNIFORM_BUFFER = 0x8a11,
UNIFORM_BUFFER_BINDING = 0x8a28,
UNIFORM_BUFFER_START = 0x8a29,
UNIFORM_BUFFER_SIZE = 0x8a2a,
MAX_VERTEX_UNIFORM_BLOCKS = 0x8a2b,
MAX_FRAGMENT_UNIFORM_BLOCKS = 0x8a2d,
MAX_COMBINED_UNIFORM_BLOCKS = 0x8a2e,
MAX_UNIFORM_BUFFER_BINDINGS = 0x8a2f,
MAX_UNIFORM_BLOCK_SIZE = 0x8a30,
MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS = 0x8a31,
MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS = 0x8a33,
UNIFORM_BUFFER_OFFSET_ALIGNMENT = 0x8a34,
ACTIVE_UNIFORM_BLOCKS = 0x8a36,
UNIFORM_TYPE = 0x8a37,
UNIFORM_SIZE = 0x8a38,
UNIFORM_BLOCK_INDEX = 0x8a3a,
UNIFORM_OFFSET = 0x8a3b,
UNIFORM_ARRAY_STRIDE = 0x8a3c,
UNIFORM_MATRIX_STRIDE = 0x8a3d,
UNIFORM_IS_ROW_MAJOR = 0x8a3e,
UNIFORM_BLOCK_BINDING = 0x8a3f,
UNIFORM_BLOCK_DATA_SIZE = 0x8a40,
UNIFORM_BLOCK_ACTIVE_UNIFORMS = 0x8a42,
UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES = 0x8a43,
UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER = 0x8a44,
UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER = 0x8a46,
// Sync objects
OBJECT_TYPE = 0x9112,
SYNC_CONDITION = 0x9113,
SYNC_STATUS = 0x9114,
SYNC_FLAGS = 0x9115,
SYNC_FENCE = 0x9116,
SYNC_GPU_COMMANDS_COMPLETE = 0x9117,
UNSIGNALED = 0x9118,
SIGNALED = 0x9119,
ALREADY_SIGNALED = 0x911a,
TIMEOUT_EXPIRED = 0x911b,
CONDITION_SATISFIED = 0x911c,
WAIT_FAILED = 0x911d,
SYNC_FLUSH_COMMANDS_BIT = 0x00000001,
// Miscellaneous constants
COLOR = 0x1800,
DEPTH = 0x1801,
STENCIL = 0x1802,
MIN = 0x8007,
MAX = 0x8008,
DEPTH_COMPONENT24 = 0x81a6,
STREAM_READ = 0x88e1,
STREAM_COPY = 0x88e2,
STATIC_READ = 0x88e5,
STATIC_COPY = 0x88e6,
DYNAMIC_READ = 0x88e9,
DYNAMIC_COPY = 0x88ea,
DEPTH_COMPONENT32F = 0x8cac,
DEPTH32F_STENCIL8 = 0x8cad,
INVALID_INDEX = 0xffffffff,
TIMEOUT_IGNORED = -1,
MAX_CLIENT_WAIT_TIMEOUT_WEBGL = 0x9247,
// Constants defined in WebGL extensions
// ANGLE_instanced_arrays
VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE = 0x88fe,
// WEBGL_debug_renderer_info
UNMASKED_VENDOR_WEBGL = 0x9245,
UNMASKED_RENDERER_WEBGL = 0x9246,
// EXT_texture_filter_anisotropic
MAX_TEXTURE_MAX_ANISOTROPY_EXT = 0x84ff,
TEXTURE_MAX_ANISOTROPY_EXT = 0x84fe,
// EXT_sRGB
SRGB_EXT = 0x8c40,
SRGB_ALPHA_EXT = 0x8c42,
SRGB8_ALPHA8_EXT = 0x8c43,
FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT = 0x8210,
// EXT_texture_norm16 - https://khronos.org/registry/webgl/extensions/EXT_texture_norm16/
R16_EXT = 0x822A,
RG16_EXT = 0x822C,
RGB16_EXT = 0x8054,
RGBA16_EXT = 0x805B,
R16_SNORM_EXT = 0x8F98,
RG16_SNORM_EXT = 0x8F99,
RGB16_SNORM_EXT = 0x8F9A,
RGBA16_SNORM_EXT = 0x8F9B,
// WEBGL_compressed_texture_s3tc (BC1, BC2, BC3)
COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83f0,
COMPRESSED_RGBA_S3TC_DXT1_EXT = 0x83f1,
COMPRESSED_RGBA_S3TC_DXT3_EXT = 0x83f2,
COMPRESSED_RGBA_S3TC_DXT5_EXT = 0x83f3,
// WEBGL_compressed_texture_s3tc_srgb (BC1, BC2, BC3 - SRGB)
COMPRESSED_SRGB_S3TC_DXT1_EXT = 0x8c4c,
COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT = 0x8c4d,
COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT = 0x8c4e,
COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT = 0x8c4f,
// WEBGL_compressed_texture_rgtc (BC4, BC5)
COMPRESSED_RED_RGTC1_EXT = 0x8dbb,
COMPRESSED_SIGNED_RED_RGTC1_EXT = 0x8dbc,
COMPRESSED_RED_GREEN_RGTC2_EXT = 0x8dbd,
COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT = 0x8dbe,
// WEBGL_compressed_texture_bptc (BC6, BC7)
COMPRESSED_RGBA_BPTC_UNORM_EXT = 0x8e8c,
COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT = 0x8e8d,
COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT = 0x8e8e,
COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT = 0x8e8f,
// WEBGL_compressed_texture_es3
COMPRESSED_R11_EAC = 0x9270,
COMPRESSED_SIGNED_R11_EAC = 0x9271,
COMPRESSED_RG11_EAC = 0x9272,
COMPRESSED_SIGNED_RG11_EAC = 0x9273,
COMPRESSED_RGB8_ETC2 = 0x9274,
COMPRESSED_RGBA8_ETC2_EAC = 0x9275,
COMPRESSED_SRGB8_ETC2 = 0x9276,
COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 0x9277,
COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9278,
COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9279,
// WEBGL_compressed_texture_pvrtc
COMPRESSED_RGB_PVRTC_4BPPV1_IMG = 0x8c00,
COMPRESSED_RGBA_PVRTC_4BPPV1_IMG = 0x8c02,
COMPRESSED_RGB_PVRTC_2BPPV1_IMG = 0x8c01,
COMPRESSED_RGBA_PVRTC_2BPPV1_IMG = 0x8c03,
// WEBGL_compressed_texture_etc1
COMPRESSED_RGB_ETC1_WEBGL = 0x8d64,
// WEBGL_compressed_texture_atc
COMPRESSED_RGB_ATC_WEBGL = 0x8c92,
COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL = 0x8c92,
COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL = 0x87ee,
// WEBGL_compressed_texture_astc
COMPRESSED_RGBA_ASTC_4x4_KHR = 0x93b0,
COMPRESSED_RGBA_ASTC_5x4_KHR = 0x93b1,
COMPRESSED_RGBA_ASTC_5x5_KHR = 0x93b2,
COMPRESSED_RGBA_ASTC_6x5_KHR = 0x93b3,
COMPRESSED_RGBA_ASTC_6x6_KHR = 0x93b4,
COMPRESSED_RGBA_ASTC_8x5_KHR = 0x93b5,
COMPRESSED_RGBA_ASTC_8x6_KHR = 0x93b6,
COMPRESSED_RGBA_ASTC_8x8_KHR = 0x93b7,
COMPRESSED_RGBA_ASTC_10x5_KHR = 0x93b8,
COMPRESSED_RGBA_ASTC_10x6_KHR = 0x93b9,
COMPRESSED_RGBA_ASTC_10x8_KHR = 0x93ba,
COMPRESSED_RGBA_ASTC_10x10_KHR = 0x93bb,
COMPRESSED_RGBA_ASTC_12x10_KHR = 0x93bc,
COMPRESSED_RGBA_ASTC_12x12_KHR = 0x93bd,
COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR = 0x93d0,
COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR = 0x93d1,
COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR = 0x93d2,
COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR = 0x93d3,
COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR = 0x93d4,
COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR = 0x93d5,
COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR = 0x93d6,
COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR = 0x93d7,
COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR = 0x93d8,
COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR = 0x93d9,
COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR = 0x93da,
COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR = 0x93db,
COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR = 0x93dc,
COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR = 0x93dd,
// WEBGL_depth_texture
UNSIGNED_INT_24_8_WEBGL = 0x84fa,
// OES_texture_half_float
HALF_FLOAT_OES = 0x8d61,
// WEBGL_color_buffer_float
RGBA32F_EXT = 0x8814,
RGB32F_EXT = 0x8815,
FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT = 0x8211,
UNSIGNED_NORMALIZED_EXT = 0x8c17,
// EXT_blend_minmax
MIN_EXT = 0x8007,
MAX_EXT = 0x8008,
// OES_standard_derivatives
FRAGMENT_SHADER_DERIVATIVE_HINT_OES = 0x8b8b,
// WEBGL_draw_buffers
COLOR_ATTACHMENT0_WEBGL = 0x8ce0,
COLOR_ATTACHMENT1_WEBGL = 0x8ce1,
COLOR_ATTACHMENT2_WEBGL = 0x8ce2,
COLOR_ATTACHMENT3_WEBGL = 0x8ce3,
COLOR_ATTACHMENT4_WEBGL = 0x8ce4,
COLOR_ATTACHMENT5_WEBGL = 0x8ce5,
COLOR_ATTACHMENT6_WEBGL = 0x8ce6,
COLOR_ATTACHMENT7_WEBGL = 0x8ce7,
COLOR_ATTACHMENT8_WEBGL = 0x8ce8,
COLOR_ATTACHMENT9_WEBGL = 0x8ce9,
COLOR_ATTACHMENT10_WEBGL = 0x8cea,
COLOR_ATTACHMENT11_WEBGL = 0x8ceb,
COLOR_ATTACHMENT12_WEBGL = 0x8cec,
COLOR_ATTACHMENT13_WEBGL = 0x8ced,
COLOR_ATTACHMENT14_WEBGL = 0x8cee,
COLOR_ATTACHMENT15_WEBGL = 0x8cef,
DRAW_BUFFER0_WEBGL = 0x8825,
DRAW_BUFFER1_WEBGL = 0x8826,
DRAW_BUFFER2_WEBGL = 0x8827,
DRAW_BUFFER3_WEBGL = 0x8828,
DRAW_BUFFER4_WEBGL = 0x8829,
DRAW_BUFFER5_WEBGL = 0x882a,
DRAW_BUFFER6_WEBGL = 0x882b,
DRAW_BUFFER7_WEBGL = 0x882c,
DRAW_BUFFER8_WEBGL = 0x882d,
DRAW_BUFFER9_WEBGL = 0x882e,
DRAW_BUFFER10_WEBGL = 0x882f,
DRAW_BUFFER11_WEBGL = 0x8830,
DRAW_BUFFER12_WEBGL = 0x8831,
DRAW_BUFFER13_WEBGL = 0x8832,
DRAW_BUFFER14_WEBGL = 0x8833,
DRAW_BUFFER15_WEBGL = 0x8834,
MAX_COLOR_ATTACHMENTS_WEBGL = 0x8cdf,
MAX_DRAW_BUFFERS_WEBGL = 0x8824,
// OES_vertex_array_object
VERTEX_ARRAY_BINDING_OES = 0x85b5,
// EXT_disjoint_timer_query
QUERY_COUNTER_BITS_EXT = 0x8864,
CURRENT_QUERY_EXT = 0x8865,
QUERY_RESULT_EXT = 0x8866,
QUERY_RESULT_AVAILABLE_EXT = 0x8867,
TIME_ELAPSED_EXT = 0x88bf,
TIMESTAMP_EXT = 0x8e28,
GPU_DISJOINT_EXT = 0x8fbb // A Boolean indicating whether or not the GPU performed any disjoint operation.
}; | the_stack |
namespace phasereditor2d.animations.ui.editors {
import FileUtils = colibri.ui.ide.FileUtils;
import controls = colibri.ui.controls;
export class AnimationsEditor extends colibri.ui.ide.FileEditor {
static ID = "phasereditor2d.animations.ui.editors.AnimationsEditor";
static _factory: colibri.ui.ide.ContentTypeEditorFactory;
private _gameCanvas: HTMLCanvasElement;
private _scene: AnimationsScene;
private _game: Phaser.Game;
private _sceneRead: boolean;
private _gameBooted: boolean;
private _overlayLayer: AnimationsOverlayLayer;
private _outlineProvider: AnimationsEditorOutlineProvider;
private _blocksProvider: AnimationsEditorBlocksProvider;
private _propertiesProvider: properties.AnimationsEditorPropertyProvider;
private _selectedAnimations: Phaser.Animations.Animation[];
private _currentDependenciesHash: string;
private _menuCreator: AnimationsEditorMenuCreator;
static getFactory() {
return this._factory ?? (this._factory = new colibri.ui.ide.ContentTypeEditorFactory("Animations Editor",
phasereditor2d.pack.core.contentTypes.CONTENT_TYPE_ANIMATIONS, () => new AnimationsEditor()
));
}
constructor() {
super(AnimationsEditor.ID, AnimationsEditor.getFactory());
this.addClass("AnimationsEditor");
this._outlineProvider = new AnimationsEditorOutlineProvider(this);
this._blocksProvider = new AnimationsEditorBlocksProvider(this);
this._propertiesProvider = new properties.AnimationsEditorPropertyProvider();
this._selectedAnimations = [];
}
protected async doSave() {
const animsData = this._scene.anims.toJSON();
for (const a of animsData.anims) {
if (a.delay === 0) delete a.delay;
if (a.repeat === 0) delete a.repeat;
if (a.repeatDelay === 0) delete a.repeatDelay;
if (!a.yoyo) delete a.yoyo;
if (!a.showOnStart) delete a.showOnStart;
if (!a.hideOnComplete) delete a.hideOnComplete;
if (!a.skipMissedFrames) delete a.skipMissedFrames;
delete a.duration;
for (const frame of a.frames) {
try {
const item = this.getScene().getMaker().getPackFinder().findAssetPackItem(frame.key);
if (item instanceof pack.core.ImageAssetPackItem) {
delete frame.frame;
}
} catch (e) {
// nothing
}
}
}
animsData["meta"] = AnimationsPlugin.getInstance().createAnimationsMetaData();
const content = JSON.stringify(animsData, null, 4);
await FileUtils.setFileString_async(this.getInput(), content);
this.setDirty(false);
}
openAddFramesDialog(cmd: "prepend" | "append"): void {
this.openSelectFramesDialog(async (frames) => {
const data = this.getScene().anims.toJSON();
const animData = data.anims.find(a => a.key === this.getSelection()[0].key);
for (const frame of frames) {
const frameData = {
key: frame.getPackItem().getKey()
};
if (!(frame.getPackItem() instanceof pack.core.ImageAssetPackItem)) {
frameData["frame"] = frame.getName();
}
if (cmd === "append") {
animData.frames.push(frameData as any);
} else {
animData.frames.splice(0, 0, frameData as any);
}
}
this.fullResetDataOperation(data);
});
}
protected async onEditorInputContentChangedByExternalEditor() {
console.log("onEditorInputContentChangedByExternalEditor");
const str = colibri.ui.ide.FileUtils.getFileString(this.getInput());
const data = JSON.parse(str);
this.fullReset(data, false);
}
private async fullReset(data: any, useAnimationIndexAsKey: boolean) {
const scene = this.getScene();
scene.removeAll();
const maker = scene.getMaker();
await maker.preload();
this._overlayLayer.setLoading(true);
await maker.updateSceneLoader(data, this._overlayLayer.createLoadingMonitor());
this._overlayLayer.setLoading(false);
this.reset(data, useAnimationIndexAsKey);
await this.updateDependenciesHash();
}
getScene() {
return this._scene;
}
getOverlayLayer() {
return this._overlayLayer;
}
selectAll() {
this.setSelection(this.getAnimations());
}
deleteSelected() {
const selectedFrames = new Set();
const selectedParentAnimations = new Set<Phaser.Animations.Animation>();
const selectedAnimations = new Set(this.getSelection().filter(a => a instanceof Phaser.Animations.Animation));
for (const obj of this.getSelection()) {
if (obj instanceof Phaser.Animations.AnimationFrame) {
const anim = AnimationsEditor.getAnimationOfAFrame(obj);
if (!selectedAnimations.has(anim)) {
selectedFrames.add(obj);
selectedParentAnimations.add(anim);
}
}
}
let exitMethod = false;
for (const anim of selectedParentAnimations) {
const found = anim.frames.find(frame => !selectedFrames.has(frame));
if (!found && !selectedAnimations.has(anim)) {
alert(`Cannot delete all frames of the animation "${anim.key}".`);
exitMethod = true;
}
}
if (exitMethod) {
return;
}
this.runOperation(() => {
this.setDirty(true);
for (const obj of this.getSelection()) {
if (obj instanceof Phaser.Animations.Animation) {
const sprite = this.getSpriteForAnimation(obj);
sprite.destroy();
this.getScene().anims.remove(obj.key);
}
}
for (const obj of this.getSelection()) {
if (obj instanceof Phaser.Animations.AnimationFrame) {
const anim = AnimationsEditor.getAnimationOfAFrame(obj);
anim.removeFrame(obj);
}
}
});
}
createEditorToolbar(parent: HTMLElement) {
const manager = new controls.ToolbarManager(parent);
manager.addCommand(CMD_ADD_ANIMATION);
return manager;
}
private openSelectFramesDialog(selectFramesCallback: (frames: pack.core.AssetPackImageFrame[]) => void) {
const viewer = new controls.viewers.TreeViewer(
"phasereditor2d.animations.ui.editors.AnimationsEditor.SelectFrames");
viewer.setLabelProvider(this._blocksProvider.getLabelProvider());
viewer.setContentProvider(this._blocksProvider.getContentProvider());
viewer.setCellRendererProvider(this._blocksProvider.getCellRendererProvider());
viewer.setTreeRenderer(this._blocksProvider.getTreeViewerRenderer(viewer));
viewer.setInput(this._blocksProvider.getInput());
viewer.expandRoots();
const dlg = new controls.dialogs.ViewerDialog(viewer, true);
dlg.setSize(window.innerWidth * 2 / 3, window.innerHeight * 2 / 3);
dlg.create();
dlg.setTitle("Select Frames");
dlg.addOpenButton("Select", sel => {
const frames: pack.core.AssetPackImageFrame[] = [];
const used = new Set();
for (const elem of sel) {
let elemFrames: pack.core.AssetPackImageFrame[];
if (elem instanceof pack.core.ImageFrameContainerAssetPackItem) {
elemFrames = elem.getFrames();
} else {
elemFrames = [elem];
}
for (const frame of elemFrames) {
const id = frame.getPackItem().getKey() + "$" + frame.getName();
if (used.has(id)) {
continue;
}
used.add(id);
frames.push(frame);
}
}
selectFramesCallback(frames);
});
dlg.addCancelButton();
}
openAddAnimationDialog() {
const dlg = new controls.dialogs.InputDialog();
dlg.create();
dlg.setTitle("New Animation");
dlg.setMessage("Enter the animation name");
dlg.setInputValidator(name => {
if (name.trim().length === 0) {
return false;
}
const found = this.getAnimation(name);
return found === null || found === undefined;
});
dlg.setInitialValue("animation");
dlg.validate();
dlg.setResultCallback(name => {
this.openSelectFramesDialog(frames => {
const animData = {
key: name,
frameRate: 24,
repeat: -1,
delay: 0,
frames: frames.map(frame => {
const packItem = frame.getPackItem();
if (packItem instanceof pack.core.ImageAssetPackItem) {
return {
key: packItem.getKey()
}
}
return {
key: packItem.getKey(),
frame: frame.getName()
}
})
}
const data = this.getScene().anims.toJSON();
data.anims.push(animData as any);
this.fullResetDataOperation(data, () => {
this.setSelection([this.getAnimation(name)]);
this.getElement().focus();
colibri.Platform.getWorkbench().setActivePart(this);
});
});
});
}
protected createPart(): void {
this.setLayoutChildren(false);
const container = document.createElement("div");
container.classList.add("AnimationsEditorContainer");
this.getElement().appendChild(container);
this._overlayLayer = new AnimationsOverlayLayer(this);
container.appendChild(this._overlayLayer.getCanvas());
const pool = Phaser.Display.Canvas.CanvasPool;
this._gameCanvas = pool.create2D(this.getElement(), 100, 100);
this._gameCanvas.style.position = "absolute";
this._gameCanvas.tabIndex = 1;
container.appendChild(this._gameCanvas);
this.createGame();
this.registerMenu();
this.registerDropListeners();
}
private registerDropListeners() {
this._gameCanvas.addEventListener("dragover", e => {
const dataArray = controls.Controls.getApplicationDragData();
for (const elem of dataArray) {
if (elem instanceof pack.core.ImageFrameContainerAssetPackItem
|| elem instanceof pack.core.AssetPackImageFrame) {
e.preventDefault();
return;
}
}
});
this._gameCanvas.addEventListener("drop", e => {
e.preventDefault();
const data = controls.Controls.getApplicationDragData();
const builder = new AnimationsBuilder(this, data);
builder.build();
});
}
private registerMenu() {
this._menuCreator = new AnimationsEditorMenuCreator(this);
this._gameCanvas.addEventListener("contextmenu", e => this.onMenu(e));
}
private onMenu(e: MouseEvent) {
e.preventDefault();
const menu = new controls.Menu();
this.fillMenu(menu);
menu.createWithEvent(e);
}
fillMenu(menu: controls.Menu) {
this._menuCreator.fillMenu(menu);
}
private createGame() {
this._scene = new AnimationsScene(this);
this._game = new Phaser.Game({
type: Phaser.CANVAS,
canvas: this._gameCanvas,
scale: {
mode: Phaser.Scale.NONE
},
render: {
pixelArt: true,
transparent: true
},
audio: {
noAudio: true
},
scene: this._scene,
});
this._sceneRead = false;
this._gameBooted = false;
(this._game.config as any).postBoot = () => {
// the scene is created just at this moment!
this.onGameBoot();
};
}
private async onGameBoot() {
this._gameBooted = true;
if (!this._sceneRead) {
await this.readScene();
}
this.layout();
this.refreshOutline();
this.setSelection([]);
}
private async readScene() {
const maker = this._scene.getMaker();
this._sceneRead = true;
try {
const file = this.getInput();
await FileUtils.preloadFileString(file);
const content = FileUtils.getFileString(file);
const data = JSON.parse(content);
this._overlayLayer.setLoading(true);
this._overlayLayer.render();
await maker.preload();
await maker.updateSceneLoader(data, this._overlayLayer.createLoadingMonitor());
const errors = [];
maker.createScene(data, errors);
this._overlayLayer.setLoading(false);
if (errors.length > 0) {
alert(errors.join("<br>"));
}
} catch (e) {
alert(e.message);
throw e;
}
this._currentDependenciesHash = await this.getScene().getMaker().buildDependenciesHash();
}
refreshOutline() {
this._outlineProvider.repaint();
}
private async refreshBlocks() {
await this._blocksProvider.preload();
this._blocksProvider.repaint();
}
repaint() {
this._overlayLayer.render();
}
layout() {
super.layout();
if (!this._game) {
return;
}
this._overlayLayer.resizeTo();
const parent = this._gameCanvas.parentElement;
const w = parent.clientWidth;
const h = parent.clientHeight;
this._game.scale.resize(w, h);
if (this._gameBooted) {
this._scene.getCamera().setSize(w, h);
}
}
onPartClosed() {
if (super.onPartClosed()) {
if (this._scene) {
this._scene.destroyGame();
}
return true;
}
return false;
}
onPartDeactivated() {
super.onPartActivated();
if (colibri.Platform.getWorkbench().getActiveEditor() !== this) {
if (this._game.loop) {
this._game.loop.stop();
}
}
}
async onPartActivated() {
super.onPartActivated();
if (this._gameBooted) {
if (!this._game.loop.running) {
this._game.loop.start(this._game.loop.callback);
}
this.updateIfDependenciesChanged();
this.refreshBlocks();
}
}
private async updateDependenciesHash() {
const hash = await this.getScene().getMaker().buildDependenciesHash();
this._currentDependenciesHash = hash;
}
private async updateIfDependenciesChanged() {
const hash = await this.getScene().getMaker().buildDependenciesHash();
if (hash !== this._currentDependenciesHash) {
this._currentDependenciesHash = hash;
const data = this.getScene().anims.toJSON();
this.fullReset(data, false);
}
}
getPropertyProvider() {
return this._propertiesProvider;
}
getEditorViewerProvider(key: string) {
if (key === outline.ui.views.OutlineView.EDITOR_VIEWER_PROVIDER_KEY) {
return this._outlineProvider;
} else if (key === blocks.ui.views.BlocksView.EDITOR_VIEWER_PROVIDER_KEY) {
return this._blocksProvider;
}
return null;
}
async fullResetDataOperation(data: Phaser.Types.Animations.JSONAnimations, op?: () => any) {
const before = AnimationsEditorSnapshotOperation.takeSnapshot(this);
await this.fullReset(data, false);
if (op) {
await op();
}
const after = AnimationsEditorSnapshotOperation.takeSnapshot(this);
this.getUndoManager().add(new AnimationsEditorSnapshotOperation(this, before, after, false));
}
runOperation(op: () => void, useAnimationIndexAsKey = false) {
const before = AnimationsEditorSnapshotOperation.takeSnapshot(this);
op();
const after = AnimationsEditorSnapshotOperation.takeSnapshot(this);
this.getUndoManager().add(new AnimationsEditorSnapshotOperation(this, before, after, useAnimationIndexAsKey));
}
private computeSelectedAnimations() {
const used = new Set();
const list: Phaser.Animations.Animation[] = [];
for (const obj of this.getSelection()) {
let anim: Phaser.Animations.Animation;
if (obj instanceof Phaser.Animations.Animation) {
anim = obj;
} else {
const frame = obj as Phaser.Animations.AnimationFrame;
anim = AnimationsEditor.getAnimationOfAFrame(frame);
}
if (anim && !used.has(anim)) {
used.add(anim);
list.push(anim);
}
}
return list;
}
getAnimations() {
return this._scene.anims["anims"].getArray();
}
getSpriteForAnimation(animation: Phaser.Animations.Animation) {
return this.getScene().getSprites().find(sprite => sprite.anims.currentAnim === animation);
}
setSelection(sel: any[], notify = true) {
super.setSelection(sel, notify);
this._selectedAnimations = this.computeSelectedAnimations();
}
getSelectedAnimations() {
return this._selectedAnimations;
}
getAnimation(key: string) {
return this.getScene().anims.get(key);
}
getAnimationFrame(animKey: string, frameTextureKey: string, frameTextureFrame: string) {
const anim = this.getAnimation(animKey);
if (anim) {
return anim.frames.find(f => f.textureKey === frameTextureKey && f.textureFrame === frameTextureFrame);
}
return undefined;
}
static getAnimationOfAFrame(obj: Phaser.Animations.AnimationFrame) {
return obj["__animation"] as Phaser.Animations.Animation;
}
static setAnimationToFrame(frame: Phaser.Animations.AnimationFrame, anim: Phaser.Animations.Animation) {
frame["__animation"] = anim;
}
reset(animsData: Phaser.Types.Animations.JSONAnimations, useAnimationIndexAsKey: boolean) {
let selectedIndexes: number[];
let selectedKeys: string[];
if (useAnimationIndexAsKey) {
const allAnimations = this.getAnimations();
selectedIndexes = this.getSelectedAnimations().map(anim => allAnimations.indexOf(anim));
} else {
selectedKeys = this.getSelectedAnimations().map(anim => anim.key);
}
const scene = this.getScene();
scene.removeAll();
scene.getMaker().createScene(animsData);
this.refreshOutline();
this.refreshBlocks();
if (useAnimationIndexAsKey) {
const allAnimations = this.getAnimations();
this.setSelection(selectedIndexes.map(i => allAnimations[i]));
} else {
const newAnimations = selectedKeys.map(key => {
return this.getAnimation(key);
}).filter(o => {
return o !== undefined && o !== null
});
this.setSelection(newAnimations);
}
// I do this here because the Inspector view at this moment
// is not listening the selection changes.
// It is like that because the active view is the Inspector
// view itself but the selection changed in the editor
colibri.inspector.ui.views.InspectorView.updateInspectorView(this.getSelection());
}
}
} | the_stack |
import TheTable from '../../vue/component/TheTable.vue'
// import TaskLoading from '../../vue/component/TaskLoading.vue'
import InputText from '../../vue/component/InputText.vue'
import ProgressBar from '../../vue/component/ProgressBar.vue'
// import { Event } from 'electron'
import { Vue, Component } from 'vue-property-decorator'
// import { generateObjectId } from '../common/object-id'
// import { ProgressInfo } from 'mishiro-core'
import getPath from '../common/get-path'
import { formatSize } from '../common/util'
import { searchResources } from './ipc-back'
import type { IDownloadProgress } from '@tybys/downloader'
import { showOpenDialog } from './ipc'
import { error } from './log'
import type { MishiroConfig } from '../main/config'
import configurer from './config'
const fs = window.node.fs
const path = window.node.path
const { shell } = window.node.electron
const { downloadDir } = getPath
const { Downloader, DownloadErrorCode } = window.node.tybys.downloader
const mishiroCore = window.node.mishiroCore
@Component({
components: {
TheTable,
ProgressBar,
InputText
}
})
export default class extends Vue {
autoDecLz4: boolean = true
dler: InstanceType<typeof Downloader> | null = null
downloadBtnDisable: boolean = false
queryString: string = ''
text: string = ''
data: ResourceData[] = []
selectedItem: ResourceData[] = []
current: number = 0
total: number = 0
page: number = 0
recordPerPage: number = 10
notDownloadedOnly: boolean = false
canDownloadRows: ResourceData[] = []
manualStop = false
get totalPage (): number {
const canDownload = this.canDownloadRows
if (!canDownload.length) return 0
return canDownload.length / this.recordPerPage === Math.floor(canDownload.length / this.recordPerPage) ? canDownload.length / this.recordPerPage - 1 : Math.floor(canDownload.length / this.recordPerPage)
}
created (): void {
this.event.$on('optionSaved', (options: MishiroConfig) => {
if (this.dler) {
this.dler.settings.agent = options.proxy ?? ''
}
})
}
// get canDownloadRows () {
// if (!this.notDownloadedOnly) return this.data
// return this.data.filter(row => !this.isDisabled(row))
// }
checkFile (data: ResourceData[]): ResourceData[] {
// return new Promise<any[]>((resolve, reject) => {
// const id = generateObjectId()
// ipcRenderer.once('checkFile', (_ev: Event, oid: string, notDownloaded: any[]) => {
// if (oid === id) {
// resolve(notDownloaded)
// } else {
// reject(new Error(`${id} !== ${oid}`))
// }
// })
// ipcRenderer.send('checkFile', id, data)
// })
return data.filter(row => !fs.existsSync(getPath.downloadDir(path.basename(row.name))))
}
isDisabled (row: ResourceData): boolean {
return fs.existsSync(downloadDir(path.basename(row.name)))
}
opendir (): void {
this.playSe(this.enterSe)
const dir = downloadDir()
if (!fs.existsSync(dir)) fs.mkdirsSync(dir)
if (window.node.process.platform === 'win32') {
shell.openExternal(dir).catch(err => {
console.error(err)
error(`HOME openExternal: ${err.stack}`)
})
} else {
shell.showItemInFolder(dir + '/.')
}
}
query (): void {
this.playSe(this.enterSe)
if (this.queryString === '') {
this.page = 0
this.data = []
this.canDownloadRows = []
// this.event.$emit('alert', this.$t('home.errorTitle'), this.$t('home.noEmptyString'))
} else {
searchResources(this.queryString.trim()).then(manifestArr => {
this.page = 0
this.data = manifestArr
if (!this.notDownloadedOnly) {
this.canDownloadRows = this.data
} else {
// this.checkFile(this.data).then((res) => {
// this.canDownloadRows = res
// }).catch(err => console.error(err))
this.canDownloadRows = this.checkFile(this.data)
}
}).catch(err => {
this.event.$emit('alert', this.$t('home.errorTitle'), err.message)
})
// ipcRenderer.send('queryManifest', this.queryString)
}
}
tableFormatter (key: string, value: any): string {
switch (key) {
case 'size':
return formatSize(value)
default:
return value
}
}
headerFormatter (key: string): string {
switch (key) {
case 'name': return this.$t('home.cName') as string
case 'hash': return this.$t('home.cHash') as string
case 'size': return this.$t('home.cSize') as string
default: return key
}
}
async decryptUSM (): Promise<void> {
const result = await showOpenDialog({
title: this.$t('home.usmbtn') as string,
defaultPath: downloadDir(),
filters: [
{ name: 'USM', extensions: ['usm'] },
{ name: 'All Files', extensions: ['*'] }
],
properties: ['openFile', 'multiSelections', 'showHiddenFiles', 'dontAddToRecent']
})
if (result.canceled) return
for (let i = 0; i < result.filePaths.length; i++) {
const usmFile = result.filePaths[i]
try {
await this.core.movie.demuxAsync(usmFile)
} catch (err) {
error(`USM: ${err.message}`)
}
}
}
filterOnClick (): void {
this.notDownloadedOnly = !this.notDownloadedOnly
if (!this.notDownloadedOnly) {
this.canDownloadRows = this.data
this.page = 0
} else {
// this.checkFile(this.data).then((res) => {
// this.canDownloadRows = res
// this.page = 0
// }).catch(err => console.error(err))
this.canDownloadRows = this.checkFile(this.data)
this.page = 0
}
}
tableChange (val: ResourceData[]): void {
this.selectedItem = val
}
stopDownload (): void {
this.playSe(this.cancelSe)
this.downloadBtnDisable = false
this.total = 0
this.current = 0
this.text = ''
this.manualStop = true
if (this.dler) {
this.dler.dispose()
this.dler = null
} else {
this.event.$emit('alert', this.$t('home.errorTitle'), this.$t('home.noTask'))
}
}
downloadSelectedItem (): void {
this.playSe(this.enterSe)
if (!navigator.onLine) {
this.event.$emit('alert', this.$t('home.errorTitle'), this.$t('home.noNetwork'))
return
}
const tasks = this.selectedItem.slice(0)
if (tasks.length <= 0) {
this.event.$emit('alert', this.$t('home.errorTitle'), this.$t('home.noEmptyDownload'))
return
}
this.downloadBtnDisable = true
let completeCount = 0
let start = 0
const createCompleteHandler = (row: ResourceData, compressed: boolean, p: string, suffix: string) => () => {
const ext = path.extname((row && row.name) || '')
if (compressed) {
if (this.autoDecLz4) {
if (fs.existsSync(p)) {
mishiroCore.util.Lz4.decompress(p, suffix)
fs.removeSync(p)
this.event.$emit('completeTask', row.hash)
} else {
this.event.$emit('completeTask', row.hash, false)
}
} else {
if (fs.existsSync(p)) {
fs.renameSync(p, p + ext)
this.event.$emit('completeTask', row.hash)
} else {
this.event.$emit('completeTask', row.hash, false)
}
}
} else {
if (fs.existsSync(p)) {
this.event.$emit('completeTask', row.hash)
} else {
this.event.$emit('completeTask', row.hash, false)
}
}
}
const onStart = (name: string) => () => {
this.current = 0
this.total = 100 * completeCount / tasks.length
this.text = name
}
const updateProgress = (prog: IDownloadProgress): void => {
const name = path.basename(prog.path)
this.text = `${name} ${Math.ceil(prog.completedLength / 1024)}/${Math.ceil(prog.totalLength / 1024)} KB`
this.current = prog.percent
this.total = 100 * completeCount / tasks.length + prog.percent / tasks.length
}
const onProgress = (prog: IDownloadProgress): void => {
if (prog.completedLength === 0 || prog.percent === 100) {
updateProgress(prog)
} else {
const now = Date.now()
if ((now - start) > mishiroCore.config.getCallbackInterval()) {
start = now
updateProgress(prog)
}
}
}
this.dler = new Downloader()
this.dler.settings.agent = configurer.get('proxy') ?? ''
this.dler.settings.headers = {
'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 7.0; Nexus 42 Build/XYZZ1Y)',
'X-Unity-Version': '2018.3.8f1',
'Accept-Encoding': 'gzip',
Connection: 'Keep-Alive'
}
const targetDir = downloadDir()
for (let i = 0; i < tasks.length; i++) {
const t = tasks[i]
const { name, hash } = t
const ext = path.extname(name)
const basename = path.basename(name, (ext !== '.acb' && ext !== '.awb' && ext !== '.usm') ? ext : '')
// const p = path.join(targetDir, basename)
let url: string
if (ext === '.acb' || ext === '.awb') {
url = mishiroCore.Downloader.getUrl(mishiroCore.ResourceType.SOUND, hash)
const download = this.dler.add(url, { dir: targetDir, out: basename })
download.on('activate', onStart(path.basename(download.path)))
download.once('complete', createCompleteHandler(t, false, download.path, ''))
download.on('progress', onProgress)
} else if (ext === '.unity3d') {
url = mishiroCore.Downloader.getUrl(mishiroCore.ResourceType.ASSET, hash)
const download = this.dler.add(url, { dir: targetDir, out: basename })
download.on('activate', onStart(path.basename(download.path)))
download.once('complete', createCompleteHandler(t, true, download.path, '.unity3d'))
download.on('progress', onProgress)
} else if (ext === '.bdb' || ext === '.mdb') {
url = mishiroCore.Downloader.getUrl(mishiroCore.ResourceType.DATABASE, hash)
const download = this.dler.add(url, { dir: targetDir, out: basename })
download.on('activate', onStart(path.basename(download.path)))
download.once('complete', createCompleteHandler(t, true, download.path, ext))
download.on('progress', onProgress)
} else if (ext === '.usm') {
url = mishiroCore.Downloader.getUrl(mishiroCore.ResourceType.MOVIE, hash)
const download = this.dler.add(url, { dir: targetDir, out: basename })
download.on('activate', onStart(path.basename(download.path)))
download.once('complete', createCompleteHandler(t, false, download.path, ''))
download.on('progress', onProgress)
} else {
continue
}
}
const downloader = this.dler
this.dler.on('done', (_download) => {
this.current = 0
this.text = ''
completeCount++
this.total = 100 * completeCount / tasks.length
if (downloader.countWaiting() <= 0 && downloader.countActive() <= 0) {
this.downloadBtnDisable = false
this.total = 0
const errorList = downloader.tellFailed().filter(d => (d.error != null) && (d.error.code !== DownloadErrorCode.ABORT))
if (errorList.length) this.event.$emit('alert', this.$t('home.download'), `Failed: ${errorList.length}`)
downloader.dispose()
this.dler = null
}
})
}
onMouseWheel (e: WheelEvent): void {
if (e.deltaY < 0) {
this.previousPage()
} else {
this.nextPage()
}
}
previousPage (): void {
this.page !== 0 ? this.page -= 1 : this.page = this.totalPage
}
nextPage (): void {
this.page !== this.totalPage ? this.page += 1 : this.page = 0
}
mounted (): void {
this.$nextTick(() => {
this.event.$on('enterKey', (block: string) => {
if (block === 'home') {
this.query()
}
})
})
}
} | the_stack |
import * as React from 'react';
import lodash from 'lodash';
import {
Icon,
Trash,
ArrowUp,
ArrowDown,
Keyboard,
Plus,
Stopwatch,
ButtonDown,
ButtonUp,
ButtonDownUp,
} from '@lunchpad/icons';
// TODO: Proper export those from a maybe ui package
import Pill from '../../pill';
import List, { ListItem } from './list';
import { Split, Child, VerticalPipe, Row, IconButton, Tooltip, Switch, COLOR_REDISH } from '@lunchpad/base';
import { useMouseHovered } from 'react-use';
import { ChangeTypeMenu } from './changeTypeMenu';
import { AddKeystrokeMenu } from './addKeystrokeMenu'
import { HotkeyKeystrokeSimpleElement } from './simple'
import { HotkeyKeystrokeDelayElement } from './delay'
import { HotkeyKeystrokeStringElement } from './string'
import { motion, AnimatePresence } from 'framer-motion';
import { Hotkey, HotkeyKeystroke, HotkeyKeystrokeType, HotkeyKeystrokeSimple, HotkeyKeystrokeEvent, HotkeyKeystrokeDelay, HotkeyKeystrokeString } from '../classes';
interface IHotkeyPill {
action: Hotkey;
expanded?: boolean;
showMenu?: (x: number, y: number, component: JSX.Element) => void;
closeMenu?: (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;
onChange?: (action: Hotkey) => void;
onRemove?: (id: string) => void;
onMoveUp: (id: string) => void;
onMoveDown: (id: string) => void;
}
interface IHotkeyKeystrokePill {
keystroke: HotkeyKeystroke
showMenu?: (x: number, y: number, component: JSX.Element) => void;
closeMenu?: (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;
onChange?: (keystroke: HotkeyKeystroke) => void;
onRemove?: (id: string) => void
onMoveUp?: (id: string) => void
onMoveDown?: (id: string) => void
}
const TypeIcons = {
[HotkeyKeystrokeType.SimpleDown]: <Icon icon={ButtonDown} />,
[HotkeyKeystrokeType.SimpleUp]: <Icon icon={ButtonUp} />,
[HotkeyKeystrokeType.SimpleDownUp]: <Icon icon={ButtonDownUp} />,
[HotkeyKeystrokeType.Delay]: <Icon icon={Stopwatch} />,
[HotkeyKeystrokeType.String]: <Icon icon={Keyboard} />,
}
const HotkeyKeystrokePill: React.SFC<IHotkeyKeystrokePill> = ({ keystroke, showMenu, closeMenu, onMoveUp, onMoveDown, onRemove, onChange }) => {
const ref = React.useRef(null);
const mouse = useMouseHovered(ref, { whenHovered: true })
const changeType = () => {
showMenu(mouse.posX, mouse.posY, (
<ChangeTypeMenu
onClose={closeMenu}
onSelect={(id) => {
const s = keystroke as HotkeyKeystrokeSimple
onChange(new HotkeyKeystrokeSimple(s.key, s.modifier, id as HotkeyKeystrokeEvent, s.id))
//setStroke(new HotkeyKeystrokeSimple(s.key, s.modifier, id as HotkeyKeystrokeEvent, s.id))
}}
/>
))
}
const change = (stroke: HotkeyKeystroke) => {
onChange(stroke);
}
return (
<ListItem>
<Split direction="row">
<Child padding={"0 1rem 0 0"}>
{((keystroke.type === HotkeyKeystrokeType.SimpleDown) ||
(keystroke.type === HotkeyKeystrokeType.SimpleUp) ||
(keystroke.type === HotkeyKeystrokeType.SimpleDownUp)) ? (
<Tooltip
title="Change the type of this keyboard event"
>
<div ref={ref}>
<IconButton
icon={TypeIcons[keystroke.type]}
onClick={() => changeType()}
/>
</div>
</Tooltip>
) : TypeIcons[keystroke.type]
}
</Child>
{((keystroke.type === HotkeyKeystrokeType.SimpleDown) ||
(keystroke.type === HotkeyKeystrokeType.SimpleUp) ||
(keystroke.type === HotkeyKeystrokeType.SimpleDownUp)) && (
<Child grow padding="0 1rem 0 0">
<HotkeyKeystrokeSimpleElement
keystroke={keystroke as HotkeyKeystrokeSimple}
onChange={change}
/>
</Child>
)}
{keystroke.type === HotkeyKeystrokeType.Delay && (
<Child grow padding="0 1rem 0 0">
<HotkeyKeystrokeDelayElement
keystroke={keystroke as HotkeyKeystrokeDelay}
onChange={change}
/>
</Child>
)}
{keystroke.type === HotkeyKeystrokeType.String && (
<Child grow padding="0 1rem 0 0">
<HotkeyKeystrokeStringElement
keystroke={keystroke as HotkeyKeystrokeString}
onChange={change}
/>
</Child>
)}
<Child padding="0">
<IconButton
disabled={!onMoveUp}
icon={<Icon icon={ArrowUp} />}
onClick={() => onMoveUp(keystroke.id)}
/>
</Child>
<Child padding="0 0 0 1rem">
<IconButton
disabled={!onMoveDown}
icon={<Icon icon={ArrowDown} />}
onClick={() => onMoveDown(keystroke.id)}
/>
</Child>
<Child padding="0 1rem 0 1rem">
<VerticalPipe />
</Child>
<Child padding="0"></Child>
<Child padding="0">
<Tooltip title="Removes the keyboard event from the list! ITS GONE!" >
<IconButton hover={COLOR_REDISH} onClick={() => onRemove(keystroke.id)} icon={<Icon icon={Trash} />} />
</Tooltip>
</Child>
</Split>
</ListItem>
)
}
const KeystrokeHeaderMenu = ({ showMenu, closeMenu, keystrokes, onAdd }) => {
const ref = React.useRef(null);
const mouse = useMouseHovered(ref, { whenHovered: true })
const onAddClick = () => {
showMenu(mouse.posX, mouse.posY, (
<AddKeystrokeMenu
onClose={closeMenu}
onSelect={onAdd}
/>
))
}
return (
<Split direction={'row'}>
<Child grow>
{keystrokes > 0 ? keystrokes : 'No'} Keyboard event(s)
</Child>
<Child padding="1rem">
<div ref={ref}>
<Tooltip title="Add a keyboard event to the list.">
<IconButton icon={<Icon icon={Plus} />} onClick={() => onAddClick()} />
</Tooltip>
</div>
</Child>
</Split>
)
}
export const HotkeyPill: React.SFC<IHotkeyPill> = (props) => {
const [showBody, setExpanded] = React.useState<boolean>(props.expanded);
const setProp = (prop) => {
props.onChange(Object.assign(props.action, prop))
}
const moveKeystrokeUp = (id: string) => {
const idx = lodash.findIndex(props.action.keystrokes, a => a.id === id);
const temp = props.action.keystrokes[idx];
props.action.keystrokes[idx] = props.action.keystrokes[idx - 1];
props.action.keystrokes[idx - 1] = temp;
setProp({ keystrokes: [...props.action.keystrokes] })
};
const moveKeystrokeDown = (id: string) => {
const idx = lodash.findIndex(props.action.keystrokes, a => a.id === id);
const temp = props.action.keystrokes[idx];
props.action.keystrokes[idx] = props.action.keystrokes[idx + 1];
props.action.keystrokes[idx + 1] = temp;
setProp({ keystrokes: [...props.action.keystrokes] })
};
const removeKeystroke = (id: string) => setProp({ keystrokes: [...props.action.keystrokes.filter(k => k.id !== id)] })
const addKeystroke = (id: string) => {
const type = id as HotkeyKeystrokeType
if (type === HotkeyKeystrokeType.Delay) setProp({ keystrokes: [...props.action.keystrokes, new HotkeyKeystrokeDelay(100) ]})
if (type === HotkeyKeystrokeType.String) setProp({ keystrokes: [...props.action.keystrokes, new HotkeyKeystrokeString(":)", 10) ]})
if (type === HotkeyKeystrokeType.SimpleDown) setProp({ keystrokes: [...props.action.keystrokes, new HotkeyKeystrokeSimple("enter", [], HotkeyKeystrokeEvent.KeyDown) ]})
if (type === HotkeyKeystrokeType.SimpleUp) setProp({ keystrokes: [...props.action.keystrokes, new HotkeyKeystrokeSimple("enter", [], HotkeyKeystrokeEvent.KeyUp) ]})
if (type === HotkeyKeystrokeType.SimpleDownUp) setProp({ keystrokes: [...props.action.keystrokes, new HotkeyKeystrokeSimple("enter", [], HotkeyKeystrokeEvent.KeyDownUp) ]})
}
const updateKeystroke = (stroke: HotkeyKeystroke) => {
setProp({ keystrokes: props.action.keystrokes.map(s => (s.id === stroke.id ? stroke : s))})
}
const Expanded = (
<Split direction="row">
<Child grow whiteSpace="nowrap" padding="0 1rem 0 0"><div style={{textOverflow: "ellipsis", overflow: "hidden"}}>Hotkey sequence: {props.action.keystrokes.length} Keystroke(s)</div></Child>
</Split>
)
return (
<Pill
isExpanded={showBody}
icon={<Icon icon={Keyboard} />}
expanded={Expanded}
collapsed={Expanded}
onRemove={() => props.onRemove(props.action.id)}
onMoveUp={props.onMoveUp ? () => props.onMoveUp(props.action.id) : null}
onMoveDown={props.onMoveDown ? () => props.onMoveDown(props.action.id) : null}
onExpand={() => setExpanded(true)}
onCollapse={() => setExpanded(false)}
>
<Split>
<Row title="">
<Split direction="row">
<Child padding="0 1rem 0 0">
<Switch value={props.action.wait} onChange={wait => setProp({ wait })} />
</Child>
<Child grow>
<span>Await execution of this action</span>
</Child>
</Split>
</Row>
<Row title="">
<Split direction="row">
<Child padding="0 1rem 0 0">
<Tooltip
title="Releases all keys that might still be in pressed state after this action ends"
>
<Switch value={props.action.restoreAllAtEnd} onChange={restoreAllAtEnd => setProp({ restoreAllAtEnd })} />
</Tooltip>
</Child>
<Child grow>
<span>Restore key states when action ends</span>
</Child>
</Split>
</Row>
<Child>
<List
menu={
<KeystrokeHeaderMenu
closeMenu={props.closeMenu}
showMenu={props.showMenu}
keystrokes={props.action.keystrokes.length}
onAdd={addKeystroke}
/>
}
>
<AnimatePresence>
{props.action.keystrokes.map((s,i) => (
<motion.div
positionTransition={{
type: 'spring',
damping: 30,
stiffness: 200
}}
initial={{ opacity: 0, translateX: -100 }}
animate={{ opacity: 1, translateX: 0 }}
exit={{ opacity: 0, translateX: 100 }}
key={s.id}
>
<HotkeyKeystrokePill
key={s.id}
showMenu={props.showMenu}
closeMenu={props.closeMenu}
keystroke={s}
onMoveUp={i !== 0 ? () => moveKeystrokeUp(s.id) : null}
onMoveDown={i < props.action.keystrokes.length - 1 ? () => moveKeystrokeDown(s.id) : null}
onRemove={removeKeystroke}
onChange={updateKeystroke}
/>
</motion.div>
))}
</AnimatePresence>
</List>
</Child>
</Split>
</Pill>
)
};
HotkeyPill.defaultProps = {
expanded: false,
onChange: () => {},
onRemove: () => {}
}; | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement } from "../shared";
/**
* Statement provider for service [ce](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awscostexplorerservice.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Ce extends PolicyStatement {
public servicePrefix = 'ce';
/**
* Statement provider for service [ce](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awscostexplorerservice.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
constructor (sid?: string) {
super(sid);
}
/**
* Grants permission to create a new Anomaly Monitor
*
* Access Level: Write
*
* https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_CreateAnomalyMonitor.html
*/
public toCreateAnomalyMonitor() {
return this.to('CreateAnomalyMonitor');
}
/**
* Grants permission to create a new Anomaly Subscription
*
* Access Level: Write
*
* https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_CreateAnomalySubscription.html
*/
public toCreateAnomalySubscription() {
return this.to('CreateAnomalySubscription');
}
/**
* Grants permission to create a new Cost Category with the requested name and rules
*
* Access Level: Write
*
* https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_CreateCostCategoryDefinition.html
*/
public toCreateCostCategoryDefinition() {
return this.to('CreateCostCategoryDefinition');
}
/**
* Grants permission to create Reservation expiration alerts
*
* Access Level: Write
*
* https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-permissions-ref.html
*/
public toCreateNotificationSubscription() {
return this.to('CreateNotificationSubscription');
}
/**
* Grants permission to create Cost Explorer Reports
*
* Access Level: Write
*
* https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-permissions-ref.html
*/
public toCreateReport() {
return this.to('CreateReport');
}
/**
* Grants permission to delete an Anomaly Monitor
*
* Access Level: Write
*
* https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_DeleteAnomalyMonitor.html
*/
public toDeleteAnomalyMonitor() {
return this.to('DeleteAnomalyMonitor');
}
/**
* Grants permission to delete an Anomaly Subscription
*
* Access Level: Write
*
* https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_DeleteAnomalySubscription.html
*/
public toDeleteAnomalySubscription() {
return this.to('DeleteAnomalySubscription');
}
/**
* Grants permission to delete a Cost Category
*
* Access Level: Write
*
* https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_DeleteCostCategoryDefinition.html
*/
public toDeleteCostCategoryDefinition() {
return this.to('DeleteCostCategoryDefinition');
}
/**
* Grants permission to delete Reservation expiration alerts
*
* Access Level: Write
*
* https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-permissions-ref.html
*/
public toDeleteNotificationSubscription() {
return this.to('DeleteNotificationSubscription');
}
/**
* Grants permission to delete Cost Explorer Reports
*
* Access Level: Write
*
* https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-permissions-ref.html
*/
public toDeleteReport() {
return this.to('DeleteReport');
}
/**
* Grants permission to retrieve descriptions such as the name, ARN, rules, definition, and effective dates of a Cost Category
*
* Access Level: Read
*
* https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_DescribeCostCategoryDefinition.html
*/
public toDescribeCostCategoryDefinition() {
return this.to('DescribeCostCategoryDefinition');
}
/**
* Grants permission to view Reservation expiration alerts
*
* Access Level: Read
*
* https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-permissions-ref.html
*/
public toDescribeNotificationSubscription() {
return this.to('DescribeNotificationSubscription');
}
/**
* Grants permission to view Cost Explorer Reports page
*
* Access Level: Read
*
* https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-permissions-ref.html
*/
public toDescribeReport() {
return this.to('DescribeReport');
}
/**
* Grants permission to retrieve anomalies
*
* Access Level: Read
*
* https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetAnomalies.html
*/
public toGetAnomalies() {
return this.to('GetAnomalies');
}
/**
* Grants permission to query Anomaly Monitors
*
* Access Level: Read
*
* https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetAnomalyMonitors.html
*/
public toGetAnomalyMonitors() {
return this.to('GetAnomalyMonitors');
}
/**
* Grants permission to query Anomaly Subscriptions
*
* Access Level: Read
*
* https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetAnomalySubscriptions.html
*/
public toGetAnomalySubscriptions() {
return this.to('GetAnomalySubscriptions');
}
/**
* Grants permission to retrieve the cost and usage metrics for your account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetCostAndUsage.html
*/
public toGetCostAndUsage() {
return this.to('GetCostAndUsage');
}
/**
* Grants permission to retrieve the cost and usage metrics with resources for your account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetCostAndUsageWithResources.html
*/
public toGetCostAndUsageWithResources() {
return this.to('GetCostAndUsageWithResources');
}
/**
* Grants permission to query Cost Catagory names and values for a specified time period
*
* Access Level: Read
*
* https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetCostCategories.html
*/
public toGetCostCategories() {
return this.to('GetCostCategories');
}
/**
* Grants permission to retrieve a cost forecast for a forecast time period
*
* Access Level: Read
*
* https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetCostForecast.html
*/
public toGetCostForecast() {
return this.to('GetCostForecast');
}
/**
* Grants permission to retrieve all available filter values for a filter for a period of time
*
* Access Level: Read
*
* https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetDimensionValues.html
*/
public toGetDimensionValues() {
return this.to('GetDimensionValues');
}
/**
* Grants permission to view Cost Explorer Preferences page
*
* Access Level: Read
*
* https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-permissions-ref.html
*/
public toGetPreferences() {
return this.to('GetPreferences');
}
/**
* Grants permission to retrieve the reservation coverage for your account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetReservationCoverage.html
*/
public toGetReservationCoverage() {
return this.to('GetReservationCoverage');
}
/**
* Grants permission to retrieve the reservation recommendations for your account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetReservationPurchaseRecommendation.html
*/
public toGetReservationPurchaseRecommendation() {
return this.to('GetReservationPurchaseRecommendation');
}
/**
* Grants permission to retrieve the reservation utilization for your account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetReservationUtilization.html
*/
public toGetReservationUtilization() {
return this.to('GetReservationUtilization');
}
/**
* Grants permission to retrieve the rightsizing recommendations for your account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetRightsizingRecommendation.html
*/
public toGetRightsizingRecommendation() {
return this.to('GetRightsizingRecommendation');
}
/**
* Grants permission to retrieve the Savings Plans coverage for your account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetSavingsPlansCoverage.html
*/
public toGetSavingsPlansCoverage() {
return this.to('GetSavingsPlansCoverage');
}
/**
* Grants permission to retrieve the Savings Plans recommendations for your account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetSavingsPlansPurchaseRecommendation.html
*/
public toGetSavingsPlansPurchaseRecommendation() {
return this.to('GetSavingsPlansPurchaseRecommendation');
}
/**
* Grants permission to retrieve the Savings Plans utilization for your account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetSavingsPlansUtilization.html
*/
public toGetSavingsPlansUtilization() {
return this.to('GetSavingsPlansUtilization');
}
/**
* Grants permission to retrieve the Savings Plans utilization details for your account
*
* Access Level: Read
*
* https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetSavingsPlansUtilizationDetails.html
*/
public toGetSavingsPlansUtilizationDetails() {
return this.to('GetSavingsPlansUtilizationDetails');
}
/**
* Grants permission to query tags for a specified time period
*
* Access Level: Read
*
* https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetTags.html
*/
public toGetTags() {
return this.to('GetTags');
}
/**
* Grants permission to retrieve a usage forecast for a forecast time period
*
* Access Level: Read
*
* https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetUsageForecast.html
*/
public toGetUsageForecast() {
return this.to('GetUsageForecast');
}
/**
* Grants permission to retrieve names, ARN, and effective dates for all Cost Categories
*
* Access Level: List
*
* https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_ListCostCategoryDefinitions.html
*/
public toListCostCategoryDefinitions() {
return this.to('ListCostCategoryDefinitions');
}
/**
* Grants permission to provide feedback on detected anomalies
*
* Access Level: Write
*
* https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_ProvideAnomalyFeedback.html
*/
public toProvideAnomalyFeedback() {
return this.to('ProvideAnomalyFeedback');
}
/**
* Grants permission to update an existing Anomaly Monitor
*
* Access Level: Write
*
* https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_UpdateAnomalyMonitor.html
*/
public toUpdateAnomalyMonitor() {
return this.to('UpdateAnomalyMonitor');
}
/**
* Grants permission to update an existing Anomaly Subscription
*
* Access Level: Write
*
* https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_UpdateAnomalySubscription.html
*/
public toUpdateAnomalySubscription() {
return this.to('UpdateAnomalySubscription');
}
/**
* Grants permission to update an existing Cost Category
*
* Access Level: Write
*
* https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_UpdateCostCategoryDefinition.html
*/
public toUpdateCostCategoryDefinition() {
return this.to('UpdateCostCategoryDefinition');
}
/**
* Grants permission to update Reservation expiration alerts
*
* Access Level: Write
*
* https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-permissions-ref.html
*/
public toUpdateNotificationSubscription() {
return this.to('UpdateNotificationSubscription');
}
/**
* Grants permission to edit Cost Explorer Preferences page
*
* Access Level: Write
*
* https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-permissions-ref.html
*/
public toUpdatePreferences() {
return this.to('UpdatePreferences');
}
/**
* Grants permission to update Cost Explorer Reports
*
* Access Level: Write
*
* https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-permissions-ref.html
*/
public toUpdateReport() {
return this.to('UpdateReport');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"CreateAnomalyMonitor",
"CreateAnomalySubscription",
"CreateCostCategoryDefinition",
"CreateNotificationSubscription",
"CreateReport",
"DeleteAnomalyMonitor",
"DeleteAnomalySubscription",
"DeleteCostCategoryDefinition",
"DeleteNotificationSubscription",
"DeleteReport",
"ProvideAnomalyFeedback",
"UpdateAnomalyMonitor",
"UpdateAnomalySubscription",
"UpdateCostCategoryDefinition",
"UpdateNotificationSubscription",
"UpdatePreferences",
"UpdateReport"
],
"Read": [
"DescribeCostCategoryDefinition",
"DescribeNotificationSubscription",
"DescribeReport",
"GetAnomalies",
"GetAnomalyMonitors",
"GetAnomalySubscriptions",
"GetCostAndUsage",
"GetCostAndUsageWithResources",
"GetCostCategories",
"GetCostForecast",
"GetDimensionValues",
"GetPreferences",
"GetReservationCoverage",
"GetReservationPurchaseRecommendation",
"GetReservationUtilization",
"GetRightsizingRecommendation",
"GetSavingsPlansCoverage",
"GetSavingsPlansPurchaseRecommendation",
"GetSavingsPlansUtilization",
"GetSavingsPlansUtilizationDetails",
"GetTags",
"GetUsageForecast"
],
"List": [
"ListCostCategoryDefinitions"
]
};
} | the_stack |
import Zip from "adm-zip";
import { basename, join, extname } from "path";
import { readJSON, readdir, writeJson, stat, mkdir, pathExists, copy, pathExistsSync } from "fs-extra";
import { Undefinable } from "../../../../shared/types";
import * as React from "react";
import * as ReactDOM from "react-dom";
import { Dialog, Classes, Button, Tooltip, Position, Divider, Callout, Intent, ButtonGroup, Alignment, ProgressBar } from "@blueprintjs/core";
import { Editor } from "../../editor";
import { Icon } from "../../gui/icon";
import { Wizard } from "../../gui/wizard";
import { Overlay } from "../../gui/overlay";
import { Alert } from "../../gui/alert";
import { Tools } from "../../tools/tools";
import { Project } from "../project";
import { IWorkSpace } from "../typings";
import { WorkspaceWizard0, IWorkspaceTemplate } from "./wizard-workspace0";
import { WorkspaceWizard1 } from "./wizard-workspace1";
import { WorkSpace } from "../workspace";
export interface IWelcomeDialogProps {
/**
* Defines the reference to the editor.
*/
editor: Editor;
/**
* Sets wether or not the dialog can be closed.
*/
canClose: boolean;
}
export interface IWelcomeDialogState {
/**
* Defines a progress (in [0, 1]) of the downloading process.
*/
downloadProgress?: Undefinable<number>;
}
export class WelcomeDialog extends React.Component<IWelcomeDialogProps, IWelcomeDialogState> {
/**
* Shows the welcome wizard.
*/
public static Show(editor: Editor, canClose: boolean): void {
ReactDOM.render(<WelcomeDialog editor={editor} canClose={canClose} />, document.getElementById("BABYLON-EDITOR-OVERLAY"));
}
private _wizard0: WorkspaceWizard0;
private _wizard1: WorkspaceWizard1;
private _refHandler = {
getWizard0: (ref: WorkspaceWizard0) => ref && (this._wizard0 = ref),
getWizard1: (ref: WorkspaceWizard1) => ref && (this._wizard1 = ref),
};
/**
* Constructor.
* @param props the component's props.
*/
public constructor(props: IWelcomeDialogProps) {
super(props);
this.state = { };
}
/**
* Renders the component.
*/
public render(): React.ReactNode {
let wizard: React.ReactNode;
if (!this.state.downloadProgress) {
wizard = (
<Wizard
key="wizard"
height={400}
onFinish={() => this._handleFinishWizard()}
steps={[{
title: "New Workspace",
element: <WorkspaceWizard0 ref={this._refHandler.getWizard0} />
}, {
title: "Workspace Settings",
element: <WorkspaceWizard1 ref={this._refHandler.getWizard1} />
}]}
></Wizard>
);
} else if (this.state.downloadProgress < 1) {
wizard = (
<>
<p>Downloading template... {(this.state.downloadProgress * 100).toFixed(0)}%</p>
<ProgressBar value={this.state.downloadProgress} />
</>
)
} else {
wizard = <p>Extracting...</p>
}
return (
<Dialog
key="welcome-wizard-dialog"
isOpen={true}
usePortal={true}
canOutsideClickClose={false}
canEscapeKeyClose={false}
title="Welcome"
icon={<Icon src="logo-babylon.svg" style={{ width: "32px", height: "32px", filter: "unset" }} />}
className={Classes.DARK}
enforceFocus={true}
style={{ width: "1000px" }}
onClose={() => this.props.canClose && this._handleClose()}
>
<div className={Classes.DIALOG_BODY}>
<Callout title="Open an existing project" icon="info-sign">
<ButtonGroup vertical={true} fill={true} alignText={Alignment.LEFT}>
<Button key="open-workspace" id="welcome-open-workspace" icon={<Icon src="workspace.svg" />} onClick={() => this._handleOpenWorkspace()}>Open Workspace...</Button>
<Button key="open-preferences" id="welcome-open-preferences" icon={<Icon src="wrench.svg" />} onClick={() => this._handleOpenPreferences()}>Preferences...</Button>
</ButtonGroup>
</Callout>
<Divider />
<Callout title="Recent projects" intent={Intent.PRIMARY} icon="document-open">
{this._getRecentProjects() ?? <p><strong>No recent project.</strong></p>}
</Callout>
<Divider />
<Callout title="Create a new workspace" intent={Intent.SUCCESS} icon="new-object">
{wizard}
</Callout>
</div>
</Dialog>
);
}
/**
* Returns the list of all available projects.
*/
private _getRecentProjects(): Undefinable<JSX.Element> {
let data = (JSON.parse(localStorage.getItem("babylonjs-editor-welcome") ?? "[]") as any[]).filter((d) => pathExistsSync(d.path));
if (!data.length) {
return undefined;
}
return (
<div style={{ width: "100%", height: "200px" }}>
{data.map((d, index) => (
<div style={{ float: "left", width: "32%", height: "100%", marginLeft: `${index}%`, backgroundColor: "black", borderRadius: "15px" }}>
<strong style={{ marginLeft: "5px" }}>{basename(d.path)}</strong>
<Tooltip content={d.path} position={Position.BOTTOM} usePortal={false}>
<img src={d.preview} onDoubleClick={() => this._handleOpenRecentProject(d.path)} style={{ width: "100%", height: "100%", objectFit: "contain" }}></img>
</Tooltip>
</div>
))}
</div>
);
}
/**
* Called on the user clicks on the "Ok" button or closes the dialog.
*/
private _handleClose(): void {
ReactDOM.unmountComponentAtNode(document.getElementById("BABYLON-EDITOR-OVERLAY") as Element);
}
/**
* Called on the user wants to load a workspace.
*/
private _handleOpenWorkspace(): void {
WorkSpace.Browse();
}
/**
* Called on the user wants to open the preferences.
*/
private _handleOpenPreferences(): void {
this.props.editor.addWindowedPlugin("preferences", undefined, WorkSpace.Path);
}
/**
* Called on the user wants to open a recent project.
*/
private async _handleOpenRecentProject(path: string): Promise<void> {
const extension = extname(path).toLowerCase();
switch (extension) {
case ".editorworkspace": await WorkSpace.SetOpeningWorkspace(path); break;
case ".editorproject": await Project.SetOpeningProject(path); break;
default: return;
}
window.location.reload();
}
/**
* Called on the user finished the new project wizard.
*/
private async _handleFinishWizard(): Promise<void> {
const templateType = this._wizard0.state.selectedTemplate;
if (templateType && templateType.name !== "Empty") {
return this._downloadTemplate(templateType);
}
const path = await Tools.ShowSaveDialog();
if (!(await this._isFolderEmpty(path))) {
await Alert.Show("Can't Create Project.", "Can't create project. The destination folder must be empty.");
return this._handleFinishWizard();
}
this._handleClose();
Overlay.Show("Creating Project...", true);
// Write project.
const projectZipPath = join(Tools.GetAppPath(), `assets/project/workspace.zip`);
const projectZip = new Zip(projectZipPath);
await new Promise<void>((resolve, reject) => {
projectZip.extractAllToAsync(path, false, (err) => err ? reject(err) : resolve());
});
// Configure workspace
const workspacePath = join(path, "workspace.editorworkspace");
await this._updateWorkspaceSettings(workspacePath);
await this._copyVsCodeLaunch(path);
// Open project!
await WorkSpace.SetOpeningWorkspace(workspacePath);
window.location.reload();
}
/**
* Downloads the tempalate.
*/
private async _downloadTemplate(template: IWorkspaceTemplate): Promise<void> {
// Get destination path.
const path = await Tools.ShowSaveDialog();
if (!(await this._isFolderEmpty(path))) {
await Alert.Show("Can't Create Project.", "Can't create project. The destination folder must be empty.");
return this._downloadTemplate(template);
}
// Download file
this.setState({ downloadProgress: 0.001 });
const contentBuffer = await Tools.LoadFile<ArrayBuffer>(`http://editor.babylonjs.com/templates/${template.file}?${Date.now()}`, true, (d) => {
this.setState({ downloadProgress: (d.loaded / d.total) });
});
const zip = new Zip(Buffer.from(contentBuffer));
await new Promise<void>((resolve, reject) => zip.extractAllToAsync(path, false, (err) => err ? reject(err) : resolve()));
// Notify
Overlay.Show("Creating Project...", true);
// Open project!
const filesList = await readdir(path);
const workspaceFile = filesList.find((f) => extname(f).toLowerCase() === ".editorworkspace") ?? "workspace.editorworkspace";
const workspacePath = join(path, workspaceFile);
await this._updateWorkspaceSettings(workspacePath);
await this._copyVsCodeLaunch(path);
await WorkSpace.SetOpeningWorkspace(join(path, workspaceFile));
window.location.reload();
}
/**
* Updates the workspace settings on
*/
private async _updateWorkspaceSettings(worksapcePath: string): Promise<void> {
const workspace = await readJSON(worksapcePath, { encoding: "utf-8" }) as IWorkSpace;
workspace.serverPort = this._wizard1.state.serverPort;
workspace.watchProject = this._wizard1.state.watchWorkspaceWithWebPack;
await writeJson(worksapcePath, workspace, {
encoding: "utf-8",
spaces: "\t",
});
}
/**
* Copies the .vscode launch folder into the new created workspace.
*/
private async _copyVsCodeLaunch(path: string): Promise<void> {
if (!await pathExists(join(path, ".vscode"))) {
await mkdir(join(path, ".vscode"));
}
await copy(join(Tools.GetAppPath(), "assets/project/launch.json"), join(path, ".vscode/launch.json"), { overwrite: false });
}
/**
* Returns wether or not the folder is empty.
*/
private async _isFolderEmpty(path: string): Promise<boolean> {
const stats = await stat(path);
if (!stats.isDirectory()) { return false; }
const files = await readdir(path);
return files.filter((f) => f[0] !== ".").length === 0;
}
} | the_stack |
* Hyperledger Cactus Plugin - Consortium Web Service
* Manage a Cactus consortium through the APIs. Needs administrative privileges.
*
* The version of the OpenAPI document: 0.0.1
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { Configuration } from './configuration';
import globalAxios, { AxiosPromise, AxiosInstance } from 'axios';
// Some imports not used depending on template conditions
// @ts-ignore
import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from './common';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError } from './base';
/**
*
* @export
* @interface GetConsortiumJwsResponse
*/
export interface GetConsortiumJwsResponse {
/**
*
* @type {JWSGeneral}
* @memberof GetConsortiumJwsResponse
*/
jws: JWSGeneral;
}
/**
*
* @export
* @interface GetNodeJwsResponse
*/
export interface GetNodeJwsResponse {
/**
*
* @type {JWSGeneral}
* @memberof GetNodeJwsResponse
*/
jws: JWSGeneral;
}
/**
*
* @export
* @interface JWSGeneral
*/
export interface JWSGeneral {
/**
*
* @type {string}
* @memberof JWSGeneral
*/
payload: string;
/**
*
* @type {Array<JWSRecipient>}
* @memberof JWSGeneral
*/
signatures: Array<JWSRecipient>;
}
/**
* A JSON Web Signature. See: https://tools.ietf.org/html/rfc7515 for info about standard.
* @export
* @interface JWSRecipient
*/
export interface JWSRecipient {
/**
*
* @type {string}
* @memberof JWSRecipient
*/
signature: string;
/**
*
* @type {string}
* @memberof JWSRecipient
*/
protected?: string;
/**
*
* @type {{ [key: string]: object; }}
* @memberof JWSRecipient
*/
header?: { [key: string]: object; };
}
/**
* DefaultApi - axios parameter creator
* @export
*/
export const DefaultApiAxiosParamCreator = function (configuration?: Configuration) {
return {
/**
* The JWS asserting the consortium metadata (pub keys and hosts of nodes)
* @summary Retrieves a consortium JWS
* @param {object} [body]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getConsortiumJwsV1: async (body?: object, options: any = {}): Promise<RequestArgs> => {
const localVarPath = `/api/v1/plugins/@hyperledger/cactus-plugin-consortium-manual/consortium/jws`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter, options.query);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(body, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Retrieves the JWT of a Cactus Node
* @param {object} [body]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getNodeJwsV1: async (body?: object, options: any = {}): Promise<RequestArgs> => {
const localVarPath = `/api/v1/plugins/@hyperledger/cactus-plugin-consortium-manual/node/jws`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter, options.query);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(body, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Get the Prometheus Metrics
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getPrometheusMetricsV1: async (options: any = {}): Promise<RequestArgs> => {
const localVarPath = `/api/v1/plugins/@hyperledger/cactus-plugin-consortium-manual/get-prometheus-exporter-metrics`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
setSearchParams(localVarUrlObj, localVarQueryParameter, options.query);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* DefaultApi - functional programming interface
* @export
*/
export const DefaultApiFp = function(configuration?: Configuration) {
const localVarAxiosParamCreator = DefaultApiAxiosParamCreator(configuration)
return {
/**
* The JWS asserting the consortium metadata (pub keys and hosts of nodes)
* @summary Retrieves a consortium JWS
* @param {object} [body]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async getConsortiumJwsV1(body?: object, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<GetConsortiumJwsResponse>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.getConsortiumJwsV1(body, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Retrieves the JWT of a Cactus Node
* @param {object} [body]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async getNodeJwsV1(body?: object, options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<GetNodeJwsResponse>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.getNodeJwsV1(body, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Get the Prometheus Metrics
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async getPrometheusMetricsV1(options?: any): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<string>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.getPrometheusMetricsV1(options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
}
};
/**
* DefaultApi - factory interface
* @export
*/
export const DefaultApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) {
const localVarFp = DefaultApiFp(configuration)
return {
/**
* The JWS asserting the consortium metadata (pub keys and hosts of nodes)
* @summary Retrieves a consortium JWS
* @param {object} [body]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getConsortiumJwsV1(body?: object, options?: any): AxiosPromise<GetConsortiumJwsResponse> {
return localVarFp.getConsortiumJwsV1(body, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Retrieves the JWT of a Cactus Node
* @param {object} [body]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getNodeJwsV1(body?: object, options?: any): AxiosPromise<GetNodeJwsResponse> {
return localVarFp.getNodeJwsV1(body, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Get the Prometheus Metrics
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getPrometheusMetricsV1(options?: any): AxiosPromise<string> {
return localVarFp.getPrometheusMetricsV1(options).then((request) => request(axios, basePath));
},
};
};
/**
* DefaultApi - object-oriented interface
* @export
* @class DefaultApi
* @extends {BaseAPI}
*/
export class DefaultApi extends BaseAPI {
/**
* The JWS asserting the consortium metadata (pub keys and hosts of nodes)
* @summary Retrieves a consortium JWS
* @param {object} [body]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof DefaultApi
*/
public getConsortiumJwsV1(body?: object, options?: any) {
return DefaultApiFp(this.configuration).getConsortiumJwsV1(body, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Retrieves the JWT of a Cactus Node
* @param {object} [body]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof DefaultApi
*/
public getNodeJwsV1(body?: object, options?: any) {
return DefaultApiFp(this.configuration).getNodeJwsV1(body, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Get the Prometheus Metrics
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof DefaultApi
*/
public getPrometheusMetricsV1(options?: any) {
return DefaultApiFp(this.configuration).getPrometheusMetricsV1(options).then((request) => request(this.axios, this.basePath));
}
} | the_stack |
import * as CSS from 'csstype';
export = vidom;
export as namespace vidom;
type MapLike<T = any> = Record<string, any>;
type DOMElement = Element;
declare namespace vidom {
type Key = string | number;
type Ref<T> = (ref: T | null) => void;
interface FunctionComponent<
TAttrs extends MapLike = {},
TChildren = unknown,
TContext extends MapLike = {}
> {
(attrs: TAttrs, children: TChildren, context: TContext): Element | null;
defaultAttrs?: Partial<TAttrs>;
}
interface ComponentClass<
TAttrs extends MapLike = {},
TChildren = unknown,
TContext extends MapLike = {}
> {
new (attrs: TAttrs, children: TChildren, context: TContext): Component<TAttrs, TChildren, {}, TContext>;
defaultAttrs?: Partial<TAttrs>;
}
type ComponentType<
TAttrs extends MapLike = {},
TChildren = unknown,
TContext extends MapLike = {}
> =
ComponentClass<TAttrs, TChildren, TContext> |
FunctionComponent<TAttrs, TChildren, TContext>;
abstract class Component<
TAttrs extends MapLike = {},
TChildren = unknown,
TState extends MapLike = {},
TContext extends MapLike = {},
TChildContext extends MapLike = {}
> {
protected readonly attrs: Readonly<TAttrs>;
protected readonly children: TChildren;
protected readonly state: Readonly<TState>;
protected readonly context: Readonly<TContext>;
constructor(attrs: TAttrs, children: TChildren, context: TContext);
protected setState(state: Partial<TState>): void;
protected update(): void;
protected isMounted(): boolean;
protected getDomNode(): DOMElement | DOMElement[];
protected onInit(): void;
protected onMount(): void;
protected onChange(
prevAttrs: TAttrs,
prevChildren: TChildren,
prevState: TState,
prevContext: TContext
): void;
protected onChildContextRequest(): TChildContext;
protected shouldRerender(
prevAttrs: TAttrs,
prevChildren: TChildren,
prevState: TState,
prevContext: TContext
): boolean;
protected abstract onRender(): Node;
protected onUpdate(
prevAttrs: TAttrs,
prevChildren: TChildren,
prevState: TState,
prevContext: TContext
): void;
protected onUnmount(): void;
}
abstract class BaseElement {
readonly key: Key | null;
clone(): BaseElement;
}
class TagElement extends BaseElement {
readonly tag: string;
readonly attrs: HTMLAttributes | SVGAttributes;
readonly children: Element[] | string | null;
readonly ref: Ref<DOMElement> | null;
constructor(
tag: string,
key?: Key | null,
attrs?: HTMLAttributes | SVGAttributes | null,
children?: Node,
ref?: Ref<DOMElement> | null,
escapeChildren?: boolean
);
clone(
attrs?: HTMLAttributes | SVGAttributes | null,
children?: Node,
ref?: Ref<DOMElement> | null
): TagElement;
}
class TextElement extends BaseElement {
readonly children: string;
constructor(
key?: Key | null,
children?: string
);
clone(children?: string): TextElement;
}
class FragmentElement extends BaseElement {
readonly children: Element[] | null;
constructor(
key?: Key | null,
children?: Node
);
clone(children?: Node): FragmentElement;
}
class ComponentElement<
TAttrs extends MapLike = MapLike,
TChildren = unknown
> extends BaseElement {
readonly component: ComponentClass<TAttrs, TChildren>;
readonly attrs: Readonly<TAttrs>;
readonly children?: TChildren;
readonly ref: Ref<Component<TAttrs, TChildren>> | null;
constructor(
component: ComponentClass<TAttrs, TChildren>,
key?: Key | null,
attrs?: TAttrs,
children?: TChildren,
ref?: Ref<Component<TAttrs, TChildren>> | null
);
clone(
attrs?: Partial<TAttrs> | null,
children?: Node,
ref?: Ref<Component<TAttrs, TChildren>> | null
): ComponentElement<TAttrs, TChildren>;
}
class FunctionComponentElement<
TAttrs extends MapLike = MapLike,
TChildren = unknown
> extends BaseElement {
readonly component: FunctionComponent<TAttrs, TChildren>;
readonly attrs: Readonly<TAttrs>;
readonly children?: TChildren;
constructor(
component: FunctionComponent<TAttrs, TChildren>,
key?: Key | null,
attrs?: TAttrs,
children?: TChildren
);
clone(
attrs?: Partial<TAttrs> | null,
children?: Node
): FunctionComponentElement<TAttrs, TChildren>;
}
type Element =
TagElement |
TextElement |
FragmentElement |
ComponentElement |
FunctionComponentElement;
type Node = Element | string | number | boolean | null | undefined | NodeArray;
interface NodeArray extends Array<Node> {}
interface WithKey {
key?: Key | null;
}
interface WithRef<T> {
ref?: Ref<T> | null;
}
interface DOMEventHandler<TEvent extends Event = Event> {
(event: TEvent): void;
}
interface DOMAttributes {
onAnimationEnd?: DOMEventHandler;
onAnimationIteration?: DOMEventHandler;
onAnimationStart?: DOMEventHandler;
onBlur?: DOMEventHandler<FocusEvent>;
onCanPlay?: DOMEventHandler;
onCanPlayThrough?: DOMEventHandler;
onChange?: DOMEventHandler;
onClick?: DOMEventHandler<MouseEvent>;
onComplete?: DOMEventHandler;
onContextMenu?: DOMEventHandler;
onCopy?: DOMEventHandler;
onCut?: DOMEventHandler;
onDblClick?: DOMEventHandler<MouseEvent>;
onDrag?: DOMEventHandler<DragEvent>;
onDragEnd?: DOMEventHandler<DragEvent>;
onDragEnter?: DOMEventHandler<DragEvent>;
onDragLeave?: DOMEventHandler<DragEvent>;
onDragOver?: DOMEventHandler<DragEvent>;
onDragStart?: DOMEventHandler<DragEvent>;
onDrop?: DOMEventHandler<DragEvent>;
onDurationChange?: DOMEventHandler;
onEmptied?: DOMEventHandler;
onEnded?: DOMEventHandler;
onError?: DOMEventHandler;
onFocus?: DOMEventHandler<FocusEvent>;
onGotPointerCapture?: DOMEventHandler<PointerEvent>;
onInput?: DOMEventHandler;
onKeyDown?: DOMEventHandler<KeyboardEvent>;
onKeyPress?: DOMEventHandler<KeyboardEvent>;
onKeyUp?: DOMEventHandler<KeyboardEvent>;
onLoad?: DOMEventHandler;
onLoadedData?: DOMEventHandler;
onLoadedMetadata?: DOMEventHandler;
onLoadStart?: DOMEventHandler;
onLostPointerCapture?: DOMEventHandler<PointerEvent>;
onMouseDown?: DOMEventHandler<MouseEvent>;
onMouseEnter?: DOMEventHandler<MouseEvent>;
onMouseLeave?: DOMEventHandler<MouseEvent>;
onMouseMove?: DOMEventHandler<MouseEvent>;
onMouseOut?: DOMEventHandler<MouseEvent>;
onMouseOver?: DOMEventHandler<MouseEvent>;
onMouseUp?: DOMEventHandler<MouseEvent>;
onPaste?: DOMEventHandler;
onPause?: DOMEventHandler;
onPlay?: DOMEventHandler;
onPlaying?: DOMEventHandler;
onPointerCancel?: DOMEventHandler<PointerEvent>;
onPointerDown?: DOMEventHandler<PointerEvent>;
onPointerEnter?: DOMEventHandler<PointerEvent>;
onPointerLeave?: DOMEventHandler<PointerEvent>;
onPointerMove?: DOMEventHandler<PointerEvent>;
onPointerOut?: DOMEventHandler<PointerEvent>;
onPointerOver?: DOMEventHandler<PointerEvent>;
onPointerUp?: DOMEventHandler<PointerEvent>;
onProgress?: DOMEventHandler;
onRateChange?: DOMEventHandler;
onScroll?: DOMEventHandler;
onSeeked?: DOMEventHandler;
onSeeking?: DOMEventHandler;
onSelect?: DOMEventHandler;
onStalled?: DOMEventHandler;
onSubmit?: DOMEventHandler;
onSuspend?: DOMEventHandler;
onTimeUpdate?: DOMEventHandler;
onTouchCancel?: DOMEventHandler<TouchEvent>;
onTouchEnd?: DOMEventHandler<TouchEvent>;
onTouchMove?: DOMEventHandler<TouchEvent>;
onTouchStart?: DOMEventHandler<TouchEvent>;
onTransitionEnd?: DOMEventHandler;
onVolumeChange?: DOMEventHandler;
onWaiting?: DOMEventHandler;
onWheel?: DOMEventHandler<WheelEvent>;
}
type CSSProperties = {
[key in keyof CSS.Properties]: CSS.Properties[key] | null;
}
interface HTMLAttributes extends DOMAttributes {
accessKey?: string;
'aria-activedescendant'?: string;
'aria-atomic'?: boolean | 'false' | 'true';
'aria-autocomplete'?: 'none' | 'inline' | 'list' | 'both';
'aria-busy'?: boolean | 'false' | 'true';
'aria-checked'?: boolean | 'false' | 'mixed' | 'true';
'aria-colcount'?: number;
'aria-colindex'?: number;
'aria-colspan'?: number;
'aria-controls'?: string;
'aria-current'?: boolean | 'false' | 'true' | 'page' | 'step' | 'location' | 'date' | 'time';
'aria-describedby'?: string;
'aria-details'?: string;
'aria-disabled'?: boolean | 'false' | 'true';
'aria-dropeffect'?: 'none' | 'copy' | 'execute' | 'link' | 'move' | 'popup';
'aria-errormessage'?: string;
'aria-expanded'?: boolean | 'false' | 'true';
'aria-flowto'?: string;
'aria-grabbed'?: boolean | 'false' | 'true';
'aria-haspopup'?: boolean | 'false' | 'true' | 'menu' | 'listbox' | 'tree' | 'grid' | 'dialog';
'aria-hidden'?: boolean | 'false' | 'true';
'aria-invalid'?: boolean | 'false' | 'true' | 'grammar' | 'spelling';
'aria-keyshortcuts'?: string;
'aria-label'?: string;
'aria-labelledby'?: string;
'aria-level'?: number;
'aria-live'?: 'off' | 'assertive' | 'polite';
'aria-modal'?: boolean | 'false' | 'true';
'aria-multiline'?: boolean | 'false' | 'true';
'aria-multiselectable'?: boolean | 'false' | 'true';
'aria-orientation'?: 'horizontal' | 'vertical';
'aria-owns'?: string;
'aria-placeholder'?: string;
'aria-posinset'?: number;
'aria-pressed'?: boolean | 'false' | 'mixed' | 'true';
'aria-readonly'?: boolean | 'false' | 'true';
'aria-relevant'?: 'additions' | 'additions text' | 'all' | 'removals' | 'text';
'aria-required'?: boolean | 'false' | 'true';
'aria-roledescription'?: string;
'aria-rowcount'?: number;
'aria-rowindex'?: number;
'aria-rowspan'?: number;
'aria-selected'?: boolean | 'false' | 'true';
'aria-setsize'?: number;
'aria-sort'?: 'none' | 'ascending' | 'descending' | 'other';
'aria-valuemax'?: number;
'aria-valuemin'?: number;
'aria-valuenow'?: number;
'aria-valuetext'?: string;
class?: string;
contentEditable?: boolean;
contextMenu?: string;
dir?: string;
draggable?: boolean;
hidden?: boolean;
html?: string,
id?: string;
inputMode?: string;
is?: string;
lang?: string;
placeholder?: string;
radioGroup?: string;
role?: string;
slot?: string;
spellCheck?: boolean;
style?: CSSProperties;
tabIndex?: number;
title?: string;
// Non-standard attributes
autoCapitalize?: string;
autoCorrect?: string;
autoSave?: string;
color?: string;
itemProp?: string;
itemScope?: boolean;
itemType?: string;
itemID?: string;
itemRef?: string;
results?: number;
security?: string;
unselectable?: 'on' | 'off';
}
type HTMLAttributeReferrerPolicy =
'' |
'no-referrer' |
'no-referrer-when-downgrade' |
'origin' |
'origin-when-cross-origin' |
'same-origin' |
'strict-origin' |
'strict-origin-when-cross-origin' |
'unsafe-url';
interface AnchorHTMLAttributes extends HTMLAttributes {
download?: any;
href?: string;
hrefLang?: string;
media?: string;
ping?: string;
rel?: string;
target?: string;
type?: string;
referrerPolicy?: HTMLAttributeReferrerPolicy;
}
interface AreaHTMLAttributes extends HTMLAttributes {
alt?: string;
coords?: string;
download?: any;
href?: string;
hrefLang?: string;
media?: string;
referrerPolicy?: HTMLAttributeReferrerPolicy;
rel?: string;
shape?: string;
target?: string;
}
interface BaseHTMLAttributes extends HTMLAttributes {
href?: string;
target?: string;
}
interface BlockquoteHTMLAttributes extends HTMLAttributes {
cite?: string;
}
interface ButtonHTMLAttributes extends HTMLAttributes {
autoFocus?: boolean;
disabled?: boolean;
form?: string;
formAction?: string;
formEncType?: string;
formMethod?: string;
formNoValidate?: boolean;
formTarget?: string;
name?: string;
type?: string;
value?: string | string[] | number;
}
interface CanvasHTMLAttributes extends HTMLAttributes {
height?: number | string;
width?: number | string;
}
interface ColHTMLAttributes extends HTMLAttributes {
span?: number;
width?: number | string;
}
interface ColgroupHTMLAttributes extends HTMLAttributes {
span?: number;
}
interface DetailsHTMLAttributes extends HTMLAttributes {
open?: boolean;
}
interface DelHTMLAttributes extends HTMLAttributes {
cite?: string;
dateTime?: string;
}
interface DialogHTMLAttributes extends HTMLAttributes {
open?: boolean;
}
interface EmbedHTMLAttributes extends HTMLAttributes {
height?: number | string;
src?: string;
type?: string;
width?: number | string;
}
interface FieldsetHTMLAttributes extends HTMLAttributes {
disabled?: boolean;
form?: string;
name?: string;
}
interface FormHTMLAttributes extends HTMLAttributes {
acceptCharset?: string;
action?: string;
autoComplete?: string;
encType?: string;
method?: string;
name?: string;
noValidate?: boolean;
target?: string;
}
interface HtmlHTMLAttributes extends HTMLAttributes {
manifest?: string;
}
interface IframeHTMLAttributes extends HTMLAttributes {
allow?: string;
allowFullScreen?: boolean;
allowTransparency?: boolean;
/** @deprecated */
frameBorder?: number | string;
height?: number | string;
/** @deprecated */
marginHeight?: number;
/** @deprecated */
marginWidth?: number;
name?: string;
referrerPolicy?: HTMLAttributeReferrerPolicy;
sandbox?: string;
/** @deprecated */
scrolling?: string;
seamless?: boolean;
src?: string;
srcDoc?: string;
width?: number | string;
}
interface ImgHTMLAttributes extends HTMLAttributes {
alt?: string;
crossOrigin?: 'anonymous' | 'use-credentials' | '';
decoding?: 'async' | 'auto' | 'sync';
height?: number | string;
loading?: 'eager' | 'lazy';
referrerPolicy?: HTMLAttributeReferrerPolicy;
sizes?: string;
src?: string;
srcSet?: string;
useMap?: string;
width?: number | string;
}
interface InsHTMLAttributes extends HTMLAttributes {
cite?: string;
dateTime?: string;
}
interface InputHTMLAttributes extends HTMLAttributes {
accept?: string;
alt?: string;
autoComplete?: string;
autoFocus?: boolean;
capture?: boolean | string;
checked?: boolean;
crossOrigin?: string;
disabled?: boolean;
form?: string;
formAction?: string;
formEncType?: string;
formMethod?: string;
formNoValidate?: boolean;
formTarget?: string;
height?: number | string;
list?: string;
max?: number | string;
maxLength?: number;
min?: number | string;
minLength?: number;
multiple?: boolean;
name?: string;
pattern?: string;
readOnly?: boolean;
required?: boolean;
size?: number;
src?: string;
step?: number | string;
type?: string;
value?: string | string[] | number;
width?: number | string;
}
interface KeygenHTMLAttributes extends HTMLAttributes {
autoFocus?: boolean;
challenge?: string;
disabled?: boolean;
form?: string;
keyType?: string;
keyParams?: string;
name?: string;
}
interface LabelHTMLAttributes extends HTMLAttributes {
form?: string;
for?: string;
}
interface LiHTMLAttributes extends HTMLAttributes {
value?: string | string[] | number;
}
interface LinkHTMLAttributes extends HTMLAttributes {
as?: string;
crossOrigin?: string;
href?: string;
hrefLang?: string;
integrity?: string;
media?: string;
referrerPolicy?: HTMLAttributeReferrerPolicy;
rel?: string;
sizes?: string;
type?: string;
}
interface MapHTMLAttributes extends HTMLAttributes {
name?: string;
}
interface MenuHTMLAttributes extends HTMLAttributes {
type?: string;
}
interface MediaHTMLAttributes extends HTMLAttributes {
autoPlay?: boolean;
controls?: boolean;
controlsList?: string;
crossOrigin?: string;
loop?: boolean;
mediaGroup?: string;
muted?: boolean;
playsinline?: boolean;
preload?: string;
src?: string;
}
interface MetaHTMLAttributes extends HTMLAttributes {
charSet?: string;
content?: string;
httpEquiv?: string;
name?: string;
}
interface MeterHTMLAttributes extends HTMLAttributes {
form?: string;
high?: number;
low?: number;
max?: number | string;
min?: number | string;
optimum?: number;
value?: string | string[] | number;
}
interface QuoteHTMLAttributes extends HTMLAttributes {
cite?: string;
}
interface ObjectHTMLAttributes extends HTMLAttributes {
classID?: string;
data?: string;
form?: string;
height?: number | string;
name?: string;
type?: string;
useMap?: string;
width?: number | string;
wmode?: string;
}
interface OlHTMLAttributes extends HTMLAttributes {
reversed?: boolean;
start?: number;
type?: '1' | 'a' | 'A' | 'i' | 'I';
}
interface OptgroupHTMLAttributes extends HTMLAttributes {
disabled?: boolean;
label?: string;
}
interface OptionHTMLAttributes extends HTMLAttributes {
disabled?: boolean;
label?: string;
selected?: boolean;
value?: string | string[] | number;
}
interface OutputHTMLAttributes extends HTMLAttributes {
form?: string;
for?: string;
name?: string;
}
interface ParamHTMLAttributes extends HTMLAttributes {
name?: string;
value?: string | string[] | number;
}
interface ProgressHTMLAttributes extends HTMLAttributes {
max?: number | string;
value?: string | string[] | number;
}
interface ScriptHTMLAttributes extends HTMLAttributes {
async?: boolean;
charSet?: string;
crossOrigin?: string;
defer?: boolean;
integrity?: string;
noModule?: boolean;
nonce?: string;
referrerPolicy?: HTMLAttributeReferrerPolicy;
src?: string;
type?: string;
}
interface SelectHTMLAttributes extends HTMLAttributes {
autoComplete?: string;
autoFocus?: boolean;
disabled?: boolean;
form?: string;
multiple?: boolean;
name?: string;
required?: boolean;
size?: number;
value?: string | string[] | number;
}
interface SourceHTMLAttributes extends HTMLAttributes {
media?: string;
sizes?: string;
src?: string;
srcSet?: string;
type?: string;
}
interface StyleHTMLAttributes extends HTMLAttributes {
media?: string;
nonce?: string;
scoped?: boolean;
type?: string;
}
interface TableHTMLAttributes extends HTMLAttributes {
cellPadding?: number | string;
cellSpacing?: number | string;
summary?: string;
}
interface TextareaHTMLAttributes extends HTMLAttributes {
autoComplete?: string;
autoFocus?: boolean;
cols?: number;
dirName?: string;
disabled?: boolean;
form?: string;
maxLength?: number;
minLength?: number;
name?: string;
placeholder?: string;
readOnly?: boolean;
required?: boolean;
rows?: number;
value?: string | string[] | number;
wrap?: string;
}
interface TdHTMLAttributes extends HTMLAttributes {
align?: 'left' | 'center' | 'right' | 'justify' | 'char';
colSpan?: number;
headers?: string;
rowSpan?: number;
scope?: string;
}
interface ThHTMLAttributes extends HTMLAttributes {
align?: 'left' | 'center' | 'right' | 'justify' | 'char';
colSpan?: number;
headers?: string;
rowSpan?: number;
scope?: string;
}
interface TimeHTMLAttributes extends HTMLAttributes {
dateTime?: string;
}
interface TrackHTMLAttributes extends HTMLAttributes {
default?: boolean;
kind?: string;
label?: string;
src?: string;
srcLang?: string;
}
interface VideoHTMLAttributes extends MediaHTMLAttributes {
height?: number | string;
poster?: string;
width?: number | string;
}
interface SVGAttributes extends DOMAttributes {
class?: string;
color?: string;
height?: number | string;
id?: string;
lang?: string;
max?: number | string;
media?: string;
method?: string;
min?: number | string;
name?: string;
style?: CSSProperties;
target?: string;
type?: string;
width?: number | string;
accentHeight?: number | string;
accumulate?: 'none' | 'sum';
additive?: 'replace' | 'sum';
alignmentBaseline?:
'auto' | 'baseline' | 'before-edge' | 'text-before-edge' | 'middle' | 'central' | 'after-edge' |
'text-after-edge' | 'ideographic' | 'alphabetic' | 'hanging' | 'mathematical' | 'inherit';
allowReorder?: 'no' | 'yes';
alphabetic?: number | string;
amplitude?: number | string;
arabicForm?: 'initial' | 'medial' | 'terminal' | 'isolated';
ascent?: number | string;
attributeName?: string;
attributeType?: string;
autoReverse?: number | string;
azimuth?: number | string;
baseFrequency?: number | string;
baselineShift?: number | string;
baseProfile?: number | string;
bbox?: number | string;
begin?: number | string;
bias?: number | string;
by?: number | string;
calcMode?: number | string;
capHeight?: number | string;
clip?: number | string;
clipPath?: string;
clipPathUnits?: number | string;
clipRule?: number | string;
colorInterpolation?: number | string;
colorInterpolationFilters?: 'auto' | 'sRGB' | 'linearRGB' | 'inherit';
colorProfile?: number | string;
colorRendering?: number | string;
contentScriptType?: number | string;
contentStyleType?: number | string;
cursor?: number | string;
cx?: number | string;
cy?: number | string;
d?: string;
decelerate?: number | string;
descent?: number | string;
diffuseConstant?: number | string;
direction?: number | string;
display?: number | string;
divisor?: number | string;
dominantBaseline?: number | string;
dur?: number | string;
dx?: number | string;
dy?: number | string;
edgeMode?: number | string;
elevation?: number | string;
enableBackground?: number | string;
end?: number | string;
exponent?: number | string;
externalResourcesRequired?: number | string;
fill?: string;
fillOpacity?: number | string;
fillRule?: 'nonzero' | 'evenodd' | 'inherit';
filter?: string;
filterRes?: number | string;
filterUnits?: number | string;
floodColor?: number | string;
floodOpacity?: number | string;
focusable?: number | string;
fontFamily?: string;
fontSize?: number | string;
fontSizeAdjust?: number | string;
fontStretch?: number | string;
fontStyle?: number | string;
fontVariant?: number | string;
fontWeight?: number | string;
format?: number | string;
from?: number | string;
fx?: number | string;
fy?: number | string;
g1?: number | string;
g2?: number | string;
glyphName?: number | string;
glyphOrientationHorizontal?: number | string;
glyphOrientationVertical?: number | string;
glyphRef?: number | string;
gradientTransform?: string;
gradientUnits?: string;
hanging?: number | string;
horizAdvX?: number | string;
horizOriginX?: number | string;
ideographic?: number | string;
imageRendering?: number | string;
in2?: number | string;
in?: string;
intercept?: number | string;
k1?: number | string;
k2?: number | string;
k3?: number | string;
k4?: number | string;
k?: number | string;
kernelMatrix?: number | string;
kernelUnitLength?: number | string;
kerning?: number | string;
keyPoints?: number | string;
keySplines?: number | string;
keyTimes?: number | string;
lengthAdjust?: number | string;
letterSpacing?: number | string;
lightingColor?: number | string;
limitingConeAngle?: number | string;
local?: number | string;
markerEnd?: string;
markerHeight?: number | string;
markerMid?: string;
markerStart?: string;
markerUnits?: number | string;
markerWidth?: number | string;
mask?: string;
maskContentUnits?: number | string;
maskUnits?: number | string;
mathematical?: number | string;
mode?: number | string;
numOctaves?: number | string;
offset?: number | string;
opacity?: number | string;
operator?: number | string;
order?: number | string;
orient?: number | string;
orientation?: number | string;
origin?: number | string;
overflow?: number | string;
overlinePosition?: number | string;
overlineThickness?: number | string;
paintOrder?: number | string;
panose1?: number | string;
pathLength?: number | string;
patternContentUnits?: string;
patternTransform?: number | string;
patternUnits?: string;
pointerEvents?: number | string;
points?: string;
pointsAtX?: number | string;
pointsAtY?: number | string;
pointsAtZ?: number | string;
preserveAlpha?: number | string;
preserveAspectRatio?: string;
primitiveUnits?: number | string;
r?: number | string;
radius?: number | string;
refX?: number | string;
refY?: number | string;
renderingIntent?: number | string;
repeatCount?: number | string;
repeatDur?: number | string;
requiredExtensions?: number | string;
requiredFeatures?: number | string;
restart?: number | string;
result?: string;
rotate?: number | string;
rx?: number | string;
ry?: number | string;
scale?: number | string;
seed?: number | string;
shapeRendering?: number | string;
slope?: number | string;
spacing?: number | string;
specularConstant?: number | string;
specularExponent?: number | string;
speed?: number | string;
spreadMethod?: string;
startOffset?: number | string;
stdDeviation?: number | string;
stemh?: number | string;
stemv?: number | string;
stitchTiles?: number | string;
stopColor?: string;
stopOpacity?: number | string;
strikethroughPosition?: number | string;
strikethroughThickness?: number | string;
string?: number | string;
stroke?: string;
strokeDasharray?: string | number;
strokeDashoffset?: string | number;
strokeLinecap?: 'butt' | 'round' | 'square' | 'inherit';
strokeLinejoin?: 'miter' | 'round' | 'bevel' | 'inherit';
strokeMiterlimit?: string;
strokeOpacity?: number | string;
strokeWidth?: number | string;
surfaceScale?: number | string;
systemLanguage?: number | string;
tableValues?: number | string;
targetX?: number | string;
targetY?: number | string;
textAnchor?: string;
textDecoration?: number | string;
textLength?: number | string;
textRendering?: number | string;
to?: number | string;
transform?: string;
u1?: number | string;
u2?: number | string;
underlinePosition?: number | string;
underlineThickness?: number | string;
unicode?: number | string;
unicodeBidi?: number | string;
unicodeRange?: number | string;
unitsPerEm?: number | string;
vAlphabetic?: number | string;
values?: string;
vectorEffect?: number | string;
version?: string;
vertAdvY?: number | string;
vertOriginX?: number | string;
vertOriginY?: number | string;
vHanging?: number | string;
vIdeographic?: number | string;
viewBox?: string;
viewTarget?: number | string;
visibility?: number | string;
vMathematical?: number | string;
widths?: number | string;
wordSpacing?: number | string;
writingMode?: number | string;
x1?: number | string;
x2?: number | string;
x?: number | string;
xChannelSelector?: string;
xHeight?: number | string;
xlinkActuate?: string;
xlinkArcrole?: string;
xlinkHref?: string;
xlinkRole?: string;
xlinkShow?: string;
xlinkTitle?: string;
xlinkType?: string;
xmlBase?: string;
xmlLang?: string;
xmlns?: string;
xmlnsXlink?: string;
xmlSpace?: string;
y1?: number | string;
y2?: number | string;
y?: number | string;
yChannelSelector?: string;
z?: number | string;
zoomAndPan?: string;
}
function elem(
tag: 'fragment',
key?: Key | null,
children?: Node
): FragmentElement;
function elem(
tag: 'plaintext',
key?: Key | null,
children?: string
): TextElement;
function elem(
tag: string,
key?: Key | null,
attrs?: HTMLAttributes | SVGAttributes | null,
children?: Node,
ref?: Ref<HTMLElement | SVGElement> | null,
escapeChildren?: boolean
): TagElement;
function elem<TAttrs, TChildren> (
component: FunctionComponent<TAttrs, TChildren>,
key?: Key | null,
attrs?: TAttrs,
children?: TChildren
): FunctionComponentElement<TAttrs, TChildren>;
function elem<TAttrs, TChildren>(
component: ComponentClass<TAttrs, TChildren>,
key?: Key | null,
attrs?: TAttrs,
children?: TChildren,
ref?: Ref<Component<TAttrs, TChildren>> | null
): ComponentElement<TAttrs, TChildren>;
function mount(domElem: DOMElement, node: Node, callback?: () => void): void;
function mount(domElem: DOMElement, node: Node, context?: MapLike, callback?: () => void): void;
function mountSync(domElem: DOMElement, node: Node, context?: MapLike): void;
function unmount(domElem: DOMElement, callback?: () => void): void;
function unmountSync(domElem: DOMElement): void;
function renderToString(node: Node): string;
function toElem(node: Node): Element;
function toElems(node: Node): Element[];
function h(
tag: 'fragment',
props: WithKey | null,
...children: Node[]
): FragmentElement;
function h(
tag: 'plaintext',
props: WithKey | null,
...children: string[]
): TextElement;
function h(
tag: string,
props: (
(
(HTMLAttributes & WithRef<HTMLElement>) |
(SVGAttributes & WithRef<SVGElement>)
) &
WithKey
) | null,
...children: Node[]
): TagElement;
function h<TAttrs, TChildren> (
component: FunctionComponent<TAttrs, TChildren>,
props: (TAttrs & WithKey) | null,
children?: TChildren
): FunctionComponentElement<TAttrs, TChildren>;
function h<
TAttrs,
TChildren
>(
component: ComponentClass<TAttrs, TChildren>,
props: (TAttrs & WithRef<vidom.Component> & WithKey) | null,
children?: TChildren
): ComponentElement<TAttrs, TChildren>;
const IS_DEBUG: boolean;
}
declare global {
namespace JSX {
type Element = vidom.Element;
type ElementClass = vidom.Component;
type ElementAttributesProperty = { attrs: {}; };
// type LibraryManagedAttributes<TComponent, TAttrs> = TComponent extends { defaultAttrs: infer DefaultAttrs; }?
// TAttrs extends any?
// string extends keyof TAttrs?
// TAttrs :
// Pick<TAttrs, Exclude<keyof TAttrs, keyof DefaultAttrs>> &
// Partial<Pick<TAttrs, Extract<keyof TAttrs, keyof DefaultAttrs>>> &
// Partial<Pick<DefaultAttrs, Exclude<keyof DefaultAttrs, keyof TAttrs>>> :
// never :
// TAttrs;
interface IntrinsicAttributes extends vidom.WithKey {}
interface IntrinsicClassAttributes extends vidom.WithKey, vidom.WithRef<vidom.Component> {}
type IntrinsicHTMLAttributes<
THTMLAttributes extends vidom.HTMLAttributes = vidom.HTMLAttributes,
THTMLElement extends HTMLElement = HTMLElement
> = THTMLAttributes & vidom.HTMLAttributes & vidom.WithRef<THTMLElement> & vidom.WithKey;
interface IntrinsicSVGAttributes<TSVGElement extends SVGElement>
extends vidom.SVGAttributes, vidom.WithRef<TSVGElement>, vidom.WithKey {}
interface IntrinsicElements {
fragment: vidom.WithKey;
plaintext: vidom.WithKey;
a: IntrinsicHTMLAttributes<vidom.AnchorHTMLAttributes, HTMLAnchorElement>;
abbr: IntrinsicHTMLAttributes;
address: IntrinsicHTMLAttributes;
area: IntrinsicHTMLAttributes<vidom.AreaHTMLAttributes, HTMLAreaElement>;
article: IntrinsicHTMLAttributes;
aside: IntrinsicHTMLAttributes;
audio: IntrinsicHTMLAttributes<vidom.MediaHTMLAttributes, HTMLAudioElement>;
b: IntrinsicHTMLAttributes;
base: IntrinsicHTMLAttributes<vidom.BaseHTMLAttributes, HTMLBaseElement>;
bdi: IntrinsicHTMLAttributes;
bdo: IntrinsicHTMLAttributes;
big: IntrinsicHTMLAttributes;
blockquote: IntrinsicHTMLAttributes<vidom.BlockquoteHTMLAttributes>;
body: IntrinsicHTMLAttributes<vidom.HTMLAttributes, HTMLBodyElement>;
br: IntrinsicHTMLAttributes<vidom.HTMLAttributes, HTMLBRElement>;
button: IntrinsicHTMLAttributes<vidom.ButtonHTMLAttributes, HTMLButtonElement>;
canvas: IntrinsicHTMLAttributes<vidom.CanvasHTMLAttributes, HTMLCanvasElement>;
caption: IntrinsicHTMLAttributes;
cite: IntrinsicHTMLAttributes;
code: IntrinsicHTMLAttributes;
col: IntrinsicHTMLAttributes<vidom.ColHTMLAttributes, HTMLTableColElement>;
colgroup: IntrinsicHTMLAttributes<vidom.ColgroupHTMLAttributes, HTMLTableColElement>;
data: IntrinsicHTMLAttributes;
datalist: IntrinsicHTMLAttributes<vidom.HTMLAttributes, HTMLDataListElement>;
dd: IntrinsicHTMLAttributes;
del: IntrinsicHTMLAttributes<vidom.DelHTMLAttributes>;
details: IntrinsicHTMLAttributes<vidom.DetailsHTMLAttributes>;
dfn: IntrinsicHTMLAttributes;
dialog: IntrinsicHTMLAttributes<vidom.DialogHTMLAttributes, HTMLDialogElement>;
div: IntrinsicHTMLAttributes<vidom.HTMLAttributes, HTMLDivElement>;
dl: IntrinsicHTMLAttributes<vidom.HTMLAttributes, HTMLDListElement>;
dt: IntrinsicHTMLAttributes;
em: IntrinsicHTMLAttributes;
embed: IntrinsicHTMLAttributes<vidom.EmbedHTMLAttributes, HTMLEmbedElement>;
fieldset: IntrinsicHTMLAttributes<vidom.FieldsetHTMLAttributes, HTMLFieldSetElement>;
figcaption: IntrinsicHTMLAttributes;
figure: IntrinsicHTMLAttributes;
footer: IntrinsicHTMLAttributes;
form: IntrinsicHTMLAttributes<vidom.FormHTMLAttributes, HTMLFormElement>;
h1: IntrinsicHTMLAttributes<vidom.HTMLAttributes, HTMLHeadingElement>;
h2: IntrinsicHTMLAttributes<vidom.HTMLAttributes, HTMLHeadingElement>;
h3: IntrinsicHTMLAttributes<vidom.HTMLAttributes, HTMLHeadingElement>;
h4: IntrinsicHTMLAttributes<vidom.HTMLAttributes, HTMLHeadingElement>;
h5: IntrinsicHTMLAttributes<vidom.HTMLAttributes, HTMLHeadingElement>;
h6: IntrinsicHTMLAttributes<vidom.HTMLAttributes, HTMLHeadingElement>;
head: IntrinsicHTMLAttributes<vidom.HTMLAttributes, HTMLHeadElement>;
header: IntrinsicHTMLAttributes;
hgroup: IntrinsicHTMLAttributes;
hr: IntrinsicHTMLAttributes<vidom.HTMLAttributes, HTMLHRElement>;
html: IntrinsicHTMLAttributes<vidom.HtmlHTMLAttributes, HTMLHtmlElement>;
i: IntrinsicHTMLAttributes;
iframe: IntrinsicHTMLAttributes<vidom.IframeHTMLAttributes, HTMLIFrameElement>;
img: IntrinsicHTMLAttributes<vidom.ImgHTMLAttributes, HTMLImageElement>;
input: IntrinsicHTMLAttributes<vidom.InputHTMLAttributes, HTMLInputElement>;
ins: IntrinsicHTMLAttributes<vidom.InsHTMLAttributes, HTMLModElement>;
kbd: IntrinsicHTMLAttributes;
keygen: IntrinsicHTMLAttributes<vidom.KeygenHTMLAttributes>;
label: IntrinsicHTMLAttributes<vidom.LabelHTMLAttributes, HTMLLabelElement>;
legend: IntrinsicHTMLAttributes<vidom.HTMLAttributes, HTMLLegendElement>;
li: IntrinsicHTMLAttributes<vidom.LiHTMLAttributes, HTMLLIElement>;
link: IntrinsicHTMLAttributes<vidom.LinkHTMLAttributes, HTMLLinkElement>;
main: IntrinsicHTMLAttributes;
map: IntrinsicHTMLAttributes<vidom.MapHTMLAttributes, HTMLMapElement>;
mark: IntrinsicHTMLAttributes;
menu: IntrinsicHTMLAttributes<vidom.MenuHTMLAttributes>;
menuitem: IntrinsicHTMLAttributes;
meta: IntrinsicHTMLAttributes<vidom.MetaHTMLAttributes, HTMLMetaElement>;
meter: IntrinsicHTMLAttributes<vidom.MeterHTMLAttributes>;
nav: IntrinsicHTMLAttributes;
noindex: IntrinsicHTMLAttributes;
noscript: IntrinsicHTMLAttributes;
object: IntrinsicHTMLAttributes<vidom.ObjectHTMLAttributes, HTMLObjectElement>;
ol: IntrinsicHTMLAttributes<vidom.OlHTMLAttributes, HTMLOListElement>;
optgroup: IntrinsicHTMLAttributes<vidom.OptgroupHTMLAttributes, HTMLOptGroupElement>;
option: IntrinsicHTMLAttributes<vidom.OptionHTMLAttributes, HTMLOptionElement>;
output: IntrinsicHTMLAttributes<vidom.HTMLAttributes>;
p: IntrinsicHTMLAttributes<vidom.HTMLAttributes, HTMLParagraphElement>;
param: IntrinsicHTMLAttributes<vidom.ParamHTMLAttributes, HTMLParamElement>;
picture: IntrinsicHTMLAttributes;
pre: IntrinsicHTMLAttributes<vidom.HTMLAttributes, HTMLPreElement>;
progress: IntrinsicHTMLAttributes<vidom.ProgressHTMLAttributes, HTMLProgressElement>;
q: IntrinsicHTMLAttributes<vidom.QuoteHTMLAttributes, HTMLQuoteElement>;
rp: IntrinsicHTMLAttributes;
rt: IntrinsicHTMLAttributes;
ruby: IntrinsicHTMLAttributes;
s: IntrinsicHTMLAttributes;
samp: IntrinsicHTMLAttributes;
script: IntrinsicHTMLAttributes<vidom.ScriptHTMLAttributes, HTMLScriptElement>;
section: IntrinsicHTMLAttributes;
select: IntrinsicHTMLAttributes<vidom.SelectHTMLAttributes, HTMLSelectElement>;
small: IntrinsicHTMLAttributes;
source: IntrinsicHTMLAttributes<vidom.SourceHTMLAttributes, HTMLSourceElement>;
span: IntrinsicHTMLAttributes<vidom.HTMLAttributes, HTMLSpanElement>;
strong: IntrinsicHTMLAttributes;
style: IntrinsicHTMLAttributes<vidom.StyleHTMLAttributes, HTMLStyleElement>;
sub: IntrinsicHTMLAttributes;
summary: IntrinsicHTMLAttributes;
sup: IntrinsicHTMLAttributes;
table: IntrinsicHTMLAttributes<vidom.TableHTMLAttributes, HTMLTableElement>;
tbody: IntrinsicHTMLAttributes<vidom.HTMLAttributes, HTMLTableSectionElement>;
td: IntrinsicHTMLAttributes<vidom.TdHTMLAttributes, HTMLTableDataCellElement>;
textarea: IntrinsicHTMLAttributes<vidom.TextareaHTMLAttributes, HTMLTextAreaElement>;
tfoot: IntrinsicHTMLAttributes<vidom.HTMLAttributes, HTMLTableSectionElement>;
th: IntrinsicHTMLAttributes<vidom.ThHTMLAttributes, HTMLTableHeaderCellElement>;
thead: IntrinsicHTMLAttributes<vidom.HTMLAttributes, HTMLTableSectionElement>;
time: IntrinsicHTMLAttributes<vidom.TimeHTMLAttributes>;
title: IntrinsicHTMLAttributes<vidom.HTMLAttributes, HTMLTitleElement>;
tr: IntrinsicHTMLAttributes<vidom.HTMLAttributes, HTMLTableRowElement>;
track: IntrinsicHTMLAttributes<vidom.TrackHTMLAttributes, HTMLTrackElement>;
u: IntrinsicHTMLAttributes;
ul: IntrinsicHTMLAttributes<vidom.HTMLAttributes, HTMLUListElement>;
'var': IntrinsicHTMLAttributes;
video: IntrinsicHTMLAttributes<vidom.VideoHTMLAttributes, HTMLVideoElement>;
wbr: IntrinsicHTMLAttributes;
// SVG
svg: IntrinsicSVGAttributes<SVGSVGElement>;
animate: IntrinsicSVGAttributes<SVGElement>;
circle: IntrinsicSVGAttributes<SVGCircleElement>;
clipPath: IntrinsicSVGAttributes<SVGClipPathElement>;
defs: IntrinsicSVGAttributes<SVGDefsElement>;
desc: IntrinsicSVGAttributes<SVGDescElement>;
ellipse: IntrinsicSVGAttributes<SVGEllipseElement>;
feBlend: IntrinsicSVGAttributes<SVGFEBlendElement>;
feColorMatrix: IntrinsicSVGAttributes<SVGFEColorMatrixElement>;
feComponentTransfer: IntrinsicSVGAttributes<SVGFEComponentTransferElement>;
feComposite: IntrinsicSVGAttributes<SVGFECompositeElement>;
feConvolveMatrix: IntrinsicSVGAttributes<SVGFEConvolveMatrixElement>;
feDiffuseLighting: IntrinsicSVGAttributes<SVGFEDiffuseLightingElement>;
feDisplacementMap: IntrinsicSVGAttributes<SVGFEDisplacementMapElement>;
feDistantLight: IntrinsicSVGAttributes<SVGFEDistantLightElement>;
feFlood: IntrinsicSVGAttributes<SVGFEFloodElement>;
feFuncA: IntrinsicSVGAttributes<SVGFEFuncAElement>;
feFuncB: IntrinsicSVGAttributes<SVGFEFuncBElement>;
feFuncG: IntrinsicSVGAttributes<SVGFEFuncGElement>;
feFuncR: IntrinsicSVGAttributes<SVGFEFuncRElement>;
feGaussianBlur: IntrinsicSVGAttributes<SVGFEGaussianBlurElement>;
feImage: IntrinsicSVGAttributes<SVGFEImageElement>;
feMerge: IntrinsicSVGAttributes<SVGFEMergeElement>;
feMergeNode: IntrinsicSVGAttributes<SVGFEMergeNodeElement>;
feMorphology: IntrinsicSVGAttributes<SVGFEMorphologyElement>;
feOffset: IntrinsicSVGAttributes<SVGFEOffsetElement>;
fePointLight: IntrinsicSVGAttributes<SVGFEPointLightElement>;
feSpecularLighting: IntrinsicSVGAttributes<SVGFESpecularLightingElement>;
feSpotLight: IntrinsicSVGAttributes<SVGFESpotLightElement>;
feTile: IntrinsicSVGAttributes<SVGFETileElement>;
feTurbulence: IntrinsicSVGAttributes<SVGFETurbulenceElement>;
filter: IntrinsicSVGAttributes<SVGFilterElement>;
foreignObject: IntrinsicSVGAttributes<SVGForeignObjectElement>;
g: IntrinsicSVGAttributes<SVGGElement>;
image: IntrinsicSVGAttributes<SVGImageElement>;
line: IntrinsicSVGAttributes<SVGLineElement>;
linearGradient: IntrinsicSVGAttributes<SVGLinearGradientElement>;
marker: IntrinsicSVGAttributes<SVGMarkerElement>;
mask: IntrinsicSVGAttributes<SVGMaskElement>;
metadata: IntrinsicSVGAttributes<SVGMetadataElement>;
path: IntrinsicSVGAttributes<SVGPathElement>;
pattern: IntrinsicSVGAttributes<SVGPatternElement>;
polygon: IntrinsicSVGAttributes<SVGPolygonElement>;
polyline: IntrinsicSVGAttributes<SVGPolylineElement>;
radialGradient: IntrinsicSVGAttributes<SVGRadialGradientElement>;
rect: IntrinsicSVGAttributes<SVGRectElement>;
stop: IntrinsicSVGAttributes<SVGStopElement>;
switch: IntrinsicSVGAttributes<SVGSwitchElement>;
symbol: IntrinsicSVGAttributes<SVGSymbolElement>;
text: IntrinsicSVGAttributes<SVGTextElement>;
textPath: IntrinsicSVGAttributes<SVGTextPathElement>;
tspan: IntrinsicSVGAttributes<SVGTSpanElement>;
use: IntrinsicSVGAttributes<SVGUseElement>;
view: IntrinsicSVGAttributes<SVGViewElement>;
}
}
} | the_stack |
import dayjs from 'dayjs';
import React, { useEffect, useState } from 'react';
import { apis } from '../apis';
import { Button } from '../components/button';
import { FOCUS_END_CLASS, FOCUS_START_CLASS } from '../components/constants';
import {
Dialog,
DialogBody,
DialogFooter,
DialogHeader,
DialogProps,
DialogTitle,
} from '../components/dialog';
import { Input } from '../components/input';
import { ControlLabel, Label, LabelWrapper, SubLabel } from '../components/label';
import { Menu, MenuItem } from '../components/menu';
import { Portal } from '../components/portal';
import { Row, RowItem } from '../components/row';
import {
Section,
SectionBody,
SectionHeader,
SectionItem,
SectionTitle,
} from '../components/section';
import {
Table,
TableBody,
TableCell,
TableHeader,
TableHeaderCell,
TableHeaderRow,
TableRow,
} from '../components/table';
import { TextArea } from '../components/textarea';
import { useClassName, usePrevious } from '../components/utilities';
import { translate } from '../locales';
import { addMessageListeners, sendMessage } from '../messages';
import { Subscription, SubscriptionId, Subscriptions } from '../types';
import { AltURL, MatchPattern, isErrorResult, numberEntries, numberKeys } from '../utilities';
import { FromNow } from './from-now';
import { useOptionsContext } from './options-context';
import { SetIntervalItem } from './set-interval-item';
const PERMISSION_PASSLIST = [
'*://*.githubusercontent.com/*',
// A third-party CDN service supporting GitHub, GitLab and BitBucket
'*://cdn.statically.io/*',
];
async function requestPermission(urls: readonly string[]): Promise<boolean> {
const origins: string[] = [];
const passlist = PERMISSION_PASSLIST.map(pass => new MatchPattern(pass));
for (const url of urls) {
const u = new AltURL(url);
if (passlist.some(pass => pass.test(u))) {
continue;
}
origins.push(`${u.scheme}://${u.host}/*`);
}
// Don't call `permissions.request` when unnecessary. re #110
return origins.length ? apis.permissions.request({ origins }) : true;
}
const AddSubscriptionDialog: React.VFC<
{
initialName: string;
initialURL: string;
setSubscriptions: React.Dispatch<React.SetStateAction<Subscriptions>>;
} & DialogProps
> = ({ close, open, initialName, initialURL, setSubscriptions }) => {
const [state, setState] = useState(() => ({
name: initialName,
// required
nameValid: initialName !== '',
url: initialURL,
urlValid: (() => {
// pattern="https?:.*"
// required
if (!initialURL || !/^https?:/.test(initialURL)) {
return false;
}
// type="url"
try {
new URL(initialURL);
} catch {
return false;
}
return true;
})(),
}));
const prevOpen = usePrevious(open);
if (open && prevOpen === false) {
state.name = '';
state.nameValid = false;
state.url = '';
state.urlValid = false;
}
const ok = state.nameValid && state.urlValid;
return (
<Dialog aria-labelledby="addSubscriptionDialogTitle" close={close} open={open}>
<DialogHeader>
<DialogTitle id="addSubscriptionDialogTitle">
{translate('options_addSubscriptionDialog_title')}
</DialogTitle>
</DialogHeader>
<DialogBody>
<Row>
<RowItem expanded>
<LabelWrapper fullWidth>
<ControlLabel for="subscriptionName">
{translate('options_addSubscriptionDialog_nameLabel')}
</ControlLabel>
</LabelWrapper>
{open && (
<Input
className={FOCUS_START_CLASS}
id="subscriptionName"
required={true}
value={state.name}
onChange={e =>
setState(s => ({
...s,
name: e.currentTarget.value,
nameValid: e.currentTarget.validity.valid,
}))
}
/>
)}
</RowItem>
</Row>
<Row>
<RowItem expanded>
<LabelWrapper fullWidth>
<ControlLabel for="subscriptionURL">
{translate('options_addSubscriptionDialog_urlLabel')}
</ControlLabel>
</LabelWrapper>
{open && (
<Input
id="subscriptionURL"
pattern="https?:.*"
required={true}
type="url"
value={state.url}
onChange={e =>
setState(s => ({
...s,
url: e.currentTarget.value,
urlValid: e.currentTarget.validity.valid,
}))
}
/>
)}
</RowItem>
</Row>
</DialogBody>
<DialogFooter>
<Row right>
<RowItem>
<Button {...(!ok ? { className: FOCUS_END_CLASS } : {})} onClick={close}>
{translate('cancelButton')}
</Button>
</RowItem>
<RowItem>
<Button
{...(ok ? { className: FOCUS_END_CLASS } : {})}
disabled={!ok}
primary
onClick={async () => {
if (!(await requestPermission([state.url]))) {
return;
}
const subscription = {
name: state.name,
url: state.url,
blacklist: '',
updateResult: null,
};
const id = await sendMessage('add-subscription', subscription);
setSubscriptions(subscriptions => ({ ...subscriptions, [id]: subscription }));
close();
}}
>
{translate('options_addSubscriptionDialog_addButton')}
</Button>
</RowItem>
</Row>
</DialogFooter>
</Dialog>
);
};
const ShowSubscriptionDialog: React.VFC<{ subscription: Subscription | null } & DialogProps> = ({
close,
open,
subscription,
}) => {
return (
<Dialog aria-labelledby="showSubscriptionDialogTitle" close={close} open={open}>
<DialogHeader>
<DialogTitle id="showSubscriptionDialogTitle">{subscription?.name ?? ''}</DialogTitle>
</DialogHeader>
<DialogBody>
<Row>
<RowItem expanded>
{open && (
<TextArea
aria-label={translate('options_showSubscriptionDialog_blacklistLabel')}
className={FOCUS_START_CLASS}
readOnly
rows={10}
value={subscription?.blacklist ?? ''}
wrap="off"
/>
)}
</RowItem>
</Row>
</DialogBody>
<DialogFooter>
<Row right>
<RowItem>
<Button className={FOCUS_END_CLASS} primary onClick={close}>
{translate('okButton')}
</Button>
</RowItem>
</Row>
</DialogFooter>
</Dialog>
);
};
const ManageSubscription: React.VFC<{
id: SubscriptionId;
setShowSubscriptionDialogOpen: React.Dispatch<React.SetStateAction<boolean>>;
setShowSubscriptionDialogSubscription: React.Dispatch<React.SetStateAction<Subscription | null>>;
setSubscriptions: React.Dispatch<React.SetStateAction<Subscriptions>>;
subscription: Subscription;
updating: boolean;
}> = ({
id,
setSubscriptions,
setShowSubscriptionDialogOpen,
setShowSubscriptionDialogSubscription,
subscription,
updating,
}) => {
return (
<TableRow>
<TableCell>{subscription.name}</TableCell>
<TableCell breakAll>{subscription.url}</TableCell>
<TableCell>
{updating ? (
translate('options_subscriptionUpdateRunning')
) : !subscription.updateResult ? (
''
) : isErrorResult(subscription.updateResult) ? (
translate('error', subscription.updateResult.message)
) : (
<FromNow time={dayjs(subscription.updateResult.timestamp)} />
)}
</TableCell>
<TableCell>
<Menu aria-label={translate('options_subscriptionMenuButtonLabel')}>
<MenuItem
onClick={() => {
requestAnimationFrame(() => {
setShowSubscriptionDialogOpen(true);
setShowSubscriptionDialogSubscription(subscription);
});
}}
>
{translate('options_showSubscriptionMenu')}
</MenuItem>
<MenuItem
onClick={async () => {
if (!(await requestPermission([subscription.url]))) {
return;
}
await sendMessage('update-subscription', id);
}}
>
{translate('options_updateSubscriptionNowMenu')}
</MenuItem>
<MenuItem
onClick={async () => {
await sendMessage('remove-subscription', id);
setSubscriptions(subscriptions => {
const newSubscriptions = { ...subscriptions };
delete newSubscriptions[id];
return newSubscriptions;
});
}}
>
{translate('options_removeSubscriptionMenu')}
</MenuItem>
</Menu>
</TableCell>
</TableRow>
);
};
export const ManageSubscriptions: React.VFC<{
subscriptions: Subscriptions;
setSubscriptions: React.Dispatch<React.SetStateAction<Subscriptions>>;
}> = ({ subscriptions, setSubscriptions }) => {
const { query } = useOptionsContext();
const [updating, setUpdating] = useState<Record<SubscriptionId, boolean>>({});
const [addSubscriptionDialogOpen, setAddSubscriptionDialogOpen] = useState(
query.addSubscriptionName != null || query.addSubscriptionURL != null,
);
const [showSubscriptionDialogOpen, setShowSubscriptionDialogOpen] = useState(false);
const [showSubscriptionDialogSubscription, setShowSubscriptionDialogSubscription] =
useState<Subscription | null>(null);
useEffect(
() =>
addMessageListeners({
'subscription-updating': id => {
setUpdating(updating => ({ ...updating, [id]: true }));
},
'subscription-updated': (id, subscription) => {
setSubscriptions(subscriptions =>
subscriptions[id] ? { ...subscriptions, [id]: subscription } : subscriptions,
);
setUpdating(updating => ({ ...updating, [id]: false }));
},
}),
[subscriptions, setSubscriptions],
);
const emptyClass = useClassName({
minHeight: '3em',
textAlign: 'center',
});
return (
<SectionItem>
<Row>
<RowItem expanded>
<LabelWrapper>
<Label>{translate('options_subscriptionFeature')}</Label>
<SubLabel>{translate('options_subscriptionFeatureDescription')}</SubLabel>
</LabelWrapper>
</RowItem>
<RowItem>
<Button
primary
onClick={() => {
setAddSubscriptionDialogOpen(true);
}}
>
{translate('options_addSubscriptionButton')}
</Button>
</RowItem>
</Row>
{numberKeys(subscriptions).length ? (
<Row>
<RowItem expanded>
<Table>
<TableHeader>
<TableHeaderRow>
<TableHeaderCell width="20%">
{translate('options_subscriptionNameHeader')}
</TableHeaderCell>
{
// #if !SAFARI
<TableHeaderCell width="calc(60% - 0.75em - 36px)">
{translate('options_subscriptionURLHeader')}
</TableHeaderCell>
/* #else
<TableHeaderCell width="calc((min(640px, 100vw) - 1.25em * 2) * 0.6 - 0.75em - 36px)">
{translate('options_subscriptionURLHeader')}
</TableHeaderCell>
*/
// #endif
}
<TableHeaderCell width="20%">
{translate('options_subscriptionUpdateResultHeader')}
</TableHeaderCell>
<TableHeaderCell width="calc(0.75em + 36px)" />
</TableHeaderRow>
</TableHeader>
<TableBody>
{numberEntries(subscriptions)
.sort(([id1, { name: name1 }], [id2, { name: name2 }]) =>
name1 < name2 ? -1 : name1 > name2 ? 1 : id1 - id2,
)
.map(([id, subscription]) => (
<ManageSubscription
id={id}
key={id}
setShowSubscriptionDialogOpen={setShowSubscriptionDialogOpen}
setShowSubscriptionDialogSubscription={setShowSubscriptionDialogSubscription}
setSubscriptions={setSubscriptions}
subscription={subscription}
updating={updating[id] ?? false}
/>
))}
</TableBody>
</Table>
</RowItem>
</Row>
) : (
<Row className={emptyClass}>
<RowItem expanded>{translate('options_noSubscriptionsAdded')}</RowItem>
</Row>
)}
<Row right>
<RowItem>
<Button
disabled={!numberKeys(subscriptions).length}
onClick={async () => {
if (!(await requestPermission(Object.values(subscriptions).map(s => s.url)))) {
return;
}
await sendMessage('update-all-subscriptions');
}}
>
{translate('options_updateAllSubscriptionsNowButton')}
</Button>
</RowItem>
</Row>
<Portal id="addSubscriptionDialogPortal">
<AddSubscriptionDialog
close={() => setAddSubscriptionDialogOpen(false)}
initialName={query.addSubscriptionName ?? ''}
initialURL={query.addSubscriptionURL ?? ''}
open={addSubscriptionDialogOpen}
setSubscriptions={setSubscriptions}
/>
</Portal>
<Portal id="showSubscriptionDialogPortal">
<ShowSubscriptionDialog
close={() => setShowSubscriptionDialogOpen(false)}
open={showSubscriptionDialogOpen}
subscription={showSubscriptionDialogSubscription}
/>
</Portal>
</SectionItem>
);
};
export const SubscriptionSection: React.VFC = () => {
const {
initialItems: { subscriptions: initialSubscriptions },
} = useOptionsContext();
const [subscriptions, setSubscriptions] = useState(initialSubscriptions);
return (
<Section aria-labelledby="subscriptionSectionTitle" id="subscription">
<SectionHeader>
<SectionTitle id="subscriptionSectionTitle">
{translate('options_subscriptionTitle')}
</SectionTitle>
</SectionHeader>
<SectionBody>
<ManageSubscriptions setSubscriptions={setSubscriptions} subscriptions={subscriptions} />
<SectionItem>
<SetIntervalItem
disabled={!numberKeys(subscriptions).length}
itemKey="updateInterval"
label={translate('options_updateInterval')}
valueOptions={[5, 15, 30, 60, 120, 300]}
/>
</SectionItem>
</SectionBody>
</Section>
);
}; | the_stack |
import { hyper } from 'hyperhtml/esm'
import { OsmWay } from '../../../utils/types/osm-data'
import { WaysInRelation } from '../../../utils/types/osm-data-storage'
import { OsmKeyValue } from '../../../utils/types/preset'
import { presets } from './presets'
import { getAllTagsBlock } from '../lane-info'
export function getLaneEditForm(osm: OsmWay, waysInRelation: WaysInRelation, cutLaneListener: (way: OsmWay) => void): HTMLFormElement {
const form = hyper`
<form id="${osm.id}"
class="editor-form">
<label class="editor-form__side-switcher">
<input id="side-switcher"
type="checkbox"
class="editor-form__side-switcher-checkbox"
onchange=${handleSideSwitcherChange}>
Both
</label>
<button title="Cut lane"
type="button"
class="editor-form__cut-button"
style="${waysInRelation[osm.id] ? displayNone : null}"
onclick=${() => cutLaneListener(osm)}>
✂
</button>
<dl>
${getSideGroup(osm, 'both')}
${getSideGroup(osm, 'right')}
${getSideGroup(osm, 'left')}
</dl>
</form>` as HTMLFormElement
const existsRightTags = existsSideTags(form, 'right')
const existsLeftTags = existsSideTags(form, 'left')
const existsBothTags = existsSideTags(form, 'both')
if (!existsRightTags && !existsLeftTags && existsBothTags) {
form.querySelector<HTMLElement>('#right')!.style.display = 'none'
form.querySelector<HTMLElement>('#left')!.style.display = 'none'
} else if (!existsBothTags) {
form.querySelector<HTMLElement>('#both')!.style.display = 'none'
}
form.querySelector<HTMLInputElement>('#side-switcher')!.checked = existsBothTags
return form
}
function existsSideTags(form: HTMLFormElement, side: string) {
const regex = new RegExp('^parking:.*' + side)
for (const input of Array.from(form)) {
if ((input instanceof HTMLInputElement || input instanceof HTMLSelectElement) &&
regex.test(input.name) && input.value !== '')
return true
}
return false
}
function handleSideSwitcherChange(e: Event) {
if (!(e.currentTarget instanceof HTMLInputElement))
return
if (e.currentTarget.checked) {
hideElement('right')
hideElement('left')
showElement('both')
} else {
showElement('right')
showElement('left')
hideElement('both')
}
}
function getSideGroup(osm: OsmWay, side: 'both'|'left'|'right') {
return hyper`
<div id=${side}
class="tags-block tags-block_${side}">
${getPresetSigns(osm, side)}
<table>
${getTagInputs(osm, side)}
</table>
${getAllTagsBlock(osm.tags, side)}
</div>`
}
const parkingLaneTagTemplates = [
'parking:lane:{side}',
'parking:lane:{side}:{type}',
'parking:condition:{side}',
'parking:condition:{side}:time_interval',
'parking:condition:{side}:default',
'parking:condition:{side}:maxstay',
'parking:condition:{side}:capacity',
]
function getTagInputs(osm: OsmWay, side: 'both'|'left'|'right') {
const inputs: HTMLElement[] = []
const type = osm.tags[`parking:lane:${side}`] || 'type'
for (const tagTemplate of parkingLaneTagTemplates)
inputs.push(getTagInput(osm, side, type, tagTemplate))
return inputs
}
function getTagInput(osm: OsmWay, side: string, parkingType: string, tagTemplate: string) {
const tag = tagTemplate
.replace('{side}', side)
.replace('{type}', parkingType)
const tagSplit = tag.split(':')
const label = tagSplit[Math.floor(tagSplit.length / 2) * 2 - 1]
const value = osm.tags[tag]
let input: HTMLInputElement | HTMLSelectElement
let hide = false
switch (tagTemplate) {
case 'parking:lane:{side}':
input = getSelectInput(tag, value, laneValues)
input.oninput = handleLaneTagInput
break
case 'parking:condition:{side}:time_interval':
input = getTextInput(tag, value)
input.oninput = handleTimeIntervalTagInput
break
case 'parking:lane:{side}:{type}': {
input = getSelectInput(tag, value, typeValues)
const laneTag = 'parking:lane:{side}'
.replace('{side}', side)
hide = !['parallel', 'diagonal', 'perpendicular']
.includes(osm.tags[laneTag])
break
}
case 'parking:condition:{side}':
input = getSelectInput(tag, value, conditionValues)
input.oninput = handleConditionTagInput
break
case 'parking:condition:{side}:default': {
input = getTextInput(tag, value)
const timeIntervalTag = 'parking:condition:{side}:time_interval'
.replace('{side}', side)
hide = !osm.tags[timeIntervalTag]
break
}
case 'parking:condition:{side}:maxstay': {
input = getTextInput(tag, value)
const conditionTag = 'parking:condition:{side}'
.replace('{side}', side)
hide = osm.tags[conditionTag] !== 'disc'
break
}
default:
input = getTextInput(tag, value)
break
}
input.onchange = (e) => {
if (!(e.currentTarget instanceof HTMLInputElement || e.currentTarget instanceof HTMLSelectElement) ||
e.currentTarget.form == null)
return
const newOsm = formToOsmWay(osm, e.currentTarget.form)
osmChangeListener?.(newOsm)
}
return hyper`
<tr id="${tag}"
style=${{ display: hide ? 'none' : null }}>
<td><label title="${tag}">${label}</label></td>
<td>
${input}
</td>
</tr>` as HTMLElement
}
function getSelectInput(tag: string, value: string, values: string[]): HTMLSelectElement {
const options = !value || values.includes(value) ?
['', ...values] :
['', value, ...values]
return hyper`
<select name=${tag}>
${options.map(o => hyper`<option value=${o} selected=${value === o}>${o}</option>`)}
</select>`
}
function getTextInput(tag: string, value: string): HTMLInputElement {
return hyper`
<input type="text"
placeholder="${tag}"
name="${tag}"
value="${value ?? ''}">`
}
function getPresetSigns(osm: OsmWay, side: 'both'|'left'|'right') {
return presets.map(x => hyper`
<img src=${x.img.src}
class="sign-preset"
height=${x.img.height}
width=${x.img.width}
alt=${x.img.alt}
title=${x.img.title}
onclick=${() => handlePresetClick(x.tags, osm, side)}>`)
}
/**
* Set the content of all the select and input elements in the form when clicking on a preset.
* @param tags An array of objects containing an OSM key and corresponding value for the preset
* @param osm The OSM way we have selected
* @param side What side of the OSM way we are applying this preset to
*/
function handlePresetClick(
tags: OsmKeyValue[], osm: OsmWay, side: 'both' | 'left' | 'right',
): void {
for (const tag of tags) {
// Replace the placeholder `{side}` in the key with the actual side
const osmTagKey = tag.k.replace('{side}', side)
// Some controls are selects, some are textboxes
const inputSelector = `form[id='${osm.id}'] [name='${osmTagKey}']`
const currentInput = document.querySelector(inputSelector) as
HTMLInputElement | HTMLSelectElement
// Set the textbox/select content
currentInput.value = tag.v
}
const inputSelector = `form[id='${osm.id}'] [name='${`parking:lane:${side}`}']`
const element = document.querySelector(inputSelector) as HTMLInputElement | HTMLSelectElement
element.dispatchEvent(new Event('change'))
}
function handleLaneTagInput(e: Event) {
const el = e.target as HTMLSelectElement
const side = el.name.split(':')[2]
// Type tag should only exist when parking:lane:side has one on the following values
if (['parallel', 'diagonal', 'perpendicular'].includes(el.value)) {
// exact name of the tag depends on parking:lane:side value
const typeTagTr = document.querySelector<HTMLElement>(`[id^="parking:lane:${side}:"]`)
typeTagTr!.id = `parking:lane:${side}:${el.value}`
typeTagTr!.style.display = ''
typeTagTr!.querySelector<HTMLElement>('label')!.innerText = el.value
const typeTagSelect = document.querySelector<HTMLInputElement>(`[name^="parking:lane:${side}:"]`)
typeTagSelect!.name = `parking:lane:${side}:${el.value}`
} else {
document.querySelector<HTMLElement>(`[id^="parking:lane:${side}:"]`)!.style.display = 'none'
document.querySelector<HTMLInputElement>(`[name^="parking:lane:${side}:"]`)!.value = ''
}
}
function handleConditionTagInput(e: Event) {
const el = e.target as HTMLInputElement
const side = el.name.split(':')[2]
const maxstayTr = document.getElementById(`parking:condition:${side}:maxstay`)
if (el.value === 'disc')
hideElement(maxstayTr!.id)
else
showElement(maxstayTr!.id)
}
function handleTimeIntervalTagInput(e: Event) {
const el = e.target as HTMLInputElement
const side = el.name.split(':')[2]
const defaultConditionTr = document.getElementById(`parking:condition:${side}:default`)
if (el.value === '')
hideElement(defaultConditionTr!.id)
else
showElement(defaultConditionTr!.id)
}
function showElement(id: string) {
document.getElementById(id)!.style.display = ''
}
function hideElement(id: string) {
document.getElementById(id)!.style.display = 'none'
}
const displayNone = { display: 'none' }
const laneValues = [
'parallel',
'diagonal',
'perpendicular',
'no_parking',
'no_stopping',
'marked',
'fire_lane',
'no',
]
const typeValues = [
'on_street',
'street_side',
'on_kerb',
'half_on_kerb',
'painted_area_only',
'shoulder',
]
const conditionValues = [
'free',
'ticket',
'disc',
'residents',
'customers',
'private',
]
let osmChangeListener: (way: OsmWay) => void
export function setOsmChangeListener(listener: (way: OsmWay) => void) {
osmChangeListener = listener
}
function formToOsmWay(osm: OsmWay, form: HTMLFormElement) {
const regex = /^parking:/
const supprtedTags = parkingLaneTagTemplates
.map(x => {
const tagRegexPart = x
.replace('{side}', '(both|right|left)')
.replace('{type}', '(parallel|diagonal|perpendicular)')
return new RegExp('^' + tagRegexPart + '$')
})
for (const tagKey of Object.keys(osm.tags)) {
if (supprtedTags.some(regex => regex.test(tagKey)))
delete osm.tags[tagKey]
}
for (const input of Array.from(form.elements)) {
if ((input instanceof HTMLInputElement || input instanceof HTMLSelectElement) &&
regex.test(input.name) && input.value)
osm.tags[input.name] = input.value
}
return osm
} | the_stack |
import type { ITabTable, SheetSDK, SheetValues } from './SheetSDK'
import { SheetError } from './SheetSDK'
import type { ColumnHeaders, IRowModel } from './RowModel'
import { RowAction, rowPosition, stringer } from './RowModel'
/**
* Compare dates without running into numeric comparison problems
* @param a first date to compare
* @param b second date to compare
* @returns 0 if dates are equal, positive if a > b, negative if a < b
*/
export const compareDates = (a: Date, b: Date) => a.getTime() - b.getTime()
export interface IMaker<T> {
new (values?: any): T
}
export interface IRowDelta<T extends IRowModel> {
updates: T[]
deletes: T[]
creates: T[]
}
// TODO maybe get a technique from https://stackoverflow.com/a/34698946 or
// https://www.logicbig.com/tutorials/misc/typescript/generic-constraints.html
// TODO refactor WhollySheet<T> into something a bit cleaner
// ref https://www.smashingmagazine.com/2020/10/understanding-typescript-generics/
export class TypedRows<T> {
rows: T[] = []
constructor(rows: T[], Maker?: IMaker<T>) {
if (Maker) {
this.rows = rows.map((v) => new Maker(v))
} else {
this.rows = rows
}
}
public add(value: T): void {
this.rows.push(value)
}
public where(predicate: (value: T) => boolean): TypedRows<T> {
return TypedRows.from<T>(this.rows.filter(predicate))
}
public select<U>(selector: (value: T) => U): TypedRows<U> {
return TypedRows.from<U>(this.rows.map(selector))
}
public toArray(): T[] {
return this.rows
}
public static from<U>(values: U[]): TypedRows<U> {
// Perhaps we perform some logic here.
// ...
return new TypedRows<U>(values)
}
public static create<U>(values?: U[]): TypedRows<U> {
return new TypedRows<U>(values ?? [])
}
// Other collection functions.
// ..
}
export interface IWhollySheet<T extends IRowModel, P> {
/** Initialized REST-based GSheets SDK */
sheets: SheetSDK
/** Name of the tab in the sheet */
name: string
/**
* Header column names for reading from/writing to the sheet.
* The order of the column names **must** match the order of the columns in the sheet.
* The values used to read and write the sheet are always in column order position.
*/
header: ColumnHeaders
/** Column names to display */
displayHeader: ColumnHeaders
/** Name of the key column that represents the "id" */
keyColumn: string
/** All data in the sheet */
rows: T[]
/** Keyed row retrieval */
index: Record<string, T>
/** What's the next row of the sheet? */
nextRow: number
// TODO figure out init generic typing issue
// init(values?: any): (values?: any) => T
/**
* Verify the column order in the sheet matches the key order of the row type
* @param header array of column names in order
*/
checkHeader(header: ColumnHeaders): boolean
/**
* True if the column name should be displayed in a UI
*
* False if it's an "internal" column name
*
* @param columnName to check for display
*/
displayable(columnName: string): boolean
/**
* Gets the row's values in table.header column order
* @param model row to introspect
*/
values(model: T): SheetValues
/**
* Returns a 2D array of all row values based on the current rows collection.
* The result include the header row
*/
allValues(): SheetValues
/**
* Create a new row of this type
* @param values either a value array or an object
*/
typeRow<T extends IRowModel>(values?: any): T
/**
* Converts raw rows into typed rows.
*
* @param rows array of data to convert. Either value arrays or a collection of objects
*/
typeRows<T extends IRowModel>(rows: SheetValues): T[]
/** Reload the entire tab by fetching all its values from the GSheet */
refresh<T extends IRowModel>(): Promise<T[]>
/**
* Save the specified row to the sheet.
*
* This routine determines whether to call update or create based on whether the row position is < 1
*
* @param model row to save
* @param force true to skip checking for outdated values. Defaults to false.
*/
save<T extends IRowModel>(model: T, force?: boolean): Promise<T>
/**
* Create a row in the sheet
*
* If the row position is > 0 an error is thrown
*
* @param model row to create in sheet
*/
create<T extends IRowModel>(model: T): Promise<T>
/**
* Update a row in the sheet
*
* If the row position is < 1 an error is thrown
*
* If the row is checkOutdated an error is thrown
*
* @param model row to create in sheet
* @param force true to skip checking for outdated values. Defaults to false.
*/
update<T extends IRowModel>(model: T, force?: boolean): Promise<T>
/**
* Reads the specified row directly from the sheet
* @param row
*/
rowGet<T extends IRowModel>(row: number): Promise<T | undefined>
/**
* Delete a row if it still exists
* @param model to delete
* @param force true to skip checking for outdated values. Defaults to false.
*/
delete<T extends IRowModel>(model: T, force?: boolean): Promise<boolean>
/**
* If the row is out of date, it throws a SheetError
* @param model row for status check
* @param source row to compare against
*/
checkOutdated<T extends IRowModel>(model: T, source?: T): Promise<boolean>
/**
* Find the matching row. If columnName is the primary key field, indexed retrieval is used
*
* @param value to find
* @param columnName in which to find the value. Defaults to primary key. If primary key, indexed retrieval is use.
*/
find(value: any, columnName?: string): T | undefined
/**
* Reassigns collection rows, checks header, and reindexes
* @param rows to overwrite current list
*/
loadRows<T extends IRowModel>(rows: SheetValues): T[]
/** Converts the row collection to a plain javascript object array */
toObject(): P[]
/** Assigns the passed object[] to the rows collection */
fromObject<T extends IRowModel>(obj: P[]): T[]
/** Gets the delta rows for a batch update */
getDelta<T extends IRowModel>(): IRowDelta<T>
/**
* Processes a delta change against the tab values snapshot
* @param tab SheetValues to update (includes header row)
* @param delta row changes to apply
*/
mergePurge<T extends IRowModel>(
tab: SheetValues,
delta: IRowDelta<T>
): SheetValues
/**
* Prepare a batch for processing
*
* If `force` is false and update rows are outdated, a SheetError with outdated list is thrown
* @param tab of sheet values to use for update checks (includes header row)
* @param delta change to merge and purge
* @param force prepare each row but don't worry about outdated rows
*/
prepareBatch<T extends IRowModel>(
tab: SheetValues,
delta: IRowDelta<T>,
force?: boolean
): boolean
/**
* Perform a batch update by retrieving the delta for the sheet, check for outdated update rows,
* and update the entire tab sheet with the changes
* @param force true to skip checking for outdated update rows
*/
batchUpdate<T extends IRowModel>(force?: boolean): Promise<T[]>
}
/** CRUDF operations for a GSheet tab */
export abstract class WhollySheet<T extends IRowModel, P>
extends TypedRows<T>
implements IWhollySheet<T, P>
{
index: Record<string, T> = {}
constructor(
public readonly sheets: SheetSDK,
/** name of the tab in the GSheet document */
public readonly name: string,
public readonly table: ITabTable,
public readonly keyColumn: string = '_id'
) {
super([])
this.loadRows(table.rows)
}
loadRows<T extends IRowModel>(rows: SheetValues): T[] {
this.rows = this.typeRows(rows)
this.checkHeader()
this.createIndex()
return this.rows as unknown as T[]
}
abstract typeRow<T extends IRowModel>(values?: any): T
typeRows<T extends IRowModel>(rows: SheetValues): T[] {
const result: T[] = []
let pos = 1
rows.forEach((r) => {
const row: T = this.typeRow(r)
pos++
// fixup row position?
if (!row[rowPosition]) row[rowPosition] = pos
result.push(row)
})
return result
}
// // TODO figure out init generic typing issue
// init(values?: any): T {
// const result: T = new this.NewItem(values)
// return result
// }
/**
* convert value to the strong type, or undefined if not value
* @param value to strongly type
* @private
*/
private static toAT<T extends IRowModel>(value: unknown): T | undefined {
if (value) return value as T
return undefined
}
checkHeader() {
// Nothing to check
if (this.rows.length === 0) return true
const row = this.rows[0]
const rowHeader = row.header().join()
const tableHeader = this.table.header.join()
if (tableHeader !== rowHeader)
throw new SheetError(
`Expected ${this.name} header to be ${rowHeader} not ${tableHeader}`
)
return true
}
get header() {
return this.table.header
}
get nextRow() {
// +1 for header row
// +1 for 1-based rows
return this.rows.length + 2
}
private createIndex() {
this.index = {}
this.rows.forEach((r) => {
this.index[r[this.keyColumn]] = r
})
}
values<T extends IRowModel>(model: T) {
const result: SheetValues = []
this.header.forEach((h) => {
result.push(stringer(model[h]))
})
return result
}
allValues(): SheetValues {
const values: SheetValues = [this.header]
values.push(...this.rows.map((r) => this.values(r)))
return values
}
async save<T extends IRowModel>(model: T, force = false): Promise<T> {
// A model with a non-zero row is an update
if (model._row) return await this.update<T>(model, force)
// Create currently returns the row not the model
return (await this.create<T>(model)) as unknown as T
}
checkId<T extends IRowModel>(model: T) {
if (!model[this.keyColumn])
throw new SheetError(
`"${this.keyColumn}" must be assigned for ${this.name} row ${model._row}`
)
}
async create<T extends IRowModel>(model: T): Promise<T> {
if (model._row > 0)
throw new SheetError(
`create needs ${this.name} "${
model[this.keyColumn]
}" row to be < 1, not ${model._row}`
)
model.prepare()
this.checkId(model)
const values = this.values(model)
const result = await this.sheets.rowCreate(this.name, this.nextRow, values)
if (result.row < 1 || !result.values || result.values.length === 0)
throw new SheetError(`Could not create row for ${model[this.keyColumn]}`)
// This returns an array of values with 1 entry per row value array
const newRow = this.typeRow(result.values[0])
newRow._row = result.row
if (result.row === this.nextRow) {
// No other rows have been added
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this.rows.push(newRow as unknown as T)
this.createIndex()
} else {
await this.refresh()
}
return this.index[newRow[this.keyColumn]] as unknown as T
}
async update<T extends IRowModel>(model: T, force = false): Promise<T> {
if (!model._row)
throw new SheetError(
`${this.name} "${model[this.keyColumn]}" row must be > 0 to update`
)
if (!force) await this.checkOutdated(model)
let rowPos = -1
model.prepare()
this.checkId(model)
const values = this.values(model)
/** This will throw an error if the request fails */
const result = await this.sheets.rowUpdate(this.name, model._row, values)
if (result.values) {
// This returns an array of values with 1 entry per row value array
const updateValues = result.values[0]
rowPos = this.rows.findIndex((row) => (row._row = model._row))
this.rows[rowPos].assign(updateValues)
}
// ID may have changed?
this.createIndex()
return this.rows[rowPos] as unknown as T
}
find(value: any, columnName?: string): T | undefined {
if (!value) return undefined
let key = columnName || this.keyColumn
if (typeof value === 'number') {
// Default key to row
if (!columnName) key = '_row'
}
if (columnName === this.keyColumn) {
// Find by index
return WhollySheet.toAT(this.index[value.toString()])
}
return WhollySheet.toAT(this.rows.find((r) => r[key] === value))
}
private _displayHeader: ColumnHeaders = []
get displayHeader(): ColumnHeaders {
if (this._displayHeader.length === 0) {
this._displayHeader = this.header.filter((colName) =>
this.displayable(colName)
)
}
return this._displayHeader
}
async delete<T extends IRowModel>(model: T, force = false) {
if (!force) await this.checkOutdated(model)
const values = await this.sheets.rowDelete(this.name, model._row)
this.rows = this.typeRows(values)
this.createIndex()
return true
}
displayable(columnName: string): boolean {
return !(columnName.startsWith('_') || columnName.startsWith('$'))
}
async rowGet<T extends IRowModel>(row: number): Promise<T | undefined> {
const values = await this.sheets.rowGet(this.name, row)
if (!values || values.length === 0) return undefined
// Returns a nested array of values, 1 top element per row
const typed = this.typeRow(values[0])
// ugly hack cheat for type conversion
return typed as unknown as T
}
async checkOutdated<T extends IRowModel>(model: T, source?: T) {
if (model._row < 1) return false
const errors: string[] = []
if (!source) source = await this.rowGet<T>(model._row)
if (!source) {
errors.push(`Row not found`)
} else {
if (
source._updated !== undefined &&
compareDates(source._updated, model._updated) !== 0
) {
errors.push(`update is ${source._updated} not ${model._updated}`)
}
if (source[this.keyColumn] !== model[this.keyColumn])
errors.push(
`${this.keyColumn} is "${source[this.keyColumn]}" not "${
model[this.keyColumn]
}"`
)
}
if (errors.length > 0)
throw new SheetError(
`${this.name} row ${model._row} is outdated: ${errors.join()}`
)
return false
}
async refresh<T extends IRowModel>(): Promise<T[]> {
let values = await this.sheets.tabValues(this.name)
// trim header row
values = values.slice(1)
const rows = this.typeRows(values) as unknown as T[]
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this.rows = rows
this.createIndex()
return rows
}
fromObject<T extends IRowModel>(obj: P[]): T[] {
this.loadRows(obj)
return this.rows as unknown as T[]
}
toObject(): P[] {
return this.rows.map((r) => r.toObject() as unknown as P)
}
async batchUpdate<T extends IRowModel>(force = false): Promise<T[]> {
const delta = this.getDelta()
let values = await this.sheets.tabValues(this.name)
this.prepareBatch(values, delta, force)
values = this.mergePurge(values, delta)
if (delta.deletes.length > 0) await this.sheets.tabClear(this.name)
const response = await this.sheets.batchUpdate(this.name, values)
return this.loadRows(response)
}
getDelta<T extends IRowModel>(): IRowDelta<T> {
const updates = this.rows.filter((r) => r.$action === RowAction.Update)
// Sort deletions in descending row order
const deletes = this.rows
.filter((r) => r.$action === RowAction.Delete)
.sort((a, b) => b._row - a._row)
const creates = this.rows.filter((r) => r.$action === RowAction.Create)
return {
updates: updates as unknown as T[],
deletes: deletes as unknown as T[],
creates: creates as unknown as T[],
}
}
mergePurge<T extends IRowModel>(
values: SheetValues,
delta: IRowDelta<T>
): SheetValues {
delta.updates.forEach((u) => (values[u._row - 1] = this.values(u)))
delta.deletes.forEach((d) => values.splice(d._row - 1, 1))
delta.creates.forEach((c) => values.push(this.values(c)))
return values
}
prepareBatch<T extends IRowModel>(
values: SheetValues,
delta: IRowDelta<T>,
force?: boolean
): boolean {
if (!force) {
const errors = []
try {
delta.updates.forEach((u) =>
this.checkOutdated(u, this.typeRow(values[u._row - 1]))
)
delta.deletes.forEach((d) =>
this.checkOutdated(d, this.typeRow(values[d._row - 1]))
)
} catch (e: any) {
errors.push(e.message)
}
if (errors.length > 0) throw new SheetError(errors.join('\n'))
}
delta.updates.forEach((u) => u.prepare())
delta.creates.forEach((c) => c.prepare())
return true
}
} | the_stack |
import * as assert from 'assert'
import * as sinon from 'sinon'
import * as vscode from 'vscode'
import { AslVisualizationCDK } from '../../../stepFunctions/commands/visualizeStateMachine/aslVisualizationCDK'
import { AslVisualizationCDKManager } from '../../../stepFunctions/commands/visualizeStateMachine/aslVisualizationCDKManager'
import { ConstructNode, isStateMachine } from '../../../cdk/explorer/nodes/constructNode'
import { ConstructTreeEntity } from '../../../cdk/explorer/tree/types'
import { Disposable } from 'vscode-languageclient'
import { ext } from '../../../shared/extensionGlobals'
import { FakeParentNode } from '../../cdk/explorer/constructNode.test'
import { getLogger, Logger } from '../../../shared/logger'
import { StateMachineGraphCache } from '../../../stepFunctions/utils'
// Top level defintions
let mockAslVisualizationCDKManager: MockAslVisualizationCDKManager
let sandbox: sinon.SinonSandbox
const mockGlobalStorage: vscode.Memento = {
update: sinon.spy(),
get: sinon.stub().returns(undefined),
}
const mockUri: vscode.Uri = {
authority: 'amazon.com',
fragment: 'MockFragmentOne',
fsPath: 'MockFSPathOne',
query: 'MockQueryOne',
path: '/MockPathOne',
scheme: 'MockSchemeOne',
with: () => {
return mockUri
},
toJSON: sinon.spy(),
}
const mockTextDocument: vscode.TextDocument = {
eol: 1,
fileName: 'MockFileNameOne',
isClosed: false,
isDirty: false,
isUntitled: false,
languageId: 'MockLanguageIdOne',
lineCount: 0,
uri: mockUri,
version: 0,
getText: () => {
return 'MockDocumentTextOne'
},
getWordRangeAtPosition: sinon.spy(),
lineAt: sinon.spy(),
offsetAt: sinon.spy(),
positionAt: sinon.spy(),
save: sinon.spy(),
validatePosition: sinon.spy(),
validateRange: sinon.spy(),
}
const mockJsonData =
'{"Comment":"A Hello World example of the Amazon States Language using Pass states","StartAt":"Hello","States":{"Hello":{"Type":"Pass","Result":"Hello","Next":"World"},"World":{"Type":"Pass","Result":"${Text}","End":true}}}'
const mockExtensionContext: vscode.ExtensionContext = {
extensionPath: '',
globalState: mockGlobalStorage,
globalStoragePath: '',
logPath: '',
storagePath: '',
subscriptions: [],
workspaceState: mockGlobalStorage,
asAbsolutePath: sinon.spy(),
}
const mockNonSMConstructTreeEntity: ConstructTreeEntity = {
id: 'MyLambdaFunction',
path: 'aws-tester/MyLambdaFunction',
children: {
Resource: {
id: 'Resource',
path: 'aws-tester/MyLambdaFunction/Resource',
attributes: {
'aws:cdk:cloudformation:type': 'AWS::StepFunctions::LambdaFunction',
},
},
},
}
const mockStateMachineConstructTreeEntity: ConstructTreeEntity = {
id: 'MyStateMachine',
path: 'aws-tester/MyStateMachine',
children: {
Resource: {
id: 'Resource',
path: 'aws-tester/MyStateMachine/Resource',
attributes: {
'aws:cdk:cloudformation:type': 'AWS::StepFunctions::StateMachine',
},
},
},
}
const mockNonStateMachineNode = new ConstructNode(
new FakeParentNode('cdkJsonPath'),
'MyCDKApp1/MyLambdaFunction',
vscode.TreeItemCollapsibleState.Collapsed,
mockNonSMConstructTreeEntity
)
const mockStateMachineNode = new ConstructNode(
new FakeParentNode('cdkJsonPath'),
'MyCDKApp1/MyStateMachine',
vscode.TreeItemCollapsibleState.Collapsed,
mockStateMachineConstructTreeEntity
)
const mockStateMachineNodeDiffAppSameName = new ConstructNode(
new FakeParentNode('cdkJsonPath'),
'MyCDKApp2/MyStateMachine',
vscode.TreeItemCollapsibleState.Collapsed,
mockStateMachineConstructTreeEntity
)
const mockStateMachineNodeSameAppDiffName = new ConstructNode(
new FakeParentNode('cdkJsonPath'),
'MyCDKApp1/MyStateMachine2',
vscode.TreeItemCollapsibleState.Collapsed,
mockStateMachineConstructTreeEntity
)
describe('StepFunctions VisualizeStateMachine', async function () {
const oldWebviewScriptsPath = ext.visualizationResourcePaths.localWebviewScriptsPath
const oldWebviewBodyPath = ext.visualizationResourcePaths.webviewBodyScript
const oldCachePath = ext.visualizationResourcePaths.visualizationLibraryCachePath
const oldScriptPath = ext.visualizationResourcePaths.visualizationLibraryScript
const oldCssPath = ext.visualizationResourcePaths.visualizationLibraryCSS
const oldThemePath = ext.visualizationResourcePaths.stateMachineCustomThemePath
const oldThemeCssPath = ext.visualizationResourcePaths.stateMachineCustomThemeCSS
// Before all
before(function () {
ext.visualizationResourcePaths.localWebviewScriptsPath = mockUri
ext.visualizationResourcePaths.visualizationLibraryCachePath = mockUri
ext.visualizationResourcePaths.stateMachineCustomThemePath = mockUri
ext.visualizationResourcePaths.webviewBodyScript = mockUri
ext.visualizationResourcePaths.visualizationLibraryScript = mockUri
ext.visualizationResourcePaths.visualizationLibraryCSS = mockUri
ext.visualizationResourcePaths.stateMachineCustomThemeCSS = mockUri
sandbox = sinon.createSandbox()
sandbox.stub(StateMachineGraphCache.prototype, 'updateCachedFile').callsFake(async options => {
return
})
})
// Before each
beforeEach(function () {
mockAslVisualizationCDKManager = new MockAslVisualizationCDKManager(mockExtensionContext, 'Workspace1')
})
// After all
after(function () {
sandbox.restore()
ext.visualizationResourcePaths.localWebviewScriptsPath = oldWebviewScriptsPath
ext.visualizationResourcePaths.webviewBodyScript = oldWebviewBodyPath
ext.visualizationResourcePaths.visualizationLibraryCachePath = oldCachePath
ext.visualizationResourcePaths.visualizationLibraryScript = oldScriptPath
ext.visualizationResourcePaths.visualizationLibraryCSS = oldCssPath
ext.visualizationResourcePaths.stateMachineCustomThemePath = oldThemePath
ext.visualizationResourcePaths.stateMachineCustomThemeCSS = oldThemeCssPath
})
// Tests
it('Test AslVisualizationCDK on setup all properties are correct', function () {
const vis = new MockAslVisualizationCDK(mockTextDocument, '', '', '')
assert.deepStrictEqual(vis.documentUri, mockTextDocument.uri)
assert.strictEqual(vis.getIsPanelDisposed(), false)
assert.strictEqual(vis.getDisposables().length, 5)
const panel = vis.getPanel() as vscode.WebviewPanel
assert.ok(panel)
assert.ok(panel.title.length > 0)
assert.strictEqual(panel.viewType, 'stateMachineVisualization')
let webview = vis.getWebview()
webview = webview as vscode.Webview
assert.ok(webview)
assert.ok(webview.html)
})
it('Test AslVisualizationCDKManager on setup managedVisualizationsCDK set is empty', function () {
assert.strictEqual(mockAslVisualizationCDKManager.getManagedVisualizations().size, 0)
})
it('Test AslVisualizationCDKManager managedVisualizationsCDK set still empty if node is not of type state machine', async function () {
assert.strictEqual(mockAslVisualizationCDKManager.getManagedVisualizations().size, 0)
// Preview with non state machine node
assert.strictEqual(
await mockAslVisualizationCDKManager.visualizeStateMachine(mockGlobalStorage, mockNonStateMachineNode),
undefined
)
assert.strictEqual(mockAslVisualizationCDKManager.getManagedVisualizations().size, 0)
})
it('Test AslVisualizationCDKManager managedVisualizationsCDK set has one AslVisCDK on first visualization', async function () {
assert.strictEqual(mockAslVisualizationCDKManager.getManagedVisualizations().size, 0)
assert.ok(await mockAslVisualizationCDKManager.visualizeStateMachine(mockGlobalStorage, mockStateMachineNode))
assert.strictEqual(mockAslVisualizationCDKManager.getManagedVisualizations().size, 1)
})
it('Test AslVisualizationCDKManager managedVisualizationsCDK set does not add second VisCDK on duplicate state machine node', async function () {
assert.strictEqual(mockAslVisualizationCDKManager.getManagedVisualizations().size, 0)
// visualization for mockStateMachineNode
await mockAslVisualizationCDKManager.visualizeStateMachine(mockGlobalStorage, mockStateMachineNode)
assert.strictEqual(mockAslVisualizationCDKManager.getManagedVisualizations().size, 1)
// visualization for the same mockStateMachineNode
await mockAslVisualizationCDKManager.visualizeStateMachine(mockGlobalStorage, mockStateMachineNode)
assert.strictEqual(mockAslVisualizationCDKManager.getManagedVisualizations().size, 1)
})
it('Test AslVisualizationCDKManager managedVisualizationsCDK set adds second VisCDK on different state machine nodes (same workspace, same cdk application name with different state machine names)', async function () {
assert.strictEqual(mockAslVisualizationCDKManager.getManagedVisualizations().size, 0)
// visualization for mockStateMachineNode
await mockAslVisualizationCDKManager.visualizeStateMachine(mockGlobalStorage, mockStateMachineNode)
assert.strictEqual(mockAslVisualizationCDKManager.getManagedVisualizations().size, 1)
// visualization for mockStateMachineNode2
await mockAslVisualizationCDKManager.visualizeStateMachine(
mockGlobalStorage,
mockStateMachineNodeSameAppDiffName
)
assert.strictEqual(
mockAslVisualizationCDKManager
.getManagedVisualizations()
.get(mockAslVisualizationCDKManager.getWorkspaceName())?.size,
2
)
})
it('Test AslVisualizationCDKManager managedVisualizationsCDK set adds second VisCDK on different state machine nodes (same workspace, different cdk application names with same state machine name)', async function () {
assert.strictEqual(mockAslVisualizationCDKManager.getManagedVisualizations().size, 0)
// visualization for mockStateMachineNode
await mockAslVisualizationCDKManager.visualizeStateMachine(mockGlobalStorage, mockStateMachineNode)
assert.strictEqual(mockAslVisualizationCDKManager.getManagedVisualizations().size, 1)
// visualization for mockStateMachineNode2
await mockAslVisualizationCDKManager.visualizeStateMachine(
mockGlobalStorage,
mockStateMachineNodeDiffAppSameName
)
assert.strictEqual(
mockAslVisualizationCDKManager
.getManagedVisualizations()
.get(mockAslVisualizationCDKManager.getWorkspaceName())?.size,
2
)
})
it('Test AslVisualizationCDKManager managedVisualizationsCDK set adds second VisCDK on different state machine nodes (different workspaces, same cdk application name with same state machine name)', async function () {
assert.strictEqual(mockAslVisualizationCDKManager.getManagedVisualizations().size, 0)
// visualization for mockStateMachineNode
await mockAslVisualizationCDKManager.visualizeStateMachine(mockGlobalStorage, mockStateMachineNode)
assert.strictEqual(mockAslVisualizationCDKManager.getManagedVisualizations().size, 1)
//change workspace
mockAslVisualizationCDKManager.setWorkspaceName('Workspace2')
// visualization for mockStateMachineNode2
await mockAslVisualizationCDKManager.visualizeStateMachine(mockGlobalStorage, mockStateMachineNode)
assert.strictEqual(mockAslVisualizationCDKManager.getManagedVisualizations().size, 2)
})
it('Test AslVisualizationCDKManager managedVisualizationsCDK set does not add duplicate renders when multiple VisCDK active', async function () {
assert.strictEqual(mockAslVisualizationCDKManager.getManagedVisualizations().size, 0)
// visualization for mockStateMachineNode
await mockAslVisualizationCDKManager.visualizeStateMachine(mockGlobalStorage, mockStateMachineNode)
assert.strictEqual(mockAslVisualizationCDKManager.getManagedVisualizations().size, 1)
// visualization for mockStateMachineNode2
await mockAslVisualizationCDKManager.visualizeStateMachine(
mockGlobalStorage,
mockStateMachineNodeSameAppDiffName
)
assert.strictEqual(
mockAslVisualizationCDKManager
.getManagedVisualizations()
.get(mockAslVisualizationCDKManager.getWorkspaceName())?.size,
2
)
// visualization for mockStateMachineNode again
await mockAslVisualizationCDKManager.visualizeStateMachine(mockGlobalStorage, mockStateMachineNode)
assert.strictEqual(
mockAslVisualizationCDKManager
.getManagedVisualizations()
.get(mockAslVisualizationCDKManager.getWorkspaceName())?.size,
2
)
// visualization for mockStateMachineNode2 again
await mockAslVisualizationCDKManager.visualizeStateMachine(
mockGlobalStorage,
mockStateMachineNodeSameAppDiffName
)
assert.strictEqual(
mockAslVisualizationCDKManager
.getManagedVisualizations()
.get(mockAslVisualizationCDKManager.getWorkspaceName())?.size,
2
)
})
})
class MockAslVisualizationCDK extends AslVisualizationCDK {
protected getText(textDocument: vscode.TextDocument): string {
return mockJsonData
}
protected getTemplateJsonDocument(templatePath: string): vscode.Uri {
return mockUri
}
public getIsPanelDisposed(): boolean {
return this.isPanelDisposed
}
public getDisposables(): Disposable[] {
return this.disposables
}
}
class MockAslVisualizationCDKManager extends AslVisualizationCDKManager {
protected workspaceName: string
constructor(extensionContext: vscode.ExtensionContext, workspaceName: string) {
super(extensionContext)
this.workspaceName = workspaceName
}
public getWorkspaceName(): string {
return this.workspaceName
}
public setWorkspaceName(workspaceName: string): void {
this.workspaceName = workspaceName
}
public async visualizeStateMachine(
globalStorage: vscode.Memento,
node: ConstructNode
): Promise<vscode.WebviewPanel | undefined> {
if (!isStateMachine(node.construct)) {
return
}
const logger: Logger = getLogger()
const uniqueIdentifier = node.label
const stateMachineName = uniqueIdentifier.substring(
uniqueIdentifier.lastIndexOf('/') + 1,
uniqueIdentifier.length
)
const templatePath = 'templatePath'
const existingVisualization = this.getExistingVisualization(this.workspaceName, uniqueIdentifier)
if (existingVisualization) {
existingVisualization.showPanel()
return existingVisualization.getPanel()
}
// If existing visualization does not exist, construct new visualization
try {
const newVisualization = new MockAslVisualizationCDK(
mockTextDocument,
templatePath,
uniqueIdentifier,
stateMachineName
)
if (newVisualization) {
this.handleNewVisualization(this.workspaceName, newVisualization)
return newVisualization.getPanel()
}
} catch (err) {
this.handleErr(err as Error, logger)
}
return
}
} | the_stack |
export default `
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
# Compl_icated_H€aDer
## [2.16.0] - 2021-03-26
### Added
- Metrics for http requests ([#1586](https://github.com/scm-manager/scm-manager/issues/1586))
- Metrics for executor services ([#1586](https://github.com/scm-manager/scm-manager/issues/1586))
- Metrics about logging, file descriptors, process threads and process memory ([#1609](https://github.com/scm-manager/scm-manager/pull/1609))
- Metrics for events ([#1601](https://github.com/scm-manager/scm-manager/pull/1601))
- Authentication and access metrics ([#1595](https://github.com/scm-manager/scm-manager/pull/1595))
- Adds metrics over lifetime duration of working copies ([#1591](https://github.com/scm-manager/scm-manager/pull/1591))
- Collect guava caching statistics as metrics ([#1590](https://github.com/scm-manager/scm-manager/pull/1590))
- Add global flag to enable/disable api keys ([#1606](https://github.com/scm-manager/scm-manager/pull/1606))
### Fixed
- Adjust path and filename validation to prevent path traversal ([#1604](https://github.com/scm-manager/scm-manager/pull/1604))
- Wrong subject context for asynchronous subscriber ([#1601](https://github.com/scm-manager/scm-manager/pull/1601))
- Fix repository creation route from repository namespace overview page ([#1602](https://github.com/scm-manager/scm-manager/pull/1602))
- external nav links now correctly collapse when used in a menu ([#1596](https://github.com/scm-manager/scm-manager/pull/1596))
- Response with exception stack trace for invalid urls ([#1605](https://github.com/scm-manager/scm-manager/pull/1605))
- Do not show repositories on overview for not existing namespace ([#1608](https://github.com/scm-manager/scm-manager/pull/1608))
### Changed
- Show "CUSTOM" name instead empty entry for permission roles ([#1597](https://github.com/scm-manager/scm-manager/pull/1597))
- Improve error messages for invalid media types ([#1607](https://github.com/scm-manager/scm-manager/pull/1607))
- Allow all UTF-8 characters except URL identifiers as user and group names and for namespaces. ([#1600](https://github.com/scm-manager/scm-manager/pull/1600))
## [2.15.1] - 2021-03-17
### Fixed
- Encode revision on extension points to fix breaking change ([#1585](https://github.com/scm-manager/scm-manager/pull/1585))
- Index link collection in repository initialize extensions ([#1594](https://github.com/scm-manager/scm-manager/issues/1588) and [#1587](https://github.com/scm-manager/scm-manager/issues/1594))
- Mercurial encoding configuration per repository ([#1577](https://github.com/scm-manager/scm-manager/issues/1577), [#1583](https://github.com/scm-manager/scm-manager/issues/1583))
- Authentication names in open api spec ([#1582](https://github.com/scm-manager/scm-manager/issues/1582))
- Sometimes no redirect after login ([#1592](https://github.com/scm-manager/scm-manager/pull/1592))
- Navigate after search ([#1589](https://github.com/scm-manager/scm-manager/pull/1589))
- Diff for mercurial and subversion ([#1588](https://github.com/scm-manager/scm-manager/issues/1588) and [#1587](https://github.com/scm-manager/scm-manager/issues/1587))
## [2.15.0] - 2021-03-12
### Added
- Create api for markdown ast plugins ([#1578](https://github.com/scm-manager/scm-manager/pull/1578))
- Partial diff ([#1581](https://github.com/scm-manager/scm-manager/issues/1581))
- Added filepath search ([#1568](https://github.com/scm-manager/scm-manager/issues/1568))
- API for metrics ([#1576](https://github.com/scm-manager/scm-manager/issues/1576))
- Add repository-specific non-fast-forward disallowed option ([#1579](https://github.com/scm-manager/scm-manager/issues/1579))
### Fixed
- Fix wrapping of title and actions in source view ([#1569](https://github.com/scm-manager/scm-manager/issues/1569))
- Split SetupContextListener logic into new Privileged Startup API ([#1573](https://github.com/scm-manager/scm-manager/pull/1573))
- Mark configuration files in debian package ([#1574](https://github.com/scm-manager/scm-manager/issues/1574))
## [2.14.1] - 2021-03-03
### Fixed
- Prevent breadcrumb overflow and shrink large elements ([#1563](https://github.com/scm-manager/scm-manager/pull/1563))
- Clarify that FileUpload component does not upload directly ([#1566](https://github.com/scm-manager/scm-manager/pull/1566))
- Prevent xss from stored markdown ([#1566](https://github.com/scm-manager/scm-manager/pull/1566))
- Fix endless loading spinner for sources of empty repositories ([#1565](https://github.com/scm-manager/scm-manager/issues/1565))
- Fix missing permalink button to markdown headings ([#1564](https://github.com/scm-manager/scm-manager/pull/1564))
- Fix redirect after logout if is set
## [2.14.0] - 2021-03-01
### Added
- Repository data can be migrated independently to enable the import of dumps from older versions ([#1526](https://github.com/scm-manager/scm-manager/pull/1526))
- XML attribute in root element of config entry stores ([#1545](https://github.com/scm-manager/scm-manager/pull/1545))
- Add option to encrypt repository exports with a password and decrypt them on repository import ([#1533](https://github.com/scm-manager/scm-manager/pull/1533))
- Make repository export asynchronous. ([#1533](https://github.com/scm-manager/scm-manager/pull/1533))
- Lock repository to "read-only" access during export ([#1519](https://github.com/scm-manager/scm-manager/pull/1519))
- Warn user to not leave page during repository import ([#1536](https://github.com/scm-manager/scm-manager/pull/1536))
- Import repository permissions from repository archive ([#1520](https://github.com/scm-manager/scm-manager/pull/1520))
- Added import protocols ([#1558](https://github.com/scm-manager/scm-manager/pull/1558))
### Fixed
- Loading of cache configuration from plugins ([#1540](https://github.com/scm-manager/scm-manager/pull/1540))
- Missing error message for wrong password ([#1527](https://github.com/scm-manager/scm-manager/pull/1527))
- Sporadic error in reading git pack files ([#1518](https://github.com/scm-manager/scm-manager/issues/1518))
- Fix permission check for branch deletion ([#1515](https://github.com/scm-manager/scm-manager/pull/1515))
- Fix broken mercurial http post args configuration ([#1532](https://github.com/scm-manager/scm-manager/issues/1532))
- Do not resolve external groups for system accounts ([#1541](https://github.com/scm-manager/scm-manager/pull/1541))
- Wrong redirect on paginated overviews ([#1535](https://github.com/scm-manager/scm-manager/pull/1535))
### Changed
- Config entry stores are handled explicitly in exports ([#1545](https://github.com/scm-manager/scm-manager/pull/1545))
- Allow usage of cache as shiro authentication and authorization cache ([#1540](https://github.com/scm-manager/scm-manager/pull/1540))
- Implement new changelog process ([#1517](https://github.com/scm-manager/scm-manager/issues/1517))
- Fire post receive repository hook event after the repository import has been finished. ([#1544](https://github.com/scm-manager/scm-manager/pull/1544))
- improve frontend performance with stale while revalidate pattern ([#1555](https://github.com/scm-manager/scm-manager/pull/1555))
- Change the order of files inside the repository archive ([#1538](https://github.com/scm-manager/scm-manager/pull/1538))
## [2.13.0] - 2021-01-29
### Added
- Repository export for Subversion ([#1488](https://github.com/scm-manager/scm-manager/pull/1488))
- Provide more options for Helm chart ([#1485](https://github.com/scm-manager/scm-manager/pull/1485))
- Option to create a permanent link to a source file ([#1489](https://github.com/scm-manager/scm-manager/pull/1489))
- Markdown codeblock renderer extension point ([#1492](https://github.com/scm-manager/scm-manager/pull/1492))
- Java version added to plugin center url ([#1494](https://github.com/scm-manager/scm-manager/pull/1494))
- Font ttf-dejavu included oci image ([#1498](https://github.com/scm-manager/scm-manager/issues/1498))
- Repository import and export with metadata for Subversion ([#1501](https://github.com/scm-manager/scm-manager/pull/1501))
- API for store rename/delete in update steps ([#1505](https://github.com/scm-manager/scm-manager/pull/1505))
- Import and export for Git via dump file ([#1507](https://github.com/scm-manager/scm-manager/pull/1507))
- Import and export for Mercurial via dump file ([#1511](https://github.com/scm-manager/scm-manager/pull/1511))
### Changed
- Directory name for git LFS files ([#1504](https://github.com/scm-manager/scm-manager/pull/1504))
- Temporary data for repositories is kept in the repository directory, not in a global directory ([#1510](https://github.com/scm-manager/scm-manager/pull/1510))
- Migrate integration tests to bdd ([#1497](https://github.com/scm-manager/scm-manager/pull/1497))
- Layout of proxy settings ([#1502](https://github.com/scm-manager/scm-manager/pull/1502))
- Apply test ids to production builds for usage in e2e tests ([#1499](https://github.com/scm-manager/scm-manager/pull/1499))
- Bump google guava version to 30.1-jre
- Refactor table component so that it can be styled by styled-components ([#1503](https://github.com/scm-manager/scm-manager/pull/1503))
- Enrich styleguide with new features, rules and changes ([#1506](https://github.com/scm-manager/scm-manager/pull/1506))
### Fixed
- Add explicit provider setup for bouncy castle ([#1500](https://github.com/scm-manager/scm-manager/pull/1500))
- Repository contact information is editable ([#1508](https://github.com/scm-manager/scm-manager/pull/1508))
- Usage of custom realm description for scm protocols ([#1512](https://github.com/scm-manager/scm-manager/pull/1512))
## [2.12.0] - 2020-12-17
### Added
- Add repository import via dump file for Subversion ([#1471](https://github.com/scm-manager/scm-manager/pull/1471))
- Add support for permalinks to lines in source code view ([#1472](https://github.com/scm-manager/scm-manager/pull/1472))
- Add "archive" flag for repositories to make them immutable ([#1477](https://github.com/scm-manager/scm-manager/pull/1477))
### Changed
- Implement mercurial cgi protocol as extension ([#1458](https://github.com/scm-manager/scm-manager/pull/1458))
### Fixed
- Add "Api Key" page link to sub-navigation of "User" and "Me" sections ([#1464](https://github.com/scm-manager/scm-manager/pull/1464))
- Empty page on repository namespace filter ([#1476](https://github.com/scm-manager/scm-manager/pull/1476))
- Usage of namespace filter and search action together on repository overview ([#1476](https://github.com/scm-manager/scm-manager/pull/1476))
- Fix tooltip arrow height in firefox ([#1479](https://github.com/scm-manager/scm-manager/pull/1479))
- Accidentally blocked requests with non ascii characters ([#1480](https://github.com/scm-manager/scm-manager/issues/1480) and [#1469](https://github.com/scm-manager/scm-manager/issues/1469))
## [2.11.1] - 2020-12-07
### Fixed
- Initialization of new git repository with master set as default branch ([#1467](https://github.com/scm-manager/scm-manager/issues/1467) and [#1470](https://github.com/scm-manager/scm-manager/pull/1470))
## [2.11.0] - 2020-12-04
### Added
- Add tooltips to short links on repository overview ([#1441](https://github.com/scm-manager/scm-manager/pull/1441))
- Show the date of the last commit for branches in the frontend ([#1439](https://github.com/scm-manager/scm-manager/pull/1439))
- Unify and add description to key view across user settings ([#1440](https://github.com/scm-manager/scm-manager/pull/1440))
- Healthcheck for docker image ([#1428](https://github.com/scm-manager/scm-manager/issues/1428) and [#1454](https://github.com/scm-manager/scm-manager/issues/1454))
- Tags can now be added and deleted through the ui ([#1456](https://github.com/scm-manager/scm-manager/pull/1456))
- The ui now displays tag signatures ([#1456](https://github.com/scm-manager/scm-manager/pull/1456))
- Repository import via URL for git ([#1460](https://github.com/scm-manager/scm-manager/pull/1460))
- Repository import via URL for hg ([#1463](https://github.com/scm-manager/scm-manager/pull/1463))
### Changed
- Send mercurial hook callbacks over separate tcp socket instead of http ([#1416](https://github.com/scm-manager/scm-manager/pull/1416))
### Fixed
- Language detection of files with interpreter parameters e.g.: \`#!/usr/bin/make -f\` ([#1450](https://github.com/scm-manager/scm-manager/issues/1450))
- Unexpected mercurial server pool stop ([#1446](https://github.com/scm-manager/scm-manager/issues/1446) and [#1457](https://github.com/scm-manager/scm-manager/issues/1457))
## [2.10.1] - 2020-11-24
### Fixed
- Improved logging of failures during plugin installation ([#1442](https://github.com/scm-manager/scm-manager/pull/1442))
- Do not throw exception when plugin file does not exist on cancelled installation ([#1442](https://github.com/scm-manager/scm-manager/pull/1442))
## [2.10.0] - 2020-11-20
### Added
- Delete branches directly in the UI ([#1422](https://github.com/scm-manager/scm-manager/pull/1422))
- Lookup command which provides further repository information ([#1415](https://github.com/scm-manager/scm-manager/pull/1415))
- Include messages from scm protocol in modification or merge errors ([#1420](https://github.com/scm-manager/scm-manager/pull/1420))
- Enhance trace api to accepted status codes ([#1430](https://github.com/scm-manager/scm-manager/pull/1430))
- Add examples to core resources to simplify usage of rest api ([#1434](https://github.com/scm-manager/scm-manager/pull/1434))
### Fixed
- Missing close of hg diff command ([#1417](https://github.com/scm-manager/scm-manager/pull/1417))
- Error on repository initialization with least-privilege user ([#1414](https://github.com/scm-manager/scm-manager/pull/1414))
- Adhere to git quiet flag ([#1421](https://github.com/scm-manager/scm-manager/pull/1421))
- Resolve svn binary diffs properly [#1427](https://github.com/scm-manager/scm-manager/pull/1427)
## [2.9.1] - 2020-11-11
### Fixed
- German translation for repositories view
## [2.9.0] - 2020-11-06
### Added
- Tracing api ([#1393](https://github.com/scm-manager/scm-manager/pull/#1393))
- Automatic user converter for external users ([#1380](https://github.com/scm-manager/scm-manager/pull/1380))
- Create _authenticated group on setup ([#1396](https://github.com/scm-manager/scm-manager/pull/1396))
- The name of the initial git branch can be configured and is set to \`main\` by default ([#1399](https://github.com/scm-manager/scm-manager/pull/1399))
### Fixed
- Internal server error for git sub modules without tree object ([#1397](https://github.com/scm-manager/scm-manager/pull/1397))
- Do not expose subversion commit with id 0 ([#1395](https://github.com/scm-manager/scm-manager/pull/1395))
- Cloning of Mercurial repositories with api keys ([#1407](https://github.com/scm-manager/scm-manager/pull/1407))
- Disable cloning repositories via ssh for anonymous users ([#1403](https://github.com/scm-manager/scm-manager/pull/1403))
- Support anonymous file download through rest api for non-browser clients (e.g. curl or postman) when anonymous mode is set to protocol-only ([#1402](https://github.com/scm-manager/scm-manager/pull/1402))
- SVN diff with property changes ([#1400](https://github.com/scm-manager/scm-manager/pull/1400))
- Branches link in repository overview ([#1404](https://github.com/scm-manager/scm-manager/pull/1404))
## [2.8.0] - 2020-10-27
### Added
- Generation of email addresses for users, where none is configured ([#1370](https://github.com/scm-manager/scm-manager/pull/1370))
- Source code fullscreen view ([#1376](https://github.com/scm-manager/scm-manager/pull/1376))
- Plugins can now expose ui components to be shared with other plugins ([#1382](https://github.com/scm-manager/scm-manager/pull/1382))
### Changed
- Reduce logging of ApiTokenRealm ([#1385](https://github.com/scm-manager/scm-manager/pull/1385))
- Centralise syntax highlighting ([#1382](https://github.com/scm-manager/scm-manager/pull/1382))
### Fixed
- Handling of snapshot plugin dependencies ([#1384](https://github.com/scm-manager/scm-manager/pull/1384))
- SyntaxHighlighting for GoLang ([#1386](https://github.com/scm-manager/scm-manager/pull/1386))
- Privilege escalation for api keys ([#1388](https://github.com/scm-manager/scm-manager/pull/1388))
## [2.6.3] - 2020-10-16
### Fixed
- Missing default permission to manage public gpg keys ([#1377](https://github.com/scm-manager/scm-manager/pull/1377))
## [2.7.1] - 2020-10-14
### Fixed
- Null Pointer Exception on anonymous migration with deleted repositories ([#1371](https://github.com/scm-manager/scm-manager/pull/1371))
- Null Pointer Exception on parsing SVN properties ([#1373](https://github.com/scm-manager/scm-manager/pull/1373))
### Changed
- Reduced logging for invalid JWT or api keys ([#1374](https://github.com/scm-manager/scm-manager/pull/1374))
## [2.7.0] - 2020-10-12
### Added
- Users can create API keys with limited permissions ([#1359](https://github.com/scm-manager/scm-manager/pull/1359))
## [2.6.2] - 2020-10-09
### Added
- Introduce api for handling token validation failed exception ([#1362](https://github.com/scm-manager/scm-manager/pull/1362))
### Fixed
- Align actionbar item horizontal and enforce correct margin between them ([#1358](https://github.com/scm-manager/scm-manager/pull/1358))
- Fix recursive browse command for git ([#1361](https://github.com/scm-manager/scm-manager/pull/1361))
- SubRepository support ([#1357](https://github.com/scm-manager/scm-manager/pull/1357))
## [2.6.1] - 2020-09-30
### Fixed
- Not found error when using browse command in empty hg repository ([#1355](https://github.com/scm-manager/scm-manager/pull/1355))
## [2.6.0] - 2020-09-25
### Added
- Add support for pr merge with prior rebase ([#1332](https://github.com/scm-manager/scm-manager/pull/1332))
- Tags overview for repository ([#1331](https://github.com/scm-manager/scm-manager/pull/1331))
- Permissions can be specified for namespaces ([#1335](https://github.com/scm-manager/scm-manager/pull/1335))
- Show update info on admin information page ([#1342](https://github.com/scm-manager/scm-manager/pull/1342))
### Changed
- Rework modal to use react portal ([#1349](https://github.com/scm-manager/scm-manager/pull/1349))
### Fixed
- Missing synchronization during repository creation ([#1328](https://github.com/scm-manager/scm-manager/pull/1328))
- Missing BranchCreatedEvent for mercurial ([#1334](https://github.com/scm-manager/scm-manager/pull/1334))
- Branch not found right after creation ([#1334](https://github.com/scm-manager/scm-manager/pull/1334))
- Overflow for too long branch names ([#1339](https://github.com/scm-manager/scm-manager/pull/1339))
- Set default branch in branch selector if nothing is selected ([#1338](https://github.com/scm-manager/scm-manager/pull/1338))
- Handling of branch with slashes in source view ([#1340](https://github.com/scm-manager/scm-manager/pull/1340))
- Detect not existing paths correctly in Mercurial ([#1343](https://github.com/scm-manager/scm-manager/pull/1343))
- Return correct revisions for tags in hooks for git repositories ([#1344](https://github.com/scm-manager/scm-manager/pull/1344))
- Add option for concrete commit message in merges without templating ([#1351](https://github.com/scm-manager/scm-manager/pull/1351))
## [2.5.0] - 2020-09-10
### Added
- Tags now have date information attached ([#1305](https://github.com/scm-manager/scm-manager/pull/1305))
- Add support for scroll anchors in url hash of diff page ([#1304](https://github.com/scm-manager/scm-manager/pull/1304))
- Documentation regarding data and plugin migration from v1 to v2 ([#1321](https://github.com/scm-manager/scm-manager/pull/1321))
- Add RepositoryCreationDto with creation context and extension-point for repository initialization ([#1324](https://github.com/scm-manager/scm-manager/pull/1324))
- UI filter and rest endpoints for namespaces ([#1323](https://github.com/scm-manager/scm-manager/pull/1323))
### Fixed
- Redirection to requested page after login in anonymous mode
- Update filter state on property change ([#1327](https://github.com/scm-manager/scm-manager/pull/1327))
- Diff view for svn now handles whitespaces in filenames properly ([1325](https://github.com/scm-manager/scm-manager/pull/1325))
- Validate new namespace on repository rename ([#1322](https://github.com/scm-manager/scm-manager/pull/1322))
## [2.4.1] - 2020-09-01
### Added
- Add "sonia.scm.restart-migration.wait" to set wait in milliseconds before restarting scm-server after migration ([#1308](https://github.com/scm-manager/scm-manager/pull/1308))
### Fixed
- Fix detection of markdown files for files having content does not start with '#' ([#1306](https://github.com/scm-manager/scm-manager/pull/1306))
- Fix broken markdown rendering ([#1303](https://github.com/scm-manager/scm-manager/pull/1303))
- JWT token timeout is now handled properly ([#1297](https://github.com/scm-manager/scm-manager/pull/1297))
- Fix text-overflow in danger zone ([#1298](https://github.com/scm-manager/scm-manager/pull/1298))
- Fix plugin installation error if previously a plugin was installed with the same dependency which is still pending. ([#1300](https://github.com/scm-manager/scm-manager/pull/1300))
- Fix layout overflow on changesets with multiple tags ([#1314](https://github.com/scm-manager/scm-manager/pull/1314))
- Make checkbox accessible from keyboard ([#1309](https://github.com/scm-manager/scm-manager/pull/1309))
- Fix logging of large stacktrace for unknown language ([#1313](https://github.com/scm-manager/scm-manager/pull/1313))
- Fix incorrect word breaking behaviour in markdown ([#1317](https://github.com/scm-manager/scm-manager/pull/1317))
- Remove obsolete revision encoding on sources ([#1315](https://github.com/scm-manager/scm-manager/pull/1315))
- Map generic JaxRS 'web application exceptions' to appropriate response instead of "internal server error" ([#1318](https://github.com/scm-manager/scm-manager/pull/1312))
## [2.4.0] - 2020-08-14
### Added
- Introduced merge detection for receive hooks ([#1278](https://github.com/scm-manager/scm-manager/pull/1278))
- Anonymous mode for the web ui ([#1284](https://github.com/scm-manager/scm-manager/pull/1284))
- Add link to source file in diff sections ([#1267](https://github.com/scm-manager/scm-manager/pull/1267))
- Check versions of plugin dependencies on plugin installation ([#1283](https://github.com/scm-manager/scm-manager/pull/1283))
- Sign PR merges and commits performed through ui with generated private key ([#1285](https://github.com/scm-manager/scm-manager/pull/1285))
- Add generic popover component to ui-components ([#1285](https://github.com/scm-manager/scm-manager/pull/1285))
- Show changeset signatures in ui and add public keys ([#1273](https://github.com/scm-manager/scm-manager/pull/1273))
### Fixed
- Repository names may not end with ".git" ([#1277](https://github.com/scm-manager/scm-manager/pull/1277))
- Add preselected value to options in dropdown component if missing ([#1287](https://github.com/scm-manager/scm-manager/pull/1287))
- Show error message if plugin loading failed ([#1289](https://github.com/scm-manager/scm-manager/pull/1289))
- Fix timing problem with anchor links for markdown view ([#1290](https://github.com/scm-manager/scm-manager/pull/1290))
## [2.3.1] - 2020-08-04
### Added
- New api to resolve SCM-Manager root url ([#1276](https://github.com/scm-manager/scm-manager/pull/1276))
### Changed
- Help tooltips are now multiline by default ([#1271](https://github.com/scm-manager/scm-manager/pull/1271))
### Fixed
- Fixed unnecessary horizontal scrollbar in modal dialogs ([#1271](https://github.com/scm-manager/scm-manager/pull/1271))
- Avoid stacktrace logging when protocol url is accessed outside of request scope ([#1276](https://github.com/scm-manager/scm-manager/pull/1276))
## [2.3.0] - 2020-07-23
### Added
- Add branch link provider to access branch links in plugins ([#1243](https://github.com/scm-manager/scm-manager/pull/1243))
- Add key value input field component ([#1246](https://github.com/scm-manager/scm-manager/pull/1246))
- Update installed optional plugin dependencies upon plugin upgrade ([#1260](https://github.com/scm-manager/scm-manager/pull/1260))
### Changed
- Adding start delay to liveness and readiness probes in helm chart template
- Init svn repositories with trunk folder ([#1259](https://github.com/scm-manager/scm-manager/pull/1259))
- Show line numbers in source code view by default ([#1265](https://github.com/scm-manager/scm-manager/pull/1265))
### Fixed
- Fixed file extension detection with new spotter version
- Fixed wrong cache directory location ([#1236](https://github.com/scm-manager/scm-manager/issues/1236) and [#1242](https://github.com/scm-manager/scm-manager/issues/1242))
- Fixed error in update step ([#1237](https://github.com/scm-manager/scm-manager/issues/1237) and [#1244](https://github.com/scm-manager/scm-manager/issues/1244))
- Fix incorrect trimming of whitespaces in helm chart templates
- Fixed error on empty diff expand response ([#1247](https://github.com/scm-manager/scm-manager/pull/1247))
- Ignore ports on proxy exclusions ([#1256](https://github.com/scm-manager/scm-manager/pull/1256))
- Invalidate branches cache synchronously on create new branch ([#1261](https://github.com/scm-manager/scm-manager/pull/1261))
## [2.2.0] - 2020-07-03
### Added
- Rename repository name (and namespace if permitted) ([#1218](https://github.com/scm-manager/scm-manager/pull/1218))
- Enrich commit mentions in markdown viewer by internal links ([#1210](https://github.com/scm-manager/scm-manager/pull/1210))
- New extension point \`changeset.description.tokens\` to "enrich" commit messages ([#1231](https://github.com/scm-manager/scm-manager/pull/1231))
- Restart service after rpm or deb package upgrade
### Changed
- Checkboxes can now be 'indeterminate' ([#1215](https://github.com/scm-manager/scm-manager/pull/1215))
- The old frontend extension point \`changeset.description\` is deprecated and should be replaced with \`changeset.description.tokens\` ([#1231](https://github.com/scm-manager/scm-manager/pull/1231))
- Required plugins will be updated, too, when a plugin is updated ([#1233](https://github.com/scm-manager/scm-manager/pull/1233))
### Fixed
- Fixed installation of debian packages on distros without preinstalled \`at\` ([#1216](https://github.com/scm-manager/scm-manager/issues/1216) and [#1217](https://github.com/scm-manager/scm-manager/pull/1217))
- Fixed restart with deb or rpm installation ([#1222](https://github.com/scm-manager/scm-manager/issues/1222) and [#1227](https://github.com/scm-manager/scm-manager/pull/1227))
- Fixed broken migration with empty security.xml ([#1219](https://github.com/scm-manager/scm-manager/issues/1219) and [#1221](https://github.com/scm-manager/scm-manager/pull/1221))
- Added missing architecture to debian installation documentation ([#1230](https://github.com/scm-manager/scm-manager/pull/1230))
- Mercurial on Python 3 ([#1232](https://github.com/scm-manager/scm-manager/pull/1232))
- Fixed wrong package information for deb and rpm packages ([#1229](https://github.com/scm-manager/scm-manager/pull/1229))
- Fixed missing content type on migration wizard ([#1234](https://github.com/scm-manager/scm-manager/pull/1234))
## [2.1.1] - 2020-06-23
### Fixed
- Wait until recommended java installation is available for deb packages ([#1209](https://github.com/scm-manager/scm-manager/pull/1209))
- Do not force java home of recommended java dependency for rpm and deb packages ([#1195](https://github.com/scm-manager/scm-manager/issues/1195) and [#1208](https://github.com/scm-manager/scm-manager/pull/1208))
- Migration of non-bare repositories ([#1213](https://github.com/scm-manager/scm-manager/pull/1213))
## [2.1.0] - 2020-06-18
### Added
- Option to configure jvm parameter of docker container with env JAVA_OPTS or with arguments ([#1175](https://github.com/scm-manager/scm-manager/pull/1175))
- Added links in diff views to expand the gaps between "hunks" ([#1178](https://github.com/scm-manager/scm-manager/pull/1178))
- Show commit contributors in table on changeset details view ([#1169](https://github.com/scm-manager/scm-manager/pull/1169))
- Show changeset parents on changeset details view ([#1189](https://github.com/scm-manager/scm-manager/pull/1189))
- Annotate view to display commit metadata for each line of a file ([#1196](https://github.com/scm-manager/scm-manager/pull/1196))
### Fixed
- Avoid caching of detected browser language ([#1176](https://github.com/scm-manager/scm-manager/pull/1176))
- Fixes configuration of jetty listener address with system property \`jetty.host\` ([#1173](https://github.com/scm-manager/scm-manager/pull/1173), [#1174](https://github.com/scm-manager/scm-manager/pull/1174))
- Fixes loading plugin bundles with context path \`/\` ([#1182](https://github.com/scm-manager/scm-manager/pull/1182/files), [#1181](https://github.com/scm-manager/scm-manager/issues/1181))
- Sets the new plugin center URL once ([#1184](https://github.com/scm-manager/scm-manager/pull/1184))
- Diffs with CR characters are parsed correctly ([#1185](https://github.com/scm-manager/scm-manager/pull/1185))
- Close file lists in migration ([#1191](https://github.com/scm-manager/scm-manager/pull/1191))
- Use command in javahg.py from registrar (Upgrade to newer javahg version) ([#1192](https://github.com/scm-manager/scm-manager/pull/1192))
- Fixed wrong e-tag format ([sdorra/web-resource #1](https://github.com/sdorra/web-resources/pull/1))
- Fixed refetching loop for non existing changesets ([#1203](https://github.com/scm-manager/scm-manager/pull/1203))
- Fixed active state of sub navigation items, which are using activeWhenMatch ([#1199](https://github.com/scm-manager/scm-manager/pull/1199))
- Handles repositories in custom directories correctly in migration from 1.x ([#1201](https://github.com/scm-manager/scm-manager/pull/1201))
- Usage of short git commit ids in changeset urls ([#1200](https://github.com/scm-manager/scm-manager/pull/1200))
- Fixes linebreaks in multiline tooltip ([#1207](https://github.com/scm-manager/scm-manager/pull/1207))
## [2.0.0] - 2020-06-04
### Added
- Detect renamed files in git and hg diffs ([#1157](https://github.com/scm-manager/scm-manager/pull/1157))
- ClassLoader and Adapter parameters to typed store apis ([#1111](https://github.com/scm-manager/scm-manager/pull/1111))
- Native packaging for Debian, Red Hat, Windows, Unix, Docker and Kubernetes ([#1165](https://github.com/scm-manager/scm-manager/pull/1165))
- Cache for working directories ([#1166](https://github.com/scm-manager/scm-manager/pull/1166))
### Fixed
- Correctly resolve Links in markdown files ([#1152](https://github.com/scm-manager/scm-manager/pull/1152))
- Missing copy on write in the data store ([#1155](https://github.com/scm-manager/scm-manager/pull/1155))
- Resolved conflicting dependencies for scm-webapp ([#1159](https://github.com/scm-manager/scm-manager/pull/1159))
## [2.0.0-rc8] - 2020-05-08
### Added
- Add iconStyle + onClick option and story shot for icon component ([#1100](https://github.com/scm-manager/scm-manager/pull/1100))
- Making WebElements (Servlet or Filter) optional by using the \`@Requires\` annotation ([#1101](https://github.com/scm-manager/scm-manager/pull/1101))
- Add class to manually validate rest data transfer objects with javax validation annotations ([#1114](https://github.com/scm-manager/scm-manager/pull/1114))
- Missing stories for ui-components ([#1140](https://github.com/scm-manager/scm-manager/pull/1140))
### Changed
- Removed the \`requires\` attribute on the \`@Extension\` annotation and instead create a new \`@Requires\` annotation ([#1097](https://github.com/scm-manager/scm-manager/pull/1097))
- Update guide to prevent common pitfalls in ui development ([#1107](https://github.com/scm-manager/scm-manager/pull/1107))
- Use os specific locations for scm home directory ([#1109](https://github.com/scm-manager/scm-manager/pull/1109))
- Use Library/Logs/SCM-Manager on OSX for logging ([#1109](https://github.com/scm-manager/scm-manager/pull/1109))
- Cleanup outdated jaxb annotation in scm-core ([#1136](https://github.com/scm-manager/scm-manager/pull/1136))
### Fixed
- Protocol URI for git commands under windows ([#1108](https://github.com/scm-manager/scm-manager/pull/1108))
- Fix usage of invalid cipher algorithm on newer java versions ([#1110](https://github.com/scm-manager/scm-manager/issues/1110),[#1112](https://github.com/scm-manager/scm-manager/pull/1112))
- Handle obscure line breaks in diff viewer ([#1129](https://github.com/scm-manager/scm-manager/pull/1129))
- Validate subversion client checksum ([#1113](https://github.com/scm-manager/scm-manager/issues/1113))
- Fix plugin manage permission ([#1135](https://github.com/scm-manager/scm-manager/pull/1135))
## [2.0.0-rc7] - 2020-04-09
### Added
- Fire various plugin events ([#1088](https://github.com/scm-manager/scm-manager/pull/1088))
- Display version for plugins ([#1089](https://github.com/scm-manager/scm-manager/pull/1089))
### Changed
- Simplified collapse state management of the secondary navigation ([#1086](https://github.com/scm-manager/scm-manager/pull/1086))
- Ensure same monospace font-family throughout whole SCM-Manager ([#1091](https://github.com/scm-manager/scm-manager/pull/1091))
### Fixed
- Authentication for write requests for repositories with anonymous read access ([#108](https://github.com/scm-manager/scm-manager/pull/1081))
- Submodules in git do no longer lead to a server error in the browser command ([#1093](https://github.com/scm-manager/scm-manager/pull/1093))
## [2.0.0-rc6] - 2020-03-26
### Added
- Extension point to add links to the repository cards from plug ins ([#1041](https://github.com/scm-manager/scm-manager/pull/1041))
- Libc based restart strategy for posix operating systems ([#1079](https://github.com/scm-manager/scm-manager/pull/1079))
- Simple restart strategy with System.exit ([#1079](https://github.com/scm-manager/scm-manager/pull/1079))
- Notification if restart is not supported on the underlying platform ([#1079](https://github.com/scm-manager/scm-manager/pull/1079))
- Extension point before title in repository cards ([#1080](https://github.com/scm-manager/scm-manager/pull/1080))
- Extension point after title on repository detail page ([#1080](https://github.com/scm-manager/scm-manager/pull/1080))
### Changed
- Update resteasy to version 4.5.2.Final
- Update shiro to version 1.5.2
- Use browser built-in EventSource for apiClient subscriptions
- Changeover to MIT license ([#1066](https://github.com/scm-manager/scm-manager/pull/1066))
### Removed
- EventSource Polyfill
- ClassLoader based restart logic ([#1079](https://github.com/scm-manager/scm-manager/pull/1079))
### Fixed
- Build on windows ([#1048](https://github.com/scm-manager/scm-manager/issues/1048), [#1049](https://github.com/scm-manager/scm-manager/issues/1049), [#1056](https://github.com/scm-manager/scm-manager/pull/1056))
- Show specific notification for plugin actions on plugin administration ([#1057](https://github.com/scm-manager/scm-manager/pull/1057))
- Invalid markdown could make parts of the page inaccessible ([#1077](https://github.com/scm-manager/scm-manager/pull/1077))
## [2.0.0-rc5] - 2020-03-12
### Added
- Added footer extension points for links and avatar
- Create OpenAPI specification during build
- Extension point entries with supplied extensionName are sorted ascending
- Possibility to configure git core config entries for jgit like core.trustfolderstat and core.supportsatomicfilecreation
- Babel-plugin-styled-components for persistent generated classnames
- By default, only 100 files will be listed in source view in one request
### Changed
- New footer design
- Update jgit to version 5.6.1.202002131546-r-scm1
- Update svnkit to version 1.10.1-scm1
- Secondary navigation collapsable
### Fixed
- Modification for mercurial repositories with enabled XSRF protection
- Does not throw NullPointerException when merge fails without normal merge conflicts
- Keep file attributes on modification
- Drop Down Component works again with translations
### Removed
- Enunciate rest documentation
- Obsolete fields in data transfer objects
## [2.0.0-rc4] - 2020-02-14
### Added
- Support for Java versions > 8
- Simple ClassLoaderLifeCycle to fix integration tests on Java > 8
- Option to use a function for default collapse state in diffs
### Changed
- Use icon only buttons for diff file controls
- Upgrade [Legman](https://github.com/sdorra/legman) to v1.6.2 in order to fix execution on Java versions > 8
- Upgrade [Lombok](https://projectlombok.org/) to version 1.18.10 in order to fix build on Java versions > 8
- Upgrade [Mockito](https://site.mockito.org/) to version 2.28.2 in order to fix tests on Java versions > 8
- Upgrade smp-maven-plugin to version 1.0.0-rc3
### Fixed
- Committer of new Git commits set to "SCM-Manager <noreply@scm-manager.org>"
## [2.0.0-rc3] - 2020-01-31
### Fixed
- Broken plugin order fixed
- MarkdownViewer in code section renders markdown properly
## [2.0.0-rc2] - 2020-01-29
### Added
- Set individual page title
- Copy on write
- A new repository can be initialized with a branch (for git and mercurial) and custom files (README.md on default)
- Plugins are validated directly after download
- Code highlighting in diffs
- Switch between rendered version and source view for Markdown files
### Changed
- Stop fetching commits when it takes too long
- Unification of source and commits become "code"
### Fixed
- Classloader leak which caused problems when restarting
- Failing git push does not lead to an GitAPIException
- Subversion revision 0 leads to error
- Create mock subject to satisfy legman
- Multiple versions of hibernate-validator caused problems when starting from plugins
- Page title is now set correctly
- Restart after migration
## [2.0.0-rc1] - 2019-12-02
### Added
- Namespace concept and endpoints
- File history
- Global permission concept
- Completely translated into German with all the text and controls of the UI
- Frontend provides further details on corresponding errors
- Repository branch overview, detailed view and create branch functionality
- Search and filter for repos, users and groups
- Repository Permissions roles
- Migration step framework and wizard
- Plugin center integration
- Plugins can be installed (even without restart), updated and uninstalled using the new plugins overview
- Git-LFS support (with SSH authentication)
- Anonymous access via git-clone and API access with anonymous user
- Cache and x-requested-with header to bundle requests
- remove public flag from repository and migrate permissions to anonymous user
[2.0.0-rc1]: https://www.scm-manager.org/download/2.0.0-rc1
[2.0.0-rc2]: https://www.scm-manager.org/download/2.0.0-rc2
[2.0.0-rc3]: https://www.scm-manager.org/download/2.0.0-rc3
[2.0.0-rc4]: https://www.scm-manager.org/download/2.0.0-rc4
[2.0.0-rc5]: https://www.scm-manager.org/download/2.0.0-rc5
[2.0.0-rc6]: https://www.scm-manager.org/download/2.0.0-rc6
[2.0.0-rc7]: https://www.scm-manager.org/download/2.0.0-rc7
[2.0.0-rc8]: https://www.scm-manager.org/download/2.0.0-rc8
[2.0.0]: https://www.scm-manager.org/download/2.0.0
[2.1.0]: https://www.scm-manager.org/download/2.1.0
[2.1.1]: https://www.scm-manager.org/download/2.1.1
[2.2.0]: https://www.scm-manager.org/download/2.2.0
[2.3.0]: https://www.scm-manager.org/download/2.3.0
[2.3.1]: https://www.scm-manager.org/download/2.3.1
[2.4.0]: https://www.scm-manager.org/download/2.4.0
[2.4.1]: https://www.scm-manager.org/download/2.4.1
[2.5.0]: https://www.scm-manager.org/download/2.5.0
[2.6.0]: https://www.scm-manager.org/download/2.6.0
[2.6.1]: https://www.scm-manager.org/download/2.6.1
[2.6.2]: https://www.scm-manager.org/download/2.6.2
[2.6.3]: https://www.scm-manager.org/download/2.6.3
[2.7.0]: https://www.scm-manager.org/download/2.7.0
[2.7.1]: https://www.scm-manager.org/download/2.7.1
[2.8.0]: https://www.scm-manager.org/download/2.8.0
[2.9.0]: https://www.scm-manager.org/download/2.9.0
[2.9.1]: https://www.scm-manager.org/download/2.9.1
[2.10.0]: https://www.scm-manager.org/download/2.10.0
[2.10.1]: https://www.scm-manager.org/download/2.10.1
[2.11.0]: https://www.scm-manager.org/download/2.11.0
[2.11.1]: https://www.scm-manager.org/download/2.11.1
[2.12.0]: https://www.scm-manager.org/download/2.12.0
[2.13.0]: https://www.scm-manager.org/download/2.13.0
[2.14.0]: https://www.scm-manager.org/download/2.14.0
[2.14.1]: https://www.scm-manager.org/download/2.14.1
[2.15.0]: https://www.scm-manager.org/download/2.15.0
[2.15.1]: https://www.scm-manager.org/download/2.15.1
[2.16.0]: https://www.scm-manager.org/download/2.16.0
`; | the_stack |
import SubscriptionClass, { Repositories, Repository, RepositoryData, SyncStatus, TaskStatus } from "../models/subscription";
import { Subscription } from "../models";
import getJiraClient from "../jira/client";
import { getRepositorySummary } from "./jobs";
import enhanceOctokit from "../config/enhance-octokit";
import statsd from "../config/statsd";
import getPullRequests from "./pull-request";
import getBranches from "./branches";
import getCommits from "./commits";
import { Application, GitHubAPI } from "probot";
import {metricSyncStatus, metricTaskStatus} from "../config/metric-names";
import Queue from "bull";
import { booleanFlag, BooleanFlags, stringFlag, StringFlags } from "../config/feature-flags";
import {LoggerWithTarget} from "probot/lib/wrap-logger";
export const INSTALLATION_LOGGER_NAME = "sync.installation";
const tasks: TaskProcessors = {
pull: getPullRequests,
branch: getBranches,
commit: getCommits
};
interface TaskProcessors {
[task: string]:
(
github: GitHubAPI,
repository: Repository,
cursor?: string | number,
perPage?: number
) => Promise<{ edges: any[], jiraPayload: any }>;
}
type TaskType = "pull" | "commit" | "branch";
const taskTypes = Object.keys(tasks) as TaskType[];
// TODO: why are we ignoring failed status as completed?
const taskStatusCompleted:TaskStatus[] = ["complete", "failed"]
const isAllTasksStatusesCompleted = (...statuses: (TaskStatus | undefined)[]): boolean =>
statuses.every(status => !!status && taskStatusCompleted.includes(status));
const updateNumberOfReposSynced = async (
repos: Repositories,
subscription: SubscriptionClass
): Promise<void> => {
const repoIds = Object.keys(repos || {});
if (!repoIds.length) {
return;
}
const syncedRepos = repoIds.filter((id: string) => {
// all 3 statuses need to be complete for a repo to be fully synced
const { pullStatus, branchStatus, commitStatus } = repos[id];
return isAllTasksStatusesCompleted(pullStatus, branchStatus, commitStatus);
});
await subscription.updateNumberOfSyncedRepos(syncedRepos.length);
};
export const sortedRepos = (repos: Repositories): [string, RepositoryData][] =>
Object.entries(repos).sort(
(a, b) =>
new Date(b[1].repository?.updated_at || 0).getTime() -
new Date(a[1].repository?.updated_at || 0).getTime()
);
const getNextTask = async (subscription: SubscriptionClass): Promise<Task | undefined> => {
const repos = subscription?.repoSyncState?.repos || {};
await updateNumberOfReposSynced(repos, subscription);
for (const [repositoryId, repoData] of sortedRepos(repos)) {
const task = taskTypes.find(
(taskType) => repoData[getStatusKey(taskType)] === undefined || repoData[getStatusKey(taskType)] === "pending"
);
if (!task) continue;
const { repository, [getCursorKey(task)]: cursor } = repoData;
return {
task,
repositoryId,
repository: repository as Repository,
cursor: cursor as any
};
}
return undefined;
};
export interface Task {
task: TaskType;
repositoryId: string;
repository: Repository;
cursor?: string | number;
}
const upperFirst = (str: string) =>
str.substring(0, 1).toUpperCase() + str.substring(1);
const getCursorKey = (type: TaskType) => `last${upperFirst(type)}Cursor`;
const getStatusKey = (type: TaskType) => `${type}Status`;
const updateJobStatus = async (
queues,
job: Queue.Job,
edges: any[] | undefined,
task: TaskType,
repositoryId: string,
logger: LoggerWithTarget
) => {
const { installationId, jiraHost } = job.data;
// Get a fresh subscription instance
const subscription = await Subscription.getSingleInstallation(
jiraHost,
installationId
);
// handle promise rejection when an org is removed during a sync
if (!subscription) {
// Include job and task in any micros env logs, exclude from local
const loggerObj = process.env.MICROS_ENV ? { job, task } : {}
logger.info(loggerObj, "Organization has been deleted. Other active syncs will continue.");
return;
}
const status = edges?.length ? "pending" : "complete";
logger.info({ job, task, status }, "Updating job status");
await subscription.updateRepoSyncStateItem(repositoryId, getStatusKey(task), status);
if (edges?.length) {
// there's more data to get
await subscription.updateRepoSyncStateItem(repositoryId, getCursorKey(task), edges[edges.length - 1].cursor);
queues.installation.add(job.data);
// no more data (last page was processed of this job type)
} else if (!(await getNextTask(subscription))) {
await subscription.update({ syncStatus: SyncStatus.COMPLETE });
const endTime = Date.now();
const startTime = job.data?.startTime || 0;
const timeDiff = endTime - Date.parse(startTime);
if (startTime) {
// full_sync measures the duration from start to finish of a complete scan and sync of github issues translated to tickets
// startTime will be passed in when this sync job is queued from the discovery
statsd.histogram(metricSyncStatus.fullSyncDuration, timeDiff);
}
logger.info({ job, task, startTime, endTime, timeDiff }, "Sync status is complete");
} else {
logger.info({ job, task }, "Sync status is pending");
queues.installation.add(job.data);
}
};
const getEnhancedGitHub = async (app: Application, installationId) =>
enhanceOctokit(await app.auth(installationId));
const isBlocked = async (installationId: number, logger: LoggerWithTarget): Promise<boolean> => {
try {
const blockedInstallationsString = await stringFlag(StringFlags.BLOCKED_INSTALLATIONS, "[]");
const blockedInstallations: number[] = JSON.parse(blockedInstallationsString);
return blockedInstallations.includes(installationId);
} catch (e) {
logger.error(e);
return false;
}
};
/**
* Determines if an an error returned by the GitHub API means that we should retry it
* with a smaller request (i.e. with fewer pages).
* @param err the error thrown by Octokit.
*/
export const isRetryableWithSmallerRequest = (err): boolean => {
if (err.errors) {
const retryableErrors = err.errors.filter(
(error) => {
return "MAX_NODE_LIMIT_EXCEEDED" == error.type
|| error.message?.startsWith("Something went wrong while executing your query");
}
);
return retryableErrors.length;
} else {
return false;
}
};
// Checks if parsed error type is NOT_FOUND / status is 404 which come from 2 different sources
// - GraphqlError: https://github.com/octokit/graphql.js/tree/master#errors
// - RequestError: https://github.com/octokit/request.js/blob/5cef43ea4008728139686b6e542a62df28bb112a/src/fetch-wrapper.ts#L77
export const isNotFoundError = (
err: any,
job: any,
nextTask: Task,
logger: LoggerWithTarget
): boolean | undefined => {
const isNotFoundErrorType =
err?.errors && err.errors?.filter((error) => error.type === "NOT_FOUND");
const isNotFoundError = isNotFoundErrorType?.length > 0 || err?.status === 404;
isNotFoundError &&
logger.info(
{ job, task: nextTask },
"Repository deleted after discovery, skipping initial sync"
);
return isNotFoundError;
};
// TODO: type queues
export const processInstallation =
(app: Application, queues) =>
async (job, logger: LoggerWithTarget): Promise<void> => {
const { installationId, jiraHost } = job.data;
if (await isBlocked(installationId, logger)) {
logger.warn({ job }, "blocking installation job");
return;
}
job.sentry.setUser({
gitHubInstallationId: installationId,
jiraHost
});
const subscription = await Subscription.getSingleInstallation(
jiraHost,
installationId
);
// TODO: should this reject instead? it's just ignoring an error
if (!subscription) return;
const jiraClient = await getJiraClient(
subscription.jiraHost,
installationId,
logger
);
const github = await getEnhancedGitHub(app, installationId);
const nextTask = await getNextTask(subscription);
if (!nextTask) {
await subscription.update({ syncStatus: "COMPLETE" });
statsd.increment(metricSyncStatus.complete);
logger.info({ job, task: nextTask }, "Sync complete");
return;
}
await subscription.update({ syncStatus: "ACTIVE" });
const { task, repositoryId, cursor } = nextTask;
let { repository } = nextTask;
if (!repository) {
// Old records don't have this info. New ones have it
const { data: repo } = await github.request("GET /repositories/:id", {
id: repositoryId
});
repository = getRepositorySummary(repo);
await subscription.updateSyncState({
repos: {
[repository.id]: {
repository
}
}
});
}
logger.info({ job, task: nextTask }, "Starting task");
const processor = tasks[task];
const execute = async () => {
if (await booleanFlag(BooleanFlags.SIMPLER_PROCESSOR, true)) {
// just try with one page size
return await processor(github, repository, cursor, 20);
} else {
for (const perPage of [20, 10, 5, 1]) {
// try for decreasing page sizes in case GitHub returns errors that should be retryable with smaller requests
try {
return await processor(github, repository, cursor, perPage);
} catch (err) {
logger.error({
err,
job,
github,
repository,
cursor,
task
}, `Error processing job with page size ${perPage}, retrying with next smallest page size`);
if (isRetryableWithSmallerRequest(err)) {
// error is retryable, retrying with next smaller page size
continue;
} else {
// error is not retryable, re-throwing it
throw err;
}
}
}
}
throw new Error(`Error processing GraphQL query: installationId=${installationId}, repositoryId=${repositoryId}, task=${task}`);
};
try {
const { edges, jiraPayload } = await execute();
if (jiraPayload) {
try {
await jiraClient.devinfo.repository.update(jiraPayload, {
preventTransitions: true
});
} catch (err) {
if (err?.response?.status === 400) {
job.sentry.setExtra(
"Response body",
err.response.data.errorMessages
);
job.sentry.setExtra("Jira payload", err.response.data.jiraPayload);
}
if (err.request) {
job.sentry.setExtra("Request", {
host: err.request.domain,
path: err.request.path,
method: err.request.method
});
}
if (err.response) {
job.sentry.setExtra("Response", {
status: err.response.status,
statusText: err.response.statusText,
body: err.response.body
});
}
throw err;
}
}
await updateJobStatus(
queues,
job,
edges,
task,
repositoryId,
logger,
);
statsd.increment(metricTaskStatus.complete, [`type: ${nextTask.task}`]);
} catch (err) {
const rateLimit = Number(err?.headers?.["x-ratelimit-reset"]);
const delay = Math.max(Date.now() - rateLimit * 1000, 0);
if (delay) {
// if not NaN or 0
logger.info({ delay, job, task: nextTask }, `Delaying job for ${delay}ms`);
queues.installation.add(job.data, { delay });
return;
}
if (String(err).includes("connect ETIMEDOUT")) {
// There was a network connection issue.
// Add the job back to the queue with a 5 second delay
logger.warn({ job, task: nextTask }, "ETIMEDOUT error, retrying in 5 seconds");
queues.installation.add(job.data, { delay: 5000 });
return;
}
if (
String(err.message).includes(
"You have triggered an abuse detection mechanism"
)
) {
// Too much server processing time, wait 60 seconds and try again
logger.warn({ job, task: nextTask }, "Abuse detection triggered. Retrying in 60 seconds");
queues.installation.add(job.data, { delay: 60000 });
return;
}
// Continue sync when a 404/NOT_FOUND is returned
if (isNotFoundError(err, job, nextTask, logger)) {
const edgesLeft = []; // No edges left to process since the repository doesn't exist
await updateJobStatus(queues, job, edgesLeft, task, repositoryId, logger);
return;
}
if (await booleanFlag(BooleanFlags.CONTINUE_SYNC_ON_ERROR, false, jiraHost)) {
// TODO: add the jiraHost to the logger with logger.child()
const host = subscription.jiraHost || "none";
logger.warn({ job, task: nextTask, err, jiraHost: host }, "Task failed, continuing with next task");
// marking the current task as failed
await subscription.updateRepoSyncStateItem(nextTask.repositoryId, getStatusKey(nextTask.task as TaskType), "failed");
statsd.increment(metricTaskStatus.failed, [`type: ${nextTask.task}`]);
// queueing the job again to pick up the next task
queues.installation.add(job.data);
} else {
await subscription.update({ syncStatus: "FAILED" });
// TODO: add the jiraHost to the logger with logger.child()
const host = subscription.jiraHost || "none";
logger.warn({ job, task: nextTask, err, jiraHost: host }, "Sync failed");
job.sentry.setExtra("Installation FAILED", JSON.stringify(err, null, 2));
job.sentry.captureException(err);
statsd.increment(metricSyncStatus.failed);
throw err;
}
}
}; | the_stack |
import { ShapeBpmnElementKind } from '../../../../../src/model/bpmn/internal';
import { expectAsWarning, parseJson, parseJsonAndExpectOnlyLanes, parsingMessageCollector, verifyShape } from './JsonTestUtils';
import { LaneUnknownFlowNodeRefWarning } from '../../../../../src/component/parser/json/warnings';
describe('parse bpmn as json for lane', () => {
it('json containing one process with a single lane without flowNodeRef', () => {
const json = {
definitions: {
targetNamespace: '',
process: {
lane: { id: 'Lane_12u5n6x' },
},
BPMNDiagram: {
BPMNPlane: {
BPMNShape: {
id: 'Lane_1h5yeu4_di',
bpmnElement: 'Lane_12u5n6x',
isHorizontal: true,
Bounds: { x: 362, y: 232, width: 36, height: 45 },
},
},
},
},
};
const model = parseJsonAndExpectOnlyLanes(json, 1);
verifyShape(model.lanes[0], {
shapeId: 'Lane_1h5yeu4_di',
bpmnElementId: 'Lane_12u5n6x',
bpmnElementName: undefined,
bpmnElementKind: ShapeBpmnElementKind.LANE,
bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
isHorizontal: true,
});
});
it('json containing one process with a single lane with flowNodeRef as object & flowNode already parsed', () => {
const json = {
definitions: {
targetNamespace: '',
process: {
lane: { id: 'Lane_12u5n6x', flowNodeRef: 'event_id_0' },
startEvent: { id: 'event_id_0' },
},
BPMNDiagram: {
BPMNPlane: {
BPMNShape: [
{
id: 'Lane_1h5yeu4_di',
bpmnElement: 'Lane_12u5n6x',
isHorizontal: true,
Bounds: { x: 362, y: 232, width: 36, height: 45 },
},
{
id: 'event_id_0_di',
bpmnElement: 'event_id_0',
Bounds: { x: 11, y: 11, width: 11, height: 11 },
},
],
},
},
},
};
const model = parseJson(json);
expect(model.lanes).toHaveLength(1);
verifyShape(model.lanes[0], {
shapeId: 'Lane_1h5yeu4_di',
bpmnElementId: 'Lane_12u5n6x',
bpmnElementName: undefined,
bpmnElementKind: ShapeBpmnElementKind.LANE,
bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
isHorizontal: true,
});
expect(model.flowNodes).toHaveLength(1);
expect(model.flowNodes[0].bpmnElement.parentId).toEqual('Lane_12u5n6x');
});
it('json containing one process with a single lane with flowNodeRef as object & flowNode not parsed', () => {
const json = {
definitions: {
targetNamespace: '',
process: {
lane: { id: 'Lane_12u5n6x', flowNodeRef: 'event_id_0' },
},
BPMNDiagram: {
BPMNPlane: {
BPMNShape: {
id: 'Lane_1h5yeu4_di',
bpmnElement: 'Lane_12u5n6x',
isHorizontal: true,
Bounds: { x: 362, y: 232, width: 36, height: 45 },
},
},
},
},
};
const model = parseJsonAndExpectOnlyLanes(json, 1, 1);
verifyShape(model.lanes[0], {
shapeId: 'Lane_1h5yeu4_di',
bpmnElementId: 'Lane_12u5n6x',
bpmnElementName: undefined,
bpmnElementKind: ShapeBpmnElementKind.LANE,
bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
isHorizontal: true,
});
const warning = expectAsWarning<LaneUnknownFlowNodeRefWarning>(parsingMessageCollector.getWarnings()[0], LaneUnknownFlowNodeRefWarning);
expect(warning.laneId).toEqual('Lane_12u5n6x');
expect(warning.flowNodeRef).toEqual('event_id_0');
});
it('json containing one process with a single lane with flowNodeRef as object & flowNode not parsed', () => {
const json = {
definitions: {
targetNamespace: '',
process: {
lane: { id: 'Lane_12u5n6x', flowNodeRef: 'event_id_0' },
},
BPMNDiagram: {
BPMNPlane: {
BPMNShape: {
id: 'Lane_1h5yeu4_di',
bpmnElement: 'Lane_12u5n6x',
isHorizontal: true,
Bounds: { x: 362, y: 232, width: 36, height: 45 },
},
},
},
},
};
const model = parseJson(json);
expect(model.lanes).toHaveLength(1);
verifyShape(model.lanes[0], {
shapeId: 'Lane_1h5yeu4_di',
bpmnElementId: 'Lane_12u5n6x',
bpmnElementName: undefined,
bpmnElementKind: ShapeBpmnElementKind.LANE,
bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
isHorizontal: true,
});
});
it('json containing one process with a single lane with flowNodeRef as array', () => {
const json = {
definitions: {
targetNamespace: '',
process: {
lane: { id: 'Lane_12u5n6x', flowNodeRef: ['event_id_0'] },
startEvent: { id: 'event_id_0' },
},
BPMNDiagram: {
BPMNPlane: {
BPMNShape: [
{
id: 'Lane_1h5yeu4_di',
bpmnElement: 'Lane_12u5n6x',
isHorizontal: true,
Bounds: { x: 362, y: 232, width: 36, height: 45 },
},
{
id: 'event_id_0_di',
bpmnElement: 'event_id_0',
Bounds: { x: 11, y: 11, width: 11, height: 11 },
},
],
},
},
},
};
const model = parseJson(json);
expect(model.lanes).toHaveLength(1);
verifyShape(model.lanes[0], {
shapeId: 'Lane_1h5yeu4_di',
bpmnElementId: 'Lane_12u5n6x',
bpmnElementName: undefined,
bpmnElementKind: ShapeBpmnElementKind.LANE,
bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
isHorizontal: true,
});
expect(model.flowNodes).toHaveLength(1);
expect(model.flowNodes[0].bpmnElement.parentId).toEqual('Lane_12u5n6x');
});
it('json containing one process declared as array with a laneSet', () => {
const json = {
definitions: {
targetNamespace: '',
process: [
{
laneSet: {
id: 'LaneSet_1i59xiy',
lane: { id: 'Lane_12u5n6x' },
},
},
],
BPMNDiagram: {
BPMNPlane: {
BPMNShape: {
id: 'Lane_1h5yeu4_di',
bpmnElement: 'Lane_12u5n6x',
isHorizontal: true,
Bounds: { x: 362, y: 232, width: 36, height: 45 },
},
},
},
},
};
const model = parseJsonAndExpectOnlyLanes(json, 1);
verifyShape(model.lanes[0], {
shapeId: 'Lane_1h5yeu4_di',
bpmnElementId: 'Lane_12u5n6x',
bpmnElementName: undefined,
bpmnElementKind: ShapeBpmnElementKind.LANE,
bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
isHorizontal: true,
});
});
it('json containing one process with an array of lanes with & without name', () => {
const json = {
definitions: {
targetNamespace: '',
process: {
laneSet: {
id: 'LaneSet_1i59xiy',
lane: [
{
id: 'Lane_164yevk',
name: 'Customer',
flowNodeRef: 'event_id_0',
},
{ id: 'Lane_12u5n6x' },
],
},
startEvent: { id: 'event_id_0' },
},
BPMNDiagram: {
BPMNPlane: {
BPMNShape: [
{
id: 'Lane_164yevk_di',
bpmnElement: 'Lane_164yevk',
isHorizontal: true,
Bounds: { x: 362, y: 232, width: 36, height: 45 },
},
{
id: 'Lane_12u5n6x_di',
bpmnElement: 'Lane_12u5n6x',
isHorizontal: true,
Bounds: { x: 666, y: 222, width: 22, height: 33 },
},
],
},
},
},
};
const model = parseJsonAndExpectOnlyLanes(json, 2);
verifyShape(model.lanes[0], {
shapeId: 'Lane_164yevk_di',
bpmnElementId: 'Lane_164yevk',
bpmnElementName: 'Customer',
bpmnElementKind: ShapeBpmnElementKind.LANE,
bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
isHorizontal: true,
});
verifyShape(model.lanes[1], {
shapeId: 'Lane_12u5n6x_di',
bpmnElementId: 'Lane_12u5n6x',
bpmnElementName: undefined,
bpmnElementKind: ShapeBpmnElementKind.LANE,
bounds: {
x: 666,
y: 222,
width: 22,
height: 33,
},
isHorizontal: true,
});
});
describe.each([
['vertical', false],
['horizontal', true],
])('parse bpmn as json for %s lane', (title: string, isHorizontal: boolean) => {
it(`json containing one process declared as array with a ${title} laneSet with childLaneSet`, () => {
const json = {
definitions: {
targetNamespace: '',
process: [
{
id: 'Process_07bsa3h',
laneSet: {
id: 'LaneSet_1rqtug0',
lane: [
{
id: 'Lane_040h8y5',
childLaneSet: {
id: 'LaneSet_1pyljtf',
lane: [
{
id: 'Lane_06so1v5',
},
{
id: 'Lane_0amyaod',
childLaneSet: {
id: 'LaneSet_0lzaj18',
},
},
],
},
},
{
id: 'Lane_1gdg64y',
},
],
},
},
],
BPMNDiagram: {
id: 'BPMNDiagram_1',
BPMNPlane: {
id: 'BPMNPlane_1',
bpmnElement: 'Collaboration_0um5kdl',
BPMNShape: [
{
id: 'Lane_1gdg64y_di',
bpmnElement: 'Lane_1gdg64y',
isHorizontal: isHorizontal,
Bounds: {
x: 186,
y: 340,
width: 584,
height: 200,
},
},
{
id: 'Lane_040h8y5_di',
bpmnElement: 'Lane_040h8y5',
isHorizontal: isHorizontal,
Bounds: {
x: 186,
y: 80,
width: 584,
height: 260,
},
},
{
id: 'Lane_0amyaod_di',
bpmnElement: 'Lane_0amyaod',
isHorizontal: isHorizontal,
Bounds: {
x: 216,
y: 214,
width: 554,
height: 126,
},
},
{
id: 'Lane_06so1v5_di',
bpmnElement: 'Lane_06so1v5',
isHorizontal: isHorizontal,
Bounds: {
x: 216,
y: 80,
width: 554,
height: 134,
},
},
],
},
},
},
};
const model = parseJsonAndExpectOnlyLanes(json, 4);
verifyShape(model.lanes[0], {
shapeId: 'Lane_1gdg64y_di',
bpmnElementId: 'Lane_1gdg64y',
bpmnElementName: undefined,
parentId: 'Process_07bsa3h',
bpmnElementKind: ShapeBpmnElementKind.LANE,
bounds: {
x: 186,
y: 340,
width: 584,
height: 200,
},
isHorizontal: isHorizontal,
});
verifyShape(model.lanes[1], {
shapeId: 'Lane_040h8y5_di',
bpmnElementId: 'Lane_040h8y5',
bpmnElementName: undefined,
parentId: 'Process_07bsa3h',
bpmnElementKind: ShapeBpmnElementKind.LANE,
bounds: {
x: 186,
y: 80,
width: 584,
height: 260,
},
isHorizontal: isHorizontal,
});
verifyShape(model.lanes[2], {
shapeId: 'Lane_0amyaod_di',
bpmnElementId: 'Lane_0amyaod',
bpmnElementName: undefined,
parentId: 'Lane_040h8y5',
bpmnElementKind: ShapeBpmnElementKind.LANE,
bounds: {
x: 216,
y: 214,
width: 554,
height: 126,
},
isHorizontal: isHorizontal,
});
verifyShape(model.lanes[3], {
shapeId: 'Lane_06so1v5_di',
bpmnElementId: 'Lane_06so1v5',
bpmnElementName: undefined,
parentId: 'Lane_040h8y5',
bpmnElementKind: ShapeBpmnElementKind.LANE,
bounds: {
x: 216,
y: 80,
width: 554,
height: 134,
},
isHorizontal: isHorizontal,
});
});
it(`json containing one process with a ${title} lane`, () => {
const json = {
definitions: {
targetNamespace: '',
process: {
lane: { id: 'Lane_12u5n6x' },
},
BPMNDiagram: {
BPMNPlane: {
BPMNShape: {
id: 'Lane_1h5yeu4_di',
bpmnElement: 'Lane_12u5n6x',
isHorizontal: isHorizontal,
Bounds: { x: 362, y: 232, width: 36, height: 45 },
},
},
},
},
};
const model = parseJsonAndExpectOnlyLanes(json, 1);
verifyShape(model.lanes[0], {
shapeId: 'Lane_1h5yeu4_di',
bpmnElementId: 'Lane_12u5n6x',
bpmnElementName: undefined,
bpmnElementKind: ShapeBpmnElementKind.LANE,
parentId: undefined,
bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
isHorizontal: isHorizontal,
});
});
});
it("json containing one process with a lane without 'isHorizontal' attribute", () => {
const json = {
definitions: {
targetNamespace: '',
process: {
lane: { id: 'Lane_12u5n6x' },
},
BPMNDiagram: {
BPMNPlane: {
BPMNShape: {
id: 'Lane_1h5yeu4_di',
bpmnElement: 'Lane_12u5n6x',
Bounds: { x: 362, y: 232, width: 36, height: 45 },
},
},
},
},
};
const model = parseJsonAndExpectOnlyLanes(json, 1);
verifyShape(model.lanes[0], {
shapeId: 'Lane_1h5yeu4_di',
bpmnElementId: 'Lane_12u5n6x',
bpmnElementName: undefined,
bpmnElementKind: ShapeBpmnElementKind.LANE,
parentId: undefined,
bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
isHorizontal: true,
});
});
}); | the_stack |
import * as jsonx from './index';
import * as _jsonxComponents from './components';
import {getCustomComponentsCacheKey, getCustomFunctionComponent, getReactLibrariesAndComponents} from './components';
import mochaJSDOM from 'jsdom-global';
import chai from 'chai';
import sinon from 'sinon';
import React, { Component, JSXElementConstructor, ReactComponentElement, ReactElement, ReactInstance } from 'react';
import ReactTestUtils,{isElement} from 'react-dom/test-utils'; // ES6
import ReactDOM from 'react-dom';
import ReactDOMServer from "react-dom/server";
import ReactDOMElements from 'react-dom-factories';
import * as defs from "./types/jsonx/index";
import { render, fireEvent, waitFor, screen } from '@testing-library/react'
import '@testing-library/jest-dom/extend-expect'
import { expect as expectCHAI, } from 'chai';
import { JSDOM, } from 'jsdom';
chai.use(require('sinon-chai'));
// import 'mocha-sinon';
// import Enzyme, { mount, } from 'enzyme';
// import Adapter from 'enzyme-adapter-react-16';
// chai.use(require('sinon-chai'));
// import 'mocha-sinon';
// import useGlobalHook from 'use-global-hook';
// Enzyme.configure({ adapter: new Adapter() });
const sampleJSONX = {
component: 'div',
props: {
id: 'generatedJSONX',
className:'jsonx',
},
children: 'some div',
};
const sampleCustomElementJSONX = {
component: 'div',
props: {
id: 'customJSONX',
className:'jsonx',
},
thisprops: {
title: ['extraname', ],
},
children: [
{
component: 'p',
children:'some text',
},
{
component: 'Welcome',
props: {
style: {
color: 'red',
fontWeight:'bold',
},
name:'fromCustom',
},
thisprops: {
title: ['elementProperties', 'title', ],
},
children:'hello customElement2',
},
{
component: 'WelcomeBindSpy',
props: {
style: {
color: 'red',
fontWeight:'bold',
},
name:'fromCustom',
},
thisprops: {
title: ['elementProperties', 'title', ],
},
children:'hello customElement2',
},
{
component: 'WelcomeNonBind',
props: {
style: {
color: 'red',
fontWeight:'bold',
},
name:'fromCustom',
},
thisprops: {
title: ['elementProperties', 'title', ],
},
children:'hello customElement2',
},
],
};
class Welcome extends React.Component {
render() {
//@ts-ignore
return React.createElement('h1', { name: 'Welcome', }, `Hello, ${this.props.name} ${this.props.title||'NA'}`);
}
}
class WelcomeBindSpy extends React.Component {
render() {
//@ts-ignore
return React.createElement('h1', { name: 'Welcome', }, `Hello, ${this.props.name} ${this.props.title||'NA'}`);
}
}
class WelcomeNonBind extends React.Component {
render() {
//@ts-ignore
return React.createElement('h1', { name: 'Welcome', }, `Hello, ${this.props.name} ${this.props.title||'NA'}`);
}
}
const customComponents:defs.jsonxCustomComponent[] = [
{
type: 'function',
name: 'genFuncDef',
functionComponent:function(){
console.log("called generated function")
return {
component:'span',
children:'gen custom def',
}
},
options:{
name:'genFuncDef'
}
},
{
type: 'function',
name: 'genFunc',
functionBody:'console.log("called generated function")',
jsonxComponent:{
component:'span',
children:'gen custom',
},
options:{
name:'genFun'
}
},
{
type: 'component',
name: 'genClass',
jsonx:{
componentDidMount: {
body: 'console.log(\'mounted\',this.props)',
arguments: [],
},
render: {
body: {
component: 'p',
children: [
{
component: 'span',
children: 'My Custom React Component Status: ',
},
{
component: 'span',
thisprops: {
children: ['status',],
},
},
],
},
},
},
options:{
name:'genClass'
}
},
{
type:'library',
name:'MyLib',
jsonx:{
CompA:{
name:'CompA',
type:'function',
functionBody:'console.log("called generated function")',
jsonxComponent:{
component:'div',
children:'gen lib function comp a',
},
options:{
name:'CompA'
}
},
CompB:{
name:'CompB',
type:'function',
jsonxComponent:{
component:'div',
children:'gen lib function comp b',
},
options:{
name:'CompB'
}
},
CompC:{
type: 'component',
name: 'CompC',
jsonxComponent:{
componentDidMount: {
body: 'console.log(\'mounted CompC\',this.props)',
arguments: [],
},
render: {
body: {
component: 'div',
children: 'CompC Class Component',
},
},
},
options:{
name:'genClass'
}
}
}
}
];
describe('jsonx components', function () {
describe('advancedBinding', () => {
it('should use advancedBinding based on user agent', () => {
expectCHAI(_jsonxComponents.advancedBinding).to.be.true;
});
});
describe('componentMap', () => {
it('should export an object of components', () => {
expectCHAI(_jsonxComponents.componentMap).to.be.a('object');
});
// it('should export an object of components', () => {
// global.window = {
// __jsonx_custom_elements: {
// cusEl: {},
// },
// };
// const comps = _jsonxComponents.componentMap;
// console.log({ comps });
// expectCHAI(_jsonxComponents.componentMap.cusEl).to.eql(global.window.__jsonx_custom_elements.cusEl);
// });
});
describe('getBoundedComponents', () => {
it('should bind this to reactComponents', () => {
const bindSpy = sinon.spy();
WelcomeBindSpy.bind = bindSpy;
const reactComponents = {
Welcome,
WelcomeNonBind,
WelcomeBindSpy,
};
const boundedComponents = ['Welcome', 'WelcomeBindSpy', ];
const customThis = {
props: {
name:'customElementTest',
extraname: 'customElementTestName',
elementProperties: {
title: 'AddedWithThis',
},
},
boundedComponents,
reactComponents,
debug: false,
returnJSON: true,
logError:()=>{},
};
const customComponents = _jsonxComponents.getBoundedComponents.call(customThis,{ reactComponents, boundedComponents, advancedBinding:true, });
const customComponentsNotBound = _jsonxComponents.getBoundedComponents.call(customThis,{ reactComponents, boundedComponents, advancedBinding:false, });
// console.log(customComponents,customComponentsNotBound)
const JSONXPropCheck = jsonx.getRenderedJSON.call(customThis, sampleCustomElementJSONX);
expectCHAI(bindSpy.called).to.be.true;
//@ts-ignore
expectCHAI(JSONXPropCheck.props.title).to.eql(customThis.props.extraname);
//@ts-ignore
expectCHAI(customComponents.length).to.eql(reactComponents.length);
//@ts-ignore
expectCHAI(customComponentsNotBound).to.be.ok
});
});
describe('getComponentFromMap', () => {
const reactBootstrap = {
Welcome,
WelcomeNonBind,
};
const componentLibraries = {
reactBootstrap,
};
it('should return a function if jsonx.component is not a string', () => {
expectCHAI(_jsonxComponents.getComponentFromMap({
jsonx: {
//@ts-ignore
component:Welcome,
}, })).to.be.a('function').and.to.eql(Welcome);
});
it('should return the dom element string if a valid DOM elmenet in ReactDOM', () => {
['div', 'span', 'p', 'section', ].forEach(el => {
const jsonxObj = { jsonx: { component: el, }, };
expectCHAI(_jsonxComponents.getComponentFromMap(jsonxObj)).to.eql(el);
});
});
it('should return a custom element', () => {
const jsonxObj = {
jsonx: {
component: 'Welcome',
},
reactComponents: {
Welcome,
},
};
expectCHAI(_jsonxComponents.getComponentFromMap(jsonxObj)).to.eql(Welcome);
});
it('should return a component library react element', () => {
const jsonxObj = {
jsonx: {
component: 'reactBootstrap.Welcome',
},
componentLibraries,
};
expectCHAI(_jsonxComponents.getComponentFromMap(jsonxObj)).to.eql(Welcome);
});
it('should handle errors', () => {
const logError = sinon.spy();
expectCHAI(_jsonxComponents.getComponentFromMap.bind(null)).to.throw();
try {
//@ts-ignore
_jsonxComponents.getComponentFromMap({ debug: true, logError, jsonx:false, });
} catch (e) {
expectCHAI(e).to.be.a('error');
expectCHAI(logError.called).to.be.true;
}
});
});
describe('getComponentFromLibrary', () => {
const reactBootstrap = {
Welcome,
WelcomeNonBind,
};
const componentLibraries = {
reactBootstrap,
testLib: {
testGrouping: {
testComponent: {},
},
},
};
it('should return undefined if not valid', () => {
expectCHAI(_jsonxComponents.getComponentFromLibrary()).to.be.undefined;
});
it('should return a function if selecting valid component library', () => {
const jsonxObj = {
jsonx: {
component: 'reactBootstrap.Welcome',
},
componentLibraries,
};
expectCHAI(_jsonxComponents.getComponentFromLibrary(jsonxObj)).to.be.eql(Welcome);
const jsonxObjDeep = {
jsonx: {
component: 'testLib.testGrouping.testComponent',
},
componentLibraries,
};
expectCHAI(_jsonxComponents.getComponentFromLibrary(jsonxObjDeep)).to.be.eql(componentLibraries.testLib.testGrouping.testComponent);
});
});
describe('componentMap', () => {
// before(function () {
// this.jsdom = mochaJSDOM();
// });
// it('should accept components from a window property', function (done) {
// window.__jsonx_custom_elements = {
// Welcome,
// WelcomeNonBind,
// WelcomeBindSpy,
// };
// Object.defineProperty(window, '__jsonx_custom_elements', {
// value: {
// Welcome,
// WelcomeNonBind,
// WelcomeBindSpy,
// },
// });
// // delete require.cache[ require.resolve('../../dist/jsonx.cjs') ];
// import('./index')
// .then(jsonxModule => {
// const window_test_jsonx = jsonxModule;
// console.log('window.__jsonx_custom_elements', window.__jsonx_custom_elements);
// expectCHAI(window_test_jsonx._jsonxComponents.componentMap).to.haveOwnProperty('Welcome');
// expectCHAI(window_test_jsonx._jsonxComponents.componentMap).to.haveOwnProperty('WelcomeNonBind');
// expectCHAI(window_test_jsonx._jsonxComponents.componentMap).to.haveOwnProperty('WelcomeBindSpy');
// done();
// })
// .catch(done);
// });
// after(function () {
// this.jsdom();
// });
});
describe('getFunctionFromEval', () => {
const getFunctionFromEval = _jsonxComponents.getFunctionFromEval;
it('should return a new function', () => {
const myFunc = getFunctionFromEval({
body: 'return 3;',
});
expectCHAI(myFunc()).to.eql(3);
});
it('should name the function',()=>{
const myFunc = getFunctionFromEval({
body: 'return 3;',
name:'myFunction'
});
expectCHAI(myFunc.name).to.eql('myFunction');
})
});
describe('getReactClassComponent', () => {
const getReactClassComponent = _jsonxComponents.getReactClassComponent;
const classBody = {
componentDidMount: {
body: 'console.log(\'mounted\',this.props)',
arguments: [],
},
render: {
body: {
component: 'p',
children: [
{
component: 'span',
children: 'My Custom React Component Status: ',
},
{
component: 'span',
thisprops: {
children: ['status',],
},
},
],
},
},
};
it('should create a React Component', () => {
//@ts-ignore
const MyCustomComponent = getReactClassComponent(classBody);
//@ts-ignore
const MyCustomComponentClass = getReactClassComponent(classBody, { returnFactory:false, });
// const MyCustomComponentFactory = getReactClassComponent(classBody);
// console.log({MyCustomComponentClass});
expectCHAI(MyCustomComponent).to.be.a('function');
expectCHAI(MyCustomComponentClass).to.be.a('function');
expectCHAI(ReactTestUtils.isElement(MyCustomComponent)).to.be.false;
// expectCHAI(ReactTestUtils.isCompositeComponent(MyCustomComponentClass())).to.be.true;
});
it('should allow for functions as object props', () => {
const classBodyOpts = Object.assign({}, classBody);
//@ts-ignore
classBodyOpts.componentDidMount = function () {
console.log('mounted!');
};
//@ts-ignore
expectCHAI(getReactClassComponent.bind(null, classBodyOpts)).to.not.throw;
});
it('should allow for custom class names', () => {
//@ts-ignore
const MyCustomComponentNameClass = getReactClassComponent(classBody, '', { name: 'myClass', });
expectCHAI(MyCustomComponentNameClass).to.be.a('function');
});
it('should throw an error if missing a render function', () => {
//@ts-ignore
expectCHAI(getReactClassComponent.bind()).to.throw;
});
it('should throw an error if missing a function is missing a body', () => {
//@ts-ignore
expectCHAI(getReactClassComponent.bind({ render: {}, })).to.throw;
});
it('should create suspense/lazy components', () => {
//@ts-ignore
const MyCustomLazyComponent = getReactClassComponent(
{
component: 'p',
children: [
{
component: 'span',
children: 'My Custom React Component Status: ',
},
{
component: 'span',
thisprops: {
children: ['status',],
},
},
],
},
{
name: 'myComp',
//@ts-ignore
lazy: (comp, options) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve([
comp, Object.assign(options, { lazy: false, }),]);
}, 3000);
});
},
},
);
expectCHAI(MyCustomLazyComponent).to.be.a('object');
});
});
describe('makeFunctionComponent', () => {
const makeFunctionComponent = _jsonxComponents.makeFunctionComponent;
it('should create a React Function Component from a regular function', () => {
function functionComponentWithHook(){
//@ts-ignore
const [count, setCount] = useState(0);
//@ts-ignore
useEffect(()=>{
console.log('only run once')
},[])
const exposeprops = {count,setCount}
return {
component:'div',
passprops:true,
children:[
{
component:'p',
children: 'This is from functionComponentWithHook '
},
{
component:'p',
passprops:true,
children:[
{
component:'span',
children:'You clicked ',
},
{
component:'input',
props:{
defaultValue:0
},
thisprops:{
value:['count'],
},
},
{
component:'span',
children:' times'
}
]
},
{
component:'button',
__dangerouslyBindEvalProps:{
//@ts-ignore
onClick(count,setCount){
setCount(count+1)
},
},
children:'Click me'
}
],
}
}
//@ts-ignore
const MyCustomComponentMadeFunction = makeFunctionComponent(functionComponentWithHook);
expectCHAI(MyCustomComponentMadeFunction.name).to.eql('functionComponentWithHook');
expectCHAI(MyCustomComponentMadeFunction).to.be.a('function');
});
}),
describe('getReactFunctionComponent', () => {
const getReactFunctionComponent = _jsonxComponents.getReactFunctionComponent;
it('should react a React Function Component', () => {
//@ts-ignore
const MyCustomComponentNameless = getReactFunctionComponent(
{
component:'p',
children:'hello',
},
'console.log("lazy function body");',
{ },
);
expectCHAI(MyCustomComponentNameless.name).to.eql('Anonymous');
expectCHAI(MyCustomComponentNameless).to.be.a('function');
});
it('should create react a React Function Component', () => {
//@ts-ignore
const MyCustomComponentNameless = getReactFunctionComponent(
{
component:'p',
children:'hello',
},
function myFuncBody(){ console.log('some function body') },
{ },
);
expectCHAI(MyCustomComponentNameless.name).to.eql('Anonymous');
expectCHAI(MyCustomComponentNameless).to.be.a('function');
});
it('should create a React Function Component with a name', () => {
//@ts-ignore
const MyCustomComponent = getReactFunctionComponent(
{
component:'p',
children:[
{
component:'span',
children: 'My Custom React Component Status: ',
},
{
component:'span',
thisprops:{
children:['status', ],
},
},
],
},
'console.log("lazy function body");',
{ name:'myComp', },
);
expectCHAI(MyCustomComponent.name).to.eql('myComp');
expectCHAI(MyCustomComponent).to.be.a('function');
});
it('should create suspense/lazy components', () => {
//@ts-ignore
const MyCustomLazyComponent = getReactFunctionComponent(
{
component: 'p',
children: [
{
component: 'span',
children: 'My Custom React Component Status: ',
},
{
component: 'span',
thisprops: {
children: ['status',],
},
},
],
},
'console.log("lazy function body");',
{
name: 'myComp',
//@ts-ignore
lazy: (comp, options) => {
return new Promise((resolve) => {
setTimeout(() => {
resolve([
comp, Object.assign(options, { lazy: false, }),]);
}, 3000);
});
},
},
);
expectCHAI(MyCustomLazyComponent).to.be.a('object');
});
});
describe('DynamicComponent', () => {
const DynamicComponent = _jsonxComponents.DynamicComponent;
it('should react a React Function Component', () => {
// //@ts-ignore
const MyDynamicComponent = DynamicComponent.call( {disableRenderIndexKey:false},{ name:'MyDynamicComponent', }) as any
// //@ts-ignore
const wrapper = render(<MyDynamicComponent id="testingForm" />);
expectCHAI(wrapper).to.be.ok
//@ts-ignore
// const wrapper = mount(<DynamicComponent key={3}
// fetchURL='#'
// fetchOptions={{}}
// jsonx={{ component: 'div', children: 'test' }} />);
// expectCHAI(wrapper.text()).to.contain('...Loading');
expectCHAI(DynamicComponent).to.be.a('function');
});
it('should render a component',()=>{
const myDynamicFunction = DynamicComponent.call({},{
jsonx:{
component:'div',
children:[
{
component:'h1',
props:{
id:'fetchedTitle'
},
children:'Fetched Data'
},
{
component:'p',
props:{
id:'fetchedP'
},
resourceprops:{
children:['DynamicComponentData','result']
}
}
]
},
fetchURL:'#',
name: 'myDynamicFunction',
fetchFunction:()=>{
return new Promise(resolve=>{
setTimeout(()=>{
resolve({result:'some mock data'})
},1000)
})
}
})
expectCHAI(myDynamicFunction).to.be.a('function');
expectCHAI(myDynamicFunction.name).to.eql('bound myDynamicFunction');
//@ts-ignore
const m = React.createElement(myDynamicFunction,{},undefined)
//@ts-ignore
const r = ReactDOMServer.renderToString(myDynamicFunction,{title:'called prop'},undefined)
// console.log({r},r)
// console.log({m},m)
expectCHAI(m.type).to.eql(myDynamicFunction)
// console.log('myDynamicFunction',myDynamicFunction,{myDynamicFunction})
})
});
describe('FormComponent', () => {
const FormComponent = _jsonxComponents.FormComponent;
it('should react a React Function Component', () => {
// //@ts-ignore
const MyFormComponent = FormComponent.call( {disableRenderIndexKey:false},{ name:'MyFormComponent', }) as any
// //@ts-ignore
const wrapper = render(<MyFormComponent id="testingForm" />);
// //@ts-ignore
// const someElement = wrapper.container.querySelector('#testingForm');
// console.log('someElement',someElement)
// console.log('wrapper.text()',wrapper.text())
// expectCHAI(wrapper.text()).to.contain('empty');
expectCHAI(FormComponent).to.be.a('function');
expectCHAI(wrapper).to.be.ok
});
it('should render a component',()=>{
const myFormComponent = FormComponent.call({},{
name:'myFormComponent',
})
expectCHAI(myFormComponent).to.be.a('function');
expectCHAI(myFormComponent.name).to.eql('bound myFormComponent');
// console.log('myFormComponent',myFormComponent,{myFormComponent})
//@ts-ignore
const m = React.createElement(myFormComponent,undefined,undefined)
expectCHAI(m.type).to.eql(myFormComponent)
// console.log({m},m)
})
it('should handle props passed to function',()=>{
const options = {
formComponent:{
component:'form',
children:'using form component'
},
onSubmit:(data:any)=>'submitted: '+JSON.stringify(data),
hookFormOptions:{
defaultValues:{ title:'testing form component' }
}
}
//@ts-ignore
const FormFunctionComponent:React.FunctionComponent = FormComponent.call({},options);
//@ts-ignore
const invokedFormFunctionComponent =React.createElement(FormFunctionComponent,{sub_title:'called props'},'');
expectCHAI(invokedFormFunctionComponent).to.be.ok
const wrapperOptions = {
...options,
formWrapperProps:{title:'added wrapped prop'},
formWrapperComponent:{component:'div'}
}
//@ts-ignore
const WrappedFormFunctionComponent:React.FunctionComponent = FormComponent.call({},wrapperOptions);
//@ts-ignore
const invokedWrappedFormFunctionComponent =React.createElement(WrappedFormFunctionComponent,{sub_title:'called props'},'');
expectCHAI(invokedWrappedFormFunctionComponent).to.be.ok
})
});
describe('getReactContext', () => {
const getReactContext = _jsonxComponents.getReactContext;
it('should return a React Context Object', () => {
const context = getReactContext({ some: 'c', });
expectCHAI(ReactTestUtils.isElement(context)).to.be.false;
expectCHAI(context).to.be.an('object');
// expectCHAI(context).to.be.an.instanceOf(React.createContext);
});
});
describe('getCustomFunctionComponent',()=>{
it('should generate function components from custom components',()=>{
const FuncString = getCustomFunctionComponent.call({},customComponents[0] as defs.jsonxCustomComponent);
const FuncDef = getCustomFunctionComponent.call({},customComponents[1] as defs.jsonxCustomComponent);
// console.log('funcString',FuncString)
// console.log('FuncDef',FuncDef)
const originalConsoleLog = console.log;
console.log = jest.fn()
//@ts-ignore
const {container:containerFuncString} =render(<FuncString />)
//@ts-ignore
const {container:containerFuncDef} =render(<FuncDef />)
expect(containerFuncString.innerHTML).toMatch('<span>gen custom def</span>')
expect(containerFuncDef.innerHTML).toMatch('<span>gen custom</span>')
expect(console.log).toBeCalledWith('called generated function')
console.log=originalConsoleLog
})
});
describe('getCustomComponentsCacheKey',()=>{
it('should return a cachekey string from custom components',()=>{
expect(getCustomComponentsCacheKey(customComponents as defs.jsonxCustomComponent[])).toMatch( 'genFuncDefgenFuncgenClassMyLib');
})
});
describe('getReactLibrariesAndComponents',()=>{
it('should generate components from customComponents',()=>{
const { customComponentLibraries, customReactComponents } = getReactLibrariesAndComponents.call({},customComponents);
expect(typeof customReactComponents.genFuncDef).toBe('function')
expect(typeof customReactComponents.genFunc).toBe('function')
expect(typeof customReactComponents.genClass).toBe('function')
expect(typeof customComponentLibraries.MyLib.CompA).toBe('function')
expect(typeof customComponentLibraries.MyLib.CompB).toBe('function')
expect(typeof customComponentLibraries.MyLib.CompC).toBe('function')
})
})
}); | the_stack |
import type { DataItem } from "../../core/render/Component";
import type { Percent } from "../../core/util/Percent";
import type { LinkedHierarchyNode } from "./LinkedHierarchyNode";
import type { HierarchyLink } from "./HierarchyLink";
import type * as d3Hierarchy from "d3-hierarchy";
import { LinkedHierarchy, ILinkedHierarchySettings, ILinkedHierarchyDataItem, ILinkedHierarchyPrivate, ILinkedHierarchyEvents } from "./LinkedHierarchy";
import * as $array from "../../core/util/Array";
import * as $utils from "../../core/util/Utils";
import * as $type from "../../core/util/Type";
import * as d3Force from "d3-force";
/**
* @ignore
*/
export interface IForceDirectedDataObject {
name?: string,
value?: number,
children?: IForceDirectedDataObject[],
dataItem?: DataItem<IForceDirectedDataItem>
};
export interface IForceDirectedDataItem extends ILinkedHierarchyDataItem {
/**
* An array of data items of child nodes.
*/
children: Array<DataItem<IForceDirectedDataItem>>;
/**
* Data item of a parent node.
*/
parent: DataItem<IForceDirectedDataItem>;
/**
* @ignore
*/
d3ForceNode: d3Force.SimulationNodeDatum;
/**
* X coordinate.
*/
x: number;
/**
* Y coordinate.
*/
y: number;
}
export interface IForceDirectedSettings extends ILinkedHierarchySettings {
/**
* Minimum gap in pixels between the nodes.
*/
nodePadding?: number;
/**
* A force that attracts (or pushes back) all nodes to the center of the
* chart.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/hierarchy/force-directed/#Layout_and_force_simulation} for more info
* @default 0.5
*/
centerStrength?: number;
/**
* A force that attracts (or pushes back) all nodes to each other.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/hierarchy/force-directed/#Layout_and_force_simulation} for more info
* @default -15
*/
manyBodyStrength?: number;
/**
* A force that attracts (or pushes back) nodes that are linked together
* via `linkWithField`.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/hierarchy/force-directed/#Layout_and_force_simulation} for more info
* @default 0.5
*/
linkWithStrength?: number | undefined;
/**
* Resistance acting agains node speed.
*
* The greater the value, the more "sluggish" the nodes will be.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/hierarchy/force-directed/#Layout_and_force_simulation} for more info
* @default 0.5
*/
velocityDecay?: number;
/**
* Length of how long initial force simulation would run in frames.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/hierarchy/force-directed/#Layout_and_force_simulation} for more info
* @default 500
*/
initialFrames?: number;
/**
* If set to a number will wait X number of frames before revealing
* the tree.
*
* Can be used to hide initial animations where nodes settle into their
* places.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/hierarchy/force-directed/#Layout_and_force_simulation} for more info
* @default 10
*/
showOnFrame?: number;
/**
* Smallest possible radius for a node circle.
*
* Can be a fixed pixel value or percent relative to chart size.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/hierarchy/force-directed/#Sizing_nodes} for more info
* @default 1%
*/
minRadius?: number | Percent;
/**
* Biggest possible radius for a node circle.
*
* Can be a fixed pixel value or percent relative to chart size.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/hierarchy/force-directed/#Sizing_nodes} for more info
* @default 8%
*/
maxRadius?: number | Percent;
/**
* Field in data that holds X coordinate of the node.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/hierarchy/force-directed/#Fixed_nodes} for more info
*/
xField?: string;
/**
* Field in data that holds X coordinate of the node.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/hierarchy/force-directed/#Fixed_nodes} for more info
*/
yField?: string;
}
export interface IForceDirectedPrivate extends ILinkedHierarchyPrivate {
}
export interface IForceDirectedEvents extends ILinkedHierarchyEvents {
}
/**
* Creates a force-directed tree.
*
* @see {@link https://www.amcharts.com/docs/v5/charts/hierarchy/force-directed/} for more info
* @important
*/
export class ForceDirected extends LinkedHierarchy {
protected _tag: string = "forcedirected";
/**
* @ignore
*/
public readonly d3forceSimulation: d3Force.Simulation<{}, d3Force.SimulationLinkDatum<d3Force.SimulationNodeDatum>> = d3Force.forceSimulation();
/**
* @ignore
*/
public readonly collisionForce: d3Force.ForceCollide<d3Force.SimulationNodeDatum> = d3Force.forceCollide(20);
/**
* @ignore
*/
public linkForce: d3Force.ForceLink<d3Force.SimulationNodeDatum, d3Force.SimulationLinkDatum<d3Force.SimulationNodeDatum>> = d3Force.forceLink();
public static className: string = "ForceDirected";
public static classNames: Array<string> = LinkedHierarchy.classNames.concat([ForceDirected.className]);
declare public _settings: IForceDirectedSettings;
declare public _privateSettings: IForceDirectedPrivate;
declare public _dataItemSettings: IForceDirectedDataItem;
declare public _events: IForceDirectedEvents;
protected _nodes: Array<any> = [];
protected _links: Array<any> = [];
protected _afterNew() {
super._afterNew();
this.d3forceSimulation.on("tick", () => {
this._tick++;
this.updateNodePositions();
});
}
protected _tick: number = 0;
protected _nodesDirty: boolean = false;
public _prepareChildren() {
super._prepareChildren();
if (this.isDirty("showOnFrame")) {
const showOnFrame = this.get("showOnFrame");
if (showOnFrame > this._tick) {
this.nodesContainer.setPrivate("visible", false);
this.linksContainer.setPrivate("visible", false);
}
}
const d3forceSimulation = this.d3forceSimulation;
if (this.isDirty("velocityDecay")) {
d3forceSimulation.velocityDecay(this.get("velocityDecay", 0));
}
if (this.isDirty("initialFrames")) {
d3forceSimulation.alphaDecay(1 - Math.pow(0.001, 1 / this.get("initialFrames", 500)));
}
}
/**
* @ignore
*/
public restartSimulation(alpha: number): void {
const d3forceSimulation = this.d3forceSimulation;
if (d3forceSimulation.alpha() < alpha) {
d3forceSimulation.alpha(alpha);
d3forceSimulation.restart();
}
}
public _handleRadiusChange() {
this._updateForces();
}
protected processDataItem(dataItem: DataItem<this["_dataItemSettings"]>) {
const d3ForceNode: any = { index: this._index, x: this.innerWidth() / 2, y: this.innerHeight() / 2, dataItem: dataItem };
const index = this._nodes.push(d3ForceNode) - 1;
d3ForceNode.index = index;
this.d3forceSimulation.nodes(this._nodes);
dataItem.set("d3ForceNode", d3ForceNode);
super.processDataItem(dataItem);
const node = dataItem.get("node");
node.on("scale", () => {
this._nodesDirty = true;
this.markDirty();
})
node.events.on("dragged", () => {
d3ForceNode.fx = node.x();
d3ForceNode.fy = node.y();
this._updateForces();
})
node.events.on("dragstop", () => {
if (dataItem.get("x") == null) {
d3ForceNode.fx = undefined;
}
if (dataItem.get("y") == null) {
d3ForceNode.fy = undefined;
}
})
}
protected _updateValues(d3HierarchyNode: d3Hierarchy.HierarchyNode<IForceDirectedDataObject>) {
super._updateValues(d3HierarchyNode);
this._nodesDirty = true;
const d3forceSimulation = this.d3forceSimulation;
d3forceSimulation.force("collision", this.collisionForce);
d3forceSimulation.nodes(this._nodes);
this.linkForce = d3Force.forceLink(this._links);
d3forceSimulation.force("link", this.linkForce);
}
protected _updateVisuals() {
super._updateVisuals();
this.restartSimulation(1);
}
public _updateChildren() {
super._updateChildren();
const d3forceSimulation = this.d3forceSimulation;
if (this._sizeDirty) {
let w = Math.max(50, this.innerWidth());
let h = Math.max(50, this.innerHeight());
let pt = this.get("paddingTop", 0);
let pl = this.get("paddingLeft", 0);
let centerStrength = this.get("centerStrength", 1);
d3forceSimulation.force("x", d3Force.forceX().x(w / 2 + pl).strength(centerStrength * 100 / w));
d3forceSimulation.force("y", d3Force.forceY().y(h / 2 + pt).strength(centerStrength * 100 / h));
}
if (this._nodesDirty) {
this._updateForces();
}
}
public _updateForces() {
const d3forceSimulation = this.d3forceSimulation;
d3forceSimulation.force("manybody", d3Force.forceManyBody().strength((d3node) => {
let dataItem = (d3node as any).dataItem;
let node = dataItem.get("node") as LinkedHierarchyNode;
let circle = dataItem.get("circle");
let manyBodyStrength = this.get("manyBodyStrength", -15);
if(circle){
return circle.get("radius", 1) * node.get("scale", 1) * manyBodyStrength;
}
return 0;
}));
this.collisionForce.radius((d3node) => {
let dataItem = (d3node as any).dataItem;
let node = dataItem.get("node") as LinkedHierarchyNode;
let circle = dataItem.get("circle");
let outerCircle = dataItem.get("outerCircle");
if(circle && outerCircle){
let radius = circle.get("radius", 1);
if (!outerCircle.isHidden()) {
radius = radius * outerCircle.get("scale", 1.1);
}
radius *= node.get("scale", 1);
return radius + this.get("nodePadding", 0);
}
})
this.restartSimulation(1);
}
public _clearDirty() {
super._clearDirty();
this._nodesDirty = false;
}
/**
* @ignore
*/
public updateNodePositions() {
const linkForce = this.linkForce;
if (linkForce) {
linkForce.distance((linkDatum) => {
return this.getDistance(linkDatum)
});
linkForce.strength((linkDatum) => {
return this.getStrength(linkDatum)
});
}
if (this._tick == this.get("showOnFrame")) {
this.nodesContainer.setPrivate("visible", true);
this.linksContainer.setPrivate("visible", true);
}
let d3Nodes = this.d3forceSimulation.nodes();
$array.each(d3Nodes, (d3Node: any) => {
const dataItem = d3Node.dataItem as DataItem<this["_dataItemSettings"]>;
const node = dataItem.get("node");
node.set("x", d3Node.x);
node.set("y", d3Node.y);
})
}
/**
* @ignore
*/
public updateLinkWith(dataItems: Array<DataItem<this["_dataItemSettings"]>>) {
$array.each(dataItems, (dataItem) => {
const linkWith = dataItem.get("linkWith");
if (linkWith) {
$array.each(linkWith, (id) => {
const linkWithDataItem = this._getDataItemById(this.dataItems, id);
if (linkWithDataItem) {
this.linkDataItems(dataItem, linkWithDataItem, this.get("linkWithStrength"));
}
})
}
const children = dataItem.get("children");
if (children) {
this.updateLinkWith(children);
}
})
}
/**
* @ignore
*/
protected getDistance(linkDatum: any) {
let sourceDataItem: DataItem<this["_dataItemSettings"]> = <DataItem<this["_dataItemSettings"]>>linkDatum.sourceDataItem;
let targetDataItem: DataItem<this["_dataItemSettings"]> = <DataItem<this["_dataItemSettings"]>>linkDatum.targetDataItem;
let distance = 0;
if (sourceDataItem && targetDataItem) {
const targetNode = targetDataItem.get("node");
if (targetNode.isHidden()) {
return 0;
}
let link = linkDatum.link;
if (link) {
distance = link.get("distance", 1);
}
const sourceNode = sourceDataItem.get("node");
if (targetNode.isHidden()) {
distance = 1;
}
return (distance * (sourceDataItem.get("circle").get("radius", 1) * sourceNode.get("scale", 1) + targetDataItem.get("circle").get("radius", 1) * targetNode.get("scale", 1)));
}
return distance;
}
/**
* @ignore
* @todo description
*/
protected getStrength(linkDatum: any) {
let strength = 0;
let link = linkDatum.link;
if (link) {
strength = link.get("strength", 1);
}
const targetDataItem = linkDatum.targetDataItem;
strength *= targetDataItem.get("node").get("scale");
return strength;
}
protected _updateNode(dataItem: DataItem<this["_dataItemSettings"]>) {
super._updateNode(dataItem);
this._updateRadius(dataItem);
const x = dataItem.get("x");
const y = dataItem.get("y");
const d3Node = dataItem.get("d3ForceNode");
if (x != null) {
(d3Node as any).fx = $utils.relativeToValue(x, this.innerWidth());
}
if (y != null) {
(d3Node as any).fy = $utils.relativeToValue(y, this.innerHeight());
}
}
protected _updateRadius(dataItem: DataItem<this["_dataItemSettings"]>) {
let size = (this.innerWidth() + this.innerHeight()) / 2;
let minRadius = $utils.relativeToValue(this.get("minRadius", 1), size);
let maxRadius = $utils.relativeToValue(this.get("maxRadius", 5), size);
let valueWorking = dataItem.get("sum");
let radius = maxRadius;
const min = this.getPrivate("valueLow", 0);
const max = this.getPrivate("valueHigh", 0);
if (max > 0) {
radius = minRadius + (valueWorking - min) / (max - min) * (maxRadius - minRadius);
}
if (!$type.isNumber(radius)) {
radius = minRadius;
}
const duration = this.get("animationDuration", 0);
const easing = this.get("animationEasing");
dataItem.get("circle").animate({ key: "radius", to: radius, duration: duration, easing: easing });
}
protected _processLink(link: HierarchyLink, source: DataItem<this["_dataItemSettings"]>, target: DataItem<this["_dataItemSettings"]>) {
const d3Link = { link: link, source: source.get("d3ForceNode").index, target: target.get("d3ForceNode").index, sourceDataItem: source, targetDataItem: target };
this._links.push(d3Link);
link.setPrivate("d3Link", d3Link);
this.linkForce = d3Force.forceLink(this._links);
this.d3forceSimulation.force("link", this.linkForce);
this.restartSimulation(0.5);
}
protected _disposeLink(link: HierarchyLink) {
super._disposeLink(link);
$array.remove(this._links, link.getPrivate("d3Link"));
}
protected _handleUnlink() {
this.restartSimulation(0.5);
}
protected _onDataClear() {
super._onDataClear();
this._nodes = [];
this._links = [];
}
} | the_stack |
import {ResponseHandler} from "./bin";
interface IClient {
request(
functionName: string,
functionParams?: any,
responseHandler?: ResponseHandler
): Promise<any>;
resolve_app_request(app_request_id: number | null, result: any): Promise<void>;
reject_app_request(app_request_id: number | null, error: any): Promise<void>;
}
// client module
export enum ClientErrorCode {
NotImplemented = 1,
InvalidHex = 2,
InvalidBase64 = 3,
InvalidAddress = 4,
CallbackParamsCantBeConvertedToJson = 5,
WebsocketConnectError = 6,
WebsocketReceiveError = 7,
WebsocketSendError = 8,
HttpClientCreateError = 9,
HttpRequestCreateError = 10,
HttpRequestSendError = 11,
HttpRequestParseError = 12,
CallbackNotRegistered = 13,
NetModuleNotInit = 14,
InvalidConfig = 15,
CannotCreateRuntime = 16,
InvalidContextHandle = 17,
CannotSerializeResult = 18,
CannotSerializeError = 19,
CannotConvertJsValueToJson = 20,
CannotReceiveSpawnedResult = 21,
SetTimerError = 22,
InvalidParams = 23,
ContractsAddressConversionFailed = 24,
UnknownFunction = 25,
AppRequestError = 26,
NoSuchRequest = 27,
CanNotSendRequestResult = 28,
CanNotReceiveRequestResult = 29,
CanNotParseRequestResult = 30,
UnexpectedCallbackResponse = 31,
CanNotParseNumber = 32,
InternalError = 33,
InvalidHandle = 34
}
export type ClientError = {
/**
*/
code: number,
/**
*/
message: string,
/**
*/
data: any
}
export type ClientConfig = {
/**
*/
network?: NetworkConfig,
/**
*/
crypto?: CryptoConfig,
/**
*/
abi?: AbiConfig,
/**
*/
boc?: BocConfig
}
export type NetworkConfig = {
/**
* DApp Server public address. For instance, for `net.ton.dev/graphql` GraphQL endpoint the server address will be net.ton.dev
*/
server_address?: string,
/**
* List of DApp Server addresses.
*
* @remarks
* Any correct URL format can be specified, including IP addresses This parameter is prevailing over `server_address`.
*/
endpoints?: string[],
/**
* Deprecated.
*
* @remarks
* You must use `network.max_reconnect_timeout` that allows to specify maximum network resolving timeout.
*/
network_retries_count?: number,
/**
* Maximum time for sequential reconnections.
*
* @remarks
* Must be specified in milliseconds. Default is 120000 (2 min).
*/
max_reconnect_timeout?: number,
/**
* Deprecated
*/
reconnect_timeout?: number,
/**
* The number of automatic message processing retries that SDK performs in case of `Message Expired (507)` error - but only for those messages which local emulation was successful or failed with replay protection error.
*
* @remarks
* Default is 5.
*/
message_retries_count?: number,
/**
* Timeout that is used to process message delivery for the contracts which ABI does not include "expire" header. If the message is not delivered within the specified timeout the appropriate error occurs.
*
* @remarks
* Must be specified in milliseconds. Default is 40000 (40 sec).
*/
message_processing_timeout?: number,
/**
* Maximum timeout that is used for query response.
*
* @remarks
* Must be specified in milliseconds. Default is 40000 (40 sec).
*/
wait_for_timeout?: number,
/**
* Maximum time difference between server and client.
*
* @remarks
* If client's device time is out of sync and difference is more than the threshold then error will occur. Also an error will occur if the specified threshold is more than
* `message_processing_timeout/2`.
*
* Must be specified in milliseconds. Default is 15000 (15 sec).
*/
out_of_sync_threshold?: number,
/**
* Maximum number of randomly chosen endpoints the library uses to broadcast a message.
*
* @remarks
* Default is 2.
*/
sending_endpoint_count?: number,
/**
* Frequency of sync latency detection.
*
* @remarks
* Library periodically checks the current endpoint for blockchain data syncronization latency.
* If the latency (time-lag) is less then `NetworkConfig.max_latency`
* then library selects another endpoint.
*
* Must be specified in milliseconds. Default is 60000 (1 min).
*/
latency_detection_interval?: number,
/**
* Maximum value for the endpoint's blockchain data syncronization latency (time-lag). Library periodically checks the current endpoint for blockchain data syncronization latency. If the latency (time-lag) is less then `NetworkConfig.max_latency` then library selects another endpoint.
*
* @remarks
* Must be specified in milliseconds. Default is 60000 (1 min).
*/
max_latency?: number,
/**
* Default timeout for http requests.
*
* @remarks
* Is is used when no timeout specified for the request to limit the answer waiting time. If no answer received during the timeout requests ends with
* error.
*
* Must be specified in milliseconds. Default is 60000 (1 min).
*/
query_timeout?: number,
/**
* Access key to GraphQL API.
*
* @remarks
* At the moment is not used in production.
*/
access_key?: string
}
export type CryptoConfig = {
/**
* Mnemonic dictionary that will be used by default in crypto functions. If not specified, 1 dictionary will be used.
*/
mnemonic_dictionary?: number,
/**
* Mnemonic word count that will be used by default in crypto functions. If not specified the default value will be 12.
*/
mnemonic_word_count?: number,
/**
* Derivation path that will be used by default in crypto functions. If not specified `m/44'/396'/0'/0/0` will be used.
*/
hdkey_derivation_path?: string
}
export type AbiConfig = {
/**
* Workchain id that is used by default in DeploySet
*/
workchain?: number,
/**
* Message lifetime for contracts which ABI includes "expire" header. The default value is 40 sec.
*/
message_expiration_timeout?: number,
/**
* Factor that increases the expiration timeout for each retry The default value is 1.5
*/
message_expiration_timeout_grow_factor?: number
}
export type BocConfig = {
/**
* Maximum BOC cache size in kilobytes.
*
* @remarks
* Default is 10 MB
*/
cache_max_size?: number
}
export type BuildInfoDependency = {
/**
* Dependency name.
*
* @remarks
* Usually it is a crate name.
*/
name: string,
/**
* Git commit hash of the related repository.
*/
git_commit: string
}
export type ParamsOfAppRequest = {
/**
* Request ID.
*
* @remarks
* Should be used in `resolve_app_request` call
*/
app_request_id: number,
/**
* Request describing data
*/
request_data: any
}
export type AppRequestResult = {
type: 'Error'
/**
* Error description
*/
text: string
} | {
type: 'Ok'
/**
* Request processing result
*/
result: any
}
export function appRequestResultError(text: string): AppRequestResult {
return {
type: 'Error',
text,
};
}
export function appRequestResultOk(result: any): AppRequestResult {
return {
type: 'Ok',
result,
};
}
export type ResultOfGetApiReference = {
/**
*/
api: any
}
export type ResultOfVersion = {
/**
* Core Library version
*/
version: string
}
export type ResultOfBuildInfo = {
/**
* Build number assigned to this build by the CI.
*/
build_number: number,
/**
* Fingerprint of the most important dependencies.
*/
dependencies: BuildInfoDependency[]
}
export type ParamsOfResolveAppRequest = {
/**
* Request ID received from SDK
*/
app_request_id: number,
/**
* Result of request processing
*/
result: AppRequestResult
}
/**
* Provides information about library.
*/
export class ClientModule {
client: IClient;
constructor(client: IClient) {
this.client = client;
}
/**
* Returns Core Library API reference
* @returns ResultOfGetApiReference
*/
get_api_reference(): Promise<ResultOfGetApiReference> {
return this.client.request('client.get_api_reference');
}
/**
* Returns Core Library version
* @returns ResultOfVersion
*/
version(): Promise<ResultOfVersion> {
return this.client.request('client.version');
}
/**
* Returns detailed information about this build.
* @returns ResultOfBuildInfo
*/
build_info(): Promise<ResultOfBuildInfo> {
return this.client.request('client.build_info');
}
/**
* Resolves application request processing result
*
* @param {ParamsOfResolveAppRequest} params
* @returns
*/
resolve_app_request(params: ParamsOfResolveAppRequest): Promise<void> {
return this.client.request('client.resolve_app_request', params);
}
}
// crypto module
export enum CryptoErrorCode {
InvalidPublicKey = 100,
InvalidSecretKey = 101,
InvalidKey = 102,
InvalidFactorizeChallenge = 106,
InvalidBigInt = 107,
ScryptFailed = 108,
InvalidKeySize = 109,
NaclSecretBoxFailed = 110,
NaclBoxFailed = 111,
NaclSignFailed = 112,
Bip39InvalidEntropy = 113,
Bip39InvalidPhrase = 114,
Bip32InvalidKey = 115,
Bip32InvalidDerivePath = 116,
Bip39InvalidDictionary = 117,
Bip39InvalidWordCount = 118,
MnemonicGenerationFailed = 119,
MnemonicFromEntropyFailed = 120,
SigningBoxNotRegistered = 121,
InvalidSignature = 122,
EncryptionBoxNotRegistered = 123,
InvalidIvSize = 124,
UnsupportedCipherMode = 125,
CannotCreateCipher = 126,
EncryptDataError = 127,
DecryptDataError = 128,
IvRequired = 129
}
export type SigningBoxHandle = number
export type EncryptionBoxHandle = number
export type EncryptionBoxInfo = {
/**
* Derivation path, for instance "m/44'/396'/0'/0/0"
*/
hdpath?: string,
/**
* Cryptographic algorithm, used by this encryption box
*/
algorithm?: string,
/**
* Options, depends on algorithm and specific encryption box implementation
*/
options?: any,
/**
* Public information, depends on algorithm
*/
public?: any
}
export type EncryptionAlgorithm = ({
type: 'AES'
} & AesParams)
export function encryptionAlgorithmAES(params: AesParams): EncryptionAlgorithm {
return {
type: 'AES',
...params,
};
}
export enum CipherMode {
CBC = "CBC",
CFB = "CFB",
CTR = "CTR",
ECB = "ECB",
OFB = "OFB"
}
export type AesParams = {
/**
*/
mode: CipherMode,
/**
*/
key: string,
/**
*/
iv?: string
}
export type AesInfo = {
/**
*/
mode: CipherMode,
/**
*/
iv?: string
}
export type ParamsOfFactorize = {
/**
* Hexadecimal representation of u64 composite number.
*/
composite: string
}
export type ResultOfFactorize = {
/**
* Two factors of composite or empty if composite can't be factorized.
*/
factors: string[]
}
export type ParamsOfModularPower = {
/**
* `base` argument of calculation.
*/
base: string,
/**
* `exponent` argument of calculation.
*/
exponent: string,
/**
* `modulus` argument of calculation.
*/
modulus: string
}
export type ResultOfModularPower = {
/**
* Result of modular exponentiation
*/
modular_power: string
}
export type ParamsOfTonCrc16 = {
/**
* Input data for CRC calculation.
*
* @remarks
* Encoded with `base64`.
*/
data: string
}
export type ResultOfTonCrc16 = {
/**
* Calculated CRC for input data.
*/
crc: number
}
export type ParamsOfGenerateRandomBytes = {
/**
* Size of random byte array.
*/
length: number
}
export type ResultOfGenerateRandomBytes = {
/**
* Generated bytes encoded in `base64`.
*/
bytes: string
}
export type ParamsOfConvertPublicKeyToTonSafeFormat = {
/**
* Public key - 64 symbols hex string
*/
public_key: string
}
export type ResultOfConvertPublicKeyToTonSafeFormat = {
/**
* Public key represented in TON safe format.
*/
ton_public_key: string
}
export type KeyPair = {
/**
* Public key - 64 symbols hex string
*/
public: string,
/**
* Private key - u64 symbols hex string
*/
secret: string
}
export type ParamsOfSign = {
/**
* Data that must be signed encoded in `base64`.
*/
unsigned: string,
/**
* Sign keys.
*/
keys: KeyPair
}
export type ResultOfSign = {
/**
* Signed data combined with signature encoded in `base64`.
*/
signed: string,
/**
* Signature encoded in `hex`.
*/
signature: string
}
export type ParamsOfVerifySignature = {
/**
* Signed data that must be verified encoded in `base64`.
*/
signed: string,
/**
* Signer's public key - 64 symbols hex string
*/
public: string
}
export type ResultOfVerifySignature = {
/**
* Unsigned data encoded in `base64`.
*/
unsigned: string
}
export type ParamsOfHash = {
/**
* Input data for hash calculation.
*
* @remarks
* Encoded with `base64`.
*/
data: string
}
export type ResultOfHash = {
/**
* Hash of input `data`.
*
* @remarks
* Encoded with 'hex'.
*/
hash: string
}
export type ParamsOfScrypt = {
/**
* The password bytes to be hashed. Must be encoded with `base64`.
*/
password: string,
/**
* Salt bytes that modify the hash to protect against Rainbow table attacks. Must be encoded with `base64`.
*/
salt: string,
/**
* CPU/memory cost parameter
*/
log_n: number,
/**
* The block size parameter, which fine-tunes sequential memory read size and performance.
*/
r: number,
/**
* Parallelization parameter.
*/
p: number,
/**
* Intended output length in octets of the derived key.
*/
dk_len: number
}
export type ResultOfScrypt = {
/**
* Derived key.
*
* @remarks
* Encoded with `hex`.
*/
key: string
}
export type ParamsOfNaclSignKeyPairFromSecret = {
/**
* Secret key - unprefixed 0-padded to 64 symbols hex string
*/
secret: string
}
export type ParamsOfNaclSign = {
/**
* Data that must be signed encoded in `base64`.
*/
unsigned: string,
/**
* Signer's secret key - unprefixed 0-padded to 128 symbols hex string (concatenation of 64 symbols secret and 64 symbols public keys). See `nacl_sign_keypair_from_secret_key`.
*/
secret: string
}
export type ResultOfNaclSign = {
/**
* Signed data, encoded in `base64`.
*/
signed: string
}
export type ParamsOfNaclSignOpen = {
/**
* Signed data that must be unsigned.
*
* @remarks
* Encoded with `base64`.
*/
signed: string,
/**
* Signer's public key - unprefixed 0-padded to 64 symbols hex string
*/
public: string
}
export type ResultOfNaclSignOpen = {
/**
* Unsigned data, encoded in `base64`.
*/
unsigned: string
}
export type ResultOfNaclSignDetached = {
/**
* Signature encoded in `hex`.
*/
signature: string
}
export type ParamsOfNaclSignDetachedVerify = {
/**
* Unsigned data that must be verified.
*
* @remarks
* Encoded with `base64`.
*/
unsigned: string,
/**
* Signature that must be verified.
*
* @remarks
* Encoded with `hex`.
*/
signature: string,
/**
* Signer's public key - unprefixed 0-padded to 64 symbols hex string.
*/
public: string
}
export type ResultOfNaclSignDetachedVerify = {
/**
* `true` if verification succeeded or `false` if it failed
*/
succeeded: boolean
}
export type ParamsOfNaclBoxKeyPairFromSecret = {
/**
* Secret key - unprefixed 0-padded to 64 symbols hex string
*/
secret: string
}
export type ParamsOfNaclBox = {
/**
* Data that must be encrypted encoded in `base64`.
*/
decrypted: string,
/**
* Nonce, encoded in `hex`
*/
nonce: string,
/**
* Receiver's public key - unprefixed 0-padded to 64 symbols hex string
*/
their_public: string,
/**
* Sender's private key - unprefixed 0-padded to 64 symbols hex string
*/
secret: string
}
export type ResultOfNaclBox = {
/**
* Encrypted data encoded in `base64`.
*/
encrypted: string
}
export type ParamsOfNaclBoxOpen = {
/**
* Data that must be decrypted.
*
* @remarks
* Encoded with `base64`.
*/
encrypted: string,
/**
*/
nonce: string,
/**
* Sender's public key - unprefixed 0-padded to 64 symbols hex string
*/
their_public: string,
/**
* Receiver's private key - unprefixed 0-padded to 64 symbols hex string
*/
secret: string
}
export type ResultOfNaclBoxOpen = {
/**
* Decrypted data encoded in `base64`.
*/
decrypted: string
}
export type ParamsOfNaclSecretBox = {
/**
* Data that must be encrypted.
*
* @remarks
* Encoded with `base64`.
*/
decrypted: string,
/**
* Nonce in `hex`
*/
nonce: string,
/**
* Secret key - unprefixed 0-padded to 64 symbols hex string
*/
key: string
}
export type ParamsOfNaclSecretBoxOpen = {
/**
* Data that must be decrypted.
*
* @remarks
* Encoded with `base64`.
*/
encrypted: string,
/**
* Nonce in `hex`
*/
nonce: string,
/**
* Public key - unprefixed 0-padded to 64 symbols hex string
*/
key: string
}
export type ParamsOfMnemonicWords = {
/**
* Dictionary identifier
*/
dictionary?: number
}
export type ResultOfMnemonicWords = {
/**
* The list of mnemonic words
*/
words: string
}
export type ParamsOfMnemonicFromRandom = {
/**
* Dictionary identifier
*/
dictionary?: number,
/**
* Mnemonic word count
*/
word_count?: number
}
export type ResultOfMnemonicFromRandom = {
/**
* String of mnemonic words
*/
phrase: string
}
export type ParamsOfMnemonicFromEntropy = {
/**
* Entropy bytes.
*
* @remarks
* Hex encoded.
*/
entropy: string,
/**
* Dictionary identifier
*/
dictionary?: number,
/**
* Mnemonic word count
*/
word_count?: number
}
export type ResultOfMnemonicFromEntropy = {
/**
* Phrase
*/
phrase: string
}
export type ParamsOfMnemonicVerify = {
/**
* Phrase
*/
phrase: string,
/**
* Dictionary identifier
*/
dictionary?: number,
/**
* Word count
*/
word_count?: number
}
export type ResultOfMnemonicVerify = {
/**
* Flag indicating if the mnemonic is valid or not
*/
valid: boolean
}
export type ParamsOfMnemonicDeriveSignKeys = {
/**
* Phrase
*/
phrase: string,
/**
* Derivation path, for instance "m/44'/396'/0'/0/0"
*/
path?: string,
/**
* Dictionary identifier
*/
dictionary?: number,
/**
* Word count
*/
word_count?: number
}
export type ParamsOfHDKeyXPrvFromMnemonic = {
/**
* String with seed phrase
*/
phrase: string,
/**
* Dictionary identifier
*/
dictionary?: number,
/**
* Mnemonic word count
*/
word_count?: number
}
export type ResultOfHDKeyXPrvFromMnemonic = {
/**
* Serialized extended master private key
*/
xprv: string
}
export type ParamsOfHDKeyDeriveFromXPrv = {
/**
* Serialized extended private key
*/
xprv: string,
/**
* Child index (see BIP-0032)
*/
child_index: number,
/**
* Indicates the derivation of hardened/not-hardened key (see BIP-0032)
*/
hardened: boolean
}
export type ResultOfHDKeyDeriveFromXPrv = {
/**
* Serialized extended private key
*/
xprv: string
}
export type ParamsOfHDKeyDeriveFromXPrvPath = {
/**
* Serialized extended private key
*/
xprv: string,
/**
* Derivation path, for instance "m/44'/396'/0'/0/0"
*/
path: string
}
export type ResultOfHDKeyDeriveFromXPrvPath = {
/**
* Derived serialized extended private key
*/
xprv: string
}
export type ParamsOfHDKeySecretFromXPrv = {
/**
* Serialized extended private key
*/
xprv: string
}
export type ResultOfHDKeySecretFromXPrv = {
/**
* Private key - 64 symbols hex string
*/
secret: string
}
export type ParamsOfHDKeyPublicFromXPrv = {
/**
* Serialized extended private key
*/
xprv: string
}
export type ResultOfHDKeyPublicFromXPrv = {
/**
* Public key - 64 symbols hex string
*/
public: string
}
export type ParamsOfChaCha20 = {
/**
* Source data to be encrypted or decrypted.
*
* @remarks
* Must be encoded with `base64`.
*/
data: string,
/**
* 256-bit key.
*
* @remarks
* Must be encoded with `hex`.
*/
key: string,
/**
* 96-bit nonce.
*
* @remarks
* Must be encoded with `hex`.
*/
nonce: string
}
export type ResultOfChaCha20 = {
/**
* Encrypted/decrypted data.
*
* @remarks
* Encoded with `base64`.
*/
data: string
}
export type RegisteredSigningBox = {
/**
* Handle of the signing box.
*/
handle: SigningBoxHandle
}
export type ParamsOfAppSigningBox = {
type: 'GetPublicKey'
} | {
type: 'Sign'
/**
* Data to sign encoded as base64
*/
unsigned: string
}
export function paramsOfAppSigningBoxGetPublicKey(): ParamsOfAppSigningBox {
return {
type: 'GetPublicKey',
};
}
export function paramsOfAppSigningBoxSign(unsigned: string): ParamsOfAppSigningBox {
return {
type: 'Sign',
unsigned,
};
}
export type ResultOfAppSigningBox = {
type: 'GetPublicKey'
/**
* Signing box public key
*/
public_key: string
} | {
type: 'Sign'
/**
* Data signature encoded as hex
*/
signature: string
}
export function resultOfAppSigningBoxGetPublicKey(public_key: string): ResultOfAppSigningBox {
return {
type: 'GetPublicKey',
public_key,
};
}
export function resultOfAppSigningBoxSign(signature: string): ResultOfAppSigningBox {
return {
type: 'Sign',
signature,
};
}
export type ResultOfSigningBoxGetPublicKey = {
/**
* Public key of signing box.
*
* @remarks
* Encoded with hex
*/
pubkey: string
}
export type ParamsOfSigningBoxSign = {
/**
* Signing Box handle.
*/
signing_box: SigningBoxHandle,
/**
* Unsigned user data.
*
* @remarks
* Must be encoded with `base64`.
*/
unsigned: string
}
export type ResultOfSigningBoxSign = {
/**
* Data signature.
*
* @remarks
* Encoded with `hex`.
*/
signature: string
}
export type RegisteredEncryptionBox = {
/**
* Handle of the encryption box
*/
handle: EncryptionBoxHandle
}
export type ParamsOfAppEncryptionBox = {
type: 'GetInfo'
} | {
type: 'Encrypt'
/**
* Data, encoded in Base64
*/
data: string
} | {
type: 'Decrypt'
/**
* Data, encoded in Base64
*/
data: string
}
export function paramsOfAppEncryptionBoxGetInfo(): ParamsOfAppEncryptionBox {
return {
type: 'GetInfo',
};
}
export function paramsOfAppEncryptionBoxEncrypt(data: string): ParamsOfAppEncryptionBox {
return {
type: 'Encrypt',
data,
};
}
export function paramsOfAppEncryptionBoxDecrypt(data: string): ParamsOfAppEncryptionBox {
return {
type: 'Decrypt',
data,
};
}
export type ResultOfAppEncryptionBox = {
type: 'GetInfo'
/**
*/
info: EncryptionBoxInfo
} | {
type: 'Encrypt'
/**
* Encrypted data, encoded in Base64
*/
data: string
} | {
type: 'Decrypt'
/**
* Decrypted data, encoded in Base64
*/
data: string
}
export function resultOfAppEncryptionBoxGetInfo(info: EncryptionBoxInfo): ResultOfAppEncryptionBox {
return {
type: 'GetInfo',
info,
};
}
export function resultOfAppEncryptionBoxEncrypt(data: string): ResultOfAppEncryptionBox {
return {
type: 'Encrypt',
data,
};
}
export function resultOfAppEncryptionBoxDecrypt(data: string): ResultOfAppEncryptionBox {
return {
type: 'Decrypt',
data,
};
}
export type ParamsOfEncryptionBoxGetInfo = {
/**
* Encryption box handle
*/
encryption_box: EncryptionBoxHandle
}
export type ResultOfEncryptionBoxGetInfo = {
/**
* Encryption box information
*/
info: EncryptionBoxInfo
}
export type ParamsOfEncryptionBoxEncrypt = {
/**
* Encryption box handle
*/
encryption_box: EncryptionBoxHandle,
/**
* Data to be encrypted, encoded in Base64
*/
data: string
}
export type ResultOfEncryptionBoxEncrypt = {
/**
* Encrypted data, encoded in Base64.
*
* @remarks
* Padded to cipher block size
*/
data: string
}
export type ParamsOfEncryptionBoxDecrypt = {
/**
* Encryption box handle
*/
encryption_box: EncryptionBoxHandle,
/**
* Data to be decrypted, encoded in Base64
*/
data: string
}
export type ResultOfEncryptionBoxDecrypt = {
/**
* Decrypted data, encoded in Base64.
*/
data: string
}
export type ParamsOfCreateEncryptionBox = {
/**
* Encryption algorithm specifier including cipher parameters (key, IV, etc)
*/
algorithm: EncryptionAlgorithm
}
type ResultOfAppSigningBoxGetPublicKey = {
public_key: string
}
type ParamsOfAppSigningBoxSign = {
unsigned: string
}
type ResultOfAppSigningBoxSign = {
signature: string
}
export interface AppSigningBox {
get_public_key(): Promise<ResultOfAppSigningBoxGetPublicKey>,
sign(params: ParamsOfAppSigningBoxSign): Promise<ResultOfAppSigningBoxSign>,
}
async function dispatchAppSigningBox(obj: AppSigningBox, params: ParamsOfAppSigningBox, app_request_id: number | null, client: IClient) {
try {
let result = {};
switch (params.type) {
case 'GetPublicKey':
result = await obj.get_public_key();
break;
case 'Sign':
result = await obj.sign(params);
break;
}
client.resolve_app_request(app_request_id, { type: params.type, ...result });
}
catch (error) {
client.reject_app_request(app_request_id, error);
}
}
type ResultOfAppEncryptionBoxGetInfo = {
info: EncryptionBoxInfo
}
type ParamsOfAppEncryptionBoxEncrypt = {
data: string
}
type ResultOfAppEncryptionBoxEncrypt = {
data: string
}
type ParamsOfAppEncryptionBoxDecrypt = {
data: string
}
type ResultOfAppEncryptionBoxDecrypt = {
data: string
}
export interface AppEncryptionBox {
get_info(): Promise<ResultOfAppEncryptionBoxGetInfo>,
encrypt(params: ParamsOfAppEncryptionBoxEncrypt): Promise<ResultOfAppEncryptionBoxEncrypt>,
decrypt(params: ParamsOfAppEncryptionBoxDecrypt): Promise<ResultOfAppEncryptionBoxDecrypt>,
}
async function dispatchAppEncryptionBox(obj: AppEncryptionBox, params: ParamsOfAppEncryptionBox, app_request_id: number | null, client: IClient) {
try {
let result = {};
switch (params.type) {
case 'GetInfo':
result = await obj.get_info();
break;
case 'Encrypt':
result = await obj.encrypt(params);
break;
case 'Decrypt':
result = await obj.decrypt(params);
break;
}
client.resolve_app_request(app_request_id, { type: params.type, ...result });
}
catch (error) {
client.reject_app_request(app_request_id, error);
}
}
/**
* Crypto functions.
*/
export class CryptoModule {
client: IClient;
constructor(client: IClient) {
this.client = client;
}
/**
* Integer factorization
*
* @remarks
* Performs prime factorization – decomposition of a composite number
* into a product of smaller prime integers (factors).
* See [https://en.wikipedia.org/wiki/Integer_factorization]
*
* @param {ParamsOfFactorize} params
* @returns ResultOfFactorize
*/
factorize(params: ParamsOfFactorize): Promise<ResultOfFactorize> {
return this.client.request('crypto.factorize', params);
}
/**
* Modular exponentiation
*
* @remarks
* Performs modular exponentiation for big integers (`base`^`exponent` mod `modulus`).
* See [https://en.wikipedia.org/wiki/Modular_exponentiation]
*
* @param {ParamsOfModularPower} params
* @returns ResultOfModularPower
*/
modular_power(params: ParamsOfModularPower): Promise<ResultOfModularPower> {
return this.client.request('crypto.modular_power', params);
}
/**
* Calculates CRC16 using TON algorithm.
*
* @param {ParamsOfTonCrc16} params
* @returns ResultOfTonCrc16
*/
ton_crc16(params: ParamsOfTonCrc16): Promise<ResultOfTonCrc16> {
return this.client.request('crypto.ton_crc16', params);
}
/**
* Generates random byte array of the specified length and returns it in `base64` format
*
* @param {ParamsOfGenerateRandomBytes} params
* @returns ResultOfGenerateRandomBytes
*/
generate_random_bytes(params: ParamsOfGenerateRandomBytes): Promise<ResultOfGenerateRandomBytes> {
return this.client.request('crypto.generate_random_bytes', params);
}
/**
* Converts public key to ton safe_format
*
* @param {ParamsOfConvertPublicKeyToTonSafeFormat} params
* @returns ResultOfConvertPublicKeyToTonSafeFormat
*/
convert_public_key_to_ton_safe_format(params: ParamsOfConvertPublicKeyToTonSafeFormat): Promise<ResultOfConvertPublicKeyToTonSafeFormat> {
return this.client.request('crypto.convert_public_key_to_ton_safe_format', params);
}
/**
* Generates random ed25519 key pair.
* @returns KeyPair
*/
generate_random_sign_keys(): Promise<KeyPair> {
return this.client.request('crypto.generate_random_sign_keys');
}
/**
* Signs a data using the provided keys.
*
* @param {ParamsOfSign} params
* @returns ResultOfSign
*/
sign(params: ParamsOfSign): Promise<ResultOfSign> {
return this.client.request('crypto.sign', params);
}
/**
* Verifies signed data using the provided public key. Raises error if verification is failed.
*
* @param {ParamsOfVerifySignature} params
* @returns ResultOfVerifySignature
*/
verify_signature(params: ParamsOfVerifySignature): Promise<ResultOfVerifySignature> {
return this.client.request('crypto.verify_signature', params);
}
/**
* Calculates SHA256 hash of the specified data.
*
* @param {ParamsOfHash} params
* @returns ResultOfHash
*/
sha256(params: ParamsOfHash): Promise<ResultOfHash> {
return this.client.request('crypto.sha256', params);
}
/**
* Calculates SHA512 hash of the specified data.
*
* @param {ParamsOfHash} params
* @returns ResultOfHash
*/
sha512(params: ParamsOfHash): Promise<ResultOfHash> {
return this.client.request('crypto.sha512', params);
}
/**
* Perform `scrypt` encryption
*
* @remarks
* Derives key from `password` and `key` using `scrypt` algorithm.
* See [https://en.wikipedia.org/wiki/Scrypt].
*
* # Arguments
* - `log_n` - The log2 of the Scrypt parameter `N`
* - `r` - The Scrypt parameter `r`
* - `p` - The Scrypt parameter `p`
* # Conditions
* - `log_n` must be less than `64`
* - `r` must be greater than `0` and less than or equal to `4294967295`
* - `p` must be greater than `0` and less than `4294967295`
* # Recommended values sufficient for most use-cases
* - `log_n = 15` (`n = 32768`)
* - `r = 8`
* - `p = 1`
*
* @param {ParamsOfScrypt} params
* @returns ResultOfScrypt
*/
scrypt(params: ParamsOfScrypt): Promise<ResultOfScrypt> {
return this.client.request('crypto.scrypt', params);
}
/**
* Generates a key pair for signing from the secret key
*
* @remarks
* **NOTE:** In the result the secret key is actually the concatenation
* of secret and public keys (128 symbols hex string) by design of [NaCL](http://nacl.cr.yp.to/sign.html).
* See also [the stackexchange question](https://crypto.stackexchange.com/questions/54353/).
*
* @param {ParamsOfNaclSignKeyPairFromSecret} params
* @returns KeyPair
*/
nacl_sign_keypair_from_secret_key(params: ParamsOfNaclSignKeyPairFromSecret): Promise<KeyPair> {
return this.client.request('crypto.nacl_sign_keypair_from_secret_key', params);
}
/**
* Signs data using the signer's secret key.
*
* @param {ParamsOfNaclSign} params
* @returns ResultOfNaclSign
*/
nacl_sign(params: ParamsOfNaclSign): Promise<ResultOfNaclSign> {
return this.client.request('crypto.nacl_sign', params);
}
/**
* Verifies the signature and returns the unsigned message
*
* @remarks
* Verifies the signature in `signed` using the signer's public key `public`
* and returns the message `unsigned`.
*
* If the signature fails verification, crypto_sign_open raises an exception.
*
* @param {ParamsOfNaclSignOpen} params
* @returns ResultOfNaclSignOpen
*/
nacl_sign_open(params: ParamsOfNaclSignOpen): Promise<ResultOfNaclSignOpen> {
return this.client.request('crypto.nacl_sign_open', params);
}
/**
* Signs the message using the secret key and returns a signature.
*
* @remarks
* Signs the message `unsigned` using the secret key `secret`
* and returns a signature `signature`.
*
* @param {ParamsOfNaclSign} params
* @returns ResultOfNaclSignDetached
*/
nacl_sign_detached(params: ParamsOfNaclSign): Promise<ResultOfNaclSignDetached> {
return this.client.request('crypto.nacl_sign_detached', params);
}
/**
* Verifies the signature with public key and `unsigned` data.
*
* @param {ParamsOfNaclSignDetachedVerify} params
* @returns ResultOfNaclSignDetachedVerify
*/
nacl_sign_detached_verify(params: ParamsOfNaclSignDetachedVerify): Promise<ResultOfNaclSignDetachedVerify> {
return this.client.request('crypto.nacl_sign_detached_verify', params);
}
/**
* Generates a random NaCl key pair
* @returns KeyPair
*/
nacl_box_keypair(): Promise<KeyPair> {
return this.client.request('crypto.nacl_box_keypair');
}
/**
* Generates key pair from a secret key
*
* @param {ParamsOfNaclBoxKeyPairFromSecret} params
* @returns KeyPair
*/
nacl_box_keypair_from_secret_key(params: ParamsOfNaclBoxKeyPairFromSecret): Promise<KeyPair> {
return this.client.request('crypto.nacl_box_keypair_from_secret_key', params);
}
/**
* Public key authenticated encryption
*
* @remarks
* Encrypt and authenticate a message using the senders secret key, the receivers public
* key, and a nonce.
*
* @param {ParamsOfNaclBox} params
* @returns ResultOfNaclBox
*/
nacl_box(params: ParamsOfNaclBox): Promise<ResultOfNaclBox> {
return this.client.request('crypto.nacl_box', params);
}
/**
* Decrypt and verify the cipher text using the receivers secret key, the senders public key, and the nonce.
*
* @param {ParamsOfNaclBoxOpen} params
* @returns ResultOfNaclBoxOpen
*/
nacl_box_open(params: ParamsOfNaclBoxOpen): Promise<ResultOfNaclBoxOpen> {
return this.client.request('crypto.nacl_box_open', params);
}
/**
* Encrypt and authenticate message using nonce and secret key.
*
* @param {ParamsOfNaclSecretBox} params
* @returns ResultOfNaclBox
*/
nacl_secret_box(params: ParamsOfNaclSecretBox): Promise<ResultOfNaclBox> {
return this.client.request('crypto.nacl_secret_box', params);
}
/**
* Decrypts and verifies cipher text using `nonce` and secret `key`.
*
* @param {ParamsOfNaclSecretBoxOpen} params
* @returns ResultOfNaclBoxOpen
*/
nacl_secret_box_open(params: ParamsOfNaclSecretBoxOpen): Promise<ResultOfNaclBoxOpen> {
return this.client.request('crypto.nacl_secret_box_open', params);
}
/**
* Prints the list of words from the specified dictionary
*
* @param {ParamsOfMnemonicWords} params
* @returns ResultOfMnemonicWords
*/
mnemonic_words(params: ParamsOfMnemonicWords): Promise<ResultOfMnemonicWords> {
return this.client.request('crypto.mnemonic_words', params);
}
/**
* Generates a random mnemonic
*
* @remarks
* Generates a random mnemonic from the specified dictionary and word count
*
* @param {ParamsOfMnemonicFromRandom} params
* @returns ResultOfMnemonicFromRandom
*/
mnemonic_from_random(params: ParamsOfMnemonicFromRandom): Promise<ResultOfMnemonicFromRandom> {
return this.client.request('crypto.mnemonic_from_random', params);
}
/**
* Generates mnemonic from pre-generated entropy
*
* @param {ParamsOfMnemonicFromEntropy} params
* @returns ResultOfMnemonicFromEntropy
*/
mnemonic_from_entropy(params: ParamsOfMnemonicFromEntropy): Promise<ResultOfMnemonicFromEntropy> {
return this.client.request('crypto.mnemonic_from_entropy', params);
}
/**
* Validates a mnemonic phrase
*
* @remarks
* The phrase supplied will be checked for word length and validated according to the checksum
* specified in BIP0039.
*
* @param {ParamsOfMnemonicVerify} params
* @returns ResultOfMnemonicVerify
*/
mnemonic_verify(params: ParamsOfMnemonicVerify): Promise<ResultOfMnemonicVerify> {
return this.client.request('crypto.mnemonic_verify', params);
}
/**
* Derives a key pair for signing from the seed phrase
*
* @remarks
* Validates the seed phrase, generates master key and then derives
* the key pair from the master key and the specified path
*
* @param {ParamsOfMnemonicDeriveSignKeys} params
* @returns KeyPair
*/
mnemonic_derive_sign_keys(params: ParamsOfMnemonicDeriveSignKeys): Promise<KeyPair> {
return this.client.request('crypto.mnemonic_derive_sign_keys', params);
}
/**
* Generates an extended master private key that will be the root for all the derived keys
*
* @param {ParamsOfHDKeyXPrvFromMnemonic} params
* @returns ResultOfHDKeyXPrvFromMnemonic
*/
hdkey_xprv_from_mnemonic(params: ParamsOfHDKeyXPrvFromMnemonic): Promise<ResultOfHDKeyXPrvFromMnemonic> {
return this.client.request('crypto.hdkey_xprv_from_mnemonic', params);
}
/**
* Returns extended private key derived from the specified extended private key and child index
*
* @param {ParamsOfHDKeyDeriveFromXPrv} params
* @returns ResultOfHDKeyDeriveFromXPrv
*/
hdkey_derive_from_xprv(params: ParamsOfHDKeyDeriveFromXPrv): Promise<ResultOfHDKeyDeriveFromXPrv> {
return this.client.request('crypto.hdkey_derive_from_xprv', params);
}
/**
* Derives the extended private key from the specified key and path
*
* @param {ParamsOfHDKeyDeriveFromXPrvPath} params
* @returns ResultOfHDKeyDeriveFromXPrvPath
*/
hdkey_derive_from_xprv_path(params: ParamsOfHDKeyDeriveFromXPrvPath): Promise<ResultOfHDKeyDeriveFromXPrvPath> {
return this.client.request('crypto.hdkey_derive_from_xprv_path', params);
}
/**
* Extracts the private key from the serialized extended private key
*
* @param {ParamsOfHDKeySecretFromXPrv} params
* @returns ResultOfHDKeySecretFromXPrv
*/
hdkey_secret_from_xprv(params: ParamsOfHDKeySecretFromXPrv): Promise<ResultOfHDKeySecretFromXPrv> {
return this.client.request('crypto.hdkey_secret_from_xprv', params);
}
/**
* Extracts the public key from the serialized extended private key
*
* @param {ParamsOfHDKeyPublicFromXPrv} params
* @returns ResultOfHDKeyPublicFromXPrv
*/
hdkey_public_from_xprv(params: ParamsOfHDKeyPublicFromXPrv): Promise<ResultOfHDKeyPublicFromXPrv> {
return this.client.request('crypto.hdkey_public_from_xprv', params);
}
/**
* Performs symmetric `chacha20` encryption.
*
* @param {ParamsOfChaCha20} params
* @returns ResultOfChaCha20
*/
chacha20(params: ParamsOfChaCha20): Promise<ResultOfChaCha20> {
return this.client.request('crypto.chacha20', params);
}
/**
* Register an application implemented signing box.
* @returns RegisteredSigningBox
*/
register_signing_box(obj: AppSigningBox): Promise<RegisteredSigningBox> {
return this.client.request('crypto.register_signing_box', undefined, (params: any, responseType: number) => {
if (responseType === 3) {
dispatchAppSigningBox(obj, params.request_data, params.app_request_id, this.client);
} else if (responseType === 4) {
dispatchAppSigningBox(obj, params, null, this.client);
}
});
}
/**
* Creates a default signing box implementation.
*
* @param {KeyPair} params
* @returns RegisteredSigningBox
*/
get_signing_box(params: KeyPair): Promise<RegisteredSigningBox> {
return this.client.request('crypto.get_signing_box', params);
}
/**
* Returns public key of signing key pair.
*
* @param {RegisteredSigningBox} params
* @returns ResultOfSigningBoxGetPublicKey
*/
signing_box_get_public_key(params: RegisteredSigningBox): Promise<ResultOfSigningBoxGetPublicKey> {
return this.client.request('crypto.signing_box_get_public_key', params);
}
/**
* Returns signed user data.
*
* @param {ParamsOfSigningBoxSign} params
* @returns ResultOfSigningBoxSign
*/
signing_box_sign(params: ParamsOfSigningBoxSign): Promise<ResultOfSigningBoxSign> {
return this.client.request('crypto.signing_box_sign', params);
}
/**
* Removes signing box from SDK.
*
* @param {RegisteredSigningBox} params
* @returns
*/
remove_signing_box(params: RegisteredSigningBox): Promise<void> {
return this.client.request('crypto.remove_signing_box', params);
}
/**
* Register an application implemented encryption box.
* @returns RegisteredEncryptionBox
*/
register_encryption_box(obj: AppEncryptionBox): Promise<RegisteredEncryptionBox> {
return this.client.request('crypto.register_encryption_box', undefined, (params: any, responseType: number) => {
if (responseType === 3) {
dispatchAppEncryptionBox(obj, params.request_data, params.app_request_id, this.client);
} else if (responseType === 4) {
dispatchAppEncryptionBox(obj, params, null, this.client);
}
});
}
/**
* Removes encryption box from SDK
*
* @param {RegisteredEncryptionBox} params
* @returns
*/
remove_encryption_box(params: RegisteredEncryptionBox): Promise<void> {
return this.client.request('crypto.remove_encryption_box', params);
}
/**
* Queries info from the given encryption box
*
* @param {ParamsOfEncryptionBoxGetInfo} params
* @returns ResultOfEncryptionBoxGetInfo
*/
encryption_box_get_info(params: ParamsOfEncryptionBoxGetInfo): Promise<ResultOfEncryptionBoxGetInfo> {
return this.client.request('crypto.encryption_box_get_info', params);
}
/**
* Encrypts data using given encryption box Note.
*
* @remarks
* Block cipher algorithms pad data to cipher block size so encrypted data can be longer then original data. Client should store the original data size after encryption and use it after
* decryption to retrieve the original data from decrypted data.
*
* @param {ParamsOfEncryptionBoxEncrypt} params
* @returns ResultOfEncryptionBoxEncrypt
*/
encryption_box_encrypt(params: ParamsOfEncryptionBoxEncrypt): Promise<ResultOfEncryptionBoxEncrypt> {
return this.client.request('crypto.encryption_box_encrypt', params);
}
/**
* Decrypts data using given encryption box Note.
*
* @remarks
* Block cipher algorithms pad data to cipher block size so encrypted data can be longer then original data. Client should store the original data size after encryption and use it after
* decryption to retrieve the original data from decrypted data.
*
* @param {ParamsOfEncryptionBoxDecrypt} params
* @returns ResultOfEncryptionBoxDecrypt
*/
encryption_box_decrypt(params: ParamsOfEncryptionBoxDecrypt): Promise<ResultOfEncryptionBoxDecrypt> {
return this.client.request('crypto.encryption_box_decrypt', params);
}
/**
* Creates encryption box with specified algorithm
*
* @param {ParamsOfCreateEncryptionBox} params
* @returns RegisteredEncryptionBox
*/
create_encryption_box(params: ParamsOfCreateEncryptionBox): Promise<RegisteredEncryptionBox> {
return this.client.request('crypto.create_encryption_box', params);
}
}
// abi module
export enum AbiErrorCode {
RequiredAddressMissingForEncodeMessage = 301,
RequiredCallSetMissingForEncodeMessage = 302,
InvalidJson = 303,
InvalidMessage = 304,
EncodeDeployMessageFailed = 305,
EncodeRunMessageFailed = 306,
AttachSignatureFailed = 307,
InvalidTvcImage = 308,
RequiredPublicKeyMissingForFunctionHeader = 309,
InvalidSigner = 310,
InvalidAbi = 311,
InvalidFunctionId = 312,
InvalidData = 313,
EncodeInitialDataFailed = 314
}
export type Abi = {
type: 'Contract'
/**
*/
value: AbiContract
} | {
type: 'Json'
/**
*/
value: string
} | {
type: 'Handle'
/**
*/
value: AbiHandle
} | {
type: 'Serialized'
/**
*/
value: AbiContract
}
export function abiContract(value: AbiContract): Abi {
return {
type: 'Contract',
value,
};
}
export function abiJson(value: string): Abi {
return {
type: 'Json',
value,
};
}
export function abiHandle(value: AbiHandle): Abi {
return {
type: 'Handle',
value,
};
}
export function abiSerialized(value: AbiContract): Abi {
return {
type: 'Serialized',
value,
};
}
export type AbiHandle = number
export type FunctionHeader = {
/**
* Message expiration time in seconds. If not specified - calculated automatically from message_expiration_timeout(), try_index and message_expiration_timeout_grow_factor() (if ABI includes `expire` header).
*/
expire?: number,
/**
* Message creation time in milliseconds.
*
* @remarks
* If not specified, `now` is used (if ABI includes `time` header).
*/
time?: bigint,
/**
* Public key is used by the contract to check the signature.
*
* @remarks
* Encoded in `hex`. If not specified, method fails with exception (if ABI includes `pubkey` header)..
*/
pubkey?: string
}
export type CallSet = {
/**
* Function name that is being called. Or function id encoded as string in hex (starting with 0x).
*/
function_name: string,
/**
* Function header.
*
* @remarks
* If an application omits some header parameters required by the
* contract's ABI, the library will set the default values for
* them.
*/
header?: FunctionHeader,
/**
* Function input parameters according to ABI.
*/
input?: any
}
export type DeploySet = {
/**
* Content of TVC file encoded in `base64`.
*/
tvc: string,
/**
* Target workchain for destination address.
*
* @remarks
* Default is `0`.
*/
workchain_id?: number,
/**
* List of initial values for contract's public variables.
*/
initial_data?: any,
/**
* Optional public key that can be provided in deploy set in order to substitute one in TVM file or provided by Signer.
*
* @remarks
* Public key resolving priority:
* 1. Public key from deploy set.
* 2. Public key, specified in TVM file.
* 3. Public key, provided by Signer.
*/
initial_pubkey?: string
}
export type Signer = {
type: 'None'
} | {
type: 'External'
/**
*/
public_key: string
} | {
type: 'Keys'
/**
*/
keys: KeyPair
} | {
type: 'SigningBox'
/**
*/
handle: SigningBoxHandle
}
export function signerNone(): Signer {
return {
type: 'None',
};
}
export function signerExternal(public_key: string): Signer {
return {
type: 'External',
public_key,
};
}
export function signerKeys(keys: KeyPair): Signer {
return {
type: 'Keys',
keys,
};
}
export function signerSigningBox(handle: SigningBoxHandle): Signer {
return {
type: 'SigningBox',
handle,
};
}
export enum MessageBodyType {
Input = "Input",
Output = "Output",
InternalOutput = "InternalOutput",
Event = "Event"
}
export type StateInitSource = {
type: 'Message'
/**
*/
source: MessageSource
} | {
type: 'StateInit'
/**
* Code BOC.
*
* @remarks
* Encoded in `base64`.
*/
code: string,
/**
* Data BOC.
*
* @remarks
* Encoded in `base64`.
*/
data: string,
/**
* Library BOC.
*
* @remarks
* Encoded in `base64`.
*/
library?: string
} | {
type: 'Tvc'
/**
*/
tvc: string,
/**
*/
public_key?: string,
/**
*/
init_params?: StateInitParams
}
export function stateInitSourceMessage(source: MessageSource): StateInitSource {
return {
type: 'Message',
source,
};
}
export function stateInitSourceStateInit(code: string, data: string, library?: string): StateInitSource {
return {
type: 'StateInit',
code,
data,
library,
};
}
export function stateInitSourceTvc(tvc: string, public_key?: string, init_params?: StateInitParams): StateInitSource {
return {
type: 'Tvc',
tvc,
public_key,
init_params,
};
}
export type StateInitParams = {
/**
*/
abi: Abi,
/**
*/
value: any
}
export type MessageSource = {
type: 'Encoded'
/**
*/
message: string,
/**
*/
abi?: Abi
} | ({
type: 'EncodingParams'
} & ParamsOfEncodeMessage)
export function messageSourceEncoded(message: string, abi?: Abi): MessageSource {
return {
type: 'Encoded',
message,
abi,
};
}
export function messageSourceEncodingParams(params: ParamsOfEncodeMessage): MessageSource {
return {
type: 'EncodingParams',
...params,
};
}
export type AbiParam = {
/**
*/
name: string,
/**
*/
type: string,
/**
*/
components?: AbiParam[]
}
export type AbiEvent = {
/**
*/
name: string,
/**
*/
inputs: AbiParam[],
/**
*/
id?: string | null
}
export type AbiData = {
/**
*/
key: number,
/**
*/
name: string,
/**
*/
type: string,
/**
*/
components?: AbiParam[]
}
export type AbiFunction = {
/**
*/
name: string,
/**
*/
inputs: AbiParam[],
/**
*/
outputs: AbiParam[],
/**
*/
id?: string | null
}
export type AbiContract = {
/**
*/
'ABI version'?: number,
/**
*/
abi_version?: number,
/**
*/
version?: string | null,
/**
*/
header?: string[],
/**
*/
functions?: AbiFunction[],
/**
*/
events?: AbiEvent[],
/**
*/
data?: AbiData[],
/**
*/
fields?: AbiParam[]
}
export type ParamsOfEncodeMessageBody = {
/**
* Contract ABI.
*/
abi: Abi,
/**
* Function call parameters.
*
* @remarks
* Must be specified in non deploy message.
*
* In case of deploy message contains parameters of constructor.
*/
call_set: CallSet,
/**
* True if internal message body must be encoded.
*/
is_internal: boolean,
/**
* Signing parameters.
*/
signer: Signer,
/**
* Processing try index.
*
* @remarks
* Used in message processing with retries.
*
* Encoder uses the provided try index to calculate message
* expiration time.
*
* Expiration timeouts will grow with every retry.
*
* Default value is 0.
*/
processing_try_index?: number
}
export type ResultOfEncodeMessageBody = {
/**
* Message body BOC encoded with `base64`.
*/
body: string,
/**
* Optional data to sign.
*
* @remarks
* Encoded with `base64`.
* Presents when `message` is unsigned. Can be used for external
* message signing. Is this case you need to sing this data and
* produce signed message using `abi.attach_signature`.
*/
data_to_sign?: string
}
export type ParamsOfAttachSignatureToMessageBody = {
/**
* Contract ABI
*/
abi: Abi,
/**
* Public key.
*
* @remarks
* Must be encoded with `hex`.
*/
public_key: string,
/**
* Unsigned message body BOC.
*
* @remarks
* Must be encoded with `base64`.
*/
message: string,
/**
* Signature.
*
* @remarks
* Must be encoded with `hex`.
*/
signature: string
}
export type ResultOfAttachSignatureToMessageBody = {
/**
*/
body: string
}
export type ParamsOfEncodeMessage = {
/**
* Contract ABI.
*/
abi: Abi,
/**
* Target address the message will be sent to.
*
* @remarks
* Must be specified in case of non-deploy message.
*/
address?: string,
/**
* Deploy parameters.
*
* @remarks
* Must be specified in case of deploy message.
*/
deploy_set?: DeploySet,
/**
* Function call parameters.
*
* @remarks
* Must be specified in case of non-deploy message.
*
* In case of deploy message it is optional and contains parameters
* of the functions that will to be called upon deploy transaction.
*/
call_set?: CallSet,
/**
* Signing parameters.
*/
signer: Signer,
/**
* Processing try index.
*
* @remarks
* Used in message processing with retries (if contract's ABI includes "expire" header).
*
* Encoder uses the provided try index to calculate message
* expiration time. The 1st message expiration time is specified in
* Client config.
*
* Expiration timeouts will grow with every retry.
* Retry grow factor is set in Client config:
* <.....add config parameter with default value here>
*
* Default value is 0.
*/
processing_try_index?: number
}
export type ResultOfEncodeMessage = {
/**
* Message BOC encoded with `base64`.
*/
message: string,
/**
* Optional data to be signed encoded in `base64`.
*
* @remarks
* Returned in case of `Signer::External`. Can be used for external
* message signing. Is this case you need to use this data to create signature and
* then produce signed message using `abi.attach_signature`.
*/
data_to_sign?: string,
/**
* Destination address.
*/
address: string,
/**
* Message id.
*/
message_id: string
}
export type ParamsOfEncodeInternalMessage = {
/**
* Contract ABI.
*
* @remarks
* Can be None if both deploy_set and call_set are None.
*/
abi?: Abi,
/**
* Target address the message will be sent to.
*
* @remarks
* Must be specified in case of non-deploy message.
*/
address?: string,
/**
* Source address of the message.
*/
src_address?: string,
/**
* Deploy parameters.
*
* @remarks
* Must be specified in case of deploy message.
*/
deploy_set?: DeploySet,
/**
* Function call parameters.
*
* @remarks
* Must be specified in case of non-deploy message.
*
* In case of deploy message it is optional and contains parameters
* of the functions that will to be called upon deploy transaction.
*/
call_set?: CallSet,
/**
* Value in nanotokens to be sent with message.
*/
value: string,
/**
* Flag of bounceable message.
*
* @remarks
* Default is true.
*/
bounce?: boolean,
/**
* Enable Instant Hypercube Routing for the message.
*
* @remarks
* Default is false.
*/
enable_ihr?: boolean
}
export type ResultOfEncodeInternalMessage = {
/**
* Message BOC encoded with `base64`.
*/
message: string,
/**
* Destination address.
*/
address: string,
/**
* Message id.
*/
message_id: string
}
export type ParamsOfAttachSignature = {
/**
* Contract ABI
*/
abi: Abi,
/**
* Public key encoded in `hex`.
*/
public_key: string,
/**
* Unsigned message BOC encoded in `base64`.
*/
message: string,
/**
* Signature encoded in `hex`.
*/
signature: string
}
export type ResultOfAttachSignature = {
/**
* Signed message BOC
*/
message: string,
/**
* Message ID
*/
message_id: string
}
export type ParamsOfDecodeMessage = {
/**
* contract ABI
*/
abi: Abi,
/**
* Message BOC
*/
message: string
}
export type DecodedMessageBody = {
/**
* Type of the message body content.
*/
body_type: MessageBodyType,
/**
* Function or event name.
*/
name: string,
/**
* Parameters or result value.
*/
value?: any,
/**
* Function header.
*/
header?: FunctionHeader
}
export type ParamsOfDecodeMessageBody = {
/**
* Contract ABI used to decode.
*/
abi: Abi,
/**
* Message body BOC encoded in `base64`.
*/
body: string,
/**
* True if the body belongs to the internal message.
*/
is_internal: boolean
}
export type ParamsOfEncodeAccount = {
/**
* Source of the account state init.
*/
state_init: StateInitSource,
/**
* Initial balance.
*/
balance?: bigint,
/**
* Initial value for the `last_trans_lt`.
*/
last_trans_lt?: bigint,
/**
* Initial value for the `last_paid`.
*/
last_paid?: number,
/**
* Cache type to put the result.
*
* @remarks
* The BOC itself returned if no cache type provided
*/
boc_cache?: BocCacheType
}
export type ResultOfEncodeAccount = {
/**
* Account BOC encoded in `base64`.
*/
account: string,
/**
* Account ID encoded in `hex`.
*/
id: string
}
export type ParamsOfDecodeAccountData = {
/**
* Contract ABI
*/
abi: Abi,
/**
* Data BOC or BOC handle
*/
data: string
}
export type ResultOfDecodeData = {
/**
* Decoded data as a JSON structure.
*/
data: any
}
export type ParamsOfUpdateInitialData = {
/**
* Contract ABI
*/
abi?: Abi,
/**
* Data BOC or BOC handle
*/
data: string,
/**
* List of initial values for contract's static variables.
*
* @remarks
* `abi` parameter should be provided to set initial data
*/
initial_data?: any,
/**
* Initial account owner's public key to set into account data
*/
initial_pubkey?: string,
/**
* Cache type to put the result. The BOC itself returned if no cache type provided.
*/
boc_cache?: BocCacheType
}
export type ResultOfUpdateInitialData = {
/**
* Updated data BOC or BOC handle
*/
data: string
}
export type ParamsOfDecodeInitialData = {
/**
* Contract ABI.
*
* @remarks
* Initial data is decoded if this parameter is provided
*/
abi?: Abi,
/**
* Data BOC or BOC handle
*/
data: string
}
export type ResultOfDecodeInitialData = {
/**
* List of initial values of contract's public variables.
*
* @remarks
* Initial data is decoded if `abi` input parameter is provided
*/
initial_data?: any,
/**
* Initial account owner's public key
*/
initial_pubkey: string
}
/**
* Provides message encoding and decoding according to the ABI specification.
*/
export class AbiModule {
client: IClient;
constructor(client: IClient) {
this.client = client;
}
/**
* Encodes message body according to ABI function call.
*
* @param {ParamsOfEncodeMessageBody} params
* @returns ResultOfEncodeMessageBody
*/
encode_message_body(params: ParamsOfEncodeMessageBody): Promise<ResultOfEncodeMessageBody> {
return this.client.request('abi.encode_message_body', params);
}
/**
*
* @param {ParamsOfAttachSignatureToMessageBody} params
* @returns ResultOfAttachSignatureToMessageBody
*/
attach_signature_to_message_body(params: ParamsOfAttachSignatureToMessageBody): Promise<ResultOfAttachSignatureToMessageBody> {
return this.client.request('abi.attach_signature_to_message_body', params);
}
/**
* Encodes an ABI-compatible message
*
* @remarks
* Allows to encode deploy and function call messages,
* both signed and unsigned.
*
* Use cases include messages of any possible type:
* - deploy with initial function call (i.e. `constructor` or any other function that is used for some kind
* of initialization);
* - deploy without initial function call;
* - signed/unsigned + data for signing.
*
* `Signer` defines how the message should or shouldn't be signed:
*
* `Signer::None` creates an unsigned message. This may be needed in case of some public methods,
* that do not require authorization by pubkey.
*
* `Signer::External` takes public key and returns `data_to_sign` for later signing.
* Use `attach_signature` method with the result signature to get the signed message.
*
* `Signer::Keys` creates a signed message with provided key pair.
*
* [SOON] `Signer::SigningBox` Allows using a special interface to implement signing
* without private key disclosure to SDK. For instance, in case of using a cold wallet or HSM,
* when application calls some API to sign data.
*
* There is an optional public key can be provided in deploy set in order to substitute one
* in TVM file.
*
* Public key resolving priority:
* 1. Public key from deploy set.
* 2. Public key, specified in TVM file.
* 3. Public key, provided by signer.
*
* @param {ParamsOfEncodeMessage} params
* @returns ResultOfEncodeMessage
*/
encode_message(params: ParamsOfEncodeMessage): Promise<ResultOfEncodeMessage> {
return this.client.request('abi.encode_message', params);
}
/**
* Encodes an internal ABI-compatible message
*
* @remarks
* Allows to encode deploy and function call messages.
*
* Use cases include messages of any possible type:
* - deploy with initial function call (i.e. `constructor` or any other function that is used for some kind
* of initialization);
* - deploy without initial function call;
* - simple function call
*
* There is an optional public key can be provided in deploy set in order to substitute one
* in TVM file.
*
* Public key resolving priority:
* 1. Public key from deploy set.
* 2. Public key, specified in TVM file.
*
* @param {ParamsOfEncodeInternalMessage} params
* @returns ResultOfEncodeInternalMessage
*/
encode_internal_message(params: ParamsOfEncodeInternalMessage): Promise<ResultOfEncodeInternalMessage> {
return this.client.request('abi.encode_internal_message', params);
}
/**
* Combines `hex`-encoded `signature` with `base64`-encoded `unsigned_message`. Returns signed message encoded in `base64`.
*
* @param {ParamsOfAttachSignature} params
* @returns ResultOfAttachSignature
*/
attach_signature(params: ParamsOfAttachSignature): Promise<ResultOfAttachSignature> {
return this.client.request('abi.attach_signature', params);
}
/**
* Decodes message body using provided message BOC and ABI.
*
* @param {ParamsOfDecodeMessage} params
* @returns DecodedMessageBody
*/
decode_message(params: ParamsOfDecodeMessage): Promise<DecodedMessageBody> {
return this.client.request('abi.decode_message', params);
}
/**
* Decodes message body using provided body BOC and ABI.
*
* @param {ParamsOfDecodeMessageBody} params
* @returns DecodedMessageBody
*/
decode_message_body(params: ParamsOfDecodeMessageBody): Promise<DecodedMessageBody> {
return this.client.request('abi.decode_message_body', params);
}
/**
* Creates account state BOC
*
* @remarks
* Creates account state provided with one of these sets of data :
* 1. BOC of code, BOC of data, BOC of library
* 2. TVC (string in `base64`), keys, init params
*
* @param {ParamsOfEncodeAccount} params
* @returns ResultOfEncodeAccount
*/
encode_account(params: ParamsOfEncodeAccount): Promise<ResultOfEncodeAccount> {
return this.client.request('abi.encode_account', params);
}
/**
* Decodes account data using provided data BOC and ABI.
*
* @remarks
* Note: this feature requires ABI 2.1 or higher.
*
* @param {ParamsOfDecodeAccountData} params
* @returns ResultOfDecodeData
*/
decode_account_data(params: ParamsOfDecodeAccountData): Promise<ResultOfDecodeData> {
return this.client.request('abi.decode_account_data', params);
}
/**
* Updates initial account data with initial values for the contract's static variables and owner's public key. This operation is applicable only for initial account data (before deploy). If the contract is already deployed, its data doesn't contain this data section any more.
*
* @param {ParamsOfUpdateInitialData} params
* @returns ResultOfUpdateInitialData
*/
update_initial_data(params: ParamsOfUpdateInitialData): Promise<ResultOfUpdateInitialData> {
return this.client.request('abi.update_initial_data', params);
}
/**
* Decodes initial values of a contract's static variables and owner's public key from account initial data This operation is applicable only for initial account data (before deploy). If the contract is already deployed, its data doesn't contain this data section any more.
*
* @param {ParamsOfDecodeInitialData} params
* @returns ResultOfDecodeInitialData
*/
decode_initial_data(params: ParamsOfDecodeInitialData): Promise<ResultOfDecodeInitialData> {
return this.client.request('abi.decode_initial_data', params);
}
}
// boc module
export type BocCacheType = {
type: 'Pinned'
/**
*/
pin: string
} | {
type: 'Unpinned'
}
export function bocCacheTypePinned(pin: string): BocCacheType {
return {
type: 'Pinned',
pin,
};
}
export function bocCacheTypeUnpinned(): BocCacheType {
return {
type: 'Unpinned',
};
}
export enum BocErrorCode {
InvalidBoc = 201,
SerializationError = 202,
InappropriateBlock = 203,
MissingSourceBoc = 204,
InsufficientCacheSize = 205,
BocRefNotFound = 206,
InvalidBocRef = 207
}
export type ParamsOfParse = {
/**
* BOC encoded as base64
*/
boc: string
}
export type ResultOfParse = {
/**
* JSON containing parsed BOC
*/
parsed: any
}
export type ParamsOfParseShardstate = {
/**
* BOC encoded as base64
*/
boc: string,
/**
* Shardstate identificator
*/
id: string,
/**
* Workchain shardstate belongs to
*/
workchain_id: number
}
export type ParamsOfGetBlockchainConfig = {
/**
* Key block BOC or zerostate BOC encoded as base64
*/
block_boc: string
}
export type ResultOfGetBlockchainConfig = {
/**
* Blockchain config BOC encoded as base64
*/
config_boc: string
}
export type ParamsOfGetBocHash = {
/**
* BOC encoded as base64 or BOC handle
*/
boc: string
}
export type ResultOfGetBocHash = {
/**
* BOC root hash encoded with hex
*/
hash: string
}
export type ParamsOfGetBocDepth = {
/**
* BOC encoded as base64 or BOC handle
*/
boc: string
}
export type ResultOfGetBocDepth = {
/**
* BOC root cell depth
*/
depth: number
}
export type ParamsOfGetCodeFromTvc = {
/**
* Contract TVC image or image BOC handle
*/
tvc: string
}
export type ResultOfGetCodeFromTvc = {
/**
* Contract code encoded as base64
*/
code: string
}
export type ParamsOfBocCacheGet = {
/**
* Reference to the cached BOC
*/
boc_ref: string
}
export type ResultOfBocCacheGet = {
/**
* BOC encoded as base64.
*/
boc?: string
}
export type ParamsOfBocCacheSet = {
/**
* BOC encoded as base64 or BOC reference
*/
boc: string,
/**
* Cache type
*/
cache_type: BocCacheType
}
export type ResultOfBocCacheSet = {
/**
* Reference to the cached BOC
*/
boc_ref: string
}
export type ParamsOfBocCacheUnpin = {
/**
* Pinned name
*/
pin: string,
/**
* Reference to the cached BOC.
*
* @remarks
* If it is provided then only referenced BOC is unpinned
*/
boc_ref?: string
}
export type BuilderOp = {
type: 'Integer'
/**
* Bit size of the value.
*/
size: number,
/**
* Value: - `Number` containing integer number.
*
* @remarks
* e.g. `123`, `-123`. - Decimal string. e.g. `"123"`, `"-123"`.
* - `0x` prefixed hexadecimal string.
* e.g `0x123`, `0X123`, `-0x123`.
*/
value: any
} | {
type: 'BitString'
/**
* Bit string content using bitstring notation. See `TON VM specification` 1.0.
*
* @remarks
* Contains hexadecimal string representation:
* - Can end with `_` tag.
* - Can be prefixed with `x` or `X`.
* - Can be prefixed with `x{` or `X{` and ended with `}`.
*
* Contains binary string represented as a sequence
* of `0` and `1` prefixed with `n` or `N`.
*
* Examples:
* `1AB`, `x1ab`, `X1AB`, `x{1abc}`, `X{1ABC}`
* `2D9_`, `x2D9_`, `X2D9_`, `x{2D9_}`, `X{2D9_}`
* `n00101101100`, `N00101101100`
*/
value: string
} | {
type: 'Cell'
/**
* Nested cell builder
*/
builder: BuilderOp[]
} | {
type: 'CellBoc'
/**
* Nested cell BOC encoded with `base64` or BOC cache key.
*/
boc: string
}
export function builderOpInteger(size: number, value: any): BuilderOp {
return {
type: 'Integer',
size,
value,
};
}
export function builderOpBitString(value: string): BuilderOp {
return {
type: 'BitString',
value,
};
}
export function builderOpCell(builder: BuilderOp[]): BuilderOp {
return {
type: 'Cell',
builder,
};
}
export function builderOpCellBoc(boc: string): BuilderOp {
return {
type: 'CellBoc',
boc,
};
}
export type ParamsOfEncodeBoc = {
/**
* Cell builder operations.
*/
builder: BuilderOp[],
/**
* Cache type to put the result. The BOC itself returned if no cache type provided.
*/
boc_cache?: BocCacheType
}
export type ResultOfEncodeBoc = {
/**
* Encoded cell BOC or BOC cache key.
*/
boc: string
}
export type ParamsOfGetCodeSalt = {
/**
* Contract code BOC encoded as base64 or code BOC handle
*/
code: string,
/**
* Cache type to put the result. The BOC itself returned if no cache type provided.
*/
boc_cache?: BocCacheType
}
export type ResultOfGetCodeSalt = {
/**
* Contract code salt if present.
*
* @remarks
* BOC encoded as base64 or BOC handle
*/
salt?: string
}
export type ParamsOfSetCodeSalt = {
/**
* Contract code BOC encoded as base64 or code BOC handle
*/
code: string,
/**
* Code salt to set.
*
* @remarks
* BOC encoded as base64 or BOC handle
*/
salt: string,
/**
* Cache type to put the result. The BOC itself returned if no cache type provided.
*/
boc_cache?: BocCacheType
}
export type ResultOfSetCodeSalt = {
/**
* Contract code with salt set.
*
* @remarks
* BOC encoded as base64 or BOC handle
*/
code: string
}
export type ParamsOfDecodeTvc = {
/**
* Contract TVC image BOC encoded as base64 or BOC handle
*/
tvc: string,
/**
* Cache type to put the result. The BOC itself returned if no cache type provided.
*/
boc_cache?: BocCacheType
}
export type ResultOfDecodeTvc = {
/**
* Contract code BOC encoded as base64 or BOC handle
*/
code?: string,
/**
* Contract code hash
*/
code_hash?: string,
/**
* Contract code depth
*/
code_depth?: number,
/**
* Contract data BOC encoded as base64 or BOC handle
*/
data?: string,
/**
* Contract data hash
*/
data_hash?: string,
/**
* Contract data depth
*/
data_depth?: number,
/**
* Contract library BOC encoded as base64 or BOC handle
*/
library?: string,
/**
* `special.tick` field.
*
* @remarks
* Specifies the contract ability to handle tick transactions
*/
tick?: boolean,
/**
* `special.tock` field.
*
* @remarks
* Specifies the contract ability to handle tock transactions
*/
tock?: boolean,
/**
* Is present and non-zero only in instances of large smart contracts
*/
split_depth?: number,
/**
* Compiler version, for example 'sol 0.49.0'
*/
compiler_version?: string
}
export type ParamsOfEncodeTvc = {
/**
* Contract code BOC encoded as base64 or BOC handle
*/
code?: string,
/**
* Contract data BOC encoded as base64 or BOC handle
*/
data?: string,
/**
* Contract library BOC encoded as base64 or BOC handle
*/
library?: string,
/**
* `special.tick` field.
*
* @remarks
* Specifies the contract ability to handle tick transactions
*/
tick?: boolean,
/**
* `special.tock` field.
*
* @remarks
* Specifies the contract ability to handle tock transactions
*/
tock?: boolean,
/**
* Is present and non-zero only in instances of large smart contracts
*/
split_depth?: number,
/**
* Cache type to put the result. The BOC itself returned if no cache type provided.
*/
boc_cache?: BocCacheType
}
export type ResultOfEncodeTvc = {
/**
* Contract TVC image BOC encoded as base64 or BOC handle of boc_cache parameter was specified
*/
tvc: string
}
export type ParamsOfGetCompilerVersion = {
/**
* Contract code BOC encoded as base64 or code BOC handle
*/
code: string
}
export type ResultOfGetCompilerVersion = {
/**
* Compiler version, for example 'sol 0.49.0'
*/
version?: string
}
/**
* BOC manipulation module.
*/
export class BocModule {
client: IClient;
constructor(client: IClient) {
this.client = client;
}
/**
* Parses message boc into a JSON
*
* @remarks
* JSON structure is compatible with GraphQL API message object
*
* @param {ParamsOfParse} params
* @returns ResultOfParse
*/
parse_message(params: ParamsOfParse): Promise<ResultOfParse> {
return this.client.request('boc.parse_message', params);
}
/**
* Parses transaction boc into a JSON
*
* @remarks
* JSON structure is compatible with GraphQL API transaction object
*
* @param {ParamsOfParse} params
* @returns ResultOfParse
*/
parse_transaction(params: ParamsOfParse): Promise<ResultOfParse> {
return this.client.request('boc.parse_transaction', params);
}
/**
* Parses account boc into a JSON
*
* @remarks
* JSON structure is compatible with GraphQL API account object
*
* @param {ParamsOfParse} params
* @returns ResultOfParse
*/
parse_account(params: ParamsOfParse): Promise<ResultOfParse> {
return this.client.request('boc.parse_account', params);
}
/**
* Parses block boc into a JSON
*
* @remarks
* JSON structure is compatible with GraphQL API block object
*
* @param {ParamsOfParse} params
* @returns ResultOfParse
*/
parse_block(params: ParamsOfParse): Promise<ResultOfParse> {
return this.client.request('boc.parse_block', params);
}
/**
* Parses shardstate boc into a JSON
*
* @remarks
* JSON structure is compatible with GraphQL API shardstate object
*
* @param {ParamsOfParseShardstate} params
* @returns ResultOfParse
*/
parse_shardstate(params: ParamsOfParseShardstate): Promise<ResultOfParse> {
return this.client.request('boc.parse_shardstate', params);
}
/**
* Extract blockchain configuration from key block and also from zerostate.
*
* @param {ParamsOfGetBlockchainConfig} params
* @returns ResultOfGetBlockchainConfig
*/
get_blockchain_config(params: ParamsOfGetBlockchainConfig): Promise<ResultOfGetBlockchainConfig> {
return this.client.request('boc.get_blockchain_config', params);
}
/**
* Calculates BOC root hash
*
* @param {ParamsOfGetBocHash} params
* @returns ResultOfGetBocHash
*/
get_boc_hash(params: ParamsOfGetBocHash): Promise<ResultOfGetBocHash> {
return this.client.request('boc.get_boc_hash', params);
}
/**
* Calculates BOC depth
*
* @param {ParamsOfGetBocDepth} params
* @returns ResultOfGetBocDepth
*/
get_boc_depth(params: ParamsOfGetBocDepth): Promise<ResultOfGetBocDepth> {
return this.client.request('boc.get_boc_depth', params);
}
/**
* Extracts code from TVC contract image
*
* @param {ParamsOfGetCodeFromTvc} params
* @returns ResultOfGetCodeFromTvc
*/
get_code_from_tvc(params: ParamsOfGetCodeFromTvc): Promise<ResultOfGetCodeFromTvc> {
return this.client.request('boc.get_code_from_tvc', params);
}
/**
* Get BOC from cache
*
* @param {ParamsOfBocCacheGet} params
* @returns ResultOfBocCacheGet
*/
cache_get(params: ParamsOfBocCacheGet): Promise<ResultOfBocCacheGet> {
return this.client.request('boc.cache_get', params);
}
/**
* Save BOC into cache
*
* @param {ParamsOfBocCacheSet} params
* @returns ResultOfBocCacheSet
*/
cache_set(params: ParamsOfBocCacheSet): Promise<ResultOfBocCacheSet> {
return this.client.request('boc.cache_set', params);
}
/**
* Unpin BOCs with specified pin.
*
* @remarks
* BOCs which don't have another pins will be removed from cache
*
* @param {ParamsOfBocCacheUnpin} params
* @returns
*/
cache_unpin(params: ParamsOfBocCacheUnpin): Promise<void> {
return this.client.request('boc.cache_unpin', params);
}
/**
* Encodes bag of cells (BOC) with builder operations. This method provides the same functionality as Solidity TvmBuilder. Resulting BOC of this method can be passed into Solidity and C++ contracts as TvmCell type
*
* @param {ParamsOfEncodeBoc} params
* @returns ResultOfEncodeBoc
*/
encode_boc(params: ParamsOfEncodeBoc): Promise<ResultOfEncodeBoc> {
return this.client.request('boc.encode_boc', params);
}
/**
* Returns the contract code's salt if it is present.
*
* @param {ParamsOfGetCodeSalt} params
* @returns ResultOfGetCodeSalt
*/
get_code_salt(params: ParamsOfGetCodeSalt): Promise<ResultOfGetCodeSalt> {
return this.client.request('boc.get_code_salt', params);
}
/**
* Sets new salt to contract code.
*
* @remarks
* Returns the new contract code with salt.
*
* @param {ParamsOfSetCodeSalt} params
* @returns ResultOfSetCodeSalt
*/
set_code_salt(params: ParamsOfSetCodeSalt): Promise<ResultOfSetCodeSalt> {
return this.client.request('boc.set_code_salt', params);
}
/**
* Decodes tvc into code, data, libraries and special options.
*
* @param {ParamsOfDecodeTvc} params
* @returns ResultOfDecodeTvc
*/
decode_tvc(params: ParamsOfDecodeTvc): Promise<ResultOfDecodeTvc> {
return this.client.request('boc.decode_tvc', params);
}
/**
* Encodes tvc from code, data, libraries ans special options (see input params)
*
* @param {ParamsOfEncodeTvc} params
* @returns ResultOfEncodeTvc
*/
encode_tvc(params: ParamsOfEncodeTvc): Promise<ResultOfEncodeTvc> {
return this.client.request('boc.encode_tvc', params);
}
/**
* Returns the compiler version used to compile the code.
*
* @param {ParamsOfGetCompilerVersion} params
* @returns ResultOfGetCompilerVersion
*/
get_compiler_version(params: ParamsOfGetCompilerVersion): Promise<ResultOfGetCompilerVersion> {
return this.client.request('boc.get_compiler_version', params);
}
}
// processing module
export enum ProcessingErrorCode {
MessageAlreadyExpired = 501,
MessageHasNotDestinationAddress = 502,
CanNotBuildMessageCell = 503,
FetchBlockFailed = 504,
SendMessageFailed = 505,
InvalidMessageBoc = 506,
MessageExpired = 507,
TransactionWaitTimeout = 508,
InvalidBlockReceived = 509,
CanNotCheckBlockShard = 510,
BlockNotFound = 511,
InvalidData = 512,
ExternalSignerMustNotBeUsed = 513
}
export type ProcessingEvent = {
type: 'WillFetchFirstBlock'
} | {
type: 'FetchFirstBlockFailed'
/**
*/
error: ClientError
} | {
type: 'WillSend'
/**
*/
shard_block_id: string,
/**
*/
message_id: string,
/**
*/
message: string
} | {
type: 'DidSend'
/**
*/
shard_block_id: string,
/**
*/
message_id: string,
/**
*/
message: string
} | {
type: 'SendFailed'
/**
*/
shard_block_id: string,
/**
*/
message_id: string,
/**
*/
message: string,
/**
*/
error: ClientError
} | {
type: 'WillFetchNextBlock'
/**
*/
shard_block_id: string,
/**
*/
message_id: string,
/**
*/
message: string
} | {
type: 'FetchNextBlockFailed'
/**
*/
shard_block_id: string,
/**
*/
message_id: string,
/**
*/
message: string,
/**
*/
error: ClientError
} | {
type: 'MessageExpired'
/**
*/
message_id: string,
/**
*/
message: string,
/**
*/
error: ClientError
}
export function processingEventWillFetchFirstBlock(): ProcessingEvent {
return {
type: 'WillFetchFirstBlock',
};
}
export function processingEventFetchFirstBlockFailed(error: ClientError): ProcessingEvent {
return {
type: 'FetchFirstBlockFailed',
error,
};
}
export function processingEventWillSend(shard_block_id: string, message_id: string, message: string): ProcessingEvent {
return {
type: 'WillSend',
shard_block_id,
message_id,
message,
};
}
export function processingEventDidSend(shard_block_id: string, message_id: string, message: string): ProcessingEvent {
return {
type: 'DidSend',
shard_block_id,
message_id,
message,
};
}
export function processingEventSendFailed(shard_block_id: string, message_id: string, message: string, error: ClientError): ProcessingEvent {
return {
type: 'SendFailed',
shard_block_id,
message_id,
message,
error,
};
}
export function processingEventWillFetchNextBlock(shard_block_id: string, message_id: string, message: string): ProcessingEvent {
return {
type: 'WillFetchNextBlock',
shard_block_id,
message_id,
message,
};
}
export function processingEventFetchNextBlockFailed(shard_block_id: string, message_id: string, message: string, error: ClientError): ProcessingEvent {
return {
type: 'FetchNextBlockFailed',
shard_block_id,
message_id,
message,
error,
};
}
export function processingEventMessageExpired(message_id: string, message: string, error: ClientError): ProcessingEvent {
return {
type: 'MessageExpired',
message_id,
message,
error,
};
}
export type ResultOfProcessMessage = {
/**
* Parsed transaction.
*
* @remarks
* In addition to the regular transaction fields there is a
* `boc` field encoded with `base64` which contains source
* transaction BOC.
*/
transaction: any,
/**
* List of output messages' BOCs.
*
* @remarks
* Encoded as `base64`
*/
out_messages: string[],
/**
* Optional decoded message bodies according to the optional `abi` parameter.
*/
decoded?: DecodedOutput,
/**
* Transaction fees
*/
fees: TransactionFees
}
export type DecodedOutput = {
/**
* Decoded bodies of the out messages.
*
* @remarks
* If the message can't be decoded, then `None` will be stored in
* the appropriate position.
*/
out_messages: DecodedMessageBody | null[],
/**
* Decoded body of the function output message.
*/
output?: any
}
export type ParamsOfSendMessage = {
/**
* Message BOC.
*/
message: string,
/**
* Optional message ABI.
*
* @remarks
* If this parameter is specified and the message has the
* `expire` header then expiration time will be checked against
* the current time to prevent unnecessary sending of already expired message.
*
* The `message already expired` error will be returned in this
* case.
*
* Note, that specifying `abi` for ABI compliant contracts is
* strongly recommended, so that proper processing strategy can be
* chosen.
*/
abi?: Abi,
/**
* Flag for requesting events sending
*/
send_events: boolean
}
export type ResultOfSendMessage = {
/**
* The last generated shard block of the message destination account before the message was sent.
*
* @remarks
* This block id must be used as a parameter of the
* `wait_for_transaction`.
*/
shard_block_id: string,
/**
* The list of endpoints to which the message was sent.
*
* @remarks
* This list id must be used as a parameter of the
* `wait_for_transaction`.
*/
sending_endpoints: string[]
}
export type ParamsOfWaitForTransaction = {
/**
* Optional ABI for decoding the transaction result.
*
* @remarks
* If it is specified, then the output messages' bodies will be
* decoded according to this ABI.
*
* The `abi_decoded` result field will be filled out.
*/
abi?: Abi,
/**
* Message BOC.
*
* @remarks
* Encoded with `base64`.
*/
message: string,
/**
* The last generated block id of the destination account shard before the message was sent.
*
* @remarks
* You must provide the same value as the `send_message` has returned.
*/
shard_block_id: string,
/**
* Flag that enables/disables intermediate events
*/
send_events: boolean,
/**
* The list of endpoints to which the message was sent.
*
* @remarks
* Use this field to get more informative errors.
* Provide the same value as the `send_message` has returned.
* If the message was not delivered (expired), SDK will log the endpoint URLs, used for its sending.
*/
sending_endpoints?: string[]
}
export type ParamsOfProcessMessage = {
/**
* Message encode parameters.
*/
message_encode_params: ParamsOfEncodeMessage,
/**
* Flag for requesting events sending
*/
send_events: boolean
}
/**
* Message processing module.
*
* @remarks
* This module incorporates functions related to complex message
* processing scenarios.
*/
export class ProcessingModule {
client: IClient;
constructor(client: IClient) {
this.client = client;
}
/**
* Sends message to the network
*
* @remarks
* Sends message to the network and returns the last generated shard block of the destination account
* before the message was sent. It will be required later for message processing.
*
* @param {ParamsOfSendMessage} params
* @returns ResultOfSendMessage
*/
send_message(params: ParamsOfSendMessage, responseHandler?: ResponseHandler): Promise<ResultOfSendMessage> {
return this.client.request('processing.send_message', params, responseHandler);
}
/**
* Performs monitoring of the network for the result transaction of the external inbound message processing.
*
* @remarks
* `send_events` enables intermediate events, such as `WillFetchNextBlock`,
* `FetchNextBlockFailed` that may be useful for logging of new shard blocks creation
* during message processing.
*
* Note, that presence of the `abi` parameter is critical for ABI
* compliant contracts. Message processing uses drastically
* different strategy for processing message for contracts which
* ABI includes "expire" header.
*
* When the ABI header `expire` is present, the processing uses
* `message expiration` strategy:
* - The maximum block gen time is set to
* `message_expiration_timeout + transaction_wait_timeout`.
* - When maximum block gen time is reached, the processing will
* be finished with `MessageExpired` error.
*
* When the ABI header `expire` isn't present or `abi` parameter
* isn't specified, the processing uses `transaction waiting`
* strategy:
* - The maximum block gen time is set to
* `now() + transaction_wait_timeout`.
*
* - If maximum block gen time is reached and no result transaction is found,
* the processing will exit with an error.
*
* @param {ParamsOfWaitForTransaction} params
* @returns ResultOfProcessMessage
*/
wait_for_transaction(params: ParamsOfWaitForTransaction, responseHandler?: ResponseHandler): Promise<ResultOfProcessMessage> {
return this.client.request('processing.wait_for_transaction', params, responseHandler);
}
/**
* Creates message, sends it to the network and monitors its processing.
*
* @remarks
* Creates ABI-compatible message,
* sends it to the network and monitors for the result transaction.
* Decodes the output messages' bodies.
*
* If contract's ABI includes "expire" header, then
* SDK implements retries in case of unsuccessful message delivery within the expiration
* timeout: SDK recreates the message, sends it and processes it again.
*
* The intermediate events, such as `WillFetchFirstBlock`, `WillSend`, `DidSend`,
* `WillFetchNextBlock`, etc - are switched on/off by `send_events` flag
* and logged into the supplied callback function.
*
* The retry configuration parameters are defined in the client's `NetworkConfig` and `AbiConfig`.
*
* If contract's ABI does not include "expire" header
* then, if no transaction is found within the network timeout (see config parameter ), exits with error.
*
* @param {ParamsOfProcessMessage} params
* @returns ResultOfProcessMessage
*/
process_message(params: ParamsOfProcessMessage, responseHandler?: ResponseHandler): Promise<ResultOfProcessMessage> {
return this.client.request('processing.process_message', params, responseHandler);
}
}
// utils module
export type AddressStringFormat = {
type: 'AccountId'
} | {
type: 'Hex'
} | {
type: 'Base64'
/**
*/
url: boolean,
/**
*/
test: boolean,
/**
*/
bounce: boolean
}
export function addressStringFormatAccountId(): AddressStringFormat {
return {
type: 'AccountId',
};
}
export function addressStringFormatHex(): AddressStringFormat {
return {
type: 'Hex',
};
}
export function addressStringFormatBase64(url: boolean, test: boolean, bounce: boolean): AddressStringFormat {
return {
type: 'Base64',
url,
test,
bounce,
};
}
export enum AccountAddressType {
AccountId = "AccountId",
Hex = "Hex",
Base64 = "Base64"
}
export type ParamsOfConvertAddress = {
/**
* Account address in any TON format.
*/
address: string,
/**
* Specify the format to convert to.
*/
output_format: AddressStringFormat
}
export type ResultOfConvertAddress = {
/**
* Address in the specified format
*/
address: string
}
export type ParamsOfGetAddressType = {
/**
* Account address in any TON format.
*/
address: string
}
export type ResultOfGetAddressType = {
/**
* Account address type.
*/
address_type: AccountAddressType
}
export type ParamsOfCalcStorageFee = {
/**
*/
account: string,
/**
*/
period: number
}
export type ResultOfCalcStorageFee = {
/**
*/
fee: string
}
export type ParamsOfCompressZstd = {
/**
* Uncompressed data.
*
* @remarks
* Must be encoded as base64.
*/
uncompressed: string,
/**
* Compression level, from 1 to 21. Where: 1 - lowest compression level (fastest compression); 21 - highest compression level (slowest compression). If level is omitted, the default compression level is used (currently `3`).
*/
level?: number
}
export type ResultOfCompressZstd = {
/**
* Compressed data.
*
* @remarks
* Must be encoded as base64.
*/
compressed: string
}
export type ParamsOfDecompressZstd = {
/**
* Compressed data.
*
* @remarks
* Must be encoded as base64.
*/
compressed: string
}
export type ResultOfDecompressZstd = {
/**
* Decompressed data.
*
* @remarks
* Must be encoded as base64.
*/
decompressed: string
}
/**
* Misc utility Functions.
*/
export class UtilsModule {
client: IClient;
constructor(client: IClient) {
this.client = client;
}
/**
* Converts address from any TON format to any TON format
*
* @param {ParamsOfConvertAddress} params
* @returns ResultOfConvertAddress
*/
convert_address(params: ParamsOfConvertAddress): Promise<ResultOfConvertAddress> {
return this.client.request('utils.convert_address', params);
}
/**
* Validates and returns the type of any TON address.
*
* @remarks
* Address types are the following
*
* `0:919db8e740d50bf349df2eea03fa30c385d846b991ff5542e67098ee833fc7f7` - standard TON address most
* commonly used in all cases. Also called as hex address
* `919db8e740d50bf349df2eea03fa30c385d846b991ff5542e67098ee833fc7f7` - account ID. A part of full
* address. Identifies account inside particular workchain
* `EQCRnbjnQNUL80nfLuoD+jDDhdhGuZH/VULmcJjugz/H9wam` - base64 address. Also called "user-friendly".
* Was used at the beginning of TON. Now it is supported for compatibility
*
* @param {ParamsOfGetAddressType} params
* @returns ResultOfGetAddressType
*/
get_address_type(params: ParamsOfGetAddressType): Promise<ResultOfGetAddressType> {
return this.client.request('utils.get_address_type', params);
}
/**
* Calculates storage fee for an account over a specified time period
*
* @param {ParamsOfCalcStorageFee} params
* @returns ResultOfCalcStorageFee
*/
calc_storage_fee(params: ParamsOfCalcStorageFee): Promise<ResultOfCalcStorageFee> {
return this.client.request('utils.calc_storage_fee', params);
}
/**
* Compresses data using Zstandard algorithm
*
* @param {ParamsOfCompressZstd} params
* @returns ResultOfCompressZstd
*/
compress_zstd(params: ParamsOfCompressZstd): Promise<ResultOfCompressZstd> {
return this.client.request('utils.compress_zstd', params);
}
/**
* Decompresses data using Zstandard algorithm
*
* @param {ParamsOfDecompressZstd} params
* @returns ResultOfDecompressZstd
*/
decompress_zstd(params: ParamsOfDecompressZstd): Promise<ResultOfDecompressZstd> {
return this.client.request('utils.decompress_zstd', params);
}
}
// tvm module
export enum TvmErrorCode {
CanNotReadTransaction = 401,
CanNotReadBlockchainConfig = 402,
TransactionAborted = 403,
InternalError = 404,
ActionPhaseFailed = 405,
AccountCodeMissing = 406,
LowBalance = 407,
AccountFrozenOrDeleted = 408,
AccountMissing = 409,
UnknownExecutionError = 410,
InvalidInputStack = 411,
InvalidAccountBoc = 412,
InvalidMessageType = 413,
ContractExecutionError = 414
}
export type ExecutionOptions = {
/**
* boc with config
*/
blockchain_config?: string,
/**
* time that is used as transaction time
*/
block_time?: number,
/**
* block logical time
*/
block_lt?: bigint,
/**
* transaction logical time
*/
transaction_lt?: bigint
}
export type AccountForExecutor = {
type: 'None'
} | {
type: 'Uninit'
} | {
type: 'Account'
/**
* Account BOC.
*
* @remarks
* Encoded as base64.
*/
boc: string,
/**
* Flag for running account with the unlimited balance.
*
* @remarks
* Can be used to calculate transaction fees without balance check
*/
unlimited_balance?: boolean
}
export function accountForExecutorNone(): AccountForExecutor {
return {
type: 'None',
};
}
export function accountForExecutorUninit(): AccountForExecutor {
return {
type: 'Uninit',
};
}
export function accountForExecutorAccount(boc: string, unlimited_balance?: boolean): AccountForExecutor {
return {
type: 'Account',
boc,
unlimited_balance,
};
}
export type TransactionFees = {
/**
*/
in_msg_fwd_fee: bigint,
/**
*/
storage_fee: bigint,
/**
*/
gas_fee: bigint,
/**
*/
out_msgs_fwd_fee: bigint,
/**
*/
total_account_fees: bigint,
/**
*/
total_output: bigint
}
export type ParamsOfRunExecutor = {
/**
* Input message BOC.
*
* @remarks
* Must be encoded as base64.
*/
message: string,
/**
* Account to run on executor
*/
account: AccountForExecutor,
/**
* Execution options.
*/
execution_options?: ExecutionOptions,
/**
* Contract ABI for decoding output messages
*/
abi?: Abi,
/**
* Skip transaction check flag
*/
skip_transaction_check?: boolean,
/**
* Cache type to put the result.
*
* @remarks
* The BOC itself returned if no cache type provided
*/
boc_cache?: BocCacheType,
/**
* Return updated account flag.
*
* @remarks
* Empty string is returned if the flag is `false`
*/
return_updated_account?: boolean
}
export type ResultOfRunExecutor = {
/**
* Parsed transaction.
*
* @remarks
* In addition to the regular transaction fields there is a
* `boc` field encoded with `base64` which contains source
* transaction BOC.
*/
transaction: any,
/**
* List of output messages' BOCs.
*
* @remarks
* Encoded as `base64`
*/
out_messages: string[],
/**
* Optional decoded message bodies according to the optional `abi` parameter.
*/
decoded?: DecodedOutput,
/**
* Updated account state BOC.
*
* @remarks
* Encoded as `base64`
*/
account: string,
/**
* Transaction fees
*/
fees: TransactionFees
}
export type ParamsOfRunTvm = {
/**
* Input message BOC.
*
* @remarks
* Must be encoded as base64.
*/
message: string,
/**
* Account BOC.
*
* @remarks
* Must be encoded as base64.
*/
account: string,
/**
* Execution options.
*/
execution_options?: ExecutionOptions,
/**
* Contract ABI for decoding output messages
*/
abi?: Abi,
/**
* Cache type to put the result.
*
* @remarks
* The BOC itself returned if no cache type provided
*/
boc_cache?: BocCacheType,
/**
* Return updated account flag.
*
* @remarks
* Empty string is returned if the flag is `false`
*/
return_updated_account?: boolean
}
export type ResultOfRunTvm = {
/**
* List of output messages' BOCs.
*
* @remarks
* Encoded as `base64`
*/
out_messages: string[],
/**
* Optional decoded message bodies according to the optional `abi` parameter.
*/
decoded?: DecodedOutput,
/**
* Updated account state BOC.
*
* @remarks
* Encoded as `base64`. Attention! Only `account_state.storage.state.data` part of the BOC is updated.
*/
account: string
}
export type ParamsOfRunGet = {
/**
* Account BOC in `base64`
*/
account: string,
/**
* Function name
*/
function_name: string,
/**
* Input parameters
*/
input?: any,
/**
* Execution options
*/
execution_options?: ExecutionOptions,
/**
* Convert lists based on nested tuples in the **result** into plain arrays.
*
* @remarks
* Default is `false`. Input parameters may use any of lists representations
* If you receive this error on Web: "Runtime error. Unreachable code should not be executed...",
* set this flag to true.
* This may happen, for example, when elector contract contains too many participants
*/
tuple_list_as_array?: boolean
}
export type ResultOfRunGet = {
/**
* Values returned by get-method on stack
*/
output: any
}
/**
*/
export class TvmModule {
client: IClient;
constructor(client: IClient) {
this.client = client;
}
/**
* Emulates all the phases of contract execution locally
*
* @remarks
* Performs all the phases of contract execution on Transaction Executor -
* the same component that is used on Validator Nodes.
*
* Can be used for contract debugging, to find out the reason why a message was not delivered successfully.
* Validators throw away the failed external inbound messages (if they failed bedore `ACCEPT`) in the real network.
* This is why these messages are impossible to debug in the real network.
* With the help of run_executor you can do that. In fact, `process_message` function
* performs local check with `run_executor` if there was no transaction as a result of processing
* and returns the error, if there is one.
*
* Another use case to use `run_executor` is to estimate fees for message execution.
* Set `AccountForExecutor::Account.unlimited_balance`
* to `true` so that emulation will not depend on the actual balance.
* This may be needed to calculate deploy fees for an account that does not exist yet.
* JSON with fees is in `fees` field of the result.
*
* One more use case - you can produce the sequence of operations,
* thus emulating the sequential contract calls locally.
* And so on.
*
* Transaction executor requires account BOC (bag of cells) as a parameter.
* To get the account BOC - use `net.query` method to download it from GraphQL API
* (field `boc` of `account`) or generate it with `abi.encode_account` method.
*
* Also it requires message BOC. To get the message BOC - use `abi.encode_message` or `abi.encode_internal_message`.
*
* If you need this emulation to be as precise as possible (for instance - emulate transaction
* with particular lt in particular block or use particular blockchain config,
* downloaded from a particular key block - then specify `execution_options` parameter.
*
* If you need to see the aborted transaction as a result, not as an error, set `skip_transaction_check` to `true`.
*
* @param {ParamsOfRunExecutor} params
* @returns ResultOfRunExecutor
*/
run_executor(params: ParamsOfRunExecutor): Promise<ResultOfRunExecutor> {
return this.client.request('tvm.run_executor', params);
}
/**
* Executes get-methods of ABI-compatible contracts
*
* @remarks
* Performs only a part of compute phase of transaction execution
* that is used to run get-methods of ABI-compatible contracts.
*
* If you try to run get-methods with `run_executor` you will get an error, because it checks ACCEPT and exits
* if there is none, which is actually true for get-methods.
*
* To get the account BOC (bag of cells) - use `net.query` method to download it from GraphQL API
* (field `boc` of `account`) or generate it with `abi.encode_account method`.
* To get the message BOC - use `abi.encode_message` or prepare it any other way, for instance, with FIFT script.
*
* Attention! Updated account state is produces as well, but only
* `account_state.storage.state.data` part of the BOC is updated.
*
* @param {ParamsOfRunTvm} params
* @returns ResultOfRunTvm
*/
run_tvm(params: ParamsOfRunTvm): Promise<ResultOfRunTvm> {
return this.client.request('tvm.run_tvm', params);
}
/**
* Executes a get-method of FIFT contract
*
* @remarks
* Executes a get-method of FIFT contract that fulfills the smc-guidelines https://test.ton.org/smc-guidelines.txt
* and returns the result data from TVM's stack
*
* @param {ParamsOfRunGet} params
* @returns ResultOfRunGet
*/
run_get(params: ParamsOfRunGet): Promise<ResultOfRunGet> {
return this.client.request('tvm.run_get', params);
}
}
// net module
export enum NetErrorCode {
QueryFailed = 601,
SubscribeFailed = 602,
WaitForFailed = 603,
GetSubscriptionResultFailed = 604,
InvalidServerResponse = 605,
ClockOutOfSync = 606,
WaitForTimeout = 607,
GraphqlError = 608,
NetworkModuleSuspended = 609,
WebsocketDisconnected = 610,
NotSupported = 611,
NoEndpointsProvided = 612,
GraphqlWebsocketInitError = 613,
NetworkModuleResumed = 614
}
export type OrderBy = {
/**
*/
path: string,
/**
*/
direction: SortDirection
}
export enum SortDirection {
ASC = "ASC",
DESC = "DESC"
}
export type ParamsOfQueryOperation = ({
type: 'QueryCollection'
} & ParamsOfQueryCollection) | ({
type: 'WaitForCollection'
} & ParamsOfWaitForCollection) | ({
type: 'AggregateCollection'
} & ParamsOfAggregateCollection) | ({
type: 'QueryCounterparties'
} & ParamsOfQueryCounterparties)
export function paramsOfQueryOperationQueryCollection(params: ParamsOfQueryCollection): ParamsOfQueryOperation {
return {
type: 'QueryCollection',
...params,
};
}
export function paramsOfQueryOperationWaitForCollection(params: ParamsOfWaitForCollection): ParamsOfQueryOperation {
return {
type: 'WaitForCollection',
...params,
};
}
export function paramsOfQueryOperationAggregateCollection(params: ParamsOfAggregateCollection): ParamsOfQueryOperation {
return {
type: 'AggregateCollection',
...params,
};
}
export function paramsOfQueryOperationQueryCounterparties(params: ParamsOfQueryCounterparties): ParamsOfQueryOperation {
return {
type: 'QueryCounterparties',
...params,
};
}
export type FieldAggregation = {
/**
* Dot separated path to the field
*/
field: string,
/**
* Aggregation function that must be applied to field values
*/
fn: AggregationFn
}
export enum AggregationFn {
COUNT = "COUNT",
MIN = "MIN",
MAX = "MAX",
SUM = "SUM",
AVERAGE = "AVERAGE"
}
export type TransactionNode = {
/**
* Transaction id.
*/
id: string,
/**
* In message id.
*/
in_msg: string,
/**
* Out message ids.
*/
out_msgs: string[],
/**
* Account address.
*/
account_addr: string,
/**
* Transactions total fees.
*/
total_fees: string,
/**
* Aborted flag.
*/
aborted: boolean,
/**
* Compute phase exit code.
*/
exit_code?: number
}
export type MessageNode = {
/**
* Message id.
*/
id: string,
/**
* Source transaction id.
*
* @remarks
* This field is missing for an external inbound messages.
*/
src_transaction_id?: string,
/**
* Destination transaction id.
*
* @remarks
* This field is missing for an external outbound messages.
*/
dst_transaction_id?: string,
/**
* Source address.
*/
src?: string,
/**
* Destination address.
*/
dst?: string,
/**
* Transferred tokens value.
*/
value?: string,
/**
* Bounce flag.
*/
bounce: boolean,
/**
* Decoded body.
*
* @remarks
* Library tries to decode message body using provided `params.abi_registry`.
* This field will be missing if none of the provided abi can be used to decode.
*/
decoded_body?: DecodedMessageBody
}
export type ParamsOfQuery = {
/**
* GraphQL query text.
*/
query: string,
/**
* Variables used in query.
*
* @remarks
* Must be a map with named values that can be used in query.
*/
variables?: any
}
export type ResultOfQuery = {
/**
* Result provided by DAppServer.
*/
result: any
}
export type ParamsOfBatchQuery = {
/**
* List of query operations that must be performed per single fetch.
*/
operations: ParamsOfQueryOperation[]
}
export type ResultOfBatchQuery = {
/**
* Result values for batched queries.
*
* @remarks
* Returns an array of values. Each value corresponds to `queries` item.
*/
results: any[]
}
export type ParamsOfQueryCollection = {
/**
* Collection name (accounts, blocks, transactions, messages, block_signatures)
*/
collection: string,
/**
* Collection filter
*/
filter?: any,
/**
* Projection (result) string
*/
result: string,
/**
* Sorting order
*/
order?: OrderBy[],
/**
* Number of documents to return
*/
limit?: number
}
export type ResultOfQueryCollection = {
/**
* Objects that match the provided criteria
*/
result: any[]
}
export type ParamsOfAggregateCollection = {
/**
* Collection name (accounts, blocks, transactions, messages, block_signatures)
*/
collection: string,
/**
* Collection filter
*/
filter?: any,
/**
* Projection (result) string
*/
fields?: FieldAggregation[]
}
export type ResultOfAggregateCollection = {
/**
* Values for requested fields.
*
* @remarks
* Returns an array of strings. Each string refers to the corresponding `fields` item.
* Numeric value is returned as a decimal string representations.
*/
values: any
}
export type ParamsOfWaitForCollection = {
/**
* Collection name (accounts, blocks, transactions, messages, block_signatures)
*/
collection: string,
/**
* Collection filter
*/
filter?: any,
/**
* Projection (result) string
*/
result: string,
/**
* Query timeout
*/
timeout?: number
}
export type ResultOfWaitForCollection = {
/**
* First found object that matches the provided criteria
*/
result: any
}
export type ResultOfSubscribeCollection = {
/**
* Subscription handle.
*
* @remarks
* Must be closed with `unsubscribe`
*/
handle: number
}
export type ParamsOfSubscribeCollection = {
/**
* Collection name (accounts, blocks, transactions, messages, block_signatures)
*/
collection: string,
/**
* Collection filter
*/
filter?: any,
/**
* Projection (result) string
*/
result: string
}
export type ParamsOfFindLastShardBlock = {
/**
* Account address
*/
address: string
}
export type ResultOfFindLastShardBlock = {
/**
* Account shard last block ID
*/
block_id: string
}
export type EndpointsSet = {
/**
* List of endpoints provided by server
*/
endpoints: string[]
}
export type ResultOfGetEndpoints = {
/**
* Current query endpoint
*/
query: string,
/**
* List of all endpoints used by client
*/
endpoints: string[]
}
export type ParamsOfQueryCounterparties = {
/**
* Account address
*/
account: string,
/**
* Projection (result) string
*/
result: string,
/**
* Number of counterparties to return
*/
first?: number,
/**
* `cursor` field of the last received result
*/
after?: string
}
export type ParamsOfQueryTransactionTree = {
/**
* Input message id.
*/
in_msg: string,
/**
* List of contract ABIs that will be used to decode message bodies. Library will try to decode each returned message body using any ABI from the registry.
*/
abi_registry?: Abi[],
/**
* Timeout used to limit waiting time for the missing messages and transaction.
*
* @remarks
* If some of the following messages and transactions are missing yet
* The maximum waiting time is regulated by this option.
*
* Default value is 60000 (1 min).
*/
timeout?: number
}
export type ResultOfQueryTransactionTree = {
/**
* Messages.
*/
messages: MessageNode[],
/**
* Transactions.
*/
transactions: TransactionNode[]
}
export type ParamsOfCreateBlockIterator = {
/**
* Starting time to iterate from.
*
* @remarks
* If the application specifies this parameter then the iteration
* includes blocks with `gen_utime` >= `start_time`.
* Otherwise the iteration starts from zero state.
*
* Must be specified in seconds.
*/
start_time?: number,
/**
* Optional end time to iterate for.
*
* @remarks
* If the application specifies this parameter then the iteration
* includes blocks with `gen_utime` < `end_time`.
* Otherwise the iteration never stops.
*
* Must be specified in seconds.
*/
end_time?: number,
/**
* Shard prefix filter.
*
* @remarks
* If the application specifies this parameter and it is not the empty array
* then the iteration will include items related to accounts that belongs to
* the specified shard prefixes.
* Shard prefix must be represented as a string "workchain:prefix".
* Where `workchain` is a signed integer and the `prefix` if a hexadecimal
* representation if the 64-bit unsigned integer with tagged shard prefix.
* For example: "0:3800000000000000".
*/
shard_filter?: string[],
/**
* Projection (result) string.
*
* @remarks
* List of the fields that must be returned for iterated items.
* This field is the same as the `result` parameter of
* the `query_collection` function.
* Note that iterated items can contains additional fields that are
* not requested in the `result`.
*/
result?: string
}
export type RegisteredIterator = {
/**
* Iterator handle.
*
* @remarks
* Must be removed using `remove_iterator`
* when it is no more needed for the application.
*/
handle: number
}
export type ParamsOfResumeBlockIterator = {
/**
* Iterator state from which to resume.
*
* @remarks
* Same as value returned from `iterator_next`.
*/
resume_state: any
}
export type ParamsOfCreateTransactionIterator = {
/**
* Starting time to iterate from.
*
* @remarks
* If the application specifies this parameter then the iteration
* includes blocks with `gen_utime` >= `start_time`.
* Otherwise the iteration starts from zero state.
*
* Must be specified in seconds.
*/
start_time?: number,
/**
* Optional end time to iterate for.
*
* @remarks
* If the application specifies this parameter then the iteration
* includes blocks with `gen_utime` < `end_time`.
* Otherwise the iteration never stops.
*
* Must be specified in seconds.
*/
end_time?: number,
/**
* Shard prefix filters.
*
* @remarks
* If the application specifies this parameter and it is not an empty array
* then the iteration will include items related to accounts that belongs to
* the specified shard prefixes.
* Shard prefix must be represented as a string "workchain:prefix".
* Where `workchain` is a signed integer and the `prefix` if a hexadecimal
* representation if the 64-bit unsigned integer with tagged shard prefix.
* For example: "0:3800000000000000".
* Account address conforms to the shard filter if
* it belongs to the filter workchain and the first bits of address match to
* the shard prefix. Only transactions with suitable account addresses are iterated.
*/
shard_filter?: string[],
/**
* Account address filter.
*
* @remarks
* Application can specify the list of accounts for which
* it wants to iterate transactions.
*
* If this parameter is missing or an empty list then the library iterates
* transactions for all accounts that pass the shard filter.
*
* Note that the library doesn't detect conflicts between the account filter and the shard filter
* if both are specified.
* So it is an application responsibility to specify the correct filter combination.
*/
accounts_filter?: string[],
/**
* Projection (result) string.
*
* @remarks
* List of the fields that must be returned for iterated items.
* This field is the same as the `result` parameter of
* the `query_collection` function.
* Note that iterated items can contain additional fields that are
* not requested in the `result`.
*/
result?: string,
/**
* Include `transfers` field in iterated transactions.
*
* @remarks
* If this parameter is `true` then each transaction contains field
* `transfers` with list of transfer. See more about this structure in function description.
*/
include_transfers?: boolean
}
export type ParamsOfResumeTransactionIterator = {
/**
* Iterator state from which to resume.
*
* @remarks
* Same as value returned from `iterator_next`.
*/
resume_state: any,
/**
* Account address filter.
*
* @remarks
* Application can specify the list of accounts for which
* it wants to iterate transactions.
*
* If this parameter is missing or an empty list then the library iterates
* transactions for all accounts that passes the shard filter.
*
* Note that the library doesn't detect conflicts between the account filter and the shard filter
* if both are specified.
* So it is the application's responsibility to specify the correct filter combination.
*/
accounts_filter?: string[]
}
export type ParamsOfIteratorNext = {
/**
* Iterator handle
*/
iterator: number,
/**
* Maximum count of the returned items.
*
* @remarks
* If value is missing or is less than 1 the library uses 1.
*/
limit?: number,
/**
* Indicates that function must return the iterator state that can be used for resuming iteration.
*/
return_resume_state?: boolean
}
export type ResultOfIteratorNext = {
/**
* Next available items.
*
* @remarks
* Note that `iterator_next` can return an empty items and `has_more` equals to `true`.
* In this case the application have to continue iteration.
* Such situation can take place when there is no data yet but
* the requested `end_time` is not reached.
*/
items: any[],
/**
* Indicates that there are more available items in iterated range.
*/
has_more: boolean,
/**
* Optional iterator state that can be used for resuming iteration.
*
* @remarks
* This field is returned only if the `return_resume_state` parameter
* is specified.
*
* Note that `resume_state` corresponds to the iteration position
* after the returned items.
*/
resume_state?: any
}
/**
* Network access.
*/
export class NetModule {
client: IClient;
constructor(client: IClient) {
this.client = client;
}
/**
* Performs DAppServer GraphQL query.
*
* @param {ParamsOfQuery} params
* @returns ResultOfQuery
*/
query(params: ParamsOfQuery): Promise<ResultOfQuery> {
return this.client.request('net.query', params);
}
/**
* Performs multiple queries per single fetch.
*
* @param {ParamsOfBatchQuery} params
* @returns ResultOfBatchQuery
*/
batch_query(params: ParamsOfBatchQuery): Promise<ResultOfBatchQuery> {
return this.client.request('net.batch_query', params);
}
/**
* Queries collection data
*
* @remarks
* Queries data that satisfies the `filter` conditions,
* limits the number of returned records and orders them.
* The projection fields are limited to `result` fields
*
* @param {ParamsOfQueryCollection} params
* @returns ResultOfQueryCollection
*/
query_collection(params: ParamsOfQueryCollection): Promise<ResultOfQueryCollection> {
return this.client.request('net.query_collection', params);
}
/**
* Aggregates collection data.
*
* @remarks
* Aggregates values from the specified `fields` for records
* that satisfies the `filter` conditions,
*
* @param {ParamsOfAggregateCollection} params
* @returns ResultOfAggregateCollection
*/
aggregate_collection(params: ParamsOfAggregateCollection): Promise<ResultOfAggregateCollection> {
return this.client.request('net.aggregate_collection', params);
}
/**
* Returns an object that fulfills the conditions or waits for its appearance
*
* @remarks
* Triggers only once.
* If object that satisfies the `filter` conditions
* already exists - returns it immediately.
* If not - waits for insert/update of data within the specified `timeout`,
* and returns it.
* The projection fields are limited to `result` fields
*
* @param {ParamsOfWaitForCollection} params
* @returns ResultOfWaitForCollection
*/
wait_for_collection(params: ParamsOfWaitForCollection): Promise<ResultOfWaitForCollection> {
return this.client.request('net.wait_for_collection', params);
}
/**
* Cancels a subscription
*
* @remarks
* Cancels a subscription specified by its handle.
*
* @param {ResultOfSubscribeCollection} params
* @returns
*/
unsubscribe(params: ResultOfSubscribeCollection): Promise<void> {
return this.client.request('net.unsubscribe', params);
}
/**
* Creates a subscription
*
* @remarks
* Triggers for each insert/update of data that satisfies
* the `filter` conditions.
* The projection fields are limited to `result` fields.
*
* The subscription is a persistent communication channel between
* client and Free TON Network.
* All changes in the blockchain will be reflected in realtime.
* Changes means inserts and updates of the blockchain entities.
*
* ### Important Notes on Subscriptions
*
* Unfortunately sometimes the connection with the network brakes down.
* In this situation the library attempts to reconnect to the network.
* This reconnection sequence can take significant time.
* All of this time the client is disconnected from the network.
*
* Bad news is that all blockchain changes that happened while
* the client was disconnected are lost.
*
* Good news is that the client report errors to the callback when
* it loses and resumes connection.
*
* So, if the lost changes are important to the application then
* the application must handle these error reports.
*
* Library reports errors with `responseType` == 101
* and the error object passed via `params`.
*
* When the library has successfully reconnected
* the application receives callback with
* `responseType` == 101 and `params.code` == 614 (NetworkModuleResumed).
*
* Application can use several ways to handle this situation:
* - If application monitors changes for the single blockchain
* object (for example specific account): application
* can perform a query for this object and handle actual data as a
* regular data from the subscription.
* - If application monitors sequence of some blockchain objects
* (for example transactions of the specific account): application must
* refresh all cached (or visible to user) lists where this sequences presents.
*
* @param {ParamsOfSubscribeCollection} params
* @returns ResultOfSubscribeCollection
*/
subscribe_collection(params: ParamsOfSubscribeCollection, responseHandler?: ResponseHandler): Promise<ResultOfSubscribeCollection> {
return this.client.request('net.subscribe_collection', params, responseHandler);
}
/**
* Suspends network module to stop any network activity
* @returns
*/
suspend(): Promise<void> {
return this.client.request('net.suspend');
}
/**
* Resumes network module to enable network activity
* @returns
*/
resume(): Promise<void> {
return this.client.request('net.resume');
}
/**
* Returns ID of the last block in a specified account shard
*
* @param {ParamsOfFindLastShardBlock} params
* @returns ResultOfFindLastShardBlock
*/
find_last_shard_block(params: ParamsOfFindLastShardBlock): Promise<ResultOfFindLastShardBlock> {
return this.client.request('net.find_last_shard_block', params);
}
/**
* Requests the list of alternative endpoints from server
* @returns EndpointsSet
*/
fetch_endpoints(): Promise<EndpointsSet> {
return this.client.request('net.fetch_endpoints');
}
/**
* Sets the list of endpoints to use on reinit
*
* @param {EndpointsSet} params
* @returns
*/
set_endpoints(params: EndpointsSet): Promise<void> {
return this.client.request('net.set_endpoints', params);
}
/**
* Requests the list of alternative endpoints from server
* @returns ResultOfGetEndpoints
*/
get_endpoints(): Promise<ResultOfGetEndpoints> {
return this.client.request('net.get_endpoints');
}
/**
* Allows to query and paginate through the list of accounts that the specified account has interacted with, sorted by the time of the last internal message between accounts
*
* @remarks
* *Attention* this query retrieves data from 'Counterparties' service which is not supported in
* the opensource version of DApp Server (and will not be supported) as well as in TON OS SE (will be supported in SE in future),
* but is always accessible via [TON OS Devnet/Mainnet Clouds](https://docs.ton.dev/86757ecb2/p/85c869-networks)
*
* @param {ParamsOfQueryCounterparties} params
* @returns ResultOfQueryCollection
*/
query_counterparties(params: ParamsOfQueryCounterparties): Promise<ResultOfQueryCollection> {
return this.client.request('net.query_counterparties', params);
}
/**
* Returns a tree of transactions triggered by a specific message.
*
* @remarks
* Performs recursive retrieval of a transactions tree produced by a specific message:
* in_msg -> dst_transaction -> out_messages -> dst_transaction -> ...
* If the chain of transactions execution is in progress while the function is running,
* it will wait for the next transactions to appear until the full tree or more than 50 transactions
* are received.
*
* All the retrieved messages and transactions are included
* into `result.messages` and `result.transactions` respectively.
*
* Function reads transactions layer by layer, by pages of 20 transactions.
*
* The retrieval prosess goes like this:
* Let's assume we have an infinite chain of transactions and each transaction generates 5 messages.
* 1. Retrieve 1st message (input parameter) and corresponding transaction - put it into result.
* It is the first level of the tree of transactions - its root.
* Retrieve 5 out message ids from the transaction for next steps.
* 2. Retrieve 5 messages and corresponding transactions on the 2nd layer. Put them into result.
* Retrieve 5*5 out message ids from these transactions for next steps
* 3. Retrieve 20 (size of the page) messages and transactions (3rd layer) and 20*5=100 message ids (4th layer).
* 4. Retrieve the last 5 messages and 5 transactions on the 3rd layer + 15 messages and transactions (of 100) from the 4th layer
* + 25 message ids of the 4th layer + 75 message ids of the 5th layer.
* 5. Retrieve 20 more messages and 20 more transactions of the 4th layer + 100 more message ids of the 5th layer.
* 6. Now we have 1+5+20+20+20 = 66 transactions, which is more than 50. Function exits with the tree of
* 1m->1t->5m->5t->25m->25t->35m->35t. If we see any message ids in the last transactions out_msgs, which don't have
* corresponding messages in the function result, it means that the full tree was not received and we need to continue iteration.
*
* To summarize, it is guaranteed that each message in `result.messages` has the corresponding transaction
* in the `result.transactions`.
* But there is no guarantee that all messages from transactions `out_msgs` are
* presented in `result.messages`.
* So the application has to continue retrieval for missing messages if it requires.
*
* @param {ParamsOfQueryTransactionTree} params
* @returns ResultOfQueryTransactionTree
*/
query_transaction_tree(params: ParamsOfQueryTransactionTree): Promise<ResultOfQueryTransactionTree> {
return this.client.request('net.query_transaction_tree', params);
}
/**
* Creates block iterator.
*
* @remarks
* Block iterator uses robust iteration methods that guaranties that every
* block in the specified range isn't missed or iterated twice.
*
* Iterated range can be reduced with some filters:
* - `start_time` – the bottom time range. Only blocks with `gen_utime`
* more or equal to this value is iterated. If this parameter is omitted then there is
* no bottom time edge, so all blocks since zero state is iterated.
* - `end_time` – the upper time range. Only blocks with `gen_utime`
* less then this value is iterated. If this parameter is omitted then there is
* no upper time edge, so iterator never finishes.
* - `shard_filter` – workchains and shard prefixes that reduce the set of interesting
* blocks. Block conforms to the shard filter if it belongs to the filter workchain
* and the first bits of block's `shard` fields matches to the shard prefix.
* Only blocks with suitable shard are iterated.
*
* Items iterated is a JSON objects with block data. The minimal set of returned
* fields is:
* ```text
* id
* gen_utime
* workchain_id
* shard
* after_split
* after_merge
* prev_ref {
* root_hash
* }
* prev_alt_ref {
* root_hash
* }
* ```
* Application can request additional fields in the `result` parameter.
*
* Application should call the `remove_iterator` when iterator is no longer required.
*
* @param {ParamsOfCreateBlockIterator} params
* @returns RegisteredIterator
*/
create_block_iterator(params: ParamsOfCreateBlockIterator): Promise<RegisteredIterator> {
return this.client.request('net.create_block_iterator', params);
}
/**
* Resumes block iterator.
*
* @remarks
* The iterator stays exactly at the same position where the `resume_state` was catched.
*
* Application should call the `remove_iterator` when iterator is no longer required.
*
* @param {ParamsOfResumeBlockIterator} params
* @returns RegisteredIterator
*/
resume_block_iterator(params: ParamsOfResumeBlockIterator): Promise<RegisteredIterator> {
return this.client.request('net.resume_block_iterator', params);
}
/**
* Creates transaction iterator.
*
* @remarks
* Transaction iterator uses robust iteration methods that guaranty that every
* transaction in the specified range isn't missed or iterated twice.
*
* Iterated range can be reduced with some filters:
* - `start_time` – the bottom time range. Only transactions with `now`
* more or equal to this value are iterated. If this parameter is omitted then there is
* no bottom time edge, so all the transactions since zero state are iterated.
* - `end_time` – the upper time range. Only transactions with `now`
* less then this value are iterated. If this parameter is omitted then there is
* no upper time edge, so iterator never finishes.
* - `shard_filter` – workchains and shard prefixes that reduce the set of interesting
* accounts. Account address conforms to the shard filter if
* it belongs to the filter workchain and the first bits of address match to
* the shard prefix. Only transactions with suitable account addresses are iterated.
* - `accounts_filter` – set of account addresses whose transactions must be iterated.
* Note that accounts filter can conflict with shard filter so application must combine
* these filters carefully.
*
* Iterated item is a JSON objects with transaction data. The minimal set of returned
* fields is:
* ```text
* id
* account_addr
* now
* balance_delta(format:DEC)
* bounce { bounce_type }
* in_message {
* id
* value(format:DEC)
* msg_type
* src
* }
* out_messages {
* id
* value(format:DEC)
* msg_type
* dst
* }
* ```
* Application can request an additional fields in the `result` parameter.
*
* Another parameter that affects on the returned fields is the `include_transfers`.
* When this parameter is `true` the iterator computes and adds `transfer` field containing
* list of the useful `TransactionTransfer` objects.
* Each transfer is calculated from the particular message related to the transaction
* and has the following structure:
* - message – source message identifier.
* - isBounced – indicates that the transaction is bounced, which means the value will be returned back to the sender.
* - isDeposit – indicates that this transfer is the deposit (true) or withdraw (false).
* - counterparty – account address of the transfer source or destination depending on `isDeposit`.
* - value – amount of nano tokens transferred. The value is represented as a decimal string
* because the actual value can be more precise than the JSON number can represent. Application
* must use this string carefully – conversion to number can follow to loose of precision.
*
* Application should call the `remove_iterator` when iterator is no longer required.
*
* @param {ParamsOfCreateTransactionIterator} params
* @returns RegisteredIterator
*/
create_transaction_iterator(params: ParamsOfCreateTransactionIterator): Promise<RegisteredIterator> {
return this.client.request('net.create_transaction_iterator', params);
}
/**
* Resumes transaction iterator.
*
* @remarks
* The iterator stays exactly at the same position where the `resume_state` was caught.
* Note that `resume_state` doesn't store the account filter. If the application requires
* to use the same account filter as it was when the iterator was created then the application
* must pass the account filter again in `accounts_filter` parameter.
*
* Application should call the `remove_iterator` when iterator is no longer required.
*
* @param {ParamsOfResumeTransactionIterator} params
* @returns RegisteredIterator
*/
resume_transaction_iterator(params: ParamsOfResumeTransactionIterator): Promise<RegisteredIterator> {
return this.client.request('net.resume_transaction_iterator', params);
}
/**
* Returns next available items.
*
* @remarks
* In addition to available items this function returns the `has_more` flag
* indicating that the iterator isn't reach the end of the iterated range yet.
*
* This function can return the empty list of available items but
* indicates that there are more items is available.
* This situation appears when the iterator doesn't reach iterated range
* but database doesn't contains available items yet.
*
* If application requests resume state in `return_resume_state` parameter
* then this function returns `resume_state` that can be used later to
* resume the iteration from the position after returned items.
*
* The structure of the items returned depends on the iterator used.
* See the description to the appropriated iterator creation function.
*
* @param {ParamsOfIteratorNext} params
* @returns ResultOfIteratorNext
*/
iterator_next(params: ParamsOfIteratorNext): Promise<ResultOfIteratorNext> {
return this.client.request('net.iterator_next', params);
}
/**
* Removes an iterator
*
* @remarks
* Frees all resources allocated in library to serve iterator.
*
* Application always should call the `remove_iterator` when iterator
* is no longer required.
*
* @param {RegisteredIterator} params
* @returns
*/
remove_iterator(params: RegisteredIterator): Promise<void> {
return this.client.request('net.remove_iterator', params);
}
}
// debot module
export enum DebotErrorCode {
DebotStartFailed = 801,
DebotFetchFailed = 802,
DebotExecutionFailed = 803,
DebotInvalidHandle = 804,
DebotInvalidJsonParams = 805,
DebotInvalidFunctionId = 806,
DebotInvalidAbi = 807,
DebotGetMethodFailed = 808,
DebotInvalidMsg = 809,
DebotExternalCallFailed = 810,
DebotBrowserCallbackFailed = 811,
DebotOperationRejected = 812
}
export type DebotHandle = number
export type DebotAction = {
/**
* A short action description.
*
* @remarks
* Should be used by Debot Browser as name of menu item.
*/
description: string,
/**
* Depends on action type.
*
* @remarks
* Can be a debot function name or a print string (for Print Action).
*/
name: string,
/**
* Action type.
*/
action_type: number,
/**
* ID of debot context to switch after action execution.
*/
to: number,
/**
* Action attributes.
*
* @remarks
* In the form of "param=value,flag". attribute example: instant, args, fargs, sign.
*/
attributes: string,
/**
* Some internal action data.
*
* @remarks
* Used by debot only.
*/
misc: string
}
export type DebotInfo = {
/**
* DeBot short name.
*/
name?: string,
/**
* DeBot semantic version.
*/
version?: string,
/**
* The name of DeBot deployer.
*/
publisher?: string,
/**
* Short info about DeBot.
*/
caption?: string,
/**
* The name of DeBot developer.
*/
author?: string,
/**
* TON address of author for questions and donations.
*/
support?: string,
/**
* String with the first messsage from DeBot.
*/
hello?: string,
/**
* String with DeBot interface language (ISO-639).
*/
language?: string,
/**
* String with DeBot ABI.
*/
dabi?: string,
/**
* DeBot icon.
*/
icon?: string,
/**
* Vector with IDs of DInterfaces used by DeBot.
*/
interfaces: string[]
}
export type DebotActivity = {
type: 'Transaction'
/**
* External inbound message BOC.
*/
msg: string,
/**
* Target smart contract address.
*/
dst: string,
/**
* List of spendings as a result of transaction.
*/
out: Spending[],
/**
* Transaction total fee.
*/
fee: bigint,
/**
* Indicates if target smart contract updates its code.
*/
setcode: boolean,
/**
* Public key from keypair that was used to sign external message.
*/
signkey: string,
/**
* Signing box handle used to sign external message.
*/
signing_box_handle: number
}
export function debotActivityTransaction(msg: string, dst: string, out: Spending[], fee: bigint, setcode: boolean, signkey: string, signing_box_handle: number): DebotActivity {
return {
type: 'Transaction',
msg,
dst,
out,
fee,
setcode,
signkey,
signing_box_handle,
};
}
export type Spending = {
/**
* Amount of nanotokens that will be sent to `dst` address.
*/
amount: bigint,
/**
* Destination address of recipient of funds.
*/
dst: string
}
export type ParamsOfInit = {
/**
* Debot smart contract address
*/
address: string
}
export type RegisteredDebot = {
/**
* Debot handle which references an instance of debot engine.
*/
debot_handle: DebotHandle,
/**
* Debot abi as json string.
*/
debot_abi: string,
/**
* Debot metadata.
*/
info: DebotInfo
}
export type ParamsOfAppDebotBrowser = {
type: 'Log'
/**
* A string that must be printed to user.
*/
msg: string
} | {
type: 'Switch'
/**
* Debot context ID to which debot is switched.
*/
context_id: number
} | {
type: 'SwitchCompleted'
} | {
type: 'ShowAction'
/**
* Debot action that must be shown to user as menu item. At least `description` property must be shown from [DebotAction] structure.
*/
action: DebotAction
} | {
type: 'Input'
/**
* A prompt string that must be printed to user before input request.
*/
prompt: string
} | {
type: 'GetSigningBox'
} | {
type: 'InvokeDebot'
/**
* Address of debot in blockchain.
*/
debot_addr: string,
/**
* Debot action to execute.
*/
action: DebotAction
} | {
type: 'Send'
/**
* Internal message to DInterface address.
*
* @remarks
* Message body contains interface function and parameters.
*/
message: string
} | {
type: 'Approve'
/**
* DeBot activity details.
*/
activity: DebotActivity
}
export function paramsOfAppDebotBrowserLog(msg: string): ParamsOfAppDebotBrowser {
return {
type: 'Log',
msg,
};
}
export function paramsOfAppDebotBrowserSwitch(context_id: number): ParamsOfAppDebotBrowser {
return {
type: 'Switch',
context_id,
};
}
export function paramsOfAppDebotBrowserSwitchCompleted(): ParamsOfAppDebotBrowser {
return {
type: 'SwitchCompleted',
};
}
export function paramsOfAppDebotBrowserShowAction(action: DebotAction): ParamsOfAppDebotBrowser {
return {
type: 'ShowAction',
action,
};
}
export function paramsOfAppDebotBrowserInput(prompt: string): ParamsOfAppDebotBrowser {
return {
type: 'Input',
prompt,
};
}
export function paramsOfAppDebotBrowserGetSigningBox(): ParamsOfAppDebotBrowser {
return {
type: 'GetSigningBox',
};
}
export function paramsOfAppDebotBrowserInvokeDebot(debot_addr: string, action: DebotAction): ParamsOfAppDebotBrowser {
return {
type: 'InvokeDebot',
debot_addr,
action,
};
}
export function paramsOfAppDebotBrowserSend(message: string): ParamsOfAppDebotBrowser {
return {
type: 'Send',
message,
};
}
export function paramsOfAppDebotBrowserApprove(activity: DebotActivity): ParamsOfAppDebotBrowser {
return {
type: 'Approve',
activity,
};
}
export type ResultOfAppDebotBrowser = {
type: 'Input'
/**
* String entered by user.
*/
value: string
} | {
type: 'GetSigningBox'
/**
* Signing box for signing data requested by debot engine.
*
* @remarks
* Signing box is owned and disposed by debot engine
*/
signing_box: SigningBoxHandle
} | {
type: 'InvokeDebot'
} | {
type: 'Approve'
/**
* Indicates whether the DeBot is allowed to perform the specified operation.
*/
approved: boolean
}
export function resultOfAppDebotBrowserInput(value: string): ResultOfAppDebotBrowser {
return {
type: 'Input',
value,
};
}
export function resultOfAppDebotBrowserGetSigningBox(signing_box: SigningBoxHandle): ResultOfAppDebotBrowser {
return {
type: 'GetSigningBox',
signing_box,
};
}
export function resultOfAppDebotBrowserInvokeDebot(): ResultOfAppDebotBrowser {
return {
type: 'InvokeDebot',
};
}
export function resultOfAppDebotBrowserApprove(approved: boolean): ResultOfAppDebotBrowser {
return {
type: 'Approve',
approved,
};
}
export type ParamsOfStart = {
/**
* Debot handle which references an instance of debot engine.
*/
debot_handle: DebotHandle
}
export type ParamsOfFetch = {
/**
* Debot smart contract address.
*/
address: string
}
export type ResultOfFetch = {
/**
* Debot metadata.
*/
info: DebotInfo
}
export type ParamsOfExecute = {
/**
* Debot handle which references an instance of debot engine.
*/
debot_handle: DebotHandle,
/**
* Debot Action that must be executed.
*/
action: DebotAction
}
export type ParamsOfSend = {
/**
* Debot handle which references an instance of debot engine.
*/
debot_handle: DebotHandle,
/**
* BOC of internal message to debot encoded in base64 format.
*/
message: string
}
export type ParamsOfRemove = {
/**
* Debot handle which references an instance of debot engine.
*/
debot_handle: DebotHandle
}
type ParamsOfAppDebotBrowserLog = {
msg: string
}
type ParamsOfAppDebotBrowserSwitch = {
context_id: number
}
type ParamsOfAppDebotBrowserShowAction = {
action: DebotAction
}
type ParamsOfAppDebotBrowserInput = {
prompt: string
}
type ResultOfAppDebotBrowserInput = {
value: string
}
type ResultOfAppDebotBrowserGetSigningBox = {
signing_box: SigningBoxHandle
}
type ParamsOfAppDebotBrowserInvokeDebot = {
debot_addr: string,
action: DebotAction
}
type ParamsOfAppDebotBrowserSend = {
message: string
}
type ParamsOfAppDebotBrowserApprove = {
activity: DebotActivity
}
type ResultOfAppDebotBrowserApprove = {
approved: boolean
}
export interface AppDebotBrowser {
log(params: ParamsOfAppDebotBrowserLog): void,
switch(params: ParamsOfAppDebotBrowserSwitch): void,
switch_completed(): void,
show_action(params: ParamsOfAppDebotBrowserShowAction): void,
input(params: ParamsOfAppDebotBrowserInput): Promise<ResultOfAppDebotBrowserInput>,
get_signing_box(): Promise<ResultOfAppDebotBrowserGetSigningBox>,
invoke_debot(params: ParamsOfAppDebotBrowserInvokeDebot): Promise<void>,
send(params: ParamsOfAppDebotBrowserSend): void,
approve(params: ParamsOfAppDebotBrowserApprove): Promise<ResultOfAppDebotBrowserApprove>,
}
async function dispatchAppDebotBrowser(obj: AppDebotBrowser, params: ParamsOfAppDebotBrowser, app_request_id: number | null, client: IClient) {
try {
let result = {};
switch (params.type) {
case 'Log':
obj.log(params);
break;
case 'Switch':
obj.switch(params);
break;
case 'SwitchCompleted':
obj.switch_completed();
break;
case 'ShowAction':
obj.show_action(params);
break;
case 'Input':
result = await obj.input(params);
break;
case 'GetSigningBox':
result = await obj.get_signing_box();
break;
case 'InvokeDebot':
await obj.invoke_debot(params);
break;
case 'Send':
obj.send(params);
break;
case 'Approve':
result = await obj.approve(params);
break;
}
client.resolve_app_request(app_request_id, { type: params.type, ...result });
}
catch (error) {
client.reject_app_request(app_request_id, error);
}
}
/**
* [UNSTABLE](UNSTABLE.md) Module for working with debot.
*/
export class DebotModule {
client: IClient;
constructor(client: IClient) {
this.client = client;
}
/**
* [UNSTABLE](UNSTABLE.md) Creates and instance of DeBot.
*
* @remarks
* Downloads debot smart contract (code and data) from blockchain and creates
* an instance of Debot Engine for it.
*
* # Remarks
* It does not switch debot to context 0. Browser Callbacks are not called.
*
* @param {ParamsOfInit} params
* @returns RegisteredDebot
*/
init(params: ParamsOfInit, obj: AppDebotBrowser): Promise<RegisteredDebot> {
return this.client.request('debot.init', params, (params: any, responseType: number) => {
if (responseType === 3) {
dispatchAppDebotBrowser(obj, params.request_data, params.app_request_id, this.client);
} else if (responseType === 4) {
dispatchAppDebotBrowser(obj, params, null, this.client);
}
});
}
/**
* [UNSTABLE](UNSTABLE.md) Starts the DeBot.
*
* @remarks
* Downloads debot smart contract from blockchain and switches it to
* context zero.
*
* This function must be used by Debot Browser to start a dialog with debot.
* While the function is executing, several Browser Callbacks can be called,
* since the debot tries to display all actions from the context 0 to the user.
*
* When the debot starts SDK registers `BrowserCallbacks` AppObject.
* Therefore when `debote.remove` is called the debot is being deleted and the callback is called
* with `finish`=`true` which indicates that it will never be used again.
*
* @param {ParamsOfStart} params
* @returns
*/
start(params: ParamsOfStart): Promise<void> {
return this.client.request('debot.start', params);
}
/**
* [UNSTABLE](UNSTABLE.md) Fetches DeBot metadata from blockchain.
*
* @remarks
* Downloads DeBot from blockchain and creates and fetches its metadata.
*
* @param {ParamsOfFetch} params
* @returns ResultOfFetch
*/
fetch(params: ParamsOfFetch): Promise<ResultOfFetch> {
return this.client.request('debot.fetch', params);
}
/**
* [UNSTABLE](UNSTABLE.md) Executes debot action.
*
* @remarks
* Calls debot engine referenced by debot handle to execute input action.
* Calls Debot Browser Callbacks if needed.
*
* # Remarks
* Chain of actions can be executed if input action generates a list of subactions.
*
* @param {ParamsOfExecute} params
* @returns
*/
execute(params: ParamsOfExecute): Promise<void> {
return this.client.request('debot.execute', params);
}
/**
* [UNSTABLE](UNSTABLE.md) Sends message to Debot.
*
* @remarks
* Used by Debot Browser to send response on Dinterface call or from other Debots.
*
* @param {ParamsOfSend} params
* @returns
*/
send(params: ParamsOfSend): Promise<void> {
return this.client.request('debot.send', params);
}
/**
* [UNSTABLE](UNSTABLE.md) Destroys debot handle.
*
* @remarks
* Removes handle from Client Context and drops debot engine referenced by that handle.
*
* @param {ParamsOfRemove} params
* @returns
*/
remove(params: ParamsOfRemove): Promise<void> {
return this.client.request('debot.remove', params);
}
} | the_stack |
import { KnownMediaType } from '@azure-tools/codemodel-v3';
import { camelCase, deconstruct, nameof } from '@azure-tools/codegen';
import { IsNotNull } from '@azure-tools/codegen-csharp';
import { dotnet, System } from '@azure-tools/codegen-csharp';
import { Expression, ExpressionOrLiteral, toExpression, valueOf } from '@azure-tools/codegen-csharp';
import { ForEach } from '@azure-tools/codegen-csharp';
import { If } from '@azure-tools/codegen-csharp';
import { OneOrMoreStatements } from '@azure-tools/codegen-csharp';
import { Ternery } from '@azure-tools/codegen-csharp';
import { LocalVariable, Variable } from '@azure-tools/codegen-csharp';
import { ClientRuntime } from '../clientruntime';
import { Schema } from '../code-model';
import { Schema as NewSchema } from '@azure-tools/codemodel';
import { popTempVar, pushTempVar } from '../schema/primitive';
import { EnhancedTypeDeclaration } from './extended-type-declaration';
export class ArrayOf implements EnhancedTypeDeclaration {
public isXmlAttribute = false;
public isNullable = true;
get defaultOfType() {
return toExpression('null /* arrayOf */');
}
constructor(public schema: NewSchema, public isRequired: boolean, public elementType: EnhancedTypeDeclaration, protected minItems: number | undefined, protected maxItems: number | undefined, protected unique: boolean | undefined) {
}
protected get isWrapped(): boolean {
return this.schema.serialization?.xml && this.schema.serialization?.xml.wrapped || false;
}
protected get wrapperName(): string | undefined {
return this.schema.serialization?.xml && this.isWrapped ? this.schema.serialization.xml.name : undefined;
}
protected get serializedName(): string | undefined {
return this.schema.serialization?.xml ? this.schema.serialization.xml.name : undefined;
}
get elementTypeDeclaration(): string {
return this.elementType.declaration;
}
get declaration(): string {
return `${this.elementType.declaration}[]`;
}
get encode(): string {
this.schema.extensions = this.schema.extensions || {};
return this.schema.extensions['x-ms-skip-url-encoding'] ? '' : 'global::System.Uri.EscapeDataString';
}
get convertObjectMethod() {
try {
const v = pushTempVar();
const i = pushTempVar();
// return `${v} => ${v} is string || !(${v} is global::System.Collections.IEnumerable) ? new ${this.declaration} { ${this.elementType.convertObjectMethod}(${v}) } : System.Linq.Enumerable.ToArray( System.Linq.Enumerable.Select( System.Linq.Enumerable.OfType<object>((global::System.Collections.IEnumerable)${v}), ${this.elementType.convertObjectMethod}))`
return `${v} => TypeConverterExtensions.SelectToArray<${this.elementTypeDeclaration}>(${v}, ${this.elementType.convertObjectMethod})`;
} finally {
popTempVar();
popTempVar();
}
}
/** emits an expression to deserialize a property from a member inside a container */
deserializeFromContainerMember(mediaType: KnownMediaType, container: ExpressionOrLiteral, serializedName: string, defaultValue: Expression): Expression {
switch (mediaType) {
case KnownMediaType.Json: {
// json array
const tmp = `__${camelCase(['json', ...deconstruct(serializedName)])}`;
return toExpression(`If( ${valueOf(container)}?.PropertyT<${ClientRuntime.JsonArray}>("${serializedName}"), out var ${tmp}) ? ${this.deserializeFromNode(mediaType, tmp, toExpression('null'))} : ${defaultValue}`);
}
case KnownMediaType.Xml: {
// XElement/XElement
const tmp = `__${camelCase(['xml', ...deconstruct(serializedName)])}`;
if (this.isWrapped) {
// wrapped xml arrays will have a container around them.
return toExpression(`${this.deserializeFromNode(mediaType, `${valueOf(container)}?.Element("${this.serializedName || serializedName}")`, defaultValue)}`);
} else {
// whereas non-wrapped will have all the elements in the container directly.
return toExpression(`${this.deserializeFromNode(mediaType, `${valueOf(container)}`, defaultValue)}`);
}
}
}
return toExpression(`null /* deserializeFromContainerMember doesn't support '${mediaType}' ${__filename}*/`);
}
/** emits an expression to deserialze a container as the value itself. */
deserializeFromNode(mediaType: KnownMediaType, node: ExpressionOrLiteral, defaultValue: Expression): Expression {
try {
const tmp = pushTempVar();
const each = pushTempVar();
switch (mediaType) {
case KnownMediaType.Json: {
// const deser = `System.Linq.Enumerable.ToArray(System.Linq.Enumerable.Select( ${tmp} , (${each})=>(${this.elementType.declaration}) (${this.elementType.deserializeFromNode(mediaType, each, this.elementType.defaultOfType)}) ) )`;
const deser = System.Linq.Enumerable.ToArray(System.Linq.Enumerable.Select(tmp, `(${each})=>(${this.elementType.declaration}) (${this.elementType.deserializeFromNode(mediaType, each, this.elementType.defaultOfType)}`));
return toExpression(`If( ${valueOf(node)} as ${ClientRuntime.JsonArray}, out var ${tmp}) ? ${System.Func(this).new(`()=> ${valueOf(deser)} )`)}() : ${defaultValue}`);
}
case KnownMediaType.Xml: {
// XElement should be a container of items, right?
// if the reference doesn't define an XML schema then use its default name
//const defaultName = this.elementType.schema.details.csharp.name;
//const deser = `System.Linq.Enumerable.ToArray(System.Linq.Enumerable.Select( ${tmp}.Elements("${this.elementType.schema.xml ? this.elementType.schema.xml.name || defaultName : defaultName}"), (${each})=> ${this.elementType.deserializeFromNode(mediaType, each, toExpression('null'))} ) )`;
//return toExpression(`If( ${valueOf(node)}, out var ${tmp}) ? new System.Func<${this.elementType.declaration}[]>(()=> ${deser} )() : ${defaultValue}`);
}
}
} finally {
popTempVar();
popTempVar();
}
return toExpression(`null /* deserializeFromNode doesn't support '${mediaType}' ${__filename}*/`);
}
/** emits an expression to deserialize content from a string */
deserializeFromString(mediaType: KnownMediaType, content: ExpressionOrLiteral, defaultValue: Expression): Expression | undefined {
switch (mediaType) {
case KnownMediaType.Json: {
return this.deserializeFromNode(mediaType, ClientRuntime.JsonArray.Parse(content), defaultValue);
}
case KnownMediaType.Xml: {
return this.deserializeFromNode(mediaType, `${System.Xml.Linq.XElement}.Parse(${content})`, defaultValue);
}
}
return undefined;
}
/** emits an expression to deserialize content from a content/response */
deserializeFromResponse(mediaType: KnownMediaType, content: ExpressionOrLiteral, defaultValue: Expression): Expression | undefined {
switch (mediaType) {
case KnownMediaType.Xml:
case KnownMediaType.Json: {
return toExpression(`${content}.Content.ReadAsStringAsync().ContinueWith( body => ${this.deserializeFromString(mediaType, 'body.Result', defaultValue)})`);
}
}
return toExpression(`null /* deserializeFromResponse doesn't support '${mediaType}' ${__filename}*/`);
}
/** emits an expression serialize this to a HttpContent */
serializeToNode(mediaType: KnownMediaType, value: ExpressionOrLiteral, serializedName: string, mode: Expression): Expression {
try {
const each = pushTempVar();
switch (mediaType) {
case KnownMediaType.Json: {
const serArray = `global::System.Linq.Enumerable.ToArray(System.Linq.Enumerable.Select(${value}, (${each}) => ${this.elementType.serializeToNode(mediaType, each, serializedName, mode)}))`;
return toExpression(`null != ${value} ? new ${ClientRuntime.XNodeArray}(${serArray}) : null`);
}
case KnownMediaType.Xml: {
if (this.isWrapped) {
const name = this.elementType.schema.serialization?.xml ? this.elementType.schema.serialization?.xml.name || serializedName : serializedName;
return toExpression(`null != ${value} ? global::new System.Xml.Linq.XElement("${name}", global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(${value}, (${each}) => ${this.elementType.serializeToNode(mediaType, each, name, mode)}))`);
} else {
throw new Error('Can\'t set an Xml Array to the document without wrapping it.');
}
}
case KnownMediaType.Cookie:
case KnownMediaType.QueryParameter:
return toExpression(`(null != ${value} && ${value}.Length > 0 ? "${serializedName}=" + ${this.encode}(global::System.Linq.Enumerable.Aggregate(${value}, (current, each) => current + "," + ( ${this.encode}(each?.ToString()??${System.String.Empty}) ))) : ${System.String.Empty})`);
case KnownMediaType.Header:
case KnownMediaType.Text:
case KnownMediaType.UriParameter:
return toExpression(`(null != ${value} ? ${this.encode}(global::System.Linq.Enumerable.Aggregate(${value}, (current,each)=> current + "," + ${this.elementType.serializeToNode(mediaType, 'each', '', mode)})) : ${System.String.Empty})`);
}
} finally {
popTempVar();
}
return toExpression(`null /* serializeToNode doesn't support '${mediaType}' ${__filename}*/`);
}
/** emits an expression serialize this to the value required by the container */
serializeToContent(mediaType: KnownMediaType, value: ExpressionOrLiteral, mode: Expression): Expression {
try {
const each = pushTempVar();
switch (mediaType) {
case KnownMediaType.Json: {
return System.Net.Http.StringContent.new(
`${(this.serializeToNode(mediaType, value, '', mode))}`,
System.Text.Encoding.UTF8);
}
case KnownMediaType.Xml: {
// if the reference doesn't define an XML schema then use its default name
const defaultName = this.elementType.schema.language.csharp?.name || '';
return System.Net.Http.StringContent.new(Ternery(
IsNotNull(value),
`${this.serializeToNode(mediaType, value, this.schema.serialization?.xml ? this.schema.serialization.xml?.name || defaultName : defaultName, mode)}).ToString()`,
System.String.Empty
), System.Text.Encoding.UTF8);
}
case KnownMediaType.Cookie:
case KnownMediaType.QueryParameter:
case KnownMediaType.Header:
case KnownMediaType.Text:
case KnownMediaType.UriParameter:
return toExpression(`(null != ${value} ? ${this.encode}(System.Linq.Enumerable.Aggregate(${value}, (current,each)=> current + "," + ${this.elementType.serializeToNode(mediaType, 'each', '', mode)})) : ${System.String.Empty})`);
}
} finally {
popTempVar();
}
return toExpression(`null /* serializeToContent doesn't support '${mediaType}' ${__filename}*/`);
}
/** emits the code required to serialize this into a container */
serializeToContainerMember(mediaType: KnownMediaType, value: ExpressionOrLiteral, container: Variable, serializedName: string, mode: Expression): OneOrMoreStatements {
try {
const each = pushTempVar();
const tmp = pushTempVar();
switch (mediaType) {
case KnownMediaType.Json: {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const $this = this;
return If(`null != ${value}`, function* () {
const t = new LocalVariable(tmp, dotnet.Var, { initializer: `new ${ClientRuntime.XNodeArray}()` });
yield t.declarationStatement;
yield ForEach(each, toExpression(value), `AddIf(${$this.elementType.serializeToNode(mediaType, each, '', mode)} ,${tmp}.Add);`);
yield `${container}.Add("${serializedName}",${tmp});`;
});
}
case KnownMediaType.Xml:
if (this.isWrapped) {
return `AddIf( ${System.Xml.Linq.XElement.new('"{this.serializedName || serializedName}"', `${this.serializeToNode(mediaType, value, this.elementType.schema.serialization?.xml ? this.elementType.schema.serialization?.xml.name || '!!!' : serializedName, mode)}):null`)}, ${container}.Add); `;
} else {
return If(`null != ${value}`, ForEach(each, toExpression(value), `AddIf(${this.elementType.serializeToNode(mediaType, each, serializedName, mode)}, ${container}.Add);`));
}
}
} finally {
popTempVar();
popTempVar();
}
return (`/* serializeToContainerMember doesn't support '${mediaType}' ${__filename}*/`);
}
public validatePresence(eventListener: Variable, property: Variable): OneOrMoreStatements {
if (this.isRequired) {
return `await ${eventListener}.AssertNotNull(${nameof(property.value)}, ${property}); `;
}
return '';
}
validateValue(eventListener: Variable, property: Variable): OneOrMoreStatements {
// check if the underlyingType has validation.
if (!this.elementType.validateValue(eventListener, new LocalVariable(`${property} [{ __i }]`, dotnet.Var))) {
return '';
}
return `
if (${ property} != null ) {
for (int __i = 0; __i < ${ property}.Length; __i++) {
${ this.elementType.validateValue(eventListener, new LocalVariable(`${property}[__i]`, dotnet.Var))}
}
}
`.trim();
}
} | the_stack |
import { filter, isArray, isEqual, isUndefined, pick, pickBy, unionBy } from "lodash"
export enum FilterDisplayName {
// artist = "Artists",
additionalGeneIDs = "Medium",
artistIDs = "Artists",
artistNationalities = "Nationality & Ethnicity",
artistsIFollow = "Artist",
attributionClass = "Rarity",
categories = "Medium",
colors = "Color",
estimateRange = "Price/Estimate Range",
locationCities = "Artwork Location",
materialsTerms = "Material",
medium = "Medium",
organizations = "Auction House",
partnerIDs = "Galleries & Institutions",
priceRange = "Price",
sizes = "Size",
sort = "Sort By",
timePeriod = "Time Period",
viewAs = "View as",
waysToBuy = "Ways to Buy",
year = "Artwork Date",
}
// General filter types and objects
export enum FilterParamName {
additionalGeneIDs = "additionalGeneIDs",
allowEmptyCreatedDates = "allowEmptyCreatedDates",
artistIDs = "artistIDs",
artistNationalities = "artistNationalities",
artistsIFollow = "includeArtworksByFollowedArtists",
attributionClass = "attributionClass",
categories = "categories",
colors = "colors",
earliestCreatedYear = "earliestCreatedYear",
estimateRange = "estimateRange",
height = "height",
keyword = "keyword",
latestCreatedYear = "latestCreatedYear",
locationCities = "locationCities",
materialsTerms = "materialsTerms",
medium = "medium",
organizations = "organizations",
partnerIDs = "partnerIDs",
priceRange = "priceRange",
sizes = "sizes",
sort = "sort",
timePeriod = "majorPeriods",
viewAs = "viewAs",
waysToBuyBid = "atAuction",
waysToBuyBuy = "acquireable",
waysToBuyInquire = "inquireableOnly",
waysToBuyMakeOffer = "offerable",
width = "width",
}
// Types for the parameters passed to Relay
export type FilterParams = {
[Name in FilterParamName]: string | number | boolean | undefined | string[]
}
export enum ViewAsValues {
Grid = "grid",
List = "list",
}
export const getSortDefaultValueByFilterType = (filterType: FilterType) => {
return {
artwork: "-decayed_merch",
saleArtwork: "position",
showArtwork: "partner_show_position",
auctionResult: "DATE_DESC",
geneArtwork: "-partner_updated_at",
tagArtwork: "-partner_updated_at",
local: "",
}[filterType]
}
export const ParamDefaultValues = {
acquireable: false,
additionalGeneIDs: [],
allowEmptyCreatedDates: true,
artistIDs: [],
artistNationalities: [],
atAuction: false,
attributionClass: [],
categories: undefined,
colors: [],
earliestCreatedYear: undefined,
estimateRange: "",
height: "*-*",
includeArtworksByFollowedArtists: false,
inquireableOnly: false,
latestCreatedYear: undefined,
locationCities: [],
majorPeriods: [],
materialsTerms: [],
medium: "*",
keyword: "",
offerable: false,
organizations: undefined,
partnerIDs: [],
priceRange: "*-*",
sizes: [],
sortArtworks: "-decayed_merch",
sortSaleArtworks: "position",
viewAs: ViewAsValues.Grid,
width: "*-*",
}
export const defaultCommonFilterOptions = {
acquireable: ParamDefaultValues.acquireable,
additionalGeneIDs: ParamDefaultValues.additionalGeneIDs,
allowEmptyCreatedDates: ParamDefaultValues.allowEmptyCreatedDates,
artistIDs: ParamDefaultValues.artistIDs,
artistNationalities: ParamDefaultValues.artistNationalities,
atAuction: ParamDefaultValues.atAuction,
attributionClass: ParamDefaultValues.attributionClass,
categories: ParamDefaultValues.categories,
colors: ParamDefaultValues.colors,
earliestCreatedYear: ParamDefaultValues.earliestCreatedYear,
estimateRange: ParamDefaultValues.estimateRange,
height: ParamDefaultValues.height,
keyword: ParamDefaultValues.keyword,
includeArtworksByFollowedArtists: ParamDefaultValues.includeArtworksByFollowedArtists,
inquireableOnly: ParamDefaultValues.inquireableOnly,
latestCreatedYear: ParamDefaultValues.latestCreatedYear,
locationCities: ParamDefaultValues.locationCities,
majorPeriods: ParamDefaultValues.majorPeriods,
materialsTerms: ParamDefaultValues.materialsTerms,
medium: ParamDefaultValues.medium,
offerable: ParamDefaultValues.offerable,
organizations: ParamDefaultValues.organizations,
partnerIDs: ParamDefaultValues.partnerIDs,
priceRange: ParamDefaultValues.priceRange,
sizes: ParamDefaultValues.sizes,
sort: ParamDefaultValues.sortArtworks,
viewAs: ParamDefaultValues.viewAs,
width: ParamDefaultValues.width,
}
export type Aggregations = Array<{
slice: AggregationName
counts: Aggregation[]
}>
/**
* Possible aggregations that can be passed
*/
export type AggregationName =
| "ARTIST_NATIONALITY"
| "ARTIST"
| "COLOR"
| "DIMENSION_RANGE"
| "earliestCreatedYear"
| "FOLLOWED_ARTISTS"
| "latestCreatedYear"
| "LOCATION_CITY"
| "MAJOR_PERIOD"
| "MATERIALS_TERMS"
| "MEDIUM"
| "PARTNER"
| "PRICE_RANGE"
export interface Aggregation {
count: number
value: string
name: string
}
export interface FilterData {
readonly displayText: string
readonly paramName: FilterParamName
paramValue?: string | number | boolean | string[]
filterKey?: string // gallery and institution share a paramName so need to distinguish
count?: number | null // aggregations count
localSortAndFilter?: (items: any[], value?: any | null) => any[]
}
export type FilterArray = ReadonlyArray<FilterData>
export type FilterType =
| "artwork"
| "saleArtwork"
| "showArtwork"
| "auctionResult"
| "geneArtwork"
| "tagArtwork"
| "local"
export interface FilterCounts {
total: number | null
followedArtists: number | null
}
export type SelectedFiltersCounts = {
[Name in FilterParamName | "waysToBuy" | "year"]: number
}
export const filterKeyFromAggregation: Record<AggregationName, FilterParamName | string | undefined> = {
ARTIST_NATIONALITY: FilterParamName.artistNationalities,
ARTIST: "artistIDs",
COLOR: FilterParamName.colors,
DIMENSION_RANGE: FilterParamName.sizes,
earliestCreatedYear: "earliestCreatedYear",
FOLLOWED_ARTISTS: "artistsIFollow",
latestCreatedYear: "earliestCreatedYear",
LOCATION_CITY: FilterParamName.locationCities,
MAJOR_PERIOD: FilterParamName.timePeriod,
MATERIALS_TERMS: FilterParamName.materialsTerms,
MEDIUM: FilterParamName.additionalGeneIDs,
PARTNER: FilterParamName.partnerIDs,
PRICE_RANGE: FilterParamName.priceRange,
}
const DEFAULT_ARTWORKS_PARAMS = {
acquireable: false,
atAuction: false,
categories: undefined, // TO check
estimateRange: "",
inquireableOnly: false,
medium: "*",
offerable: false,
priceRange: "*-*",
sort: "-decayed_merch",
includeArtworksByFollowedArtists: false,
} as FilterParams
const DEFAULT_SALE_ARTWORKS_PARAMS = {
sort: "position",
estimateRange: "",
} as FilterParams
const DEFAULT_SHOW_ARTWORKS_PARAMS = {
...DEFAULT_ARTWORKS_PARAMS,
sort: "partner_show_position",
}
const DEFAULT_AUCTION_RESULT_PARAMS = {
sort: "DATE_DESC",
allowEmptyCreatedDates: true,
} as FilterParams
const DEFAULT_GENE_ARTWORK_PARAMS = {
sort: "-partner_updated_at",
priceRange: "*-*",
medium: "*",
} as FilterParams
const DEFAULT_TAG_ARTWORK_PARAMS = {
...DEFAULT_ARTWORKS_PARAMS,
sort: "-partner_updated_at",
} as FilterParams
const createdYearsFilterNames = [FilterParamName.earliestCreatedYear, FilterParamName.latestCreatedYear]
const sizesFilterNames = [FilterParamName.width, FilterParamName.height]
const waysToBuyFilterNames = [
FilterParamName.waysToBuyBuy,
FilterParamName.waysToBuyMakeOffer,
FilterParamName.waysToBuyBid,
FilterParamName.waysToBuyInquire,
]
const getDefaultParamsByType = (filterType: FilterType) => {
return {
artwork: DEFAULT_ARTWORKS_PARAMS,
saleArtwork: DEFAULT_SALE_ARTWORKS_PARAMS,
showArtwork: DEFAULT_SHOW_ARTWORKS_PARAMS,
auctionResult: DEFAULT_AUCTION_RESULT_PARAMS,
geneArtwork: DEFAULT_GENE_ARTWORK_PARAMS,
tagArtwork: DEFAULT_TAG_ARTWORK_PARAMS,
local: DEFAULT_ARTWORKS_PARAMS,
}[filterType]
}
export const changedFiltersParams = (currentFilterParams: FilterParams, selectedFilterOptions: FilterArray) => {
const changedFilters: { [key: string]: any } = {}
selectedFilterOptions.forEach((selectedFilterOption) => {
const { paramName, paramValue } = selectedFilterOption
const currentFilterParamValue = currentFilterParams[paramName]
if (currentFilterParamValue && isEqual(paramValue, currentFilterParamValue)) {
return
}
changedFilters[paramName] = paramValue
})
return changedFilters
}
export const filterArtworksParams = (appliedFilters: FilterArray, filterType: FilterType = "artwork") => {
const defaultFilterParams = getDefaultParamsByType(filterType)
const appliedFilterParams: Partial<FilterParams> = {}
appliedFilters.forEach((filterParam) => {
appliedFilterParams[filterParam.paramName] = filterParam.paramValue
})
return {
...defaultFilterParams,
...appliedFilterParams,
}
}
// For most cases filter key can simply be FilterParamName, exception
// is gallery and institution which share a paramName in metaphysics
export const aggregationNameFromFilter: Record<string, AggregationName | undefined> = {
artistIDs: "ARTIST",
artistNationalities: "ARTIST_NATIONALITY",
artistsIFollow: "FOLLOWED_ARTISTS",
colors: "COLOR",
sizes: "DIMENSION_RANGE",
earliestCreatedYear: "earliestCreatedYear",
latestCreatedYear: "latestCreatedYear",
locationCities: "LOCATION_CITY",
majorPeriods: "MAJOR_PERIOD",
materialsTerms: "MATERIALS_TERMS",
medium: "MEDIUM",
additionalGeneIDs: "MEDIUM",
partnerIDs: "PARTNER",
priceRange: "PRICE_RANGE",
}
export const aggregationForFilter = (filterKey: string, aggregations: Aggregations) => {
const aggregationName = aggregationNameFromFilter[filterKey]
const aggregation = aggregations!.find((value) => value.slice === aggregationName)
return aggregation
}
export interface AggregateOption {
displayText: string
paramValue: string
}
export type aggregationsType =
| ReadonlyArray<{
slice: string
counts: Array<{ count: number; value: string; name?: string }>
}>
| []
export const aggregationsWithFollowedArtists = (
followedArtistCount: number,
artworkAggregations: aggregationsType
): aggregationsType => {
const followedArtistAggregation =
followedArtistCount > 0
? [
{
slice: "FOLLOWED_ARTISTS",
counts: [{ count: followedArtistCount, value: "followed_artists" }],
},
]
: []
return [...artworkAggregations, ...followedArtistAggregation]
}
export const getDisplayNameForTimePeriod = (aggregationName: string) => {
const DISPLAY_TEXT: Record<string, string> = {
"2020": "2020–Today",
"2010": "2010–2019",
"2000": "2000–2009",
"1990": "1990–1999",
"1980": "1980–1989",
"1970": "1970–1979",
"1960": "1960–1969",
"1950": "1950–1959",
"1940": "1940–1949",
"1930": "1930–1939",
"1920": "1920–1929",
"1910": "1910–1919",
"1900": "1900–1909",
}
return DISPLAY_TEXT[aggregationName] ?? aggregationName
}
export const prepareFilterArtworksParamsForInput = (filters: FilterParams) => {
return pick(filters, [
"acquireable",
"additionalGeneIDs",
"after",
"aggregationPartnerCities",
"aggregations",
"artistID",
"artistIDs",
"artistNationalities",
"artistSeriesID",
"atAuction",
"attributionClass",
"before",
"colors",
"excludeArtworkIDs",
"extraAggregationGeneIDs",
"first",
"forSale",
"geneID",
"geneIDs",
"height",
"includeArtworksByFollowedArtists",
"includeMediumFilterInAggregation",
"inquireableOnly",
"keyword",
"keywordMatchExact",
"last",
"locationCities",
"majorPeriods",
"marketable",
"materialsTerms",
"medium",
"offerable",
"page",
"partnerCities",
"partnerID",
"partnerIDs",
"period",
"dimensionRange",
"periods",
"priceRange",
"saleID",
"size",
"sizes",
"sort",
"tagID",
"width",
])
}
export const getParamsForInputByFilterType = (
initialParams: Partial<FilterParams>,
filterType: FilterType = "artwork"
) => {
const defaultInputParams = getDefaultParamsByType(filterType)
const filledInitialParams = pickBy(initialParams, (item) => !isUndefined(item)) as FilterParams
const allowedParams = prepareFilterArtworksParamsForInput({
...defaultInputParams,
...filledInitialParams,
})
return allowedParams
}
export const getUnitedSelectedAndAppliedFilters = ({
filterType,
selectedFilters,
previouslyAppliedFilters,
}: {
filterType: FilterType
selectedFilters: FilterArray
previouslyAppliedFilters: FilterArray
}) => {
const defaultFilterOptions = {
...defaultCommonFilterOptions,
sort: getSortDefaultValueByFilterType(filterType),
}
// replace previously applied options with currently selected options
const filtersToUnite = unionBy(selectedFilters, previouslyAppliedFilters, "paramName")
const unitedFilters = filter(filtersToUnite, ({ paramName, paramValue }) => {
// The default sorting and lot ascending sorting at the saleArtwork filterType has the same paramValue
// with a different displayText, we want to make sure that the user can still switch between the two.
if (paramName === FilterParamName.sort && filterType === "saleArtwork") {
return true
}
return !isEqual((defaultFilterOptions as any)[paramName], paramValue)
})
return unitedFilters
}
export const getSelectedFiltersCounts = (selectedFilters: FilterArray) => {
const counts: Partial<SelectedFiltersCounts> = {}
selectedFilters.forEach(({ paramName, paramValue }: FilterData) => {
switch (true) {
case waysToBuyFilterNames.includes(paramName): {
counts.waysToBuy = (counts.waysToBuy ?? 0) + 1
break
}
case createdYearsFilterNames.includes(paramName): {
counts.year = 1
break
}
case sizesFilterNames.includes(paramName): {
const prevCountValue = counts.sizes ?? 0
counts.sizes = prevCountValue + 1
break
}
case paramName === FilterParamName.artistsIFollow: {
counts.artistIDs = (counts.artistIDs ?? 0) + 1
break
}
case isArray(paramValue): {
const isArtistsFilter = paramName === FilterParamName.artistIDs
const countToAdd = isArtistsFilter ? counts.artistIDs ?? 0 : 0
counts[paramName] = (paramValue as []).length + countToAdd
break
}
default: {
counts[paramName] = 1
}
}
})
return counts
} | the_stack |
import * as types from "../shared/types"
import * as common from "../shared/common"
import * as denoflate from "https://deno.land/x/denoflate@1.2.1/mod.ts"
declare const ESBUILD_VERSION: string
export let version = ESBUILD_VERSION
export let build: typeof types.build = (options: types.BuildOptions): Promise<any> =>
ensureServiceIsRunning().then(service =>
service.build(options))
export const serve: typeof types.serve = (serveOptions, buildOptions) =>
ensureServiceIsRunning().then(service =>
service.serve(serveOptions, buildOptions))
export const transform: typeof types.transform = (input, options) =>
ensureServiceIsRunning().then(service =>
service.transform(input, options))
export const formatMessages: typeof types.formatMessages = (messages, options) =>
ensureServiceIsRunning().then(service =>
service.formatMessages(messages, options))
export const buildSync: typeof types.buildSync = () => {
throw new Error(`The "buildSync" API does not work in Deno`)
}
export const transformSync: typeof types.transformSync = () => {
throw new Error(`The "transformSync" API does not work in Deno`)
}
export const formatMessagesSync: typeof types.formatMessagesSync = () => {
throw new Error(`The "formatMessagesSync" API does not work in Deno`)
}
export const stop = () => {
if (stopService) stopService()
}
let initializeWasCalled = false
export const initialize: typeof types.initialize = async (options) => {
options = common.validateInitializeOptions(options || {})
if (options.wasmURL) throw new Error(`The "wasmURL" option only works in the browser`)
if (options.worker) throw new Error(`The "worker" option only works in the browser`)
if (initializeWasCalled) throw new Error('Cannot call "initialize" more than once')
await ensureServiceIsRunning()
initializeWasCalled = true
}
async function installFromNPM(name: string, subpath: string): Promise<string> {
const { finalPath, finalDir } = getCachePath(name)
try {
await Deno.stat(finalPath)
return finalPath
} catch (e) {
}
const url = `https://registry.npmjs.org/${name}/-/${name}-${version}.tgz`
const buffer = await fetch(url).then(r => r.arrayBuffer())
const executable = extractFileFromTarGzip(new Uint8Array(buffer), subpath)
await Deno.mkdir(finalDir, {
recursive: true,
mode: 0o700, // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
})
await Deno.writeFile(finalPath, executable, { mode: 0o755 })
return finalPath
}
function getCachePath(name: string): { finalPath: string, finalDir: string } {
let baseDir: string | undefined
switch (Deno.build.os) {
case 'darwin':
baseDir = Deno.env.get('HOME')
if (baseDir) baseDir += '/Library/Caches'
break
case 'windows':
baseDir = Deno.env.get('LOCALAPPDATA')
if (!baseDir) {
baseDir = Deno.env.get('USERPROFILE')
if (baseDir) baseDir += '/AppData/Local'
}
if (baseDir) baseDir += '/Cache'
break
case 'linux':
// https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
const xdg = Deno.env.get('XDG_CACHE_HOME')
if (xdg && xdg[0] === '/') baseDir = xdg
break
}
if (!baseDir) {
baseDir = Deno.env.get('HOME')
if (baseDir) baseDir += '/.cache'
}
if (!baseDir) throw new Error('Failed to find cache directory')
const finalDir = baseDir + `/esbuild/bin`
const finalPath = finalDir + `/${name}@${version}`
return { finalPath, finalDir }
}
function extractFileFromTarGzip(buffer: Uint8Array, file: string): Uint8Array {
try {
buffer = denoflate.gunzip(buffer)
} catch (err: any) {
throw new Error(`Invalid gzip data in archive: ${err && err.message || err}`)
}
let str = (i: number, n: number) => String.fromCharCode(...buffer.subarray(i, i + n)).replace(/\0.*$/, '')
let offset = 0
file = `package/${file}`
while (offset < buffer.length) {
let name = str(offset, 100)
let size = parseInt(str(offset + 124, 12), 8)
offset += 512
if (!isNaN(size)) {
if (name === file) return buffer.subarray(offset, offset + size)
offset += (size + 511) & ~511
}
}
throw new Error(`Could not find ${JSON.stringify(file)} in archive`)
}
async function install(): Promise<string> {
const overridePath = Deno.env.get('ESBUILD_BINARY_PATH')
if (overridePath) return overridePath
const platformKey = Deno.build.target
const knownWindowsPackages: Record<string, string> = {
'x86_64-pc-windows-msvc': 'esbuild-windows-64',
}
const knownUnixlikePackages: Record<string, string> = {
'aarch64-apple-darwin': 'esbuild-darwin-arm64',
'x86_64-apple-darwin': 'esbuild-darwin-64',
'x86_64-unknown-linux-gnu': 'esbuild-linux-64',
}
// Pick a package to install
if (platformKey in knownWindowsPackages) {
return await installFromNPM(knownWindowsPackages[platformKey], 'esbuild.exe')
} else if (platformKey in knownUnixlikePackages) {
return await installFromNPM(knownUnixlikePackages[platformKey], 'bin/esbuild')
} else {
throw new Error(`Unsupported platform: ${platformKey}`)
}
}
interface Service {
build: typeof types.build
serve: typeof types.serve
transform: typeof types.transform
formatMessages: typeof types.formatMessages
}
let defaultWD = Deno.cwd()
let longLivedService: Promise<Service> | undefined
let stopService: (() => void) | undefined
let ensureServiceIsRunning = (): Promise<Service> => {
if (!longLivedService) {
longLivedService = (async (): Promise<Service> => {
const binPath = await install()
const isTTY = Deno.isatty(Deno.stderr.rid)
const child = Deno.run({
cmd: [binPath, `--service=${version}`],
cwd: defaultWD,
stdin: 'piped',
stdout: 'piped',
stderr: 'inherit',
})
stopService = () => {
// Close all resources related to the subprocess.
child.stdin.close()
child.stdout.close()
child.close()
initializeWasCalled = false;
longLivedService = undefined;
stopService = undefined
}
let writeQueue: Uint8Array[] = []
let isQueueLocked = false
// We need to keep calling "write()" until it actually writes the data
const startWriteFromQueueWorker = () => {
if (isQueueLocked || writeQueue.length === 0) return
isQueueLocked = true
child.stdin.write(writeQueue[0]).then(bytesWritten => {
isQueueLocked = false
if (bytesWritten === writeQueue[0].length) writeQueue.shift()
else writeQueue[0] = writeQueue[0].subarray(bytesWritten)
startWriteFromQueueWorker()
})
}
const { readFromStdout, afterClose, service } = common.createChannel({
writeToStdin(bytes) {
writeQueue.push(bytes)
startWriteFromQueueWorker()
},
isSync: false,
isBrowser: false,
})
const stdoutBuffer = new Uint8Array(4 * 1024 * 1024)
const readMoreStdout = () => child.stdout.read(stdoutBuffer).then(n => {
if (n === null) {
afterClose()
} else {
readFromStdout(stdoutBuffer.subarray(0, n))
readMoreStdout()
}
}).catch(e => {
if (e instanceof Deno.errors.Interrupted || e instanceof Deno.errors.BadResource) {
// ignore the error if read was interrupted (stdout was closed)
afterClose()
} else {
throw e;
}
})
readMoreStdout()
return {
build: (options: types.BuildOptions): Promise<any> => {
return new Promise<types.BuildResult>((resolve, reject) => {
service.buildOrServe({
callName: 'build',
refs: null,
serveOptions: null,
options,
isTTY,
defaultWD,
callback: (err, res) => err ? reject(err) : resolve(res as types.BuildResult),
})
})
},
serve: (serveOptions, buildOptions) => {
if (serveOptions === null || typeof serveOptions !== 'object')
throw new Error('The first argument must be an object')
return new Promise((resolve, reject) =>
service.buildOrServe({
callName: 'serve',
refs: null,
serveOptions,
options: buildOptions,
isTTY,
defaultWD, callback: (err, res) => err ? reject(err) : resolve(res as types.ServeResult),
}))
},
transform: (input, options) => {
return new Promise((resolve, reject) =>
service.transform({
callName: 'transform',
refs: null,
input,
options: options || {},
isTTY,
fs: {
readFile(tempFile, callback) {
Deno.readFile(tempFile).then(
bytes => {
let text = new TextDecoder().decode(bytes)
try {
Deno.remove(tempFile)
} catch (e) {
}
callback(null, text)
},
err => callback(err, null),
)
},
writeFile(contents, callback) {
Deno.makeTempFile().then(
tempFile => Deno.writeFile(tempFile, new TextEncoder().encode(contents)).then(
() => callback(tempFile),
() => callback(null)),
() => callback(null))
},
},
callback: (err, res) => err ? reject(err) : resolve(res!),
}))
},
formatMessages: (messages, options) => {
return new Promise((resolve, reject) =>
service.formatMessages({
callName: 'formatMessages',
refs: null,
messages,
options,
callback: (err, res) => err ? reject(err) : resolve(res!),
}))
},
}
})()
}
return longLivedService
} | the_stack |
import { ConcreteRequest } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type ArtworkBelowTheFoldQueryVariables = {
artworkID: string;
};
export type ArtworkBelowTheFoldQueryResponse = {
readonly artwork: {
readonly " $fragmentRefs": FragmentRefs<"Artwork_artworkBelowTheFold">;
} | null;
};
export type ArtworkBelowTheFoldQuery = {
readonly response: ArtworkBelowTheFoldQueryResponse;
readonly variables: ArtworkBelowTheFoldQueryVariables;
};
/*
query ArtworkBelowTheFoldQuery(
$artworkID: String!
) {
artwork(id: $artworkID) {
...Artwork_artworkBelowTheFold
id
}
}
fragment AboutArtist_artwork on Artwork {
artists {
id
biography_blurb: biographyBlurb {
text
}
...ArtistListItem_artist
}
}
fragment AboutWork_artwork on Artwork {
additional_information: additionalInformation
description
isInAuction
}
fragment ArtistListItem_artist on Artist {
id
internalID
slug
name
initials
href
is_followed: isFollowed
nationality
birthday
deathday
image {
url
}
}
fragment ArtistSeriesMoreSeries_artist on Artist {
internalID
slug
artistSeriesConnection(first: 4) {
totalCount
edges {
node {
slug
internalID
title
featured
artworksCountMessage
image {
url
}
}
}
}
}
fragment ArtworkDetails_artwork on Artwork {
slug
category
conditionDescription {
label
details
}
signatureInfo {
label
details
}
certificateOfAuthenticity {
label
details
}
framed {
label
details
}
series
publisher
manufacturer
image_rights: imageRights
canRequestLotConditionsReport
mediumType {
__typename
}
}
fragment ArtworkGridItem_artwork on Artwork {
title
date
saleMessage
slug
internalID
artistNames
href
sale {
isAuction
isClosed
displayTimelyAt
endAt
id
}
saleArtwork {
counts {
bidderPositions
}
currentBid {
display
}
lotLabel
id
}
partner {
name
id
}
image {
url(version: "large")
aspectRatio
}
}
fragment ArtworkHistory_artwork on Artwork {
provenance
exhibition_history: exhibitionHistory
literature
}
fragment Artwork_artworkBelowTheFold on Artwork {
additional_information: additionalInformation
description
provenance
exhibition_history: exhibitionHistory
literature
partner {
type
id
}
artist {
biography_blurb: biographyBlurb {
text
}
artistSeriesConnection(first: 4) {
totalCount
}
...ArtistSeriesMoreSeries_artist
id
}
sale {
id
isBenefit
isGalleryAuction
}
category
canRequestLotConditionsReport
conditionDescription {
details
}
signature
signatureInfo {
details
}
certificateOfAuthenticity {
details
}
framed {
details
}
series
publisher
manufacturer
image_rights: imageRights
context {
__typename
... on Sale {
isAuction
}
... on Node {
__isNode: __typename
id
}
}
contextGrids {
__typename
artworks: artworksConnection(first: 6) {
edges {
node {
id
}
}
}
}
artistSeriesConnection(first: 1) {
edges {
node {
filterArtworksConnection(first: 20, input: {sort: "-decayed_merch"}) {
edges {
node {
id
}
}
id
}
}
}
}
...PartnerCard_artwork
...AboutWork_artwork
...OtherWorks_artwork
...AboutArtist_artwork
...ArtworkDetails_artwork
...ContextCard_artwork
...ArtworkHistory_artwork
...ArtworksInSeriesRail_artwork
}
fragment ArtworksInSeriesRail_artwork on Artwork {
internalID
slug
artistSeriesConnection(first: 1) {
edges {
node {
slug
internalID
filterArtworksConnection(first: 20, input: {sort: "-decayed_merch"}) {
edges {
node {
slug
internalID
href
artistNames
image {
imageURL
aspectRatio
}
sale {
isAuction
isClosed
displayTimelyAt
id
}
saleArtwork {
counts {
bidderPositions
}
currentBid {
display
}
id
}
saleMessage
title
date
partner {
name
id
}
id
}
}
id
}
}
}
}
}
fragment ContextCard_artwork on Artwork {
id
context {
__typename
... on Sale {
id
name
isLiveOpen
href
formattedStartDateTime
isAuction
coverImage {
url
}
}
... on Fair {
id
name
href
exhibitionPeriod(format: SHORT)
image {
url
}
}
... on Show {
id
internalID
slug
name
href
exhibitionPeriod(format: SHORT)
isFollowed
coverImage {
url
}
}
... on Node {
__isNode: __typename
id
}
}
}
fragment GenericGrid_artworks on Artwork {
id
image {
aspect_ratio: aspectRatio
}
...ArtworkGridItem_artwork
}
fragment OtherWorks_artwork on Artwork {
contextGrids {
__typename
title
ctaTitle
ctaHref
artworks: artworksConnection(first: 6) {
edges {
node {
...GenericGrid_artworks
id
}
}
}
}
}
fragment PartnerCard_artwork on Artwork {
sale {
isBenefit
isGalleryAuction
id
}
partner {
cities
is_default_profile_public: isDefaultProfilePublic
type
name
slug
id
href
initials
profile {
id
internalID
is_followed: isFollowed
icon {
url(version: "square140")
}
}
}
}
*/
const node: ConcreteRequest = (function(){
var v0 = [
{
"defaultValue": null,
"kind": "LocalArgument",
"name": "artworkID"
}
],
v1 = [
{
"kind": "Variable",
"name": "id",
"variableName": "artworkID"
}
],
v2 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
},
v3 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "name",
"storageKey": null
},
v4 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "slug",
"storageKey": null
},
v5 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "href",
"storageKey": null
},
v6 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "initials",
"storageKey": null
},
v7 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "internalID",
"storageKey": null
},
v8 = {
"alias": "is_followed",
"args": null,
"kind": "ScalarField",
"name": "isFollowed",
"storageKey": null
},
v9 = {
"alias": "biography_blurb",
"args": null,
"concreteType": "ArtistBlurb",
"kind": "LinkedField",
"name": "biographyBlurb",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "text",
"storageKey": null
}
],
"storageKey": null
},
v10 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "title",
"storageKey": null
},
v11 = [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "url",
"storageKey": null
}
],
v12 = {
"alias": null,
"args": null,
"concreteType": "Image",
"kind": "LinkedField",
"name": "image",
"plural": false,
"selections": (v11/*: any*/),
"storageKey": null
},
v13 = [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "details",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "label",
"storageKey": null
}
],
v14 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "__typename",
"storageKey": null
},
v15 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "isAuction",
"storageKey": null
},
v16 = {
"alias": null,
"args": null,
"concreteType": "Image",
"kind": "LinkedField",
"name": "coverImage",
"plural": false,
"selections": (v11/*: any*/),
"storageKey": null
},
v17 = {
"alias": null,
"args": [
{
"kind": "Literal",
"name": "format",
"value": "SHORT"
}
],
"kind": "ScalarField",
"name": "exhibitionPeriod",
"storageKey": "exhibitionPeriod(format:\"SHORT\")"
},
v18 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "aspectRatio",
"storageKey": null
},
v19 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "date",
"storageKey": null
},
v20 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "saleMessage",
"storageKey": null
},
v21 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "artistNames",
"storageKey": null
},
v22 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "isClosed",
"storageKey": null
},
v23 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "displayTimelyAt",
"storageKey": null
},
v24 = {
"alias": null,
"args": null,
"concreteType": "SaleArtworkCounts",
"kind": "LinkedField",
"name": "counts",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "bidderPositions",
"storageKey": null
}
],
"storageKey": null
},
v25 = {
"alias": null,
"args": null,
"concreteType": "SaleArtworkCurrentBid",
"kind": "LinkedField",
"name": "currentBid",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "display",
"storageKey": null
}
],
"storageKey": null
},
v26 = {
"alias": null,
"args": null,
"concreteType": "Partner",
"kind": "LinkedField",
"name": "partner",
"plural": false,
"selections": [
(v3/*: any*/),
(v2/*: any*/)
],
"storageKey": null
};
return {
"fragment": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Fragment",
"metadata": null,
"name": "ArtworkBelowTheFoldQuery",
"selections": [
{
"alias": null,
"args": (v1/*: any*/),
"concreteType": "Artwork",
"kind": "LinkedField",
"name": "artwork",
"plural": false,
"selections": [
{
"args": null,
"kind": "FragmentSpread",
"name": "Artwork_artworkBelowTheFold"
}
],
"storageKey": null
}
],
"type": "Query",
"abstractKey": null
},
"kind": "Request",
"operation": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Operation",
"name": "ArtworkBelowTheFoldQuery",
"selections": [
{
"alias": null,
"args": (v1/*: any*/),
"concreteType": "Artwork",
"kind": "LinkedField",
"name": "artwork",
"plural": false,
"selections": [
{
"alias": "additional_information",
"args": null,
"kind": "ScalarField",
"name": "additionalInformation",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "description",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "provenance",
"storageKey": null
},
{
"alias": "exhibition_history",
"args": null,
"kind": "ScalarField",
"name": "exhibitionHistory",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "literature",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Partner",
"kind": "LinkedField",
"name": "partner",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "type",
"storageKey": null
},
(v2/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "cities",
"storageKey": null
},
{
"alias": "is_default_profile_public",
"args": null,
"kind": "ScalarField",
"name": "isDefaultProfilePublic",
"storageKey": null
},
(v3/*: any*/),
(v4/*: any*/),
(v5/*: any*/),
(v6/*: any*/),
{
"alias": null,
"args": null,
"concreteType": "Profile",
"kind": "LinkedField",
"name": "profile",
"plural": false,
"selections": [
(v2/*: any*/),
(v7/*: any*/),
(v8/*: any*/),
{
"alias": null,
"args": null,
"concreteType": "Image",
"kind": "LinkedField",
"name": "icon",
"plural": false,
"selections": [
{
"alias": null,
"args": [
{
"kind": "Literal",
"name": "version",
"value": "square140"
}
],
"kind": "ScalarField",
"name": "url",
"storageKey": "url(version:\"square140\")"
}
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Artist",
"kind": "LinkedField",
"name": "artist",
"plural": false,
"selections": [
(v9/*: any*/),
{
"alias": null,
"args": [
{
"kind": "Literal",
"name": "first",
"value": 4
}
],
"concreteType": "ArtistSeriesConnection",
"kind": "LinkedField",
"name": "artistSeriesConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "totalCount",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "ArtistSeriesEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "ArtistSeries",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
(v4/*: any*/),
(v7/*: any*/),
(v10/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "featured",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "artworksCountMessage",
"storageKey": null
},
(v12/*: any*/)
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": "artistSeriesConnection(first:4)"
},
(v7/*: any*/),
(v4/*: any*/),
(v2/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Sale",
"kind": "LinkedField",
"name": "sale",
"plural": false,
"selections": [
(v2/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "isBenefit",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "isGalleryAuction",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "category",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "canRequestLotConditionsReport",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "ArtworkInfoRow",
"kind": "LinkedField",
"name": "conditionDescription",
"plural": false,
"selections": (v13/*: any*/),
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "signature",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "ArtworkInfoRow",
"kind": "LinkedField",
"name": "signatureInfo",
"plural": false,
"selections": (v13/*: any*/),
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "ArtworkInfoRow",
"kind": "LinkedField",
"name": "certificateOfAuthenticity",
"plural": false,
"selections": (v13/*: any*/),
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "ArtworkInfoRow",
"kind": "LinkedField",
"name": "framed",
"plural": false,
"selections": (v13/*: any*/),
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "series",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "publisher",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "manufacturer",
"storageKey": null
},
{
"alias": "image_rights",
"args": null,
"kind": "ScalarField",
"name": "imageRights",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "context",
"plural": false,
"selections": [
(v14/*: any*/),
{
"kind": "InlineFragment",
"selections": [
(v15/*: any*/),
(v2/*: any*/),
(v3/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "isLiveOpen",
"storageKey": null
},
(v5/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "formattedStartDateTime",
"storageKey": null
},
(v16/*: any*/)
],
"type": "Sale",
"abstractKey": null
},
{
"kind": "InlineFragment",
"selections": [
(v2/*: any*/)
],
"type": "Node",
"abstractKey": "__isNode"
},
{
"kind": "InlineFragment",
"selections": [
(v2/*: any*/),
(v3/*: any*/),
(v5/*: any*/),
(v17/*: any*/),
(v12/*: any*/)
],
"type": "Fair",
"abstractKey": null
},
{
"kind": "InlineFragment",
"selections": [
(v2/*: any*/),
(v7/*: any*/),
(v4/*: any*/),
(v3/*: any*/),
(v5/*: any*/),
(v17/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "isFollowed",
"storageKey": null
},
(v16/*: any*/)
],
"type": "Show",
"abstractKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "contextGrids",
"plural": true,
"selections": [
(v14/*: any*/),
{
"alias": "artworks",
"args": [
{
"kind": "Literal",
"name": "first",
"value": 6
}
],
"concreteType": "ArtworkConnection",
"kind": "LinkedField",
"name": "artworksConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "ArtworkEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Artwork",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
(v2/*: any*/),
{
"alias": null,
"args": null,
"concreteType": "Image",
"kind": "LinkedField",
"name": "image",
"plural": false,
"selections": [
{
"alias": "aspect_ratio",
"args": null,
"kind": "ScalarField",
"name": "aspectRatio",
"storageKey": null
},
{
"alias": null,
"args": [
{
"kind": "Literal",
"name": "version",
"value": "large"
}
],
"kind": "ScalarField",
"name": "url",
"storageKey": "url(version:\"large\")"
},
(v18/*: any*/)
],
"storageKey": null
},
(v10/*: any*/),
(v19/*: any*/),
(v20/*: any*/),
(v4/*: any*/),
(v7/*: any*/),
(v21/*: any*/),
(v5/*: any*/),
{
"alias": null,
"args": null,
"concreteType": "Sale",
"kind": "LinkedField",
"name": "sale",
"plural": false,
"selections": [
(v15/*: any*/),
(v22/*: any*/),
(v23/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "endAt",
"storageKey": null
},
(v2/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "SaleArtwork",
"kind": "LinkedField",
"name": "saleArtwork",
"plural": false,
"selections": [
(v24/*: any*/),
(v25/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "lotLabel",
"storageKey": null
},
(v2/*: any*/)
],
"storageKey": null
},
(v26/*: any*/)
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": "artworksConnection(first:6)"
},
(v10/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "ctaTitle",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "ctaHref",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": [
{
"kind": "Literal",
"name": "first",
"value": 1
}
],
"concreteType": "ArtistSeriesConnection",
"kind": "LinkedField",
"name": "artistSeriesConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "ArtistSeriesEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "ArtistSeries",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
{
"alias": null,
"args": [
{
"kind": "Literal",
"name": "first",
"value": 20
},
{
"kind": "Literal",
"name": "input",
"value": {
"sort": "-decayed_merch"
}
}
],
"concreteType": "FilterArtworksConnection",
"kind": "LinkedField",
"name": "filterArtworksConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "FilterArtworksEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Artwork",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
(v2/*: any*/),
(v4/*: any*/),
(v7/*: any*/),
(v5/*: any*/),
(v21/*: any*/),
{
"alias": null,
"args": null,
"concreteType": "Image",
"kind": "LinkedField",
"name": "image",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "imageURL",
"storageKey": null
},
(v18/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Sale",
"kind": "LinkedField",
"name": "sale",
"plural": false,
"selections": [
(v15/*: any*/),
(v22/*: any*/),
(v23/*: any*/),
(v2/*: any*/)
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "SaleArtwork",
"kind": "LinkedField",
"name": "saleArtwork",
"plural": false,
"selections": [
(v24/*: any*/),
(v25/*: any*/),
(v2/*: any*/)
],
"storageKey": null
},
(v20/*: any*/),
(v10/*: any*/),
(v19/*: any*/),
(v26/*: any*/)
],
"storageKey": null
}
],
"storageKey": null
},
(v2/*: any*/)
],
"storageKey": "filterArtworksConnection(first:20,input:{\"sort\":\"-decayed_merch\"})"
},
(v4/*: any*/),
(v7/*: any*/)
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": "artistSeriesConnection(first:1)"
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "isInAuction",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Artist",
"kind": "LinkedField",
"name": "artists",
"plural": true,
"selections": [
(v2/*: any*/),
(v9/*: any*/),
(v7/*: any*/),
(v4/*: any*/),
(v3/*: any*/),
(v6/*: any*/),
(v5/*: any*/),
(v8/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "nationality",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "birthday",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "deathday",
"storageKey": null
},
(v12/*: any*/)
],
"storageKey": null
},
(v4/*: any*/),
{
"alias": null,
"args": null,
"concreteType": "ArtworkMedium",
"kind": "LinkedField",
"name": "mediumType",
"plural": false,
"selections": [
(v14/*: any*/)
],
"storageKey": null
},
(v2/*: any*/),
(v7/*: any*/)
],
"storageKey": null
}
]
},
"params": {
"id": "b29d4fda233dedafb4288a803fd1372f",
"metadata": {},
"name": "ArtworkBelowTheFoldQuery",
"operationKind": "query",
"text": null
}
};
})();
(node as any).hash = '72cb482f87d89456b64301d0e0fe0405';
export default node; | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.