text stringlengths 2.5k 6.39M | kind stringclasses 3 values |
|---|---|
// ReadLaterUI is a Mojo WebUI controller and therefore needs mojo defined to
// finish running its tests.
import 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js';
import 'chrome://read-later.top-chrome/side_panel/bookmark_folder.js';
import {BookmarkFolderElement, FOLDER_OPEN_CHANGED_EVENT, getBookmarkFromElement} from 'chrome://read-later.top-chrome/side_panel/bookmark_folder.js';
import {BookmarksApiProxyImpl} from 'chrome://read-later.top-chrome/side_panel/bookmarks_api_proxy.js';
import {getFaviconForPageURL} from 'chrome://resources/js/icon.js';
import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js';
import {eventToPromise, flushTasks, waitAfterNextRender} from 'chrome://webui-test/test_util.js';
import {TestBookmarksApiProxy} from './test_bookmarks_api_proxy.js';
suite('SidePanelBookmarkFolderTest', () => {
let bookmarkFolder: BookmarkFolderElement;
let bookmarksApi: TestBookmarksApiProxy;
const folder: chrome.bookmarks.BookmarkTreeNode = {
id: '0',
title: 'Bookmarks bar',
children: [
{
id: '1',
title: 'Shopping list',
children: [
{
id: '4',
title: 'New shoes',
url: 'http://shoes/',
},
],
},
{
id: '2',
title: 'Foo website',
url: 'http://foo/',
},
{
id: '3',
title: 'Bar website',
url: 'http://bar/',
},
],
};
function getChildElements(): Array<HTMLElement|BookmarkFolderElement> {
return Array.from(bookmarkFolder.shadowRoot!.querySelectorAll(
'bookmark-folder, .bookmark'));
}
setup(async () => {
document.body.innerHTML = '';
bookmarksApi = new TestBookmarksApiProxy();
BookmarksApiProxyImpl.setInstance(bookmarksApi);
bookmarkFolder = document.createElement('bookmark-folder');
bookmarkFolder.folder = folder;
bookmarkFolder.openFolders = ['0'];
document.body.appendChild(bookmarkFolder);
await flushTasks();
});
test('UpdatesDepthVariables', () => {
bookmarkFolder.depth = 3;
assertEquals('3', bookmarkFolder.style.getPropertyValue('--node-depth'));
assertEquals('4', bookmarkFolder.style.getPropertyValue('--child-depth'));
});
test('RendersChildren', () => {
const childElements = getChildElements();
assertEquals(3, childElements.length);
assertTrue(childElements[0] instanceof BookmarkFolderElement);
assertEquals(
folder.children![0],
(childElements[0]! as BookmarkFolderElement).folder);
assertEquals(
folder.children![1]!.title,
childElements[1]!.querySelector('.title')!.textContent);
assertEquals(
folder.children![2]!.title,
childElements[2]!.querySelector('.title')!.textContent);
});
test('UpdatesChildCountVariable', () => {
assertEquals('3', bookmarkFolder.style.getPropertyValue('--child-count'));
bookmarkFolder.folder = Object.assign({}, folder, {
children: [
{
id: '1',
title: 'Shopping list',
children: [],
},
]
});
assertEquals('1', bookmarkFolder.style.getPropertyValue('--child-count'));
bookmarkFolder.folder = Object.assign({}, folder, {children: undefined});
assertEquals('0', bookmarkFolder.style.getPropertyValue('--child-count'));
});
test('ShowsFaviconForBookmarks', () => {
const fooWebsiteElement = getChildElements()[1]!;
assertEquals(
getFaviconForPageURL(folder.children![1]!.url!, false),
fooWebsiteElement.querySelector<HTMLElement>('.icon')!.style
.getPropertyValue('background-image'));
});
test('OpensAndClosesFolder', async () => {
const arrowIcon =
bookmarkFolder.shadowRoot!.querySelector<HTMLElement>('#arrowIcon')!;
assertTrue(arrowIcon.hasAttribute('open'));
assertEquals(3, getChildElements().length);
const eventPromise =
eventToPromise(FOLDER_OPEN_CHANGED_EVENT, document.body);
bookmarkFolder.shadowRoot!.querySelector<HTMLElement>('.row')!.click();
await eventPromise;
// Normally, the event listener for FOLDER_OPEN_CHANGED_EVENT will update
// the openFolders property.
bookmarkFolder.openFolders = [];
await waitAfterNextRender(bookmarkFolder);
assertFalse(arrowIcon.hasAttribute('open'));
assertEquals(0, getChildElements().length);
});
test('UpdatesOpenStateBasedOnOpenFolders', async () => {
bookmarkFolder.openFolders = [];
await waitAfterNextRender(bookmarkFolder);
getChildElements().forEach(
child => assertEquals('none', child.style.display));
});
test('OpensBookmark', async () => {
getChildElements()[1]!.click();
const [url, parentFolderDepth] =
await bookmarksApi.whenCalled('openBookmark');
assertEquals(folder.children![1]!.url, url);
assertEquals(0, parentFolderDepth);
});
test('MovesFocusDown', () => {
// No focus yet, should focus folder row.
assertTrue(bookmarkFolder.moveFocus(1));
assertEquals(
bookmarkFolder.shadowRoot!.querySelector('.row'),
bookmarkFolder.shadowRoot!.activeElement);
// Move focus down one, should focus first child which is a folder.
assertTrue(bookmarkFolder.moveFocus(1));
assertEquals(
bookmarkFolder.shadowRoot!.querySelector('#children bookmark-folder'),
bookmarkFolder.shadowRoot!.activeElement);
const bookmarkElements =
bookmarkFolder.shadowRoot!.querySelectorAll('#children .row');
// Move focus down one, should focus second child, the first bookmark.
assertTrue(bookmarkFolder.moveFocus(1));
assertEquals(bookmarkElements[0], bookmarkFolder.shadowRoot!.activeElement);
// Move focus down one, should focus second child, the second bookmark.
assertTrue(bookmarkFolder.moveFocus(1));
assertEquals(bookmarkElements[1], bookmarkFolder.shadowRoot!.activeElement);
// No more room.
assertFalse(bookmarkFolder.moveFocus(1));
});
test('MovesFocusUp', () => {
// No focus yet, should focus last bookmark.
const bookmarkElements =
bookmarkFolder.shadowRoot!.querySelectorAll('#children .row');
assertTrue(bookmarkFolder.moveFocus(-1));
assertEquals(
bookmarkElements[bookmarkElements.length - 1],
bookmarkFolder.shadowRoot!.activeElement);
// Move focus up one, should focus the first bookmark.
assertTrue(bookmarkFolder.moveFocus(-1));
assertEquals(bookmarkElements[0], bookmarkFolder.shadowRoot!.activeElement);
// Move focus up one, should focus the child folder.
assertTrue(bookmarkFolder.moveFocus(-1));
assertEquals(
bookmarkFolder.shadowRoot!.querySelector('#children bookmark-folder'),
bookmarkFolder.shadowRoot!.activeElement);
// Move focus up one, should focus the folder itself.
assertTrue(bookmarkFolder.moveFocus(-1));
assertEquals(
bookmarkFolder.shadowRoot!.querySelector('.row'),
bookmarkFolder.shadowRoot!.activeElement);
// No more room.
assertFalse(bookmarkFolder.moveFocus(-1));
});
test('DoesNotFocusHiddenChildren', async () => {
bookmarkFolder.openFolders = [];
await waitAfterNextRender(bookmarkFolder);
assertTrue(bookmarkFolder.moveFocus(1)); // Moves focus to folder.
assertFalse(bookmarkFolder.moveFocus(1)); // No children to move focus to.
});
test('MovesFocusWithinNestedFolders', async () => {
bookmarkFolder.folder = {
id: '0',
title: 'Bookmarks bar',
children: [{
id: '1',
title: 'Nested folder 1',
children: [{
id: '2',
title: 'Nested folder 2',
children: [{
id: '3',
title: 'Nested folder 3',
children: [],
}],
}],
}],
};
bookmarkFolder.openFolders = ['0', '1', '2', '3'];
await waitAfterNextRender(bookmarkFolder);
// Move focus down 1, should focus root folder.
assertTrue(bookmarkFolder.moveFocus(1));
assertEquals(
bookmarkFolder.shadowRoot!.querySelector('.row'),
bookmarkFolder.shadowRoot!.activeElement);
// Move focus down 1, should focus first nested folder.
assertTrue(bookmarkFolder.moveFocus(1));
assertEquals(
bookmarkFolder.folder.children![0],
(bookmarkFolder.shadowRoot!.activeElement! as BookmarkFolderElement)
.folder);
// Move focus down 1, should focus grandchild folder.
assertTrue(bookmarkFolder.moveFocus(1));
assertEquals(
bookmarkFolder.folder.children![0]!.children![0],
(bookmarkFolder.shadowRoot!.activeElement!.shadowRoot!.activeElement! as
BookmarkFolderElement)
.folder);
// Move focus down 1, should focus great grandchild folder.
assertTrue(bookmarkFolder.moveFocus(1));
assertEquals(
bookmarkFolder.folder.children![0]!.children![0]!.children![0],
(bookmarkFolder.shadowRoot!.activeElement!.shadowRoot!.activeElement!
.shadowRoot!.activeElement! as BookmarkFolderElement)
.folder);
// Move focus up 1, should focus grandchild folder.
assertTrue(bookmarkFolder.moveFocus(-1));
assertEquals(
bookmarkFolder.folder.children![0]!.children![0],
(bookmarkFolder.shadowRoot!.activeElement!.shadowRoot!.activeElement! as
BookmarkFolderElement)
.folder);
});
test('SendsClickModifiers', async () => {
const item = getChildElements()[1]!;
item.dispatchEvent(new MouseEvent('click'));
const [, , click] = await bookmarksApi.whenCalled('openBookmark');
assertFalse(
click.middleButton || click.altKey || click.ctrlKey || click.metaKey ||
click.shiftKey);
bookmarksApi.resetResolver('openBookmark');
// Middle mouse button click.
item.dispatchEvent(new MouseEvent('auxclick', {button: 1}));
const [, , auxClick] = await bookmarksApi.whenCalled('openBookmark');
assertTrue(auxClick.middleButton);
assertFalse(
auxClick.altKey || auxClick.ctrlKey || auxClick.metaKey ||
auxClick.shiftKey);
bookmarksApi.resetResolver('openBookmark');
// Non-middle mouse aux clicks.
item.dispatchEvent(new MouseEvent('auxclick', {button: 2}));
assertEquals(0, bookmarksApi.getCallCount('openBookmark'));
// Modifier keys.
item.dispatchEvent(new MouseEvent('click', {
altKey: true,
ctrlKey: true,
metaKey: true,
shiftKey: true,
}));
const [, , modifiedClick] = await bookmarksApi.whenCalled('openBookmark');
assertFalse(modifiedClick.middleButton);
assertTrue(
modifiedClick.altKey && modifiedClick.ctrlKey &&
modifiedClick.metaKey && modifiedClick.shiftKey);
});
test('GetsFocusableElements', async () => {
let focusableElement = bookmarkFolder.getFocusableElement([folder]);
assertTrue(!!focusableElement);
assertEquals('folder', focusableElement!.id);
const childBookmark = folder.children![1]!;
focusableElement = bookmarkFolder.getFocusableElement([childBookmark]);
assertTrue(!!focusableElement);
assertTrue(focusableElement!.classList.contains('bookmark'));
assertEquals(childBookmark, getBookmarkFromElement(focusableElement!));
const childFolder = folder.children![0]!;
focusableElement = bookmarkFolder.getFocusableElement([childFolder]);
assertTrue(!!focusableElement);
assertEquals('folder', focusableElement!.id);
assertEquals(childFolder.id, getBookmarkFromElement(focusableElement!).id);
// Grandchild bookmark is in a closed folder, so the focusable element
// should still be the child folder.
const grandchildBookmark = childFolder.children![0]!;
focusableElement =
bookmarkFolder.getFocusableElement([childFolder, grandchildBookmark]);
assertTrue(!!focusableElement);
assertEquals('folder', focusableElement!.id);
assertEquals(childFolder.id, getBookmarkFromElement(focusableElement!).id);
// Once the child folder is opened, the grandchild bookmark element should
// be focusable.
bookmarkFolder.openFolders = ['0', '1'];
await waitAfterNextRender(bookmarkFolder);
focusableElement =
bookmarkFolder.getFocusableElement([childFolder, grandchildBookmark]);
assertTrue(!!focusableElement);
assertTrue(focusableElement!.classList.contains('bookmark'));
assertEquals(grandchildBookmark, getBookmarkFromElement(focusableElement!));
});
}); | the_stack |
import {
getViewClass,
getViewMeta,
normalizeElementName,
NSVViewMeta,
} from './registry'
import { ELEMENT_REF } from './runtimeHelpers';
import { debug } from '../shared';
import { ViewBase, View, TextBase, LayoutBase, ContentView, Style, ObservableArray, EventData } from '@nativescript/core'
import { AddChildFromBuilder } from '@nativescript/core/ui/core/view';
import { unsetValue } from '@nativescript/core/ui/core/properties'
/*
* I had some difficulty importing this as:
* import set from 'set-value';
* I believe that turning on `"esModuleInterop": true` in tsconfig.json would allow us to use the default import.
* But maybe this is just a problem in the Webpack domain.
* ... And later as:
* import set = require('set-value');
*/
import { default as set } from "set-value";
import { warn } from '../../shared/Logger';
// import unset from 'unset-value'
// import {isContentView, isLayout} from "./index";
export const enum NSVNodeTypes {
TEXT = 'text',
ELEMENT = 'element',
COMMENT = 'comment',
ROOT = 'root',
}
// View Flags indicate the kind of view the element is
// this avoids extra checks during runtime to determine
// the method to use for adding/removing child nodes
//
export const enum NSVViewFlags {
NONE = 0,
SKIP_ADD_TO_DOM = 1 << 0,
CONTENT_VIEW = 1 << 1,
LAYOUT_VIEW = 1 << 2,
NO_CHILDREN = 1 << 3,
}
export interface INSVNode {
/**
* Used to give a hint to nodeOps about how this node should be appended into its parent.
* Relevant for cases such as RadSideDrawer, which have 'mainContent' and 'drawerContent'.
*/
nodeRole?: string
nodeId: number
nodeType: NSVNodeTypes
text: string | undefined
parentNode: INSVElement | null
childNodes: INSVNode[]
firstChild: INSVNode | null
lastChild: INSVNode | null
prevSibling: INSVNode | null
nextSibling: INSVNode | null
}
export interface INSVElement<T extends ViewBase = any> extends INSVNode {
tagName: string
meta: NSVViewMeta
style: Style | string
eventListeners: Map<string, (args: EventData) => void>;
addEventListener(
event: string,
handler: any,
options?: AddEventListenerOptions
): void
removeEventListener(event: string, handler?: any): void
dispatchEvent(event: string): void
nativeView: (T) & { [ELEMENT_REF]: INSVElement<T> }
getAttribute(name: string): unknown
setAttribute(name: string, value: unknown): void
removeAttribute(name: string): void
insertBefore(el: INSVNode, anchor?: INSVNode | null): void
appendChild(el: INSVNode): void
removeChild(el: INSVNode): void
}
let nodeId = 0
export abstract class NSVNode implements INSVNode {
protected constructor(nodeType: NSVNodeTypes) {
this.nodeType = nodeType
this.nodeId = nodeId++
}
nodeRole?: string
nodeId: number
nodeType: NSVNodeTypes
protected _text: string | undefined;
get text(): string | undefined {
return this._text;
}
set text(t: string | undefined) {
this._text = t;
}
parentNode: INSVElement | null = null
childNodes: INSVNode[] = []
nextSibling: INSVNode | null = null
prevSibling: INSVNode | null = null
get firstChild() {
return this.childNodes.length ? this.childNodes[0] : null
}
get lastChild() {
return this.childNodes.length
? this.childNodes[this.childNodes.length - 1]
: null
}
toString(): string {
return this.toString();
}
}
export class NSVElement<T extends ViewBase = ViewBase> extends NSVNode implements INSVElement {
private readonly _tagName: string
private readonly _nativeView: T
private _meta: NSVViewMeta | undefined
constructor(tagName: string) {
super(NSVNodeTypes.ELEMENT)
this._tagName = normalizeElementName(tagName)
const viewClass = getViewClass(tagName)
this._nativeView = new viewClass()
this._nativeView[ELEMENT_REF] = this
}
get tagName(): string {
return this._tagName
}
get nativeView() {
return this._nativeView
}
get style(): Style | string {
return this.nativeView.style
}
set style(inlineStyle: Style | string) {
(this.nativeView as any).style = inlineStyle
}
get text(): string | undefined {
return (this.nativeView as ViewBase as TextBase).text
}
set text(t: string | undefined) {
super.text = t;
(this.nativeView as ViewBase as TextBase).text = t
}
get meta() {
if (this._meta) {
return this._meta
}
return (this._meta = getViewMeta(this.tagName))
}
/**
* We keep references to the event listeners so that the RNS HostConfig can remove any attached event listener if it needs to replace it.
*/
private _eventListeners?: Map<string, (args: EventData) => void>;
get eventListeners() {
if(!this._eventListeners){
this._eventListeners = new Map();
}
return this._eventListeners!;
}
addEventListener(
event: string,
handler: any,
options: AddEventListenerOptions = {}
) {
const { capture, once } = options
if (capture) {
debug('Bubble propagation is not supported')
return
}
if (once) {
const oldHandler = handler
const self = this
handler = (...args: any) => {
const res = oldHandler.call(null, ...args)
if (res !== null) {
self.removeEventListener(event, handler)
}
}
}
this.nativeView.addEventListener(event, handler)
this.eventListeners.set(event, handler);
}
removeEventListener(event: string, handler?: any) {
this.eventListeners.delete(event);
this.nativeView.removeEventListener(event, handler)
}
dispatchEvent(event: string) {
this.nativeView.notify({ eventName: event, object: this.nativeView })
}
getAttribute(name: string): unknown {
return this.nativeView[name]
}
setAttribute(name: string, value: unknown) {
if(name === "nodeRole" && typeof value === "string"){
this.nodeRole = value;
return;
}
/**
* The 'ios' and 'android' properties (e.g. on ActionItem)
* are readonly, so we need to assign one level lower.
*/
if(name === "ios" && value){
Object.keys(value).forEach((key: string) => {
set(this.nativeView.ios, key, value);
});
return;
}
if(name === "android" && value){
Object.keys(value).forEach((key: string) => {
set(this.nativeView.android, key, value);
});
return;
}
set(this.nativeView, name, value)
}
removeAttribute(name: string) {
if(name === "nodeRole"){
this.nodeRole = void 0;
return;
}
// potential issue: unsetValue is an empty object
// not all properties/attributes may know/check for this
set(this.nativeView, name, unsetValue)
// originally we deleted the property, but in case of built-in properties
// this would break them. For example, deleting the padding property
// will prevent us from changing the padding once we deleted it
// that's not the expected behaviour.
// unset(this.nativeView, name)
}
insertBefore(el: INSVNode, anchor?: INSVNode | null) {
if (!anchor) {
return this.appendChild(el)
}
const refIndex = this.childNodes.findIndex(
(node) => node.nodeId === anchor.nodeId
)
if (refIndex === -1) {
return this.appendChild(el)
}
if (el.parentNode) {
el.parentNode.removeChild(el)
}
this.childNodes.splice(refIndex, 0, el)
el.parentNode = this
// find index to use for the native view, since non-visual nodes
// (comment/text don't exist in the native view hierarchy)
// todo: potentially refactor based on my benchmark:
// https://www.measurethat.net/Benchmarks/Show/7450/0/filter-findindex
const trueIndex = this.childNodes
.filter((node) => node.nodeType === NSVNodeTypes.ELEMENT)
.findIndex((node) => node.nodeId === el.nodeId)
this.addChild(el, trueIndex)
}
appendChild(el: INSVNode) {
this.childNodes.push(el)
el.parentNode = this
this.addChild(el)
}
removeChild(el: INSVNode) {
const index = this.childNodes.findIndex((node) => node.nodeId === el.nodeId)
if (index > -1) {
this.childNodes.splice(index, 1)
el.parentNode = null
if (el.nodeType === NSVNodeTypes.ELEMENT) {
removeChild(el as NSVElement, this) // Removing a child span takes us down here
} else if (el.nodeType === NSVNodeTypes.TEXT) {
this.updateText()
}
}
}
// abstracted from appendChild, and insertBefore to avoid code duplication
private addChild(el: INSVNode, atIndex?: number): void {
if (el.nodeType === NSVNodeTypes.ELEMENT) {
addChild(el as NSVElement, this, atIndex)
} else if (el.nodeType === NSVNodeTypes.TEXT) {
this.updateText()
}
}
updateText() {
this.setAttribute(
'text',
this.childNodes
.filter((node) => node.nodeType === NSVNodeTypes.TEXT)
.reduce((text: string, currentNode) => {
return text + currentNode.text
}, '')
)
}
toString(): string {
return "NSVElement:" + this.nativeView.toString();
}
}
export class NSVComment extends NSVNode {
constructor(text: string) {
super(NSVNodeTypes.COMMENT)
this.text = text
}
toString(): string {
return "NSVComment:" + `"` + this.text + `"`;
}
}
export class NSVText extends NSVNode {
constructor(text: string) {
super(NSVNodeTypes.TEXT)
this.text = text
}
toString(): string {
return "NSVText:" + `"` + this.text + `"`;
}
}
export class NSVRoot<T extends ViewBase = ViewBase> extends NSVNode {
baseRef?: NSVElement<T>
constructor() {
super(NSVNodeTypes.ROOT)
}
setBaseRef(el: INSVNode|null): void {
// console.log(`NSVRoot->appendChild(${el.nodeType})`)
if (el instanceof NSVElement) {
this.baseRef = el
}
// no-op
}
toString(): string {
if(this.baseRef){
return "NSVRoot:" + this.baseRef.toString();
} else {
return "NSVRoot:" + "null";
}
}
}
function addChild(child: NSVElement, parent: NSVElement, atIndex?: number) {
if (__TEST__) return
// debug(
// `...addChild( ${child.tagName}(${child.nodeId}), ${parent.tagName}(${
// parent.nodeId
// }), ${atIndex} )`
// )
if (child.meta.viewFlags & NSVViewFlags.SKIP_ADD_TO_DOM) {
// debug('SKIP_ADD_TO_DOM')
return
}
const parentView = parent.nativeView
const childView = child.nativeView
if (parent.meta.viewFlags & NSVViewFlags.NO_CHILDREN) {
// debug('NO_CHILDREN')
return
}
if (parent.meta.nodeOps) {
return parent.meta.nodeOps.insert(child, parent, atIndex)
}
const nodeRole: string|undefined = child.nodeRole;
if(nodeRole){
return addChildByNodeRole(nodeRole, childView, parentView, atIndex);
}
if (parent.meta.viewFlags & NSVViewFlags.LAYOUT_VIEW) {
if (atIndex) {
(parentView as LayoutBase).insertChild(childView as View, atIndex)
} else {
(parentView as LayoutBase).addChild(childView as View)
}
} else if (parent.meta.viewFlags & NSVViewFlags.CONTENT_VIEW) {
(parentView as ContentView).content = childView as View;
} else {
(parentView as unknown as AddChildFromBuilder)._addChildFromBuilder(childView.constructor.name, childView)
}
}
function removeChild(child: NSVElement, parent: NSVElement) {
if (__TEST__) return
// debug(
// `...removeChild( ${child.tagName}(${child.nodeId}), ${parent.tagName}(${
// parent.nodeId
// }) )`
// )
if (child.meta.viewFlags & NSVViewFlags.SKIP_ADD_TO_DOM) {
// debug('SKIP_ADD_TO_DOM')
return
}
if (parent.meta.viewFlags & NSVViewFlags.NO_CHILDREN) {
// debug('NO_CHILDREN')
return
}
if (parent.meta.nodeOps) {
return parent.meta.nodeOps.remove(child, parent)
}
const parentView = parent.nativeView
const childView = child.nativeView
const nodeRole: string|undefined = child.nodeRole;
if(nodeRole){
return removeChildByNodeRole(nodeRole, childView, parentView);
}
if (parent.meta.viewFlags & NSVViewFlags.LAYOUT_VIEW) {
(parentView as LayoutBase).removeChild(childView as View)
} else if (parent.meta.viewFlags & NSVViewFlags.CONTENT_VIEW) {
(parentView as ContentView).content = null
} else {
// Removing a child span takes us down here
parentView._removeView(childView)
}
}
function addChildByNodeRole(nodeRole: string, childView: any, parentView: any, atIndex?: number): void {
const childrenSetter: any|undefined = parentView[nodeRole];
if(typeof childrenSetter !== "undefined" && typeof childrenSetter.length !== "undefined"){
// Treat as if it's an array.
const childrenSetterLength: number = parentView[nodeRole].length;
const atSafeIndex: number = typeof atIndex === "undefined" ? childrenSetterLength : atIndex;
if(childrenSetter instanceof ObservableArray){
parentView[nodeRole].splice(atSafeIndex, 0, childView);
} else if(Array.isArray(childrenSetter)){
parentView[nodeRole] = [...parentView[nodeRole]].splice(atSafeIndex, 0, childView);
} else {
if (__DEV__) {
warn(
`parentView "${parentView.constructor.name}" had a value for nodeRole "${nodeRole}" ` +
`that had a "length" property yet did not conform to Array or ObservableArray. Cannot add child. ` +
`Please explicitly implement nodeOps.insert() for the parentView.`
);
}
}
} else {
/*
* Treat it as if it's simply a setter.
* This assumes (quite fairly) that the plugin author is not delegating to us the responsibility
* of initialising an array for childrenSetter.
*/
parentView[nodeRole] = childView;
}
}
function removeChildByNodeRole(nodeRole: string, childView: any, parentView: any): void {
const childrenSetter = parentView[nodeRole];
if(typeof childrenSetter !== "undefined" && typeof childrenSetter.indexOf === "function"){
// Treat as if it's an array.
const childIndex: number = parentView[nodeRole].indexOf(childView);
if(childrenSetter instanceof ObservableArray){
parentView[nodeRole].splice(childIndex, 1);
} else if(Array.isArray(childrenSetter)){
parentView[nodeRole] = [...parentView[nodeRole]].splice(childIndex, 1);
} else {
if (__DEV__) {
warn(
`parentView "${parentView.constructor.name}" had a value for nodeRole "${nodeRole}" ` +
`that had an "indexOf" property yet did not conform to Array or ObservableArray. Cannot add childView "${childView.constructor.name}". ` +
`Please explicitly implement nodeOps.remove() for the parentView.`
);
}
}
} else {
/*
* Treat it as if it's simply a setter.
* We can't use unsetValue here, because the childrenSetter is not necessarily a Property (which indeed is the case for FormattedString.spans).
* TODO: If there's a way to determine whether the childrenSetter is a Property, I'd be very happy to run that first check and use unsetValue.
*/
const defaultValueForChildrenSetter: unknown = parentView.__proto__[nodeRole];
try {
parentView[nodeRole] = defaultValueForChildrenSetter;
} catch(e){
if (__DEV__) {
warn(
`parentView "${parentView.constructor.name}" failed to remove childView "${childView.constructor.name}", given nodeRole "${nodeRole}" ` +
`Please explicitly implement nodeOps.remove() for the parentView.`
);
}
}
}
} | the_stack |
import chai from "chai";
import {
ServiceBusClientForTests,
createServiceBusClientForTests,
testPeekMsgsLength,
getRandomTestClientTypeWithSessions
} from "./utils/testutils2";
import { ServiceBusSender } from "../../src";
import { ServiceBusMessage, ServiceBusSessionReceiver } from "../../src";
import { TestClientType, TestMessage } from "./utils/testUtils";
const should = chai.should();
// NOTE: these tests should be reworked, if possible. Since they need to be deterministic
// and only grab the "expected" next session you need to ensure the entity (queue, sub)
// is completely empty.
//
// I've moved these tests in here and re-create entites after each test - it'e expensive
// but it'll allow them to be reliable.
describe("sessions tests - requires completely clean entity for each test", () => {
let serviceBusClient: ServiceBusClientForTests;
let sender: ServiceBusSender;
let receiver: ServiceBusSessionReceiver;
const randomTestClientType = getRandomTestClientTypeWithSessions();
async function beforeEachNoSessionTest(testClientType: TestClientType): Promise<void> {
serviceBusClient = createServiceBusClientForTests();
const entityNames = await serviceBusClient.test.createTestEntities(testClientType);
sender = serviceBusClient.test.addToCleanup(
serviceBusClient.createSender(entityNames.queue ?? entityNames.topic!)
);
// Observation -
// Peeking into an empty session-enabled queue would run into either of the following errors..
// 1. OperationTimeoutError: Unable to create the amqp receiver 'unpartitioned-queue-sessions-794f89be-3282-8b48-8ae0-a8af43c3ce36'
// on amqp session 'local-1_remote-1_connection-2' due to operation timeout.
// 2. MessagingError: Received an incorrect sessionId 'undefined' while creating the receiver 'unpartitioned-queue-sessions-86662b2b-acdc-1045-8ad4-fa3ab8807871'.
// getSenderReceiverClients creates brand new queues/topic-subscriptions.
// Hence, commenting the following code since there is no need to purge/peek into a freshly created entity
// await purge(receiver);
// const peekedMsgs = await receiver.peekMessages();
// const receiverEntityType = receiver.entityType;
// if (peekedMsgs.length) {
// chai.assert.fail(`Please use an empty ${receiverEntityType} for integration testing`);
// }
}
afterEach(async () => {
await serviceBusClient.test.afterEach();
// each test recreates the client on start so we need to clean the entire thing up after each test.
await serviceBusClient.test.after();
});
// These tests really do need to run against both queues and subscriptions as they seem
// to behave differently on occasion when it runs against subscriptions.
//
// Basically, this test can fail if there is a delay between the message being accepted into the
// entity and it actually being available in the queue or subscription. If that happens, when we peek,
// it'll end up peeking into an empty entity which just works out as a really fast call that returns
// no messages.
//
// So to compensate for this (since speed isn't what we're testing) I just receiveMessages(1) prior to the
// peek, which _does_ wait for messages to arrive before returning.
[
getRandomTestClientTypeWithSessions("queue"),
getRandomTestClientTypeWithSessions("subscription")
].forEach((testClientType) => {
describe(testClientType + "Peek session", function(): void {
async function peekSession(
sessionReceiverType: "acceptsession" | "acceptnextsession" | ":hell"
): Promise<void> {
const testMessage = TestMessage.getSessionSample();
await sender.sendMessages(testMessage);
const entityNames = serviceBusClient.test.getTestEntities(testClientType);
if (sessionReceiverType === "acceptsession") {
receiver = await serviceBusClient.test.acceptSessionWithPeekLock(
entityNames,
testMessage.sessionId!
);
} else if (sessionReceiverType === "acceptnextsession") {
receiver = await serviceBusClient.test.acceptNextSessionWithPeekLock(entityNames);
} else {
should.fail(`Invalid session receiver type for test: ${sessionReceiverType}`);
}
await ensureMessageExists(receiver);
const peekedMsgs = await receiver.peekMessages(1);
should.equal(peekedMsgs.length, 1, "Unexpected number of messages browsed");
should.equal(
peekedMsgs[0].body,
testMessage.body,
"MessageBody is different than expected"
);
should.equal(
peekedMsgs[0].messageId,
testMessage.messageId,
"MessageId is different than expected"
);
should.equal(
peekedMsgs[0].sessionId,
testMessage.sessionId,
"SessionId is different than expected"
);
const msgs = await receiver.receiveMessages(1);
should.equal(msgs.length, 1, "Unexpected number of messages received");
should.equal(msgs[0].body, testMessage.body, "MessageBody is different than expected");
should.equal(
msgs[0].messageId,
testMessage.messageId,
"MessageId is different than expected"
);
should.equal(
msgs[0].sessionId,
testMessage.sessionId,
"SessionId is different than expected"
);
await receiver.completeMessage(msgs[0]);
}
it("acceptSession(sessionId)", async function(): Promise<void> {
await beforeEachNoSessionTest(testClientType);
await peekSession("acceptsession");
});
it("acceptNextSession()", async function(): Promise<void> {
await beforeEachNoSessionTest(testClientType);
await peekSession("acceptnextsession");
});
});
});
describe(randomTestClientType + ": SessionReceiver with no sessionId", function(): void {
const testSessionId2 = "my-session2";
const testMessagesWithDifferentSessionIds: ServiceBusMessage[] = [
{
body: "hello1",
messageId: `test message ${Math.random()}`,
sessionId: TestMessage.sessionId
},
{
body: "hello2",
messageId: `test message ${Math.random()}`,
sessionId: testSessionId2
}
];
async function testComplete_batching(): Promise<void> {
await sender.sendMessages(testMessagesWithDifferentSessionIds[0]);
await sender.sendMessages(testMessagesWithDifferentSessionIds[1]);
const entityNames = serviceBusClient.test.getTestEntities(randomTestClientType);
receiver = await serviceBusClient.test.acceptNextSessionWithPeekLock(entityNames);
let msgs = await receiver.receiveMessages(2);
should.equal(msgs.length, 1, "Unexpected number of messages received");
should.equal(receiver.sessionId, msgs[0].sessionId, "Unexpected sessionId in receiver");
should.equal(
testMessagesWithDifferentSessionIds.some(
(x) =>
msgs[0].body === x.body &&
msgs[0].messageId === x.messageId &&
msgs[0].sessionId === x.sessionId
),
true,
"Received Message doesnt match any of the test messages"
);
await receiver.completeMessage(msgs[0]);
await receiver.close();
// get the next available session ID rather than specifying one
receiver = await serviceBusClient.test.acceptNextSessionWithPeekLock(entityNames);
msgs = await receiver.receiveMessages(2);
should.equal(msgs.length, 1, "Unexpected number of messages received");
should.equal(receiver.sessionId, msgs[0].sessionId, "Unexpected sessionId in receiver");
should.equal(
testMessagesWithDifferentSessionIds.some(
(x) =>
msgs[0].body === x.body &&
msgs[0].messageId === x.messageId &&
msgs[0].sessionId === x.sessionId
),
true,
"Received Message doesnt match any of the test messages"
);
await receiver.completeMessage(msgs[0]);
await testPeekMsgsLength(receiver, 0);
}
it(
randomTestClientType + ": complete() removes message from random session",
async function(): Promise<void> {
await beforeEachNoSessionTest(randomTestClientType);
await testComplete_batching();
}
);
});
describe.skip(
randomTestClientType + ": SessionReceiver with empty string as sessionId",
function(): void {
// Sending messages with different session id, so that we know for sure we pick the right one
// and that Service Bus is not choosing a random one for us
const testMessagesWithDifferentSessionIds: ServiceBusMessage[] = [
{
body: "hello1",
messageId: `test message ${Math.random()}`,
sessionId: TestMessage.sessionId
},
{
body: "hello2",
messageId: `test message ${Math.random()}`,
sessionId: ""
}
];
async function testComplete_batching(): Promise<void> {
await sender.sendMessages(testMessagesWithDifferentSessionIds[0]);
await sender.sendMessages(testMessagesWithDifferentSessionIds[1]);
const entityNames = serviceBusClient.test.getTestEntities(randomTestClientType);
// get the next available session ID rather than specifying one
receiver = await serviceBusClient.test.acceptSessionWithPeekLock(entityNames, "");
const msgs = await receiver.receiveMessages(2);
should.equal(msgs.length, 1, "Unexpected number of messages received");
should.equal(receiver.sessionId, "", "Unexpected sessionId in receiver");
should.equal(
testMessagesWithDifferentSessionIds[1].body === msgs[0].body &&
testMessagesWithDifferentSessionIds[1].messageId === msgs[0].messageId &&
testMessagesWithDifferentSessionIds[1].sessionId === msgs[0].sessionId,
true,
"Received Message doesnt match expected test message"
);
await receiver.completeMessage(msgs[0]);
const peekedMsgsInSession = await receiver.peekMessages(1);
should.equal(peekedMsgsInSession.length, 0, "Unexpected number of messages peeked");
await receiver.close();
}
it("complete() removes message from random session", async function(): Promise<void> {
await beforeEachNoSessionTest(randomTestClientType);
await testComplete_batching();
});
}
);
});
/**
* A simple workaround to ensure that a message is actually available, prior to peeking.
*
* Without this it's possible to be too fast, and attempt to peek (with a sequence number) and
* get no messages, which isn't an error or obvious.
*
* This behavior only manifests with subscriptions. Queues won't even let you create a receiver
* when a session does not have any messages.
*/
async function ensureMessageExists(receiver: ServiceBusSessionReceiver): Promise<void> {
const messages = await receiver.receiveMessages(1);
should.equal(messages.length, 1, "Should receive a single message");
// put it right back.
await receiver.abandonMessage(messages[0]);
} | the_stack |
import assert from 'assert';
import * as Ast from '../ast';
import { NotImplementedError } from '../utils/errors';
import { getScalarExpressionName } from '../utils';
import {
PointWiseOp,
StreamOp,
TableOp,
ActionOp,
RuleOp,
QueryInvocationHints,
BooleanExpressionOp,
isUnaryStreamOp,
isUnaryTableOp
} from './ops';
// YES there are two different modules called utils
// because of course
import { getDefaultProjection, getExpressionParameters } from './utils';
import ReduceOp, { SimpleAggregationType } from './reduceop';
import { ProjectionExpression } from '../ast';
function sameDevice(lhs : Ast.DeviceSelector, rhs : Ast.DeviceSelector) : boolean {
if (lhs.kind !== rhs.kind)
return false;
if (lhs.id !== rhs.id)
return false;
if (lhs.principal !== rhs.principal)
return false;
return true;
}
function addAll<T>(set : Set<T>, values : Iterable<T>) : Set<T> {
for (const v of values)
set.add(v);
return set;
}
function setIntersect<T>(one : Set<T>, two : Set<T>) : Set<T> {
const intersection = new Set<T>();
for (const el of one) {
if (two.has(el))
intersection.add(el);
}
return intersection;
}
function addMinimalProjection(args : Iterable<string>, schema : Ast.FunctionDef) : Set<string> {
const argset = new Set<string>(args);
addAll(argset, schema.minimal_projection as string[]);
return argset;
}
/**
* Lower the query invocation hints for one side of the join.
*
* This is a limited best-effort operation. optimize.js includes a more
* thorough handling of filters and projections, which also affects
* the JS compiled code.
*/
function restrictHintsForJoin(hints : QueryInvocationHints,
schema : Ast.FunctionDef) : QueryInvocationHints {
// start with a clean slate (no sort, no index)
const clone = new QueryInvocationHints(new Set);
for (const arg of hints.projection) {
if (schema.hasArgument(arg))
clone.projection.add(arg);
}
clone.filter = (function recursiveHelper(expr : Ast.BooleanExpression) {
if (expr.isTrue || expr.isFalse)
return expr;
if (expr instanceof Ast.DontCareBooleanExpression) // dont care about dontcares
return Ast.BooleanExpression.True;
if (expr instanceof Ast.AtomBooleanExpression) {
// bail (convert to `true`) if:
// - the filter left-hand-side is not defined in this branch of the join
// - or any part of the right-hand-side uses a parameter not defined in this
// branch of the join
if (!schema.hasArgument(expr.name))
return Ast.BooleanExpression.True;
const pnames = getExpressionParameters(expr.value, schema);
for (const pname of pnames) {
if (!schema.hasArgument(pname))
return Ast.BooleanExpression.True;
}
return expr;
}
// ignore everything else
return Ast.BooleanExpression.True;
})(hints.filter);
return clone;
}
function hasParameterPassing(expression : Ast.Expression) {
for (const slot of expression.iterateSlots2({})) {
if (slot instanceof Ast.DeviceSelector)
continue;
const value = slot.get();
if (!(value instanceof Ast.VarRefValue))
continue;
if (!(value.name in slot.scope))
return true;
}
return false;
}
// compile a table that is being monitored to a stream
function compileMonitorTableToOps(table : Ast.Expression,
hints : QueryInvocationHints) : StreamOp {
if (table instanceof Ast.FunctionCallExpression ||
table instanceof Ast.AliasExpression)
throw new NotImplementedError(String(table));
if (table instanceof Ast.InvocationExpression) {
// subscribe is optimistic, we still need EdgeNew
return new StreamOp.EdgeNew(
new StreamOp.InvokeSubscribe(table.invocation, table, hints),
table
);
} else if (table instanceof Ast.FilterExpression) {
const schema = table.schema;
assert(schema);
const hintsclone = hints.clone();
addAll(hintsclone.projection, getExpressionParameters(table.filter, schema));
hintsclone.filter = new Ast.BooleanExpression.And(null, [table.filter, hints.filter]);
return new StreamOp.Filter(
compileMonitorTableToOps(table.expression, hintsclone),
compileBooleanExpressionToOp(table.filter),
table
);
} else if (table instanceof Ast.ProjectionExpression) {
// note: we must pass the inner schema to getExpressionParameters, not the outer (projected) one
const schema = table.expression.schema;
assert(schema);
// see note in stream.isProjection later
const effective = setIntersect(hints.projection, addMinimalProjection(table.args, schema));
const hintsclone = hints.clone();
hintsclone.projection = effective;
const names = new Set(effective);
// do a pass through the computations to compute the hints
// we need to do this before recursing because the hints will be cloned by the recursion
for (let i = 0; i < table.computations.length; i++)
addAll(hintsclone.projection, getExpressionParameters(table.computations[i], schema));
let streamop = compileMonitorTableToOps(table.expression, hintsclone);
for (let i = 0; i < table.computations.length; i++) {
const name = table.aliases[i] || getScalarExpressionName(table.computations[i]);
streamop = new StreamOp.Map(streamop,
new PointWiseOp.Compute(table.computations[i], name),
table
);
names.add(name);
}
streamop = new StreamOp.Map(streamop, new PointWiseOp.Projection(names), table);
// note the "edge new" operation here, because
// the projection might cause fewer values to
// be new
return new StreamOp.EdgeNew(streamop, table);
} else if (table instanceof Ast.SortExpression || table instanceof Ast.IndexExpression || table instanceof Ast.SliceExpression) {
// sort, index and slice have no effect on monitor
//
// XXX is this correct?
return compileMonitorTableToOps(table, hints);
} else if (table instanceof Ast.AggregationExpression) {
// discard the hints entirely across aggregation
const newHints = new QueryInvocationHints(table.field === '*' ? new Set([]) : new Set([table.field]));
// for an aggregation, we subscribe to the inner table
// (ie react to all changes), then when the table changes
// we fetch it completely again and compute the aggregation
// note the "edge new" operation here, because
// the aggregation might cause fewer values to
// be new
return new StreamOp.EdgeNew(new StreamOp.InvokeTable(
compileMonitorTableToOps(table.expression, newHints),
compileTableToOps(table, newHints),
table
), table);
} else if (table instanceof Ast.ChainExpression) {
assert(table.expressions.length > 0);
if (table.expressions.length === 1)
return compileMonitorTableToOps(table.expressions[0], hints);
let streamop = compileMonitorTableToOps(table.expressions[0], restrictHintsForJoin(hints, table.expressions[0].schema!));
for (let i = 1; i < table.expressions.length; i++) {
const rhs = table.expressions[i];
if (!hasParameterPassing(rhs)) {
// if there is no parameter passing, we can individually monitor
// the two tables and return the union
streamop = new StreamOp.EdgeNew(new StreamOp.Union(
streamop,
compileMonitorTableToOps(rhs, restrictHintsForJoin(hints, rhs.schema!)),
table),
table
);
} else {
// otherwise we need to subscribe to the left hand side, and
// every time it fires, create/update a subscription to the
// right hand side
// this is VERY MESSY
// so it's not implemented
throw new NotImplementedError(String(table));
}
}
return streamop;
} else {
throw new TypeError();
}
}
function findInputParam(invocation : Ast.FunctionCallExpression,
name : string) {
for (const ip of invocation.in_params) {
if (ip.name === name)
return ip.value;
}
return undefined;
}
// compile a TT stream to a stream op and zero or more
// tableops
function compileStreamToOps(stream : Ast.Expression,
hints : QueryInvocationHints) : StreamOp {
if (stream instanceof Ast.AliasExpression)
throw new NotImplementedError(String(stream));
if (stream instanceof Ast.FunctionCallExpression) {
if (stream.name === 'timer') {
const base = findInputParam(stream, 'base');
const interval = findInputParam(stream, 'interval');
const frequency = findInputParam(stream, 'frequency');
return new StreamOp.Timer(base, interval!, frequency, stream);
} else if (stream.name === 'attimer') {
const time = findInputParam(stream, 'time');
const expiration_date = findInputParam(stream, 'expiration_date');
return new StreamOp.AtTimer(time!, expiration_date, stream);
} else if (stream.name === 'ontimer') {
const date = findInputParam(stream, 'date');
return new StreamOp.OnTimer(date!, stream);
} else {
return new StreamOp.InvokeVarRef(stream.name, stream.in_params, stream, hints);
}
} else if (stream instanceof Ast.MonitorExpression) {
const schema = stream.schema;
assert(schema);
const hintsclone = hints.clone();
// if we're monitoring on specific fields, we can project on those fields
// otherwise, we need to project on all output parameters
if (stream.args)
addAll(hintsclone.projection, stream.args);
else
addAll(hintsclone.projection, Object.keys(schema.out));
return compileMonitorTableToOps(stream.expression, hintsclone);
} else if (stream instanceof Ast.FilterExpression) {
// NOTE: this code path is for a filter of a monitor, which is treated as an edge trigger
// monitor of a filter (treated as a level trigger) is handled by compileMonitorTableToOps
const schema = stream.schema;
assert(schema);
const hintsclone = hints.clone();
addAll(hintsclone.projection, getExpressionParameters(stream.filter, schema));
// NOTE: we don't lower the filter here, because if the subscribe applies the filter,
// we don't notice the edge
const op = compileStreamToOps(stream.expression, hintsclone);
return new StreamOp.EdgeFilter(op, compileBooleanExpressionToOp(stream.filter), stream);
} else if (stream instanceof Ast.ProjectionExpression) {
// NOTE: there is a tricky case of nested projection that looks like
// Projection(Filter(Projection(x, [a, b, c]), use(c)), [a, b])
//
// This is dangerous because the PointWiseOp.Projection will hard-apply
// the projection, it won't be just a hint. Yet, it is ok
// because all parameters that are used by the filter are added to the
// projection hint.
// note: we must pass the inner schema to getExpressionParameters, not the outer (projected) one
const schema = stream.expression.schema;
assert(schema);
// see note in stream.isProjection later
const effective = setIntersect(hints.projection, addMinimalProjection(stream.args, schema));
const hintsclone = hints.clone();
hintsclone.projection = effective;
const names = new Set(effective);
// do a pass through the computations to compute the hints
// we need to do this before recursing because the hints will be cloned by the recursion
for (let i = 0; i < stream.computations.length; i++)
addAll(hintsclone.projection, getExpressionParameters(stream.computations[i], schema));
let streamop = compileStreamToOps(stream.expression, hintsclone);
for (let i = 0; i < stream.computations.length; i++) {
const name = stream.aliases[i] || getScalarExpressionName(stream.computations[i]);
streamop = new StreamOp.Map(streamop,
new PointWiseOp.Compute(stream.computations[i], name),
stream
);
names.add(name);
}
return new StreamOp.Map(streamop, new PointWiseOp.Projection(names), stream);
} else if (stream instanceof Ast.ChainExpression) {
assert(stream.expressions.length > 0);
let streamop = compileStreamToOps(stream.expressions[0], restrictHintsForJoin(hints, stream.expressions[0].schema!));
for (let i = 1; i < stream.expressions.length; i++) {
const table = stream.expressions[i];
const tableop = compileTableToOps(table, restrictHintsForJoin(hints, table.schema!));
streamop = new StreamOp.Join(streamop, tableop, stream);
}
return streamop;
} else {
throw new TypeError();
}
}
function compileTableToOps(table : Ast.Expression,
hints : QueryInvocationHints) : TableOp {
if (table instanceof Ast.AliasExpression)
throw new NotImplementedError(table.constructor.name);
if (table instanceof Ast.FunctionCallExpression) {
const compiled = new TableOp.InvokeVarRef(table.name, table.in_params, table, hints);
compiled.device = null;
compiled.handle_thingtalk = false;
return compiled;
} else if (table instanceof Ast.InvocationExpression) {
const device = table.invocation.selector;
assert(device instanceof Ast.DeviceSelector);
const schema = table.schema;
assert(schema instanceof Ast.FunctionDef);
const handle_thingtalk = !!schema.getImplementationAnnotation<boolean>('handle_thingtalk');
return new TableOp.InvokeGet(
table.invocation,
device,
handle_thingtalk,
table,
hints
);
} else if (table instanceof Ast.FilterExpression) {
const hintsclone = hints.clone();
const schema = table.schema;
assert(schema);
addAll(hintsclone.projection, getExpressionParameters(table.filter, schema));
hintsclone.filter = new Ast.BooleanExpression.And(null, [table.filter, hints.filter]);
const compiled = compileTableToOps(table.expression, hintsclone);
return new TableOp.Filter(
compiled,
compileBooleanExpressionToOp(table.filter),
compiled.device,
compiled.handle_thingtalk,
table
);
} else if (table instanceof Ast.ProjectionExpression) {
// note: we must pass the inner schema to getExpressionParameters, not the outer (projected) one
const schema = table.expression.schema;
assert(schema);
// see note in stream.isProjection later
const effective = setIntersect(hints.projection, addMinimalProjection(table.args, schema));
const hintsclone = hints.clone();
hintsclone.projection = effective;
const names = new Set(effective);
// do a pass through the computations to compute the hints
// we need to do this before recursing because the hints will be cloned by the recursion
for (let i = 0; i < table.computations.length; i++)
addAll(hintsclone.projection, getExpressionParameters(table.computations[i], schema));
const compiled = compileTableToOps(table.expression, hintsclone);
let tableop = compiled;
for (let i = 0; i < table.computations.length; i++) {
const name = table.aliases[i] || getScalarExpressionName(table.computations[i]);
tableop = new TableOp.Map(tableop,
new PointWiseOp.Compute(table.computations[i], name),
compiled.device,
compiled.handle_thingtalk,
table
);
names.add(name);
}
return new TableOp.Map(tableop,
new PointWiseOp.Projection(names),
compiled.device,
compiled.handle_thingtalk,
table
);
} else if (table instanceof Ast.AggregationExpression) {
// discard the hints entirely across aggregation
const newHints = new QueryInvocationHints(table.field === '*' ? new Set([]) : new Set([table.field]));
const schema = table.schema;
assert(schema);
let reduceop;
if (table.operator === 'count' && table.field === '*')
reduceop = new ReduceOp.Count;
else if (table.operator === 'count')
reduceop = new ReduceOp.CountDistinct(table.field);
else if (table.operator === 'avg')
reduceop = new ReduceOp.Average(table.field, schema.out[table.field]);
else
reduceop = new ReduceOp.SimpleAggregation(table.operator as SimpleAggregationType, table.field, schema.out[table.field]);
const compiled = compileTableToOps(table.expression, newHints);
return new TableOp.Reduce(
compiled,
reduceop,
compiled.device,
compiled.handle_thingtalk,
table
);
} else if (table instanceof Ast.IndexExpression &&
table.indices.length === 1 && table.indices[0] instanceof Ast.NumberValue &&
table.expression instanceof Ast.SortExpression) {
const hintsclone = hints.clone();
// convert sort followed by a single index into argminmax
const index = table.indices[0] as Ast.NumberValue;
const inner = table.expression;
let reduceop;
if ((index.value === 1 || index.value === -1) && inner.value instanceof Ast.VarRefValue && !inner.value.name.includes('.')) {
// common case of simple argmin/argmax
let argminmaxop : 'argmin' | 'argmax';
if ((index.value === 1 && inner.direction === 'asc') ||
(index.value === -1 && inner.direction === 'desc'))
argminmaxop = 'argmin';
else
argminmaxop = 'argmax';
hintsclone.limit = 1;
hintsclone.sort = [inner.value.name, inner.direction];
reduceop = new ReduceOp.SimpleArgMinMax(argminmaxop, inner.value.name);
} else {
let argminmaxop : 'argmin' | 'argmax';
if (inner.direction === 'asc')
argminmaxop = 'argmin';
else
argminmaxop = 'argmax';
// across an index, the limit hint becomes the index value, if known,
// (so an index [3] would fetch 3 elements)
//
// NOTE: for correct operation, devices which implement hints MUST NOT
// implement "limit" without implementing "sort"
if (inner.value instanceof Ast.VarRefValue && !inner.value.name.includes('.')) {
hintsclone.limit = index.toJS();
hintsclone.sort = [inner.value.name, inner.direction];
} else {
// clear both limit and sort if we're asked to sort by a complex value
hintsclone.limit = undefined;
hintsclone.sort = undefined;
}
reduceop = new ReduceOp.ComplexArgMinMax(argminmaxop, inner.value, index, new Ast.Value.Number(1));
}
const compiled = compileTableToOps(inner.expression, hintsclone);
return new TableOp.Reduce(
compiled,
reduceop,
compiled.device,
compiled.handle_thingtalk,
table
);
} else if (table instanceof Ast.SliceExpression && table.expression instanceof Ast.SortExpression) {
const inner = table.expression;
// convert sort followed by a single slice into argminmax
let argminmaxop : 'argmin' | 'argmax';
if (inner.direction === 'asc')
argminmaxop = 'argmin';
else
argminmaxop = 'argmax';
const reduceop = new ReduceOp.ComplexArgMinMax(argminmaxop, inner.value, table.base, table.limit);
const hintsclone = hints.clone();
// across a slice, the limit hint becomes the base value + the limit value, if known,
// (so a slice [2:3] would fetch 4 elements, and then discard the first one)
// (note the off by one because the base is 1-based)
//
// NOTE: for correct operation, devices which implement hints MUST NOT
// implement "limit" without implementing "sort"
const base = table.base;
const limit = table.limit;
if (inner.value instanceof Ast.VarRefValue && !inner.value.name.includes('.')) {
hintsclone.limit = base instanceof Ast.NumberValue && limit instanceof Ast.NumberValue ?
(base.toJS() - 1 + limit.toJS()) : undefined;
hintsclone.sort = [inner.value.name, inner.direction];
} else {
// clear both limit and sort if we're asked to sort by a complex value
hintsclone.limit = undefined;
hintsclone.sort = undefined;
}
const compiled = compileTableToOps(inner.expression, hintsclone);
return new TableOp.Reduce(
compiled,
reduceop,
compiled.device,
compiled.handle_thingtalk,
table
);
} else if (table instanceof Ast.SortExpression) {
const hintsclone = hints.clone();
let reduceop;
if (table.value instanceof Ast.VarRefValue && !table.value.name.includes('.')) {
hintsclone.sort = [table.value.name, table.direction];
reduceop = new ReduceOp.SimpleSort(table.value.name, table.direction);
} else {
hintsclone.sort = undefined;
reduceop = new ReduceOp.ComplexSort(table.value, table.direction);
}
const compiled = compileTableToOps(table.expression, hintsclone);
return new TableOp.Reduce(
compiled,
reduceop,
compiled.device,
compiled.handle_thingtalk,
table
);
} else if (table instanceof Ast.IndexExpression &&
table.indices.length === 1 &&
table.indices[0] instanceof Ast.NumberValue &&
(table.indices[0] as Ast.NumberValue).value > 0) {
// across an index, the limit hint becomes the index value, if known,
// (so an index [3] would fetch 3 elements)
//
// NOTE: for correct operation, devices which implement hints MUST NOT
// implement "limit" without implementing "sort"
const index = table.indices[0] as Ast.NumberValue;
const hintsclone = hints.clone();
hintsclone.limit = index.toJS();
const compiled = compileTableToOps(table.expression, hintsclone);
if (compiled instanceof TableOp.Reduce) {
// simple index doesn't work if the inner table is a reduce, because
// it relies on breaking out of the loop, and there might not be a loop
return new TableOp.Reduce(
compiled,
new ReduceOp.ComplexIndex(table.indices),
compiled.device,
compiled.handle_thingtalk,
table
);
} else {
return new TableOp.Reduce(
compiled,
new ReduceOp.SimpleIndex(index),
compiled.device,
compiled.handle_thingtalk,
table
);
}
} else if (table instanceof Ast.IndexExpression) {
// if the index is not constant, we just discard it
const hintsclone = hints.clone();
hintsclone.limit = undefined;
const compiled = compileTableToOps(table.expression, hintsclone);
return new TableOp.Reduce(
compiled,
new ReduceOp.ComplexIndex(table.indices),
compiled.device,
compiled.handle_thingtalk,
table
);
} else if (table instanceof Ast.SliceExpression) {
const hintsclone = hints.clone();
// across a slice, the limit hint becomes the base value + the limit value, if known,
// (so a slice [2:3] would fetch 4 elements, and then discard the first one)
// (note the off by one because the base is 1-based)
//
// NOTE: for correct operation, devices which implement hints MUST NOT
// implement "limit" without implementing "sort"
const base = table.base;
const limit = table.limit;
hintsclone.limit = base instanceof Ast.NumberValue && limit instanceof Ast.NumberValue ?
(base.toJS() - 1 + limit.toJS()) : undefined;
const compiled = compileTableToOps(table.expression, hintsclone);
return new TableOp.Reduce(
compiled,
new ReduceOp.Slice(table.base, table.limit),
compiled.device,
compiled.handle_thingtalk,
table
);
} else if (table instanceof Ast.ChainExpression) {
assert(table.expressions.length > 0);
if (table.expressions.length === 1)
return compileTableToOps(table.expressions[0], hints);
let tableop = compileTableToOps(table.expressions[0], restrictHintsForJoin(hints, table.expressions[0].schema!));
for (let i = 1; i < table.expressions.length; i++) {
const rhs = table.expressions[i];
const rhsop = compileTableToOps(rhs, restrictHintsForJoin(hints, rhs.schema!));
let device : Ast.DeviceSelector|null = null;
let handle_thingtalk = false;
if (tableop.device && rhsop.device) {
device = sameDevice(tableop.device, rhsop.device) ? tableop.device : null;
handle_thingtalk = sameDevice(tableop.device, rhsop.device) ? tableop.handle_thingtalk && rhsop.handle_thingtalk : false;
}
if (hasParameterPassing(rhs))
tableop = new TableOp.NestedLoopJoin(tableop, rhsop, device, handle_thingtalk, table);
else
tableop = new TableOp.CrossJoin(tableop, rhsop, device, handle_thingtalk, table);
}
return tableop;
} else if (table instanceof Ast.BooleanQuestionExpression) {
const schema = table.expression.schema;
assert(schema);
const hintsclone = hints.clone();
const compiled = compileTableToOps(table.expression, hintsclone);
return new TableOp.Map(
compiled,
new PointWiseOp.BooleanCompute(table.booleanExpression),
compiled.device,
compiled.handle_thingtalk,
table
);
} else if (table instanceof Ast.JoinExpression) {
const lhsop = compileTableToOps(table.lhs, restrictHintsForJoin(hints, table.lhs.schema!));
const rhsop = compileTableToOps(table.rhs, restrictHintsForJoin(hints, table.rhs.schema!));
let device : Ast.DeviceSelector|null = null;
let handle_thingtalk = false;
if (lhsop.device && rhsop.device) {
device = sameDevice(lhsop.device, rhsop.device) ? lhsop.device : null;
handle_thingtalk = sameDevice(lhsop.device, rhsop.device) ? lhsop.handle_thingtalk && rhsop.handle_thingtalk : false;
}
return new TableOp.Join(lhsop, rhsop, device, handle_thingtalk, table);
} else {
throw new TypeError(table.constructor.name);
}
}
function optimizeStreamOp(streamop : StreamOp, hasOutputAction : boolean) : StreamOp {
// optimize edgenew of edgenew
if (streamop instanceof StreamOp.EdgeNew && streamop.stream instanceof StreamOp.EdgeNew)
return optimizeStreamOp(streamop.stream, hasOutputAction);
// remove projection if there is no "notify;"
if (!hasOutputAction && streamop instanceof StreamOp.Map &&
streamop.op instanceof PointWiseOp.Projection)
return optimizeStreamOp(streamop.stream, hasOutputAction);
// optimize projection of projection
if (streamop instanceof StreamOp.Map && streamop.op instanceof PointWiseOp.Projection) {
const inner = streamop.stream;
if (inner instanceof StreamOp.Map && inner.op instanceof PointWiseOp.Projection) {
// bypass the inner projection, as the outer one subsumes it
streamop.stream = optimizeStreamOp(inner.stream, hasOutputAction);
return streamop;
}
}
if (streamop instanceof StreamOp.InvokeTable ||
streamop instanceof StreamOp.Join) {
streamop.stream = optimizeStreamOp(streamop.stream, hasOutputAction);
streamop.table = optimizeTableOp(streamop.table, hasOutputAction);
return streamop;
}
if (isUnaryStreamOp(streamop)) {
streamop.stream = optimizeStreamOp(streamop.stream, hasOutputAction);
return streamop;
}
return streamop;
}
function optimizeTableOp(tableop : TableOp, hasOutputAction : boolean) : TableOp {
// remove projection if there is no "notify;"
if (!hasOutputAction && tableop instanceof TableOp.Map &&
tableop.op instanceof PointWiseOp.Projection)
return optimizeTableOp(tableop.table, hasOutputAction);
// optimize projection of projection
if (tableop instanceof TableOp.Map && tableop.op instanceof PointWiseOp.Projection) {
const inner = tableop.table;
if (inner instanceof TableOp.Map &&
inner.op instanceof PointWiseOp.Projection) {
// bypass the inner projection, as the outer one subsumes it
tableop.table = optimizeTableOp(inner.table, hasOutputAction);
return tableop;
}
}
if (tableop instanceof TableOp.CrossJoin ||
tableop instanceof TableOp.NestedLoopJoin) {
tableop.lhs = optimizeTableOp(tableop.lhs, hasOutputAction);
tableop.rhs = optimizeTableOp(tableop.rhs, hasOutputAction);
return tableop;
}
if (isUnaryTableOp(tableop)) {
tableop.table = optimizeTableOp(tableop.table, hasOutputAction);
return tableop;
}
return tableop;
}
function compileActionToOps(action : Ast.Expression, projection : Set<string>, statementSchema : Ast.FunctionDef|null) {
if (action instanceof Ast.InvocationExpression) {
if (statementSchema) {
for (const p of action.invocation.in_params)
addAll(projection, getExpressionParameters(p.value, statementSchema));
}
return new ActionOp.InvokeDo(action.invocation, action);
} else if (action instanceof Ast.FunctionCallExpression) {
if (statementSchema) {
for (const p of action.in_params)
addAll(projection, getExpressionParameters(p.value, statementSchema));
}
return new ActionOp.InvokeVarRef(action.name, action.in_params, action);
} else {
throw new TypeError();
}
}
// compile a rule/command statement to a RuleOp
function compileStatementToOp(statement : Ast.ExpressionStatement|Ast.ReturnStatement) : RuleOp {
const expression = statement.expression instanceof Ast.ChainExpression ?
statement.expression : new Ast.ChainExpression(null, [statement.expression], statement.expression.schema);
const lastQuery = expression.lastQuery;
const statementSchema = lastQuery ? lastQuery.schema : null;
const hasDefaultProjection = statementSchema && statementSchema.default_projection && statementSchema.default_projection.length > 0;
const default_projection = getDefaultProjection(statementSchema);
const projection = new Set<string>();
const action = expression.last;
let actionop = null;
let hasOutputAction;
let queryExpression;
if (action.schema!.functionType === 'action') {
hasOutputAction = false;
actionop = compileActionToOps(action, projection, statementSchema);
if (expression.expressions.length > 0)
queryExpression = new Ast.ChainExpression(null, expression.expressions.slice(0, -1), null);
else
queryExpression = null;
} else {
hasOutputAction = true;
addAll(projection, default_projection);
queryExpression = expression;
}
let streamop;
if (expression.first.schema!.functionType === 'stream') {
streamop = compileStreamToOps(queryExpression!, new QueryInvocationHints(projection));
// if there is no #[default_projection] annotation, we don't bother with a projection operation,
// the result will contain the right parameters already
if (hasDefaultProjection) {
streamop = new StreamOp.Map(
streamop,
new PointWiseOp.Projection(projection),
new Ast.ProjectionExpression(null, queryExpression!, [...projection], [], [], queryExpression!.schema)
);
}
} else if (queryExpression && queryExpression.expressions.length > 0) {
let tableop = compileTableToOps(queryExpression, new QueryInvocationHints(projection));
// if there is no #[default_projection] annotation, we don't bother with a projection operation,
// the result will contain the right parameters already
if (hasDefaultProjection) {
const newtable = new ProjectionExpression(null, queryExpression, [...projection], [], [], queryExpression.schema);
tableop = new TableOp.Map(
tableop,
new PointWiseOp.Projection(projection),
tableop.device,
tableop.handle_thingtalk,
newtable
);
streamop = new StreamOp.Now(tableop, newtable);
} else {
streamop = new StreamOp.Now(tableop, queryExpression);
}
} else {
streamop = null;
}
if (streamop)
streamop = optimizeStreamOp(streamop, hasOutputAction);
return new RuleOp(streamop, actionop, statement);
}
function compileBooleanExpressionToOp(expr : Ast.BooleanExpression) : BooleanExpressionOp {
if (expr instanceof Ast.AtomBooleanExpression)
return new BooleanExpressionOp.Atom(expr, new Ast.Value.VarRef(expr.name), expr.operator, expr.value, expr.overload);
if (expr instanceof Ast.NotBooleanExpression)
return new BooleanExpressionOp.Not(expr, compileBooleanExpressionToOp(expr.expr));
if (expr instanceof Ast.AndBooleanExpression) {
return new BooleanExpressionOp.And(
expr,
expr.operands.map((operand) => compileBooleanExpressionToOp(operand))
);
}
if (expr instanceof Ast.OrBooleanExpression) {
return new BooleanExpressionOp.Or(
expr,
expr.operands.map((operand) => compileBooleanExpressionToOp(operand))
);
}
if (expr instanceof Ast.ExternalBooleanExpression) {
const table = new Ast.InvocationExpression(null, new Ast.Invocation(null,
expr.selector, expr.channel, expr.in_params, expr.schema), expr.schema);
const tableop = compileTableToOps(table, new QueryInvocationHints(new Set));
const subquery = new Ast.ExistentialSubqueryBooleanExpression(null, table);
return new BooleanExpressionOp.ExistentialSubquery(subquery, tableop);
}
if (expr instanceof Ast.ExistentialSubqueryBooleanExpression) {
return new BooleanExpressionOp.ExistentialSubquery(
expr,
compileTableToOps(expr.subquery, new QueryInvocationHints(new Set))
);
}
if (expr instanceof Ast.ComparisonSubqueryBooleanExpression) {
assert(expr.rhs instanceof Ast.ProjectionExpression && expr.rhs.args.length + expr.rhs.computations.length === 1);
let rhs, hints;
if (expr.rhs.args.length) {
rhs = expr.rhs.args[0];
hints = new QueryInvocationHints(new Set(expr.rhs.args));
} else {
rhs = expr.rhs.aliases[0] || getScalarExpressionName(expr.rhs.computations[0]);
hints = new QueryInvocationHints(new Set([rhs]));
}
const subquery = compileTableToOps(expr.rhs, hints);
return new BooleanExpressionOp.ComparisonSubquery(
expr,
expr.lhs,
expr.operator,
new Ast.Value.VarRef(rhs),
subquery,
expr.overload
);
}
if (expr === Ast.BooleanExpression.True || expr instanceof Ast.DontCareBooleanExpression)
return BooleanExpressionOp.True;
if (expr === Ast.BooleanExpression.False)
return BooleanExpressionOp.False;
if (expr instanceof Ast.ComputeBooleanExpression)
return new BooleanExpressionOp.Atom(expr, expr.lhs, expr.operator, expr.rhs, expr.overload);
throw new TypeError();
}
export {
compileStatementToOp,
compileStreamToOps,
compileTableToOps,
compileActionToOps,
compileBooleanExpressionToOp
}; | the_stack |
import React, { Component } from 'react';
/*-- Apply Third-party plugins (import location should be in front of "GLOBAL STYLES") --*/
import '@/components/_plugins/_lib-bootstrap';
import '@/components/_plugins/_lib-icons';
// Slideshow
import { Swiper as SW } from '@/components/_plugins/_lib-slideshow';
/*-- Apply global scripts and styles --*/
import '@/components/_utils/styles/_all.scss';
import '@/components/_utils/styles/rtl/_all.scss';
import { __ } from '@/components/_utils/_all';
/*-- Apply this component styles --*/
import '@/components/Swiper/styles/_style.scss';
/*-- Apply Third-party animation plugins --*/
import TweenMax from '@/components/_plugins/_lib-gsap';
//get project config
import { rootDirectory } from '@/config/websiteConfig.js';
type SwiperProps = {
/** -- */
id?: string;
};
type SwiperState = false;
export default class Swiper extends Component<SwiperProps, SwiperState> {
private rootRef = React.createRef<HTMLDivElement>();
uniqueID: string;
constructor(props) {
super(props);
this.uniqueID = 'app-' + __.GUID.create();
}
componentDidMount() {
const self = this;
__( document ).ready( () => {
const reactDomEl: any = self.rootRef.current;
const $el = __( reactDomEl );
//Synchronize multiple objects
//------------------------------------------
if ( $el.find( '#app-slider1' ).len() > 0 ) {
const swiper2: any = new SW('#app-slider2', {
slidesPerView: 5,
spaceBetween: 10,
allowTouchMove: false
});
const swiper1: any = new SW('#app-slider1', {
slidesPerView: 1,
spaceBetween: 10,
speed: 1000,
pagination: {
el: '.swiper-pagination',
clickable: true,
renderBullet: function (index, className) {
return '<span class="' + className + '">' + (index + 1) + '</span>';
},
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
breakpoints: {
640 : {
slidesPerView: 2,
spaceBetween: 20,
},
768 : {
slidesPerView: 4,
spaceBetween: 40,
},
1024 : {
slidesPerView: 5,
spaceBetween: 50,
},
},
});
//Sync swiper slider
swiper1.on( 'slideChange', function(this: any) {
const index = this.activeIndex;
swiper2.slideTo( index, 1000, false );
});
}
//Swiper custom slides transform effect (Parallax effect)
//------------------------------------------
if ( $el.find( '#app-slider3' ).len() > 0 ) {
const interleaveOffset = 0.5;
const swiper3: any = new SW('#app-slider3', {
slidesPerView: 1,
spaceBetween: 0,
loop: false,
speed: 1000,
grabCursor: false,
watchSlidesProgress: true,
mousewheelControl: false,
keyboardControl: false,
pagination: {
el: '.swiper-pagination',
clickable: true,
renderBullet: function (index, className) {
return '<span class="' + className + '">' + (index + 1) + '</span>';
},
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
on: {
progress: function(this: any, e: any ) {
const thisSwiper = this;
for (let i = 0; i < thisSwiper.slides.length; i++) {
const slideProgress = thisSwiper.slides[i].progress;
const innerOffset = thisSwiper.width * interleaveOffset;
const innerTranslate = slideProgress * innerOffset;
thisSwiper.slides[i].querySelector(".slide-inner").style.transform = "translate3d(" + innerTranslate + "px, 0, 0)";
//console.log( e.passedParams );
}
},
touchStart: function(this: any, e: any ) {
const passedParams = e.passedParams;
const thisSwiper = this;
for (let i = 0; i < thisSwiper.slides.length; i++) {
thisSwiper.slides[i].style.transition = "";
}
},
setTransition: function(this: any, e: any ) {
const passedParams = e.passedParams;
const thisSwiper = this;
for (let i = 0; i < thisSwiper.slides.length; i++) {
thisSwiper.slides[i].style.transition = passedParams.speed + "ms";
thisSwiper.slides[i].querySelector(".slide-inner").style.transition = passedParams.speed + "ms";
}
}
}
});
//AutoPlay
swiper3.autoplay.start();
//swiper3.autoplay.stop();
}
//Swiper custom slides transform effect (Scale Effect without left/right swipe)
//------------------------------------------
if ( $el.find( '#app-slider4' ).len() > 0 ) {
const swiper4: any = new SW('#app-slider4', {
slidesPerView: 1,
spaceBetween: 0,
loop: false,
speed: 1000,
grabCursor: false,
watchSlidesProgress: true,
mousewheelControl: false,
keyboardControl: false,
virtualTranslate: true, /* Required */
pagination: {
el: '.swiper-pagination',
clickable: true,
renderBullet: function (index, className) {
return '<span class="' + className + '">' + (index + 1) + '</span>';
},
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
on: {
progress: function(this: any, translate: any ) {
const thisSwiper = this;
for (let i = 0; i < thisSwiper.slides.length; i++) {
const slideProgress = thisSwiper.slides[i].progress;
console.log( translate.params );
}
},
touchStart: function(this: any, translate: any ) {
const params = translate.params;
const thisSwiper = this;
},
setTransition(this: any, translate: any ) {
const params = translate.params;
const thisSwiper = this;
},
setTranslate(this: any, translate: any) {
const params = translate.params;
const thisSwiper = this;
/*
A weird way to find this out but I've found no other.
Checks if the progress on the active slide is 1 or -1 which happens when swiper navigates to next/previous slide on click and keybord navigation.
If not then the slider is being dragged, so we get the right index by finding the startTranslate from touchEvents in array of transitions the swiper snaps to.
The startTranslate doesn't exist on initial load so we use the initialSlide index instead.
*/
const getActiveIndexBeforeTransitionStart = function(curSwiper, curSlides) {
const _progress = curSlides[curSwiper.activeIndex].progress;
const _draggingProgress = Math.abs(_progress);
const isDragging = _draggingProgress === 1 ? true : false;
if (isDragging) {
return curSwiper.slidesGrid.indexOf( -curSwiper.touchEventsData.startTranslate || curSwiper.params.initialSlide);
} else {
return curSwiper.activeIndex;
}
};
const getDirection = function(animationProgress) {
if (animationProgress === 0) {
return "NONE";
} else if (animationProgress > 0) {
return "NEXT";
} else {
return "BACK";
}
};
const durationInSeconds = params.speed / 1000;
// convert slides object to plain array
const slides = thisSwiper.slides;
// get the index of the slide active before transition start (activeIndex changes halfway when dragging)
const originIndex = getActiveIndexBeforeTransitionStart(thisSwiper, slides);
// get information about animation progress from the active slide - the active slide's value is always -1 to 1.
/*
every slide has a progress attribute equal to the "distance" from the current active index.
*/
const animationProgress = slides[originIndex].progress;
// you can then get the drag direction like so:
const direction = getDirection(animationProgress);
// console.log(direction);
// do magic with each slide
slides.map(function (perSlide, index) {
// to put the slides behind each other we have to set their CSS translate accordingly since by default they are arranged in line.
const offset = perSlide.swiperSlideOffset;
let x = -offset;
if (!thisSwiper.params.virtualTranslate) x -= thisSwiper.translate;
let y = 0;
if (!thisSwiper.isHorizontal()) {
y = x;
x = 0;
}
TweenMax.set(perSlide, {
x,
y
});
// do our animation stuff!
const clip = function clip(val, min, max) {
return Math.max(min, Math.min(val, max));
};
const ZOOM_FACTOR = 0.05;
const opacity = Math.max(1 - Math.abs(perSlide.progress), 0);
const clippedProgress = clip(perSlide.progress, -1, 1);
const scale = 1 - ZOOM_FACTOR * clippedProgress;
// you can do your CSS animation instead of using tweening.
TweenMax.to(perSlide, durationInSeconds, {
scale,
opacity
});
});
}
}
});
//AutoPlay
swiper4.autoplay.start();
//swiper4.autoplay.stop();
}
//Centered Slides
//------------------------------------------
if ( $el.find( '#app-slider5' ).len() > 0 ) {
const swiper5: any = new SW('#app-slider5', {
slidesPerView: 3,
spaceBetween: 30,
loop: true,
speed: 1000,
centeredSlides: true,
pagination: {
el: '.swiper-pagination',
clickable: true,
renderBullet: function (index, className) {
return '<span class="' + className + '">' + (index + 1) + '</span>';
},
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
}
});
}
//Display half on both sides
//------------------------------------------
if ( $el.find( '#app-slider6' ).len() > 0 ) {
const swiper6: any = new SW('#app-slider6', {
slidesPerView: 'auto',//Number of slides per view, and it must be "auto"!
spaceBetween: 30,
loop: true,
speed: 1000,
centeredSlides: true, //When true, then active slide will be centered, not always on the left side.
pagination: {
el: '.swiper-pagination',
clickable: true,
renderBullet: function (index, className) {
return '<span class="' + className + '">' + (index + 1) + '</span>';
},
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
}
});
}
//Custom Progress Bar
//------------------------------------------
if ( $el.find( '#app-slider7' ).len() > 0 ) {
const cusProgressBar = function( speed, length, curIndex ) {
TweenMax.set( '#app-slider7__progress', {
width: 0,
onComplete: function() {
TweenMax.to( '#app-slider7__progress', speed/1000, {
width: '100%'
});
}
});
TweenMax.set( '#app-slider7__progress2', {
width: 100/length * (curIndex) + '%',
onComplete: function() {
TweenMax.to( '#app-slider7__progress2', speed/1000, {
width: 100/length * (curIndex+1) + '%'
});
}
});
};
const swiper7: any = new SW('#app-slider7', {
slidesPerView: 1,
spaceBetween: 0,
loop: false,
speed: 3500,
grabCursor: false,
watchSlidesProgress: true,
mousewheelControl: false,
keyboardControl: false,
pagination: {
el: '.swiper-pagination',
clickable: true,
renderBullet: function (index, className) {
return '<span class="' + className + '">' + (index + 1) + '</span>';
},
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
on: {
init: function(this: any, e: any ) {
const thisSwiper = this;
console.log( 'current index: ' + thisSwiper.activeIndex );
cusProgressBar( e.passedParams.speed, thisSwiper.slides.length, thisSwiper.activeIndex );
},
slideChange: function(this: any, e: any ) {
const thisSwiper = this;
console.log( 'current index: ' + thisSwiper.activeIndex );
cusProgressBar( e.passedParams.speed, thisSwiper.slides.length, thisSwiper.activeIndex );
}
}
});
}
//Gallery with center thumbs automatically
//------------------------------------------
if ( $el.find( '#app-slider8' ).len() > 0 ) {
const swiper8: any = new SW('#app-slider8', {
spaceBetween: 10,
grabCursor: false,
loop: true,
loopedSlides: 4,
autoplay: {
delay: 5000
},
// other parameters
on: {
click: function() {
/* do something */
}
},
keyboard: {
enabled: true,
onlyInViewport: false
},
autoHeight: true,
pagination: {
el: '.swiper-pagination',
clickable: true,
renderBullet: function (index, className) {
return '<span class="' + className + '">' + (index + 1) + '</span>';
},
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
speed: 1000
});
/* thumbs */
const swiper8Thumbs: any = new SW( '#app-slider8-thumbs', {
spaceBetween: 10,
centeredSlides: true,
slidesPerView: "auto", //If you use it with "auto" value and along with loop: true then you need to specify loopedSlides parameter with amount of slides to loop (duplicate)
touchRatio: 0.4,
slideToClickedSlide: true,
loop: true,
loopedSlides: 4,
keyboard: {
enabled: true,
onlyInViewport: false
},
speed: 1000
});
/* set conteoller */
swiper8.controller.control = swiper8Thumbs;
swiper8Thumbs.controller.control = swiper8;
}
//Gallery with manual triggers
//------------------------------------------
if ( $el.find( '#app-slider9' ).len() > 0 ) {
const swiper9: any = new SW('#app-slider9', {
spaceBetween: 10,
grabCursor: false,
autoplay: {
delay: 5000
},
// other parameters
keyboard: {
enabled: true,
onlyInViewport: false
},
autoHeight: true,
pagination: {
el: '.swiper-pagination',
clickable: true,
renderBullet: function (index, className) {
return '<span class="' + className + '">' + (index + 1) + '</span>';
},
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
speed: 1000,
on: {
click: function() {
/* do something */
},
init: function(this: any, e: any ) {
const thisSwiper = this;
swiper9BTN( thisSwiper.activeIndex, true );
}
}
});
//Sync swiper slider
swiper9.on( 'slideChange', function(this: any) {
const index = this.activeIndex;
swiper9BTN( index, false );
});
__( '#app-slider9-triggers > div' ).off( 'click' ).on( 'click', function(this: any) {
swiper9BTN( __( this ).index(), false );
});
function swiper9BTN( index, init ) {
const _btns = __( '#app-slider9-triggers > div' );
_btns.removeClass( 'is-active' );
_btns.eq( index ).addClass( 'is-active' );
if ( !init ) {
swiper9.slideTo( index, 1000 );
}
}
}
//------------------------------------------
});
}
/** Remove the global list of events, especially as scroll and interval. */
componentWillUnmount() {
// Kill all aniamtions
TweenMax.killAll();
}
render() {
const {
id
} = this.props;
return (
<>
<div ref={this.rootRef} id={id || this.uniqueID} className="poemkit-swiper">
{/*<!-- Title
====================================================== -->*/}
<section className="poemkit-spacing--s poemkit-spacing--no-top">
<div className="container">
<div className="row">
<div className="col-12">
<h3 className="app-header-title">Synchronize multiple objects</h3>
<p>For different responsive breakpoints (screen sizes) and custom buttons.</p>
<hr />
</div>
</div>
{/*<!-- .row end -->*/}
</div>
{/*<!-- .container end -->*/}
</section>
{/*<!-- Slideshow
====================================================== -->*/}
<div role="slider" className="swiper-container" id="app-slider1">
<div className="swiper-wrapper">
<div className="swiper-slide">Slide One 1</div>
<div className="swiper-slide">Slide One 2</div>
<div className="swiper-slide">Slide One 3</div>
<div className="swiper-slide">Slide One 4</div>
<div className="swiper-slide">Slide One 5</div>
<div className="swiper-slide">Slide One 6</div>
<div className="swiper-slide">Slide One 7</div>
<div className="swiper-slide">Slide One 8</div>
<div className="swiper-slide">Slide One 9</div>
<div className="swiper-slide">Slide One 10</div>
</div>
{/*<!-- Add Pagination -->*/}
<div className="swiper-pagination"></div>
{/*<!-- Add Arrows -->*/}
<div className="swiper-button-prev">
<svg viewBox="0 0 448 512"><path d="M257.5 445.1l-22.2 22.2c-9.4 9.4-24.6 9.4-33.9 0L7 273c-9.4-9.4-9.4-24.6 0-33.9L201.4 44.7c9.4-9.4 24.6-9.4 33.9 0l22.2 22.2c9.5 9.5 9.3 25-.4 34.3L136.6 216H424c13.3 0 24 10.7 24 24v32c0 13.3-10.7 24-24 24H136.6l120.5 114.8c9.8 9.3 10 24.8.4 34.3z"/></svg>
</div>
<div className="swiper-button-next">
<svg viewBox="0 0 448 512"><path d="M190.5 66.9l22.2-22.2c9.4-9.4 24.6-9.4 33.9 0L441 239c9.4 9.4 9.4 24.6 0 33.9L246.6 467.3c-9.4 9.4-24.6 9.4-33.9 0l-22.2-22.2c-9.5-9.5-9.3-25 .4-34.3L311.4 296H24c-13.3 0-24-10.7-24-24v-32c0-13.3 10.7-24 24-24h287.4L190.9 101.2c-9.8-9.3-10-24.8-.4-34.3z"/></svg>
</div>
</div>
{/*<!-- /.swiper-container -->*/}
<div role="slider" className="swiper-container" id="app-slider2" style={{marginTop:"30px"}}>
<div className="swiper-wrapper">
<div className="swiper-slide">Slide Two 1</div>
<div className="swiper-slide">Slide Two 2</div>
<div className="swiper-slide">Slide Two 3</div>
<div className="swiper-slide">Slide Two 4</div>
<div className="swiper-slide">Slide Two 5</div>
<div className="swiper-slide">Slide Two 6</div>
<div className="swiper-slide">Slide Two 7</div>
<div className="swiper-slide">Slide Two 8</div>
<div className="swiper-slide">Slide Two 9</div>
<div className="swiper-slide">Slide Two 10</div>
</div>
</div>
{/*<!-- /.swiper-container -->*/}
{/*<!-- Title
====================================================== -->*/}
<section className="poemkit-spacing--s">
<div className="container">
<div className="row">
<div className="col-12">
<h3 className="app-header-title">Parallax Effect</h3>
<p>Custom slides transform effect and custom buttons..</p>
<hr />
</div>
</div>
{/*<!-- .row end -->*/}
</div>
{/*<!-- .container end -->*/}
</section>
{/*<!-- Slideshow
====================================================== -->*/}
<div role="slider" className="swiper-container" id="app-slider3" style={{marginTop:"30px"}}>
<div className="swiper-wrapper">
<div className="swiper-slide"><span>Slide Three 1</span><div className="slide-inner" style={{backgroundImage:`url(${rootDirectory}/assets/images/demo/slide-1.jpg)`}}></div></div>
<div className="swiper-slide"><span>Slide Three 2</span><div className="slide-inner" style={{backgroundImage:`url(${rootDirectory}/assets/images/demo/slide-2.jpg)`}}></div></div>
<div className="swiper-slide"><span>Slide Three 3</span><div className="slide-inner" style={{backgroundImage:`url(${rootDirectory}/assets/images/demo/slide-3.jpg)`}}></div></div>
</div>
{/*<!-- Add Pagination -->*/}
<div className="swiper-pagination"></div>
{/*<!-- Add Arrows -->*/}
<div className="swiper-button-prev">
<svg viewBox="0 0 448 512"><path d="M257.5 445.1l-22.2 22.2c-9.4 9.4-24.6 9.4-33.9 0L7 273c-9.4-9.4-9.4-24.6 0-33.9L201.4 44.7c9.4-9.4 24.6-9.4 33.9 0l22.2 22.2c9.5 9.5 9.3 25-.4 34.3L136.6 216H424c13.3 0 24 10.7 24 24v32c0 13.3-10.7 24-24 24H136.6l120.5 114.8c9.8 9.3 10 24.8.4 34.3z"/></svg>
</div>
<div className="swiper-button-next">
<svg viewBox="0 0 448 512"><path d="M190.5 66.9l22.2-22.2c9.4-9.4 24.6-9.4 33.9 0L441 239c9.4 9.4 9.4 24.6 0 33.9L246.6 467.3c-9.4 9.4-24.6 9.4-33.9 0l-22.2-22.2c-9.5-9.5-9.3-25 .4-34.3L311.4 296H24c-13.3 0-24-10.7-24-24v-32c0-13.3 10.7-24 24-24h287.4L190.9 101.2c-9.8-9.3-10-24.8-.4-34.3z"/></svg>
</div>
</div>
{/*<!-- /.swiper-container -->*/}
{/*<!-- Title
====================================================== -->*/}
<section className="poemkit-spacing--s">
<div className="container">
<div className="row">
<div className="col-12">
<h3 className="app-header-title">Scale Effect without left/right swipe</h3>
<p>Custom slides transform effect and custom buttons..</p>
<hr />
</div>
</div>
{/*<!-- .row end -->*/}
</div>
{/*<!-- .container end -->*/}
</section>
{/*<!-- Slideshow
====================================================== -->*/}
<div role="slider" className="swiper-container" id="app-slider4" style={{marginTop:"30px"}}>
<div className="swiper-wrapper">
<div className="swiper-slide"><span>Slide Three 1</span><div className="slide-inner" style={{backgroundImage:`url(${rootDirectory}/assets/images/demo/slide-1.jpg)`}}></div></div>
<div className="swiper-slide"><span>Slide Three 2</span><div className="slide-inner" style={{backgroundImage:`url(${rootDirectory}/assets/images/demo/slide-2.jpg)`}}></div></div>
<div className="swiper-slide"><span>Slide Three 3</span><div className="slide-inner" style={{backgroundImage:`url(${rootDirectory}/assets/images/demo/slide-3.jpg)`}}></div></div>
</div>
{/*<!-- Add Pagination -->*/}
<div className="swiper-pagination"></div>
{/*<!-- Add Arrows -->*/}
<div className="swiper-button-prev">
<svg viewBox="0 0 448 512"><path d="M257.5 445.1l-22.2 22.2c-9.4 9.4-24.6 9.4-33.9 0L7 273c-9.4-9.4-9.4-24.6 0-33.9L201.4 44.7c9.4-9.4 24.6-9.4 33.9 0l22.2 22.2c9.5 9.5 9.3 25-.4 34.3L136.6 216H424c13.3 0 24 10.7 24 24v32c0 13.3-10.7 24-24 24H136.6l120.5 114.8c9.8 9.3 10 24.8.4 34.3z"/></svg>
</div>
<div className="swiper-button-next">
<svg viewBox="0 0 448 512"><path d="M190.5 66.9l22.2-22.2c9.4-9.4 24.6-9.4 33.9 0L441 239c9.4 9.4 9.4 24.6 0 33.9L246.6 467.3c-9.4 9.4-24.6 9.4-33.9 0l-22.2-22.2c-9.5-9.5-9.3-25 .4-34.3L311.4 296H24c-13.3 0-24-10.7-24-24v-32c0-13.3 10.7-24 24-24h287.4L190.9 101.2c-9.8-9.3-10-24.8-.4-34.3z"/></svg>
</div>
</div>
{/*<!-- /.swiper-container -->*/}
{/*<!-- Title
====================================================== -->*/}
<section className="poemkit-spacing--s">
<div className="container">
<div className="row">
<div className="col-12">
<h3 className="app-header-title">Centered Slides</h3>
<p>Allow this option if you want to have your active slide in the center, instead of snapped to the left side of Swiper view.</p>
<hr />
</div>
</div>
{/*<!-- .row end -->*/}
</div>
{/*<!-- .container end -->*/}
</section>
{/*<!-- Slideshow
====================================================== -->*/}
<div role="slider" className="swiper-container" id="app-slider5">
<div className="swiper-wrapper">
<div className="swiper-slide">Slide One 1</div>
<div className="swiper-slide">Slide One 2</div>
<div className="swiper-slide">Slide One 3</div>
<div className="swiper-slide">Slide One 4</div>
<div className="swiper-slide">Slide One 5</div>
<div className="swiper-slide">Slide One 6</div>
<div className="swiper-slide">Slide One 7</div>
<div className="swiper-slide">Slide One 8</div>
</div>
{/*<!-- Add Pagination -->*/}
<div className="swiper-pagination"></div>
{/*<!-- Add Arrows -->*/}
<div className="swiper-button-prev">
<svg viewBox="0 0 448 512"><path d="M257.5 445.1l-22.2 22.2c-9.4 9.4-24.6 9.4-33.9 0L7 273c-9.4-9.4-9.4-24.6 0-33.9L201.4 44.7c9.4-9.4 24.6-9.4 33.9 0l22.2 22.2c9.5 9.5 9.3 25-.4 34.3L136.6 216H424c13.3 0 24 10.7 24 24v32c0 13.3-10.7 24-24 24H136.6l120.5 114.8c9.8 9.3 10 24.8.4 34.3z"/></svg>
</div>
<div className="swiper-button-next">
<svg viewBox="0 0 448 512"><path d="M190.5 66.9l22.2-22.2c9.4-9.4 24.6-9.4 33.9 0L441 239c9.4 9.4 9.4 24.6 0 33.9L246.6 467.3c-9.4 9.4-24.6 9.4-33.9 0l-22.2-22.2c-9.5-9.5-9.3-25 .4-34.3L311.4 296H24c-13.3 0-24-10.7-24-24v-32c0-13.3 10.7-24 24-24h287.4L190.9 101.2c-9.8-9.3-10-24.8-.4-34.3z"/></svg>
</div>
</div>
{/*<!-- /.swiper-container -->*/}
{/*<!-- Title
====================================================== -->*/}
<section className="poemkit-spacing--s">
<div className="container">
<div className="row">
<div className="col-12">
<h3 className="app-header-title">Display half on both sides</h3>
<p>Set up CSS to achieve only half of the entries on both sides.</p>
<hr />
</div>
</div>
{/*<!-- .row end -->*/}
</div>
{/*<!-- .container end -->*/}
</section>
{/*<!-- Slideshow
====================================================== -->*/}
<div role="slider" className="swiper-container" id="app-slider6">
<div className="swiper-wrapper">
<div className="swiper-slide">Slide One 1</div>
<div className="swiper-slide">Slide One 2</div>
<div className="swiper-slide">Slide One 3</div>
<div className="swiper-slide">Slide One 4</div>
<div className="swiper-slide">Slide One 5</div>
<div className="swiper-slide">Slide One 6</div>
<div className="swiper-slide">Slide One 7</div>
<div className="swiper-slide">Slide One 8</div>
</div>
{/*<!-- Add Pagination -->*/}
<div className="swiper-pagination"></div>
{/*<!-- Add Arrows -->*/}
<div className="swiper-button-prev">
<svg viewBox="0 0 448 512"><path d="M257.5 445.1l-22.2 22.2c-9.4 9.4-24.6 9.4-33.9 0L7 273c-9.4-9.4-9.4-24.6 0-33.9L201.4 44.7c9.4-9.4 24.6-9.4 33.9 0l22.2 22.2c9.5 9.5 9.3 25-.4 34.3L136.6 216H424c13.3 0 24 10.7 24 24v32c0 13.3-10.7 24-24 24H136.6l120.5 114.8c9.8 9.3 10 24.8.4 34.3z"/></svg>
</div>
<div className="swiper-button-next">
<svg viewBox="0 0 448 512"><path d="M190.5 66.9l22.2-22.2c9.4-9.4 24.6-9.4 33.9 0L441 239c9.4 9.4 9.4 24.6 0 33.9L246.6 467.3c-9.4 9.4-24.6 9.4-33.9 0l-22.2-22.2c-9.5-9.5-9.3-25 .4-34.3L311.4 296H24c-13.3 0-24-10.7-24-24v-32c0-13.3 10.7-24 24-24h287.4L190.9 101.2c-9.8-9.3-10-24.8-.4-34.3z"/></svg>
</div>
</div>
{/*<!-- /.swiper-container -->*/}
{/*<!-- Title
====================================================== -->*/}
<section className="poemkit-spacing--s">
<div className="container">
<div className="row">
<div className="col-12">
<h3 className="app-header-title">Custom Progress Bar</h3>
<p>Demonstrate how to add a slide progress bar to Swiper.</p>
<hr />
</div>
</div>
{/*<!-- .row end -->*/}
</div>
{/*<!-- .container end -->*/}
</section>
{/*<!-- Slideshow
====================================================== -->*/}
<div role="slider" className="swiper-container" id="app-slider7">
<div id="app-slider7__progress"></div>
<div id="app-slider7__progress2"></div>
<div className="swiper-wrapper">
<div className="swiper-slide">Slide One 1</div>
<div className="swiper-slide">Slide One 2</div>
<div className="swiper-slide">Slide One 3</div>
<div className="swiper-slide">Slide One 4</div>
<div className="swiper-slide">Slide One 5</div>
<div className="swiper-slide">Slide One 6</div>
<div className="swiper-slide">Slide One 7</div>
<div className="swiper-slide">Slide One 8</div>
</div>
{/*<!-- Add Pagination -->*/}
<div className="swiper-pagination"></div>
{/*<!-- Add Arrows -->*/}
<div className="swiper-button-prev">
<svg viewBox="0 0 448 512"><path d="M257.5 445.1l-22.2 22.2c-9.4 9.4-24.6 9.4-33.9 0L7 273c-9.4-9.4-9.4-24.6 0-33.9L201.4 44.7c9.4-9.4 24.6-9.4 33.9 0l22.2 22.2c9.5 9.5 9.3 25-.4 34.3L136.6 216H424c13.3 0 24 10.7 24 24v32c0 13.3-10.7 24-24 24H136.6l120.5 114.8c9.8 9.3 10 24.8.4 34.3z"/></svg>
</div>
<div className="swiper-button-next">
<svg viewBox="0 0 448 512"><path d="M190.5 66.9l22.2-22.2c9.4-9.4 24.6-9.4 33.9 0L441 239c9.4 9.4 9.4 24.6 0 33.9L246.6 467.3c-9.4 9.4-24.6 9.4-33.9 0l-22.2-22.2c-9.5-9.5-9.3-25 .4-34.3L311.4 296H24c-13.3 0-24-10.7-24-24v-32c0-13.3 10.7-24 24-24h287.4L190.9 101.2c-9.8-9.3-10-24.8-.4-34.3z"/></svg>
</div>
</div>
{/*<!-- /.swiper-container -->*/}
{/*<!-- Title
====================================================== -->*/}
<section className="poemkit-spacing--s">
<div className="container">
<div className="row">
<div className="col-12">
<h3 className="app-header-title">Gallery with center thumbs automatically</h3>
<p>Using the Swiper API that enables you to add custom thumbnails and link them to your Swiper instance automatically.</p>
<hr />
</div>
</div>
{/*<!-- .row end -->*/}
</div>
{/*<!-- .container end -->*/}
</section>
{/*<!-- Slideshow
====================================================== -->*/}
<div style={{maxWidth:"600px"}}>
<div role="slider" className="swiper-container" id="app-slider8">
<div className="swiper-wrapper">
<div className="swiper-slide"><img src={`${rootDirectory}/assets/images/placeholder/320x345.jpg`} alt="null" /></div>
<div className="swiper-slide"><img src={`${rootDirectory}/assets/images/placeholder/400x279.jpg`} alt="null" /></div>
<div className="swiper-slide"><img src={`${rootDirectory}/assets/images/placeholder/400x320.jpg`} alt="null" /></div>
<div className="swiper-slide"><img src={`${rootDirectory}/assets/images/placeholder/400x320.jpg`} alt="null" /></div>
<div className="swiper-slide"><img src={`${rootDirectory}/assets/images/placeholder/400x400.jpg`} alt="null" /></div>
<div className="swiper-slide"><img src={`${rootDirectory}/assets/images/placeholder/450x338.jpg`} alt="null" /></div>
</div>
{/*<!-- Add Pagination -->*/}
<div className="swiper-pagination"></div>
{/*<!-- Add Arrows -->*/}
<div className="swiper-button-prev">
<svg viewBox="0 0 448 512"><path d="M257.5 445.1l-22.2 22.2c-9.4 9.4-24.6 9.4-33.9 0L7 273c-9.4-9.4-9.4-24.6 0-33.9L201.4 44.7c9.4-9.4 24.6-9.4 33.9 0l22.2 22.2c9.5 9.5 9.3 25-.4 34.3L136.6 216H424c13.3 0 24 10.7 24 24v32c0 13.3-10.7 24-24 24H136.6l120.5 114.8c9.8 9.3 10 24.8.4 34.3z"/></svg>
</div>
<div className="swiper-button-next">
<svg viewBox="0 0 448 512"><path d="M190.5 66.9l22.2-22.2c9.4-9.4 24.6-9.4 33.9 0L441 239c9.4 9.4 9.4 24.6 0 33.9L246.6 467.3c-9.4 9.4-24.6 9.4-33.9 0l-22.2-22.2c-9.5-9.5-9.3-25 .4-34.3L311.4 296H24c-13.3 0-24-10.7-24-24v-32c0-13.3 10.7-24 24-24h287.4L190.9 101.2c-9.8-9.3-10-24.8-.4-34.3z"/></svg>
</div>
</div>
{/*<!-- /.swiper-container -->*/}
{/*<!-- //// thumbs /// -->*/}
<div role="slider" className="swiper-container" id="app-slider8-thumbs">
<div className="swiper-wrapper">
<div className="swiper-slide"><img src={`${rootDirectory}/assets/images/placeholder/320x345.jpg`} alt="null" /></div>
<div className="swiper-slide"><img src={`${rootDirectory}/assets/images/placeholder/400x279.jpg`} alt="null" /></div>
<div className="swiper-slide"><img src={`${rootDirectory}/assets/images/placeholder/400x320.jpg`} alt="null" /></div>
<div className="swiper-slide"><img src={`${rootDirectory}/assets/images/placeholder/400x320.jpg`} alt="null" /></div>
<div className="swiper-slide"><img src={`${rootDirectory}/assets/images/placeholder/400x400.jpg`} alt="null" /></div>
<div className="swiper-slide"><img src={`${rootDirectory}/assets/images/placeholder/450x338.jpg`} alt="null" /></div>
</div>
</div>
{/*<!-- /#app-slider8-thumbs -->*/}
</div>
{/*<!-- Title
====================================================== -->*/}
<section className="poemkit-spacing--s">
<div className="container">
<div className="row">
<div className="col-12">
<h3 className="app-header-title">Gallery with manual triggers</h3>
<p>Customize the thumbnail/trigger and link it to your Swiper instance manually.</p>
<hr />
</div>
</div>
{/*<!-- .row end -->*/}
</div>
{/*<!-- .container end -->*/}
</section>
{/*<!-- Slideshow
====================================================== -->*/}
<div style={{maxWidth:"600px"}}>
<div role="slider" className="swiper-container" id="app-slider9">
<div className="swiper-wrapper">
<div className="swiper-slide"><img src={`${rootDirectory}/assets/images/placeholder/320x345.jpg`} alt="null" /></div>
<div className="swiper-slide"><img src={`${rootDirectory}/assets/images/placeholder/400x279.jpg`} alt="null" /></div>
<div className="swiper-slide"><img src={`${rootDirectory}/assets/images/placeholder/400x320.jpg`} alt="null" /></div>
<div className="swiper-slide"><img src={`${rootDirectory}/assets/images/placeholder/400x320.jpg`} alt="null" /></div>
<div className="swiper-slide"><img src={`${rootDirectory}/assets/images/placeholder/400x400.jpg`} alt="null" /></div>
<div className="swiper-slide"><img src={`${rootDirectory}/assets/images/placeholder/450x338.jpg`} alt="null" /></div>
</div>
{/*<!-- Add Pagination -->*/}
<div className="swiper-pagination"></div>
{/*<!-- Add Arrows -->*/}
<div className="swiper-button-prev">
<svg viewBox="0 0 448 512"><path d="M257.5 445.1l-22.2 22.2c-9.4 9.4-24.6 9.4-33.9 0L7 273c-9.4-9.4-9.4-24.6 0-33.9L201.4 44.7c9.4-9.4 24.6-9.4 33.9 0l22.2 22.2c9.5 9.5 9.3 25-.4 34.3L136.6 216H424c13.3 0 24 10.7 24 24v32c0 13.3-10.7 24-24 24H136.6l120.5 114.8c9.8 9.3 10 24.8.4 34.3z"/></svg>
</div>
<div className="swiper-button-next">
<svg viewBox="0 0 448 512"><path d="M190.5 66.9l22.2-22.2c9.4-9.4 24.6-9.4 33.9 0L441 239c9.4 9.4 9.4 24.6 0 33.9L246.6 467.3c-9.4 9.4-24.6 9.4-33.9 0l-22.2-22.2c-9.5-9.5-9.3-25 .4-34.3L311.4 296H24c-13.3 0-24-10.7-24-24v-32c0-13.3 10.7-24 24-24h287.4L190.9 101.2c-9.8-9.3-10-24.8-.4-34.3z"/></svg>
</div>
</div>
{/*<!-- /.swiper-container -->*/}
{/*<!-- //// triggers /// -->*/}
<div id="app-slider9-triggers">
<div><img src={`${rootDirectory}/assets/images/placeholder/320x345.jpg`} alt="null" /></div>
<div><img src={`${rootDirectory}/assets/images/placeholder/400x279.jpg`} alt="null" /></div>
<div><img src={`${rootDirectory}/assets/images/placeholder/400x320.jpg`} alt="null" /></div>
<div><img src={`${rootDirectory}/assets/images/placeholder/400x320.jpg`} alt="null" /></div>
<div><img src={`${rootDirectory}/assets/images/placeholder/400x400.jpg`} alt="null" /></div>
<div><img src={`${rootDirectory}/assets/images/placeholder/450x338.jpg`} alt="null" /></div>
</div>
{/*<!-- /#app-slider9-triggers -->*/}
</div>
</div>
{/*<!-- /.poemkit-swiper -->*/}
</>
)
}
} | the_stack |
import path from "path";
import { partition, Subject, Subscription } from "rxjs";
import { first, takeUntil } from "rxjs/operators";
import { ClientPinVersion, Fido2SpecVersion, getLatestSpecVersion } from "../../environment";
import { Fido2Crypto } from "../crypto/crypto";
import { Options } from "../ctap2/cmd/get-info";
import { AuthenticatorData } from "../ctap2/make-credential";
import { IFido2Device } from "../fido2/fido2-device-cli";
import { Fido2ClientErrCancel, Fido2ClientErrExtensionNotImplemented, Fido2ClientErrInvalidParameter, Fido2ClientErrMethodDeprecated, Fido2ClientErrMissingEventListener, Fido2ClientErrMissingParameter, Fido2ClientErrNoCredentials, Fido2ClientErrNotAllowed, Fido2ClientErrPinAuthBlocked, Fido2ClientErrPinBlocked, Fido2ClientErrPinUvAuthProtocolUnsupported, Fido2ClientErrRelyPartyNotAllowed, Fido2ClientErrTimeout, Fido2ClientErrUnknown, Fido2ClientErrUserVerificationNotCapable } from "../errors/client";
import { MethodNotImplemented } from "../errors/common";
import { Ctap2ErrActionTimeout, Ctap2ErrKeepaliveCancel, Ctap2ErrNoCredentials, Ctap2ErrPinAuthBlocked, Ctap2ErrPinBlocked, Ctap2ErrPinInvalid } from "../errors/ctap2";
import { HmacSecretInput, HmacSecretExtIdentifier, HmacSecretOutput } from "../extension/hmac-secret";
import { logger } from "../log/debug";
import { verify } from "../../third_party/sign";
import { WrapAuthenticationExtensionsClientInputs } from "../webauthn/WrapAuthenticationExtensionsClientInputs";
import { WrapAuthenticationExtensionsClientOutputs } from "../webauthn/WrapAuthenticationExtensionsClientOutputs";
import { WrapAuthenticatorAttestationResponse } from "../webauthn/WrapAuthenticatorAttestationResponse";
import { WrapCOSEAlgorithmIdentifier } from "../webauthn/WrapCOSEAlgorithmIdentifier";
import { WrapCredentialCreationOptions } from "../webauthn/WrapCredentialCreateOptions";
import { WrapCredentialRequestOptions } from "../webauthn/WrapCredentialRequestOptions";
import { WrapPublicKeyCredential } from "../webauthn/WrapPublicKeyCredential";
import { WrapPublicKeyCredentialCreationOptions } from "../webauthn/WrapPublicKeyCredentialCreationOptions";
import { WrapPublicKeyCredentialRequestOptions } from "../webauthn/WrapPublicKeyCredentialRequestOptions";
import { WrapPublicKeyCredentialType } from "../webauthn/WrapPublicKeyCredentialType";
import { Base64 } from "./base64";
import { IClientOptions } from "./options";
import { Ctap2Session } from "./session";
import { Fido2Event } from "./event";
import { DeviceCliNotInitialized, DeviceCliTransactionNotFound } from "../errors/device-cli";
interface IFido2Client {
makeCredential(origin: string, options: WrapCredentialCreationOptions, sameOriginWithAncestors: boolean): Promise<WrapPublicKeyCredential>;
getAssertion(origin: string, options: WrapCredentialRequestOptions, sameOriginWithAncestors: boolean): Promise<WrapPublicKeyCredential>;
release(): Promise<void>;
}
export interface IClientRequest {
publisher: string,
process: string,
rp: string,
trusted: boolean
}
export interface IFido2DeviceInfo {
uv?: boolean;
uvRetries?: number;
clientPin?: boolean;
pinRetries?: number;
}
export interface IClientObservable {
type: Fido2Event;
data?: IClientRequest | IFido2DeviceInfo | IFido2Device | number | boolean | string | void;
}
export class Fido2Client implements IFido2Client {
private session: Ctap2Session;
private options: IClientOptions;
private modal!: Subject<IClientObservable>;
private pin!: Subject<string>;
private device!: Subject<IFido2Device>;
private request!: Subject<boolean>;
private keepAlive!: Subject<number>;
private cancel!: Subject<void>
private error!: Subject<Fido2Event>;
private clientSubject: Subject<IClientObservable>;
private subs!: Subscription;
constructor(options: IClientOptions = {}) {
/**
* Assign default options.
*/
let defaultOptions: IClientOptions = {
defaultModal: true,
pinUvAuthProtocol: ClientPinVersion.v1,
transports: ['ble', 'nfc', 'usb'],
}
this.options = Object.assign(defaultOptions, options);
/**
* Client modal.
*/
if (this.options.defaultModal) {
/**
* Create default modal.
* @TODO fix me, using import() instead.
*/
this.modal = new (require('../modal/default').DefaultModal)();
} else {
this.modal = new Subject<IClientObservable>();
}
/**
* Fido2 client session.
*/
this.session = new Ctap2Session(this.options.pinUvAuthProtocol || ClientPinVersion.v1);
/**
* Fido2 client subject. Notify channel for all fido2 event.
* Those nofity will be handled by default modal or callback provided by the user.
*/
this.clientSubject = new Subject<IClientObservable>();
const [obs1, obs2] = partition(this.clientSubject, () => this.options.defaultModal === true);
/**
* Nofity to default modal handler.
*/
obs1.subscribe(this.modal);
/**
* Notify to user handler.
*/
obs2.subscribe(async value => {
switch (value.type) {
/**
* Required events.
*/
case 'fido2-event-request': {
let request = value.data as IClientRequest;
if (this.options.event?.onRequest) {
let status = await this.options.event.onRequest(request).catch(() => { });
this.modal.next({ type: 'fido2-event-response', data: !!status });
break;
}
}
case 'fido2-event-enter-pin': {
if (this.options.event?.onEnterPin) {
let pin = await this.options.event.onEnterPin();
this.modal.next({ type: 'fido2-event-pin-available', data: pin });
break;
}
}
case 'fido2-event-set-pin': {
if (this.options.event?.onSetPin) {
let pin = await this.options.event.onSetPin();
this.modal.next({ type: 'fido2-event-pin-available', data: pin });
break;
}
}
case 'fido2-event-device-attach': {
if (this.options.event?.onDeviceAttached) {
let device = await this.options.event.onDeviceAttached(value.data as IFido2Device);
device && this.modal.next({ type: 'fido2-event-select-device', data: device });
break;
}
}
case 'fido2-event-pin-invalid': {
if (this.options.event?.onPinInvalid) {
let pin = await this.options.event.onPinInvalid(value.data as number);
this.modal.next({ type: 'fido2-event-pin-available', data: pin });
break;
}
}
/**
* Optional events.
*/
case 'fido2-event-device-detach':
(this.options.event?.onDeviceDetached || (() => { }))(value.data as IFido2Device);
break;
case 'fido2-event-pin-valid':
(this.options.event?.onPinValid || (() => { }))();
break;
case 'fido2-event-device-selected':
(this.options.event?.onDeviceSelected || (() => { }))(value.data as IFido2DeviceInfo);
break;
case 'fido2-event-success':
(this.options.event?.onSuccess || (() => { }))();
break;
case 'fido2-event-keep-alive':
(this.options.event?.onKeepAlive || (() => { }))(value.data as number);
break;
case 'fido2-event-keep-alive-cancel':
(this.options.event?.onKeepAliveCancel || (() => { }))();
this.modal.next(value);
break;
case 'fido2-event-pin-auth-blocked':
(this.options.event?.onPinAuthBlocked || (() => { }))();
this.modal.next(value);
break;
case 'fido2-event-pin-blocked':
(this.options.event?.onPinBlocked || (() => { }))();
this.modal.next(value);
break;
case 'fido2-event-timeout':
(this.options.event?.onTimeout || (() => { }))();
this.modal.next(value);
break;
case 'fido2-event-error':
(this.options.event?.onError || (() => { }))(value.data as Error);
this.modal.next(value);
break;
/**
* Missing event handlers.
*/
default:
logger.debug(`unhandled fido2 client subject with type=${value.type}, data=${value.data}`);
throw new Fido2ClientErrMissingEventListener(value.type);
}
});
/**
* Create request Subject.
*/
this.request = new Subject<boolean>();
/**
* Create pin Subject.
*/
this.pin = new Subject<string>();
/**
* Create device Subject.
*/
this.device = new Subject<IFido2Device>();
/**
* Keep alive subject.
*/
this.keepAlive = new Subject<number>()
/**
* Create cancel Subject.
*/
this.cancel = new Subject<void>();
/**
* Create error Subject.
*/
this.error = new Subject<Fido2Event>();
/**
* Subscription.
*/
this.subs = new Subscription();
/**
* Notify from modal.
*/
this.modal.subscribe(value => {
switch (value.type) {
case 'fido2-event-response':
this.request.next(value.data as boolean);
break;
case 'fido2-event-pin-available':
this.pin.next(value.data as string);
break;
case 'fido2-event-select-device':
this.device.next(value.data as IFido2Device);
break;
case 'fido2-event-cancel':
this.cancel.next();
break;
case 'fido2-event-request':
case 'fido2-event-enter-pin':
case 'fido2-event-pin-valid':
case 'fido2-event-pin-blocked':
case 'fido2-event-pin-auth-blocked':
case 'fido2-event-device-attach':
case 'fido2-event-device-detach':
case 'fido2-event-device-selected':
case 'fido2-event-keep-alive':
case 'fido2-event-success':
case 'fido2-event-no-credentials':
case 'fido2-event-timeout':
/**
* Drop self event.
*/
break;
case 'fido2-event-keep-alive-cancel':
this.error.next(value.type);
break
case 'fido2-event-error':
this.error.next(value.data as Fido2Event);
break
default:
/**
* Shouldn't go there.
*/
logger.debug(`drop unknown notify with type=${value.type}, data=${value.data}`);
break;
}
});
logger.debug('create fido2 client success');
}
private get subscription() {
if (this.subs.closed) this.subs = new Subscription();
return this.subs;
}
private async makeExtensionsInput(input: WrapAuthenticationExtensionsClientInputs): Promise<Map<string, any> | undefined> {
let exts = new Map<string, any>();
let info = await this.session.ctap2.info();
if (input.appid) {
throw new Fido2ClientErrExtensionNotImplemented();
}
if (input.appidExclude) {
throw new Fido2ClientErrExtensionNotImplemented();
}
if (input.uvm) {
throw new Fido2ClientErrExtensionNotImplemented();
}
if (input.credProps) {
throw new Fido2ClientErrExtensionNotImplemented();
}
if (input.largeBlob) {
throw new Fido2ClientErrExtensionNotImplemented();
}
if (input.credentialProtectionPolicy) {
throw new Fido2ClientErrExtensionNotImplemented();
}
if (input.enforceCredentialProtectionPolicy) {
throw new Fido2ClientErrExtensionNotImplemented();
}
if (input.credBlob) {
throw new Fido2ClientErrExtensionNotImplemented();
}
if (input.getCredBlob) {
throw new Fido2ClientErrExtensionNotImplemented();
}
if (input.largeBlobKey) {
throw new Fido2ClientErrExtensionNotImplemented();
}
if (input.minPinLength) {
throw new Fido2ClientErrExtensionNotImplemented();
}
if (input.hmacCreateSecret && info.extensions?.includes(HmacSecretExtIdentifier)) {
exts.set(HmacSecretExtIdentifier, await new HmacSecretInput(this.session.ctap2.clientPin).make(input.hmacCreateSecret).build());
}
if (input.hmacGetSecret && info.extensions?.includes(HmacSecretExtIdentifier)) {
exts.set(HmacSecretExtIdentifier, await new HmacSecretInput(this.session.ctap2.clientPin).get(input.hmacGetSecret.salt1, input.hmacGetSecret.salt2).build());
}
return exts.size ? exts : undefined;
}
private async makeExtensionsOutput(output: any): Promise<WrapAuthenticationExtensionsClientOutputs> {
let exts: WrapAuthenticationExtensionsClientOutputs = {};
if (output === undefined) {
return exts
}
if (typeof output[HmacSecretExtIdentifier] === 'boolean') {
exts.hmacCreateSecret = (await new HmacSecretOutput(this.session.ctap2.clientPin).make(output[HmacSecretExtIdentifier]).build()) as boolean;
delete output[HmacSecretExtIdentifier];
}
if (output[HmacSecretExtIdentifier] instanceof Buffer) {
exts.hmacGetSecret = (await new HmacSecretOutput(this.session.ctap2.clientPin).get(output[HmacSecretExtIdentifier]).build()) as { output1: ArrayBuffer, output2?: ArrayBuffer };
delete output[HmacSecretExtIdentifier];
}
return exts;
}
private internalGetPinUvAuthToken(uv?: boolean, clientPin?: boolean, pinUvAuthToken?: boolean, version?: string[]): Promise<Buffer | undefined> {
return new Promise<Buffer | undefined>((resolve, reject) => {
/**
* @deprecated in CTAP 2.1 specs
*/
if (uv && !pinUvAuthToken) {
if (!(version && version.includes(Fido2SpecVersion[Fido2SpecVersion.FIDO_2_0]))) throw new Fido2ClientErrMethodDeprecated();
return resolve(undefined);
}
/**
* Get pinUvAuthToken using getPinUvAuthTokenUsingUvWithPermissions
*/
if (uv && pinUvAuthToken) {
/**
* @TODO
*/
throw new MethodNotImplemented();
}
/**
* Get pinUvAuthToken using getPinUvAuthTokenUsingPinWithPermissions
*/
if (clientPin && pinUvAuthToken) {
/**
* @TODO
*/
throw new MethodNotImplemented();
}
/**
* @superseded
*/
if (clientPin) {
this.subscription.add(this.pin.subscribe(pin => this.session.ctap2.clientPin.getPinToken(pin).then(pinUvAuthToken => {
this.clientSubject.next({ type: 'fido2-event-pin-valid' });
resolve(pinUvAuthToken);
}).catch(async e => {
if (e instanceof Ctap2ErrPinInvalid) return this.clientSubject.next({ type: 'fido2-event-pin-invalid', data: await this.session.ctap2.clientPin.getPinRetries() });
if (e instanceof Ctap2ErrPinAuthBlocked) return this.clientSubject.next({ type: 'fido2-event-pin-auth-blocked' });
if (e instanceof Ctap2ErrPinBlocked) return this.clientSubject.next({ type: 'fido2-event-pin-blocked' });
reject(e);
})));
this.clientSubject.next({ type: 'fido2-event-enter-pin' });
return;
}
/**
* Unreachable
*/
reject(new Fido2ClientErrUserVerificationNotCapable());
});
}
private getPinUvAuthToken(userVerification: UserVerificationRequirement): Promise<{ userVerification: boolean; pinUvAuthToken: Buffer | undefined; }> {
return new Promise<{ userVerification: boolean; pinUvAuthToken: Buffer | undefined }>(async (resolve, reject) => {
this.subscription.add(this.device.pipe(first()).subscribe(async device => {
/**
* Open selected authenticator.
*/
await this.session.device.open(device).catch(e => reject(e));
/**
* Get authenticator info.
*/
let info = await this.session.ctap2.info();
/**
* Set info for ctap2 device.
*/
this.session.device.info = info;
/**
* Set maxMsgSize for device cli.
*/
(await this.session.device.console).setMaxMsgSize(info.maxMsgSize || 1024);
logger.debug(info);
/**
* Emit selected authenticator info event.
*/
this.clientSubject.next({
type: 'fido2-event-device-selected',
data: {
uv: info.options?.uv,
clientPin: info.options?.clientPin,
pinRetries: info.options?.clientPin ? await this.session.ctap2.clientPin.getPinRetries().catch(e => reject(e)) || undefined : undefined,
uvRetries: info.options?.uv ? await this.session.ctap2.clientPin.getUVRetries().catch(e => reject(e)) || undefined : undefined
}
});
/**
* Check pin/uv auth protocol compatible.
*/
if (this.options.pinUvAuthProtocol &&
!info.pinUvAuthProtocols?.includes(this.options.pinUvAuthProtocol) &&
this.options.pinUvAuthProtocol !== ClientPinVersion.v1 &&
getLatestSpecVersion(info.version) < Fido2SpecVersion.FIDO_2_0) throw new Fido2ClientErrPinUvAuthProtocolUnsupported();
let { uv, clientPin, pinUvAuthToken } = info.options || {};
/**
* Built-in user verification method. For example, devices with screen, biometrics, ...
* TODO: high priority for built-in user verification method (not specified in the v2.1 specs).
*/
if (uv !== undefined) {
logger.debug('built-in user verification');
/**
* Built-in user verification not configured/disabled and relying party don't care about user verification.
*/
// if (!uv && userVerification === 'discouraged') return resolve({ userVerification: false, pinUvAuthToken: undefined });
/**
* Built-in user verification has been configured/enabled.
*/
if (uv) return this.internalGetPinUvAuthToken(uv, clientPin, pinUvAuthToken, info.version).then(token => {
if (uv) resolve({ userVerification: token === undefined, pinUvAuthToken: token });
});
if (!uv) {
/**
* Fall back to client pin
* @TODO implement built-in user verification configure.
*/
}
}
if (clientPin !== undefined) {
logger.debug('client-pin user verification');
/**
* Client PIN not configured and relying party don't care about user verification.
*/
if (!clientPin && userVerification === 'discouraged') {
return resolve({ userVerification: false, pinUvAuthToken: undefined });
}
/**
* Client PIN not configured and relying party require user verification,
* let user to configure PIN.
*/
if (!clientPin && userVerification !== 'discouraged') {
this.subscription.add(this.pin.pipe(first()).subscribe(async pin => {
await this.session.ctap2.clientPin.setPin(pin).catch(e => reject(e));
/**
* @TODO verify that the PIN has been configured.
*/
this.internalGetPinUvAuthToken(uv, true, pinUvAuthToken).then(token => {
resolve({ userVerification: false, pinUvAuthToken: token });
});
}));
this.clientSubject.next({ type: 'fido2-event-enter-pin' });
return;
}
this.internalGetPinUvAuthToken(uv, true, pinUvAuthToken).then(token => {
resolve({ userVerification: false, pinUvAuthToken: token });
});
return;
}
/**
* Relying party don't care about user verification.
*/
if (userVerification === 'discouraged') {
return resolve({ userVerification: false, pinUvAuthToken: undefined });
}
/**
* Authenticator not capable any user verification method.
*/
throw new Fido2ClientErrUserVerificationNotCapable();
}));
/**
* Subscribe for device attach.
*/
this.subscription.add((await this.session.device.enumerate(this.options.transports)).pipe(takeUntil(this.device)).subscribe({
next: device => {
logger.debug(device);
this.clientSubject.next({ type: device.status === 'attach' ? 'fido2-event-device-attach' : 'fido2-event-device-detach', data: device.device });
},
error: e => logger.debug(e)
}));
});
}
private makeClientRequest(rp: string): IClientRequest {
let { signer, verified } = verify(process.execPath);
return {
publisher: signer,
process: path.basename(process.execPath),
rp: rp,
trusted: verified
}
}
private onCancel() {
this.session.device.console.then(async x => {
/**
* Cancel current transaction.
*/
await x.cancel();
}).catch((e) => {
/**
* Device cli not available. No need to release device cli.
*/
if (e instanceof DeviceCliNotInitialized) return this.error.next('fido2-event-cancel');
/**
* Transaction not found.
*/
if (e instanceof DeviceCliTransactionNotFound) return this.error.next('fido2-event-cancel');
/**
* Unhandled error.
*/
this.error.next('fido2-event-unknown-error');
});
}
private onError(type: string, reject: (reason: Error) => void) {
/**
* Revoke client session, disconnect all fido2 device.
*/
this.session.revoke();
/**
* Unsubscribe all subscription.
*/
this.subscription.unsubscribe();
/**
* Reject error to caller.
*/
switch (type) {
case 'fido2-event-request-not-allowed':
reject(new Fido2ClientErrNotAllowed());
break;
case 'fido2-event-timeout':
reject(new Fido2ClientErrTimeout());
break;
case 'fido2-event-cancel':
case 'fido2-event-keep-alive-cancel':
reject(new Fido2ClientErrCancel());
break;
case 'fido2-event-unknown-error':
reject(new Fido2ClientErrUnknown());
break;
case 'fido2-event-pin-auth-blocked':
reject(new Fido2ClientErrPinAuthBlocked());
break;
case 'fido2-event-pin-blocked':
reject(new Fido2ClientErrPinBlocked());
break;
default:
logger.debug(`unhandled error ${type}`);
reject(new Error(`Unhandled error ${type}`));
break;
}
}
/**
*
* @param origin
* @param options
* @returns
*/
async makeCredential(origin: string, options: WrapCredentialCreationOptions, sameOriginWithAncestors: boolean = true) {
return await new Promise<WrapPublicKeyCredential>(async (resolve, reject) => {
/**
* Options for Credential Creation
* https://www.w3.org/TR/webauthn-3/#dictdef-publickeycredentialcreationoptions
*/
let pub = options.publicKey as WrapPublicKeyCredentialCreationOptions;
/**
* Validate required parameters.
*/
if (pub.rp === undefined) return reject(new Fido2ClientErrMissingParameter('rp'));
if (pub.rp.name === undefined) return reject(new Fido2ClientErrMissingParameter('rp.name'));
if (pub.user === undefined) return reject(new Fido2ClientErrMissingParameter('user'));
if (pub.user.name === undefined) return reject(new Fido2ClientErrMissingParameter('user.name'));
if (pub.user.displayName === undefined) return reject(new Fido2ClientErrMissingParameter('user.displayName'));
/**
* @TODO
* Force required icon.
*/
if (pub.user.icon === undefined) pub.user.icon = `${pub.user.name}.ico`;
if (pub.user.id === undefined) return reject(new Fido2ClientErrMissingParameter('user.id'));
if (pub.challenge === undefined) return reject(new Fido2ClientErrMissingParameter('challenge'));
if (pub.pubKeyCredParams === undefined) return reject(new Fido2ClientErrMissingParameter('pubKeyCredParams'));
/**
* Validate required parameters type.
*/
if (typeof pub.rp.name !== 'string') return reject(new Fido2ClientErrInvalidParameter('rp.name'));
/**
* @TODO
* Fore rpId to origin.
*/
if (typeof pub.rp.id !== 'string') pub.rp.id = new URL(origin).origin;
if (typeof pub.user.name !== 'string') return reject(new Fido2ClientErrInvalidParameter('user.name'));
if (typeof pub.user.displayName !== 'string') return reject(new Fido2ClientErrInvalidParameter('user.displayName'));
if (typeof pub.user.icon !== 'string') return reject(new Fido2ClientErrInvalidParameter('user.icon'));
if (ArrayBuffer.isView(pub.user.id) === false && (pub.user.id instanceof ArrayBuffer) === false) return reject(new Fido2ClientErrInvalidParameter('user.id'));
if (ArrayBuffer.isView(pub.challenge) === false && (pub.challenge instanceof ArrayBuffer) === false) return reject(new Fido2ClientErrInvalidParameter('challenge'));
if ((pub.pubKeyCredParams instanceof Array) === false) return reject(new Fido2ClientErrInvalidParameter('pubKeyCredParams'));
if (!pub.pubKeyCredParams.every(x => x.alg in WrapCOSEAlgorithmIdentifier && x.type in WrapPublicKeyCredentialType)) return reject(new Fido2ClientErrInvalidParameter('pubKeyCredParams'));
/**
* Validate optional parameters.
*/
if (pub.timeout && isNaN(pub.timeout)) return reject(new Fido2ClientErrInvalidParameter('timeout'));
// TODO: check exclude credential element type
if (pub.excludeCredentials && pub.excludeCredentials instanceof Array === false) return reject(new Fido2ClientErrInvalidParameter('excludeCredentials'));
if (pub.authenticatorSelection?.authenticatorAttachment && typeof pub.authenticatorSelection.authenticatorAttachment !== 'string') return reject(new Fido2ClientErrInvalidParameter('authenticatorSelection.authenticatorAttachment'));
if (pub.authenticatorSelection?.residentKey && typeof pub.authenticatorSelection?.residentKey !== 'string') return reject(new Fido2ClientErrInvalidParameter('authenticatorSelection.residentKey'));
if (pub.authenticatorSelection?.requireResidentKey && typeof pub.authenticatorSelection?.requireResidentKey !== 'boolean') return reject(new Fido2ClientErrInvalidParameter('authenticatorSelection.requireResidentKey'));
if (pub.authenticatorSelection?.userVerification && typeof pub.authenticatorSelection?.userVerification !== 'string') return reject(new Fido2ClientErrInvalidParameter('authenticatorSelection.userVerification'));
if (pub.attestation && typeof pub.attestation !== 'string') return reject(new Fido2ClientErrInvalidParameter('attestation'));
// if (new URL(origin).origin !== origin) throw new Fido2ClientErrRelyPartyNotAllowed();
/**
* Set timeout for request.
*/
this.session.timeout = setTimeout(() => this.clientSubject.next({ type: 'fido2-event-timeout' }), pub.timeout || (pub.authenticatorSelection?.userVerification === 'discouraged' ? 120000 : 300000));
/**
* Subscribe for cancel event.
*/
this.subscription.add(this.cancel.pipe(first()).subscribe(() => this.onCancel()));
/**
* Subscribe for error event.
*/
this.subscription.add(this.error.pipe(first()).subscribe(x => this.onError(x, reject)));
/**
* Subscribe for request event.
*/
this.subscription.add(this.request.pipe(first()).subscribe(async status => {
/**
* Request deny
*/
if (!status) return this.error.next('fido2-event-request-not-allowed');
/**
* Subscribe for keep alive event.
*/
this.keepAlive.pipe(takeUntil(this.cancel)).subscribe(status => {
this.clientSubject.next({ type: 'fido2-event-keep-alive', data: status });
});
/**
* Migrate types.
*/
Object.assign(pub, { challenge: Buffer.from(pub.challenge as ArrayBuffer) });
Object.assign(pub.user, { id: Buffer.from(pub.user.id as ArrayBuffer) });
pub.excludeCredentials && pub.excludeCredentials.map(x => Object.assign(x, { id: Buffer.from(x.id as ArrayBuffer) }));
let userVerification = pub.authenticatorSelection?.userVerification || 'required';
let discoverableCredential = pub.authenticatorSelection?.residentKey || 'discouraged';
if (pub.authenticatorSelection?.requireResidentKey) discoverableCredential = 'required';
let tup = await this.getPinUvAuthToken(userVerification);
this.session.clientData = {
type: 'webauthn.create',
challenge: Base64.encode(Buffer.from(pub.challenge as ArrayBuffer)),
origin: new URL(origin).origin,
crossOrigin: !sameOriginWithAncestors
}
let clientData = Buffer.from(JSON.stringify(this.session.clientData));
this.session.clientDataHash = Fido2Crypto.hash(clientData);
/**
* Create make credential options.
*/
let opt: Options = {};
if (discoverableCredential === 'required') opt.rk = true;
if (tup.userVerification) opt.uv = true;
/**
* Make credential.
*/
this.session.ctap2.makeCredential({
clientDataHash: this.session.clientDataHash,
rp: pub.rp,
user: pub.user,
pubKeyCredParams: pub.pubKeyCredParams,
excludeList: pub.excludeCredentials,
extensions: pub.extensions ? await this.makeExtensionsInput(pub.extensions) : undefined,
options: opt,
pinUvAuthParam: tup.pinUvAuthToken ? Fido2Crypto.hmac(tup.pinUvAuthToken, this.session.clientDataHash).slice(0, 16) : undefined,
pinUvAuthProtocol: this.options.pinUvAuthProtocol,
}, this.keepAlive).then(async credential => {
/**
* Make credential request almost done.
*/
this.clientSubject.next({ type: 'fido2-event-success' });
/**
* Parse authenticator data.
*/
let authData = new AuthenticatorData(credential.authData);
let extensions = await this.makeExtensionsOutput(authData.extensions);
/**
* Revoke client session, disconnect all fido2 device.
*/
this.session.revoke();
/**
* Unsubscribe all subscription.
*/
this.subscription.unsubscribe();
// logger.debug({
// id: Base64.encode(authData.attestedCredentialData?.credentialId as Buffer),
// rawId: authData.attestedCredentialData?.credentialId.buffer.slice(authData.attestedCredentialData?.credentialId.byteOffset, authData.attestedCredentialData?.credentialId.byteOffset + authData.attestedCredentialData?.credentialId.byteLength) as ArrayBuffer,
// type: 'public-key',
// response: new WrapAuthenticatorAttestationResponse(credential, clientData),
// clientExtensionResults: extensions,
// // getClientExtensionResults: () => extensions
// });
/**
* Resolve credential, request success.
*/
return resolve({
id: Base64.encode(authData.attestedCredentialData?.credentialId as Buffer),
rawId: authData.attestedCredentialData?.credentialId.buffer.slice(authData.attestedCredentialData?.credentialId.byteOffset, authData.attestedCredentialData?.credentialId.byteOffset + authData.attestedCredentialData?.credentialId.byteLength) as ArrayBuffer,
type: 'public-key',
response: new WrapAuthenticatorAttestationResponse(credential, clientData),
clientExtensionResults: extensions,
// getClientExtensionResults: () => extensions
});
}).catch(e => {
/**
* Request timeout.
*/
if (e instanceof Ctap2ErrActionTimeout) return this.clientSubject.next({ type: 'fido2-event-timeout' });
/**
* Keep alive cancel.
*/
if (e instanceof Ctap2ErrKeepaliveCancel) return this.clientSubject.next({ type: 'fido2-event-keep-alive-cancel' });
/**
* Reject errors to caller.
*/
this.error.next(e);
});
}));
/**
* Notify make credential request.
*/
this.clientSubject.next({ type: 'fido2-event-request', data: this.makeClientRequest(pub.rp.id) });
});
}
/**
*
* @param origin
* @param options
* @returns
*/
async getAssertion(origin: string, options: WrapCredentialRequestOptions, sameOriginWithAncestors: boolean = true): Promise<WrapPublicKeyCredential> {
return await new Promise<WrapPublicKeyCredential>(async (resolve, reject) => {
/**
* Options for Credential Creation
* https://www.w3.org/TR/webauthn-3/#dictdef-publickeycredentialcreationoptions
*/
let pub = options.publicKey as WrapPublicKeyCredentialRequestOptions;
/**
* Validate required parameters.
*/
if (pub.challenge === undefined) return reject(new Fido2ClientErrMissingParameter('challenge'));
/**
* Validate required parameters type.
*/
if (ArrayBuffer.isView(pub.challenge) === false && (pub.challenge instanceof ArrayBuffer) === false) return reject(new Fido2ClientErrMissingParameter('challenge'));
/**
* Validate optional parameters.
*/
if (pub.timeout && isNaN(pub.timeout)) return reject(new Fido2ClientErrInvalidParameter('timeout'));
if (pub.rpId && typeof pub.rpId !== 'string') return reject(new Fido2ClientErrInvalidParameter('rpId'));
if (pub.allowCredentials && pub.allowCredentials instanceof Array === false) return reject(new Fido2ClientErrInvalidParameter('allowCredentials'));
if (pub.allowCredentials && !pub.allowCredentials.every(x => (ArrayBuffer.isView(x.id) || x.id instanceof ArrayBuffer) && x.type in WrapPublicKeyCredentialType)) return reject(new Fido2ClientErrInvalidParameter('allowCredentials'));
if (pub.userVerification && typeof pub.userVerification !== 'string') return reject(new Fido2ClientErrInvalidParameter('userVerification'));
if (new URL(origin).hostname !== pub.rpId) return reject(new Fido2ClientErrRelyPartyNotAllowed());
/**
* Set timer for request timeout.
*/
this.session.timeout = setTimeout(() => this.clientSubject.next({ type: 'fido2-event-timeout' }), pub.timeout || (pub.userVerification === 'discouraged' ? 120000 : 300000));
/**
* Subscribe for cancel event.
*/
this.subscription.add(this.cancel.pipe(first()).subscribe(() => this.onCancel()));
/**
* Subscribe for error event.
*/
this.subscription.add(this.error.pipe(first()).subscribe(x => this.onError(x, reject)));
/**
* Subscribe for request event.
*/
this.subscription.add(this.request.pipe(first()).subscribe(async status => {
/**
* Request deny.
*/
if (!status) return this.error.next('fido2-event-request-not-allowed');
/**
* Subscribe for keep-alive event.
*/
this.keepAlive.pipe(takeUntil(this.cancel)).subscribe(status => {
this.clientSubject.next({ type: 'fido2-event-keep-alive', data: status });
});
/**
* Migrate type.
*/
Object.assign(pub, { challenge: Buffer.from(pub.challenge as ArrayBuffer) });
pub.allowCredentials && pub.allowCredentials.map(x => Object.assign(x, { id: Buffer.from(x.id as ArrayBuffer) }));
let token = await this.getPinUvAuthToken(pub.userVerification || 'required');
/**
* Collected client data.
*/
this.session.clientData = {
type: 'webauthn.get',
challenge: Base64.encode(Buffer.from(pub.challenge as Buffer)),
origin: new URL(origin).origin,
crossOrigin: !sameOriginWithAncestors
}
let clientData = Buffer.from(JSON.stringify(this.session.clientData));
/**
* Client data hash.
*/
this.session.clientDataHash = Fido2Crypto.hash(clientData);
/**
* Create get assertion options.
*/
let opt: Options = {};
/**
* Empty allow lists.
*/
if (pub.allowCredentials === undefined) opt.rk = true;
/**
* @deprecated in CTAP 2.1
*/
if (token.userVerification) opt.uv = true;
/**
* Get assertion.
*/
this.session.ctap2.getAssertion({
rpId: pub.rpId || new URL(origin).hostname,
clientDataHash: this.session.clientDataHash,
allowList: pub.allowCredentials,
extensions: pub.extensions ? await this.makeExtensionsInput(pub.extensions) : undefined,
options: opt,
pinUvAuthParam: token.pinUvAuthToken ? Fido2Crypto.hmac(token.pinUvAuthToken, this.session.clientDataHash).slice(0, 16) : undefined,
pinUvAuthProtocol: this.options.pinUvAuthProtocol
}, this.keepAlive).then(async credentials => {
/**
* Get assertion request almost done.
*/
this.clientSubject.next({ type: 'fido2-event-success' });
/**
* @TODO select credential.
*/
let credential = credentials[0];
/**
* Parse authenticator data.
*/
let authData = new AuthenticatorData(credential.authData);
let extensions = await this.makeExtensionsOutput(authData.extensions);
let id = credential.credential.id as Buffer;
let userHandle = credential.user?.id;
/**
* Revoke client session, disconnect all fido2 device.
*/
this.session.revoke();
/**
* Unsubscribe all subscription.
*/
this.subscription.unsubscribe();
// logger.debug(JSON.stringify({
// id: Base64.encode(id),
// rawId: Base64.encode(id),
// type: 'public-key',
// response: {
// clientDataJSON: clientData.toString('base64url'),
// authenticatorData: credential.authData.toString('base64url'),
// signature: credential.signature.toString('base64url'),
// userHandle: userHandle && userHandle instanceof Buffer && userHandle.toString('base64url')
// },
// clientExtensionResults: extensions,
// // getClientExtensionResults: () => extensions
// }));
/**
* Resolve credential, get assertion request success.
*/
resolve({
id: Base64.encode(id),
rawId: id.buffer.slice(id.byteOffset, id.byteOffset + id.byteLength),
type: 'public-key',
response: {
clientDataJSON: clientData.buffer.slice(clientData.byteOffset, clientData.byteOffset + clientData.byteLength),
authenticatorData: credential.authData.buffer.slice(credential.authData.byteOffset, credential.authData.byteOffset + credential.authData.byteLength),
signature: credential.signature.buffer.slice(credential.signature.byteOffset, credential.signature.byteOffset + credential.signature.byteLength),
userHandle: userHandle && userHandle instanceof Buffer && userHandle.buffer.slice(userHandle.byteOffset, userHandle.byteOffset + userHandle.byteLength)
} as AuthenticatorAssertionResponse,
clientExtensionResults: extensions,
// getClientExtensionResults: () => extensions
});
}).catch(e => {
/**
* Request timeout.
*/
if (e instanceof Ctap2ErrActionTimeout) return this.clientSubject.next({ type: 'fido2-event-timeout' });
/**
* No credentials found on authenticator.
*/
if (e instanceof Ctap2ErrNoCredentials) return this.clientSubject.next({ type: 'fido2-event-no-credentials' });
/**
* Keep alive cancel.
*/
if (e instanceof Ctap2ErrKeepaliveCancel) return this.clientSubject.next({ type: 'fido2-event-keep-alive-cancel' });
/**
* Reject unhandled errors to caller.
*/
this.error.next(e);
});
}));
/**
* Notify get assertion request.
*/
this.clientSubject.next({ type: 'fido2-event-request', data: this.makeClientRequest(pub.rpId) });
});
}
async release(): Promise<void> {
this.session.device.release();
this.session.revoke();
this.subscription.unsubscribe();
}
} | the_stack |
import { ServiceContainer } from '../services/ServiceContainer';
import { IDesignItem } from './IDesignItem';
import { InstanceServiceContainer } from '../services/InstanceServiceContainer';
import { CssStyleChangeAction } from '../services/undoService/transactionItems/CssStyleChangeAction';
import { ChangeGroup } from '../services/undoService/ChangeGroup';
import { NodeType } from './NodeType';
import { AttributeChangeAction } from '../services/undoService/transactionItems/AttributeChangeAction';
import { PropertyChangeAction } from '../services/undoService/transactionItems/PropertyChangeAction';
import { ExtensionType } from '../widgets/designerView/extensions/ExtensionType';
import { IDesignerExtension } from '../widgets/designerView/extensions/IDesignerExtension';
import { DomHelper } from '@node-projects/base-custom-webcomponent/dist/DomHelper';
import { CssAttributeParser } from '../helper/CssAttributeParser.js';
import { IBinding } from '../services/bindingsService/IBinding.js';
const hideAtDesignTimeAttributeName = 'node-projects-hide-at-design-time'
const hideAtRunTimeAttributeName = 'node-projects-hide-at-run-time'
const lockAtDesignTimeAttributeName = 'node-projects-lock-at-design-time'
export class DesignItem implements IDesignItem {
node: Node;
serviceContainer: ServiceContainer;
instanceServiceContainer: InstanceServiceContainer;
appliedDesignerExtensions: Map<ExtensionType, IDesignerExtension[]> = new Map();
public replaceNode(newNode: Node) {
DesignItem._designItemMap.delete(this.node);
DesignItem._designItemMap.set(newNode, this);
this.node = newNode;
}
public get nodeType(): NodeType {
if (this.node instanceof Comment)
return NodeType.Comment;
if (this.node instanceof Text)
return NodeType.TextNode;
return NodeType.Element;
}
public get hasAttributes() {
return this.attributes.size > 0;
}
public attributes: Map<string, string | IBinding>
public get hasStyles() {
return this.styles.size > 0;
}
public styles: Map<string, string | IBinding>
private static _designItemMap = new WeakMap<Node, IDesignItem>();
public get element(): Element {
return <Element>this.node;
}
public get name() {
return this.element.localName;
}
public get id(): string {
return this.element.id;
}
public set id(value: string) {
this.element.id = value;
}
private _childArray: IDesignItem[] = [];
public get hasChildren() {
return this._childArray.length > 0;
}
public *children(): IterableIterator<IDesignItem> {
for (const e of this._childArray) {
yield e;
}
}
public get childCount(): number {
return this._childArray.length;
}
public get firstChild(): IDesignItem {
return this._childArray[0];
}
public get parent(): IDesignItem {
return this.getOrCreateDesignItem(this.element.parentNode);
}
public insertChild(designItem: IDesignItem, index?: number) {
if (designItem.parent) {
designItem.parent.removeChild(designItem);
}
this.removeChild(designItem);
if (index == null || this._childArray.length == 0 || index >= this._childArray.length) {
this._childArray.push(designItem);
this.element.appendChild(designItem.node);
} else {
let el = this._childArray[index];
this.node.insertBefore(designItem.node, el.element)
this._childArray.splice(index, 0, designItem);
}
}
public removeChild(designItem: IDesignItem) {
const index = this._childArray.indexOf(designItem);
if (index > -1) {
this._childArray.splice(index, 1);
designItem.element.remove();
}
}
public remove() {
this.parent.removeChild(this);
}
public clearChildren() {
this._childArray = [];
DomHelper.removeAllChildnodes(this.element);
}
//abstract text content to own property. so only chnage via designer api will use it.
public get hasContent() {
return this.nodeType == NodeType.TextNode || (this._childArray.length === 0 && this.content !== null);
}
public get content(): string {
return this.node.textContent;
}
public set content(value: string) {
this.node.textContent = value;
}
private _hideAtDesignTime: boolean;
public get hideAtDesignTime() {
return this._hideAtDesignTime;
}
public set hideAtDesignTime(value: boolean) {
this._hideAtDesignTime = value;
if (value)
this.attributes.set(hideAtDesignTimeAttributeName, "");
else
this.attributes.delete(hideAtDesignTimeAttributeName);
if (this.element instanceof HTMLElement || this.element instanceof SVGElement) {
if (!value)
this.element.style.display = <any>this.styles.get('display') ?? "";
else
this.element.style.display = 'none';
}
}
private _hideAtRunTime: boolean;
public get hideAtRunTime() {
return this._hideAtRunTime;
}
public set hideAtRunTime(value: boolean) {
this._hideAtRunTime = value;
if (value)
this.attributes.set(hideAtRunTimeAttributeName, "");
else
this.attributes.delete(hideAtRunTimeAttributeName);
if (this.element instanceof HTMLElement || this.element instanceof SVGElement) {
if (!value)
this.element.style.opacity = <any>this.styles.get('opacity') ?? "";
else
this.element.style.opacity = '0.3';
}
}
private _lockAtDesignTime: boolean;
public get lockAtDesignTime() {
return this._lockAtDesignTime;
}
public set lockAtDesignTime(value: boolean) {
this._lockAtDesignTime = value;
if (value)
this.attributes.set(lockAtDesignTimeAttributeName, "");
else
this.attributes.delete(lockAtDesignTimeAttributeName);
if (this.element instanceof HTMLElement || this.element instanceof SVGElement) {
if (!value)
this.element.style.pointerEvents = 'auto';
else
this.element.style.pointerEvents = 'none';
}
}
public static createDesignItemFromInstance(node: Node, serviceContainer: ServiceContainer, instanceServiceContainer: InstanceServiceContainer): DesignItem {
let designItem = new DesignItem(node, serviceContainer, instanceServiceContainer);
if (designItem.nodeType == NodeType.Element) {
for (let a of designItem.element.attributes) {
if (a.name !== 'style') {
designItem.attributes.set(a.name, a.value);
if (a.name === hideAtDesignTimeAttributeName)
designItem._hideAtDesignTime = true;
if (a.name === hideAtRunTimeAttributeName)
designItem._hideAtRunTime = true;
if (a.name === lockAtDesignTimeAttributeName)
designItem._lockAtDesignTime = true;
}
}
if (node instanceof HTMLElement || node instanceof SVGElement) {
const cssParser = new CssAttributeParser();
const st = node.getAttribute("style");
if (st) {
cssParser.parse(st);
for (let e of cssParser.entries) {
designItem.styles.set(e.name, e.value);
}
}
if (!designItem._lockAtDesignTime)
node.style.pointerEvents = 'auto';
else
node.style.pointerEvents = 'none';
//node.style.cursor = 'pointer';
}
(<HTMLElement>node).draggable = false; //even if it should be true, for better designer exp.
}
designItem.updateChildrenFromNodesChildren();
return designItem;
}
updateChildrenFromNodesChildren() {
this._childArray = [];
if (this.nodeType == NodeType.Element) {
if (this.element.children && this.element.children.length === 0 && this.element.childNodes.length <= 1)
this.content = this.element.textContent; //was soll das bringen???
else {
for (const c of this.element.childNodes)
this._childArray.push(DesignItem.createDesignItemFromInstance(c, this.serviceContainer, this.instanceServiceContainer));
}
}
}
constructor(node: Node, serviceContainer: ServiceContainer, instanceServiceContainer: InstanceServiceContainer) {
this.node = node;
this.serviceContainer = serviceContainer;
this.instanceServiceContainer = instanceServiceContainer;
this.attributes = new Map();
this.styles = new Map();
DesignItem._designItemMap.set(node, this);
}
public openGroup(title: string, affectedItems?: IDesignItem[]): ChangeGroup {
return this.instanceServiceContainer.undoService.openGroup(title, affectedItems);
}
public getOrCreateDesignItem(node: Node) {
return DesignItem.GetOrCreateDesignItem(node, this.serviceContainer, this.instanceServiceContainer);
}
static GetOrCreateDesignItem(node: Node, serviceContainer: ServiceContainer, instanceServiceContainer: InstanceServiceContainer): IDesignItem {
if (!node)
return null;
let designItem: IDesignItem = DesignItem._designItemMap.get(node);
if (!designItem) {
designItem = new DesignItem(node, serviceContainer, instanceServiceContainer);
}
return designItem;
}
static GetDesignItem(node: Node): IDesignItem {
if (!node)
return null;
let designItem: IDesignItem = DesignItem._designItemMap.get(node);
return designItem;
}
public setStyle(name: keyof CSSStyleDeclaration, value?: string | IBinding | null) {
const action = new CssStyleChangeAction(this, name, value, this.styles.get(<string>name));
this.instanceServiceContainer.undoService.execute(action);
}
public removeStyle(name: keyof CSSStyleDeclaration) {
const action = new CssStyleChangeAction(this, name, '', this.styles.get(<string>name));
this.instanceServiceContainer.undoService.execute(action);
}
public setAttribute(name: string, value?: string | IBinding | null) {
const action = new AttributeChangeAction(this, name, value, this.attributes.get(name));
this.instanceServiceContainer.undoService.execute(action);
}
public removeAttribute(name: string) {
const action = new AttributeChangeAction(this, name, null, this.attributes.get(name));
this.instanceServiceContainer.undoService.execute(action);
}
public setProperty(name: string, value?: string | null) {
const propService = this.serviceContainer.getLastServiceWhere('propertyService', x => x.isHandledElement(this));
const property = propService.getProperty(this, name);
const oldValue = propService.getValue([this], property)
const action = new PropertyChangeAction(this, property, value, oldValue);
this.instanceServiceContainer.undoService.execute(action);
}
public removeProperty(name: string, value?: string | null) {
const propService = this.serviceContainer.getLastServiceWhere('propertyService', x => x.isHandledElement(this));
const property = propService.getProperty(this, name);
const oldValue = propService.getValue([this], property)
const action = new PropertyChangeAction(this, property, undefined, oldValue);
this.instanceServiceContainer.undoService.execute(action);
}
} | the_stack |
import {
EventListUnitCopyWithin,
EventListUnitDelete,
EventListUnitFill,
EventListUnitPop,
EventListUnitPush,
EventListUnitRemove,
EventListUnitReverse,
EventListUnitSet,
EventListUnitShift,
EventListUnitSort,
EventListUnitSplice,
EventListUnitUnshift,
} from '../models/events';
import {UnitConfig} from '../models/units';
import {Configuration} from '../lib/configuration';
import {ListUnit} from '../lib/list-unit';
import {
booleanOrRandomValue,
LIST_UNIT_MUTATION_FNS,
multipleOf,
randomArray,
randomBoolean,
randomNumber,
randomSortPredicate,
randomValidValue,
randomValue,
randomValuePureFn,
randomWholeNumber,
selectRandom,
somewhatValidConfig,
times,
} from './utils';
import {
deepCopy,
isObject,
isValidIndex,
IteratorSymbol,
normalizeIndex,
sanitizeIndices,
} from '../utils/funcs';
const configOptions: Array<keyof UnitConfig<any>> = [
// 'id', // tests with id are done separately to keep other tests simple
// 'immutable', // immutability tests are done separately to keep other tests simple
// 'persistent', // persistence tests are done separately to keep other tests simple
'replay',
'initialValue',
'cacheSize',
'distinctDispatchCheck',
'customDispatchCheck',
'dispatchDebounce',
'dispatchDebounceMode',
];
describe(
'ListUnit',
times(30, () => {
beforeAll(() => {
Configuration.reset();
});
describe('basic tests', () => {
let unit: ListUnit<any>;
let unitValue: any[];
beforeEach(() => {
unitValue = randomArray(1);
unit = new ListUnit<any>({initialValue: unitValue});
});
it('should only allow arrays', () => {
const randValue = randomValue(1);
const originalUnitValue = unit.value();
unit.dispatch(randValue);
if (Array.isArray(randValue)) {
expect(unit.value()).toEqual(randValue);
} else {
expect(unit.value()).toBe(originalUnitValue);
}
});
it('should have valid length', () => {
expect(unit.length).toBe(Array.isArray(unitValue) ? unitValue?.length : 0);
unitValue = randomArray(1);
unit.dispatch(unitValue);
expect(unit.length).toBe(unitValue.length);
});
it('checks objectKeys method', () => {
expect(unit.objectKeys()).toEqual(Object.keys(unitValue));
unitValue = randomArray(1);
unit.dispatch(unitValue);
expect(unit.objectKeys()).toEqual(Object.keys(unitValue));
});
it('checks objectEntries method', () => {
expect(unit.objectEntries()).toEqual(Object.entries(unitValue));
unitValue = randomArray(1);
unit.dispatch(unitValue);
expect(unit.objectEntries()).toEqual(Object.entries(unitValue));
});
it('checks objectValues method', () => {
expect(unit.objectValues()).toEqual(Object.values(unitValue));
unitValue = randomArray(1);
unit.dispatch(unitValue);
expect(unit.objectValues()).toEqual(Object.values(unitValue));
});
it('should be iterable', () => {
expect(typeof unit[IteratorSymbol]).toBe('function');
expect(typeof unit[IteratorSymbol]().next).toBe('function');
expect([...unit]).toEqual([...unit.value()]);
expect(unitValue).toEqual(unit.value());
});
it('should not mutate when frozen', () => {
const length = unit.length;
const emitCount = unit.emitCount;
unit.freeze();
selectRandom(LIST_UNIT_MUTATION_FNS)(unit);
selectRandom(LIST_UNIT_MUTATION_FNS)(unit);
selectRandom(LIST_UNIT_MUTATION_FNS)(unit);
selectRandom(LIST_UNIT_MUTATION_FNS)(unit);
selectRandom(LIST_UNIT_MUTATION_FNS)(unit);
expect(length).toBe(unit.length);
expect(emitCount).toBe(unit.emitCount);
expect(unitValue).toEqual(unit.value());
});
it('should not emit when muted', () => {
const emitCount = unit.emitCount;
unit.mute();
selectRandom(LIST_UNIT_MUTATION_FNS)(unit);
selectRandom(LIST_UNIT_MUTATION_FNS)(unit);
selectRandom(LIST_UNIT_MUTATION_FNS)(unit);
selectRandom(LIST_UNIT_MUTATION_FNS)(unit);
selectRandom(LIST_UNIT_MUTATION_FNS)(unit);
expect(emitCount).toBe(unit.emitCount);
expect(unit.isMuted).toBe(true);
});
});
describe('read-only custom methods', () => {
let unit: ListUnit<any>;
let unitValue: any[];
let emitCount: number;
let listLength: number;
beforeEach(() => {
unit = new ListUnit(somewhatValidConfig(configOptions, ListUnit));
if (randomBoolean(0.8)) {
unit.dispatch(randomValidValue(ListUnit, randomNumber(1, 3)));
}
unitValue = unit.value();
emitCount = unit.emitCount;
listLength = unit.length;
});
it('checks "forEvery" method', () => {
const callbackSpy = jasmine.createSpy();
unit.forEvery((item, index, array) => {
callbackSpy();
expect(item).toBe(unitValue[index]);
expect(unit.get(index)).toEqual(unitValue[index]);
expect(unitValue[index]).toEqual(array[index]);
});
expect(callbackSpy).toHaveBeenCalledTimes(listLength);
expect(emitCount).toEqual(unit.emitCount);
expect(unitValue).toEqual(unit.value());
});
it('checks "get" method', () => {
const randIndex = randomValue(1);
expect(unit.get(randIndex)).toEqual(unitValue[normalizeIndex(randIndex, unitValue.length)]);
expect(unit.rawValue()).toEqual(unitValue);
expect(emitCount).toEqual(unit.emitCount);
expect(unitValue).toEqual(unit.value());
});
it('checks "first" method', () => {
expect(unit.first()).toEqual(unitValue[0]);
expect(unit.rawValue()).toEqual(unitValue);
expect(emitCount).toEqual(unit.emitCount);
expect(unitValue).toEqual(unit.value());
});
it('checks "last" method', () => {
expect(unit.last()).toEqual(unitValue[listLength - 1]);
expect(unit.rawValue()).toEqual(unitValue);
expect(emitCount).toEqual(unit.emitCount);
expect(unitValue).toEqual(unit.value());
});
it('checks "jsonJoin" method', () => {
const separator = randomValue(1);
expect(unit.jsonJoin(separator)).toEqual(
unitValue.map(item => JSON.stringify(item)).join(separator)
);
expect(unit.rawValue()).toEqual(unitValue);
expect(emitCount).toEqual(unit.emitCount);
expect(unitValue).toEqual(unit.value());
});
it('checks "findByProp" method', () => {
const strictEquality = booleanOrRandomValue();
const skipStrictEqualityArg = randomBoolean(-0.5);
const allProps = Object.assign({}, ...unitValue);
const allKeys = Object.keys(allProps);
const randMatchKey = selectRandom(allKeys);
const randMatchValue = allProps[randMatchKey];
const matches = unit.findByProp(
randMatchKey,
randMatchValue,
...(skipStrictEqualityArg ? [] : [strictEquality])
);
const testMatches = unitValue.reduce((reduced, item, index) => {
if (
isObject(item) &&
(!skipStrictEqualityArg && strictEquality === false
? // tslint:disable-next-line:triple-equals
item[randMatchKey] == randMatchValue
: item[randMatchKey] === randMatchValue)
) {
reduced.push([index, item]);
}
return reduced;
}, []);
expect(matches).toEqual(testMatches);
expect(unit.rawValue()).toEqual(unitValue);
expect(emitCount).toEqual(unit.emitCount);
expect(unitValue).toEqual(unit.value());
});
});
describe('read-only Array.prototype methods', () => {
let unit: ListUnit<any>;
let unitValue: any[];
let emitCount: number;
beforeEach(() => {
unit = new ListUnit(somewhatValidConfig(configOptions, ListUnit));
if (randomBoolean(0.8)) {
unit.dispatch(randomValidValue(ListUnit, randomNumber(1, 3)));
}
unitValue = unit.value();
emitCount = unit.emitCount;
});
it('should have Array.prototype.slice', () => {
const sliceStart = randomNumber();
const sliceEnd = randomNumber();
expect(unit.slice(sliceStart, sliceEnd)).toEqual(unit.value().slice(sliceStart, sliceEnd));
expect(emitCount).toEqual(unit.emitCount);
expect(unitValue).toEqual(unit.value());
});
it('should have Array.prototype.concat', () => {
const concatItems = randomArray(1);
expect(unit.concat(...concatItems)).toEqual(unit.value().concat(...concatItems));
expect(emitCount).toEqual(unit.emitCount);
expect(unitValue).toEqual(unit.value());
});
it('should have Array.prototype.find', () => {
const findPredicate = randomValuePureFn();
expect(unit.find(findPredicate)).toEqual(unit.value().find(findPredicate));
expect(emitCount).toEqual(unit.emitCount);
expect(unitValue).toEqual(unit.value());
});
it('should have Array.prototype.findIndex', () => {
const findIndexPredicate = randomValuePureFn();
expect(unit.findIndex(findIndexPredicate)).toEqual(
unit.value().findIndex(findIndexPredicate)
);
expect(emitCount).toEqual(unit.emitCount);
expect(unitValue).toEqual(unit.value());
});
it('should have Array.prototype.entries', () => {
expect(unit.entries()).toEqual(unit.value().entries());
expect(unit.entries().toString()).toEqual('[object Array Iterator]');
expect([...unit.entries()]).toEqual([...unit.value().entries()]);
expect(emitCount).toEqual(unit.emitCount);
expect(unitValue).toEqual(unit.value());
});
it('should have Array.prototype.values', () => {
expect(unit.values()).toEqual(unit.value().values());
expect(unit.values().toString()).toEqual('[object Array Iterator]');
expect([...unit.values()]).toEqual([...unit.value().values()]);
expect(emitCount).toEqual(unit.emitCount);
expect(unitValue).toEqual(unit.value());
});
it('should have Array.prototype.keys', () => {
expect(unit.keys()).toEqual(unit.value().keys());
expect(unit.keys().toString()).toEqual('[object Array Iterator]');
expect([...unit.keys()]).toEqual([...unit.value().keys()]);
expect(emitCount).toEqual(unit.emitCount);
expect(unitValue).toEqual(unit.value());
});
it('should have Array.prototype.filter', () => {
const filterPredicate = randomValuePureFn();
expect(unit.filter(filterPredicate)).toEqual(unit.value().filter(filterPredicate));
expect(emitCount).toEqual(unit.emitCount);
expect(unitValue).toEqual(unit.value());
});
it('should have Array.prototype.flat', () => {
const flatDepth = randomNumber();
expect(unit.flat(flatDepth)).toEqual(unit.value().flat(flatDepth));
expect(emitCount).toEqual(unit.emitCount);
expect(unitValue).toEqual(unit.value());
});
it('should have Array.prototype.flatMap', () => {
const flatMapPredicate = randomValuePureFn();
expect(unit.flatMap(flatMapPredicate)).toEqual(unit.value().flatMap(flatMapPredicate));
expect(emitCount).toEqual(unit.emitCount);
expect(unitValue).toEqual(unit.value());
});
it('should have Array.prototype.map', () => {
const mapPredicate = randomValuePureFn();
expect(unit.map(mapPredicate)).toEqual(unit.value().map(mapPredicate));
expect(emitCount).toEqual(unit.emitCount);
expect(unitValue).toEqual(unit.value());
});
it('should have Array.prototype.some', () => {
const somePredicate = randomValuePureFn();
expect(unit.some(somePredicate)).toEqual(unit.value().some(somePredicate));
expect(emitCount).toEqual(unit.emitCount);
expect(unitValue).toEqual(unit.value());
});
it('should have Array.prototype.every', () => {
const everyPredicate = randomValuePureFn();
expect(unit.every(everyPredicate)).toEqual(unit.value().every(everyPredicate));
expect(emitCount).toEqual(unit.emitCount);
expect(unitValue).toEqual(unit.value());
});
it('should have Array.prototype.reduce', () => {
const reducePredicatePureFn = randomValuePureFn();
const reducePredicate = (reduced, item, i) => {
reduced[i] = reducePredicatePureFn(i) + item;
return reduced;
};
expect(unit.reduce(reducePredicate, {})).toEqual(unit.value().reduce(reducePredicate, {}));
expect(emitCount).toEqual(unit.emitCount);
expect(unitValue).toEqual(unit.value());
});
it('should have Array.prototype.reduceRight', () => {
const rightReducePredicatePureFn = randomValuePureFn();
const reduceRightPredicate = (reduced, item, i) => {
reduced[i] = rightReducePredicatePureFn(i) + item;
return reduced;
};
expect(unit.reduceRight(reduceRightPredicate, {})).toEqual(
unit.value().reduceRight(reduceRightPredicate, {})
);
expect(emitCount).toEqual(unit.emitCount);
expect(unitValue).toEqual(unit.value());
});
});
describe('mutative methods', () => {
let unit: ListUnit<any>;
let normalArray: any[];
let emitCount: number;
let listLength: number;
beforeEach(() => {
unit = new ListUnit(somewhatValidConfig(configOptions, ListUnit));
if (randomBoolean(0.8)) {
unit.dispatch(randomValidValue(ListUnit, 1));
}
normalArray = deepCopy(unit.rawValue());
emitCount = unit.emitCount;
listLength = unit.length;
});
it('checks "set" method', () => {
const index = randomBoolean(0.6) ? randomWholeNumber(50) : (randomValue(1) as number);
const normalIndex = normalizeIndex(index, unit.length);
const item = randomValue(1);
let event;
unit.events$.subscribe(e => (event = e));
unit.set(index, item);
if (isValidIndex(index)) {
normalArray[normalIndex] = item;
expect(normalArray[normalIndex]).toEqual(unit.get(index));
expect(event).toBeInstanceOf(EventListUnitSet);
expect(event).toEqual(new EventListUnitSet(index, item));
expect(unit.emitCount).toBe(emitCount + 1);
} else {
expect(event).toBe(undefined);
expect(unit.emitCount).toBe(emitCount);
}
expect(unit.rawValue()).toEqual(normalArray);
});
it('checks "insert" method', () => {
const startIndex = randomValue(1) as number;
const newItems = randomArray(1);
let event: EventListUnitSplice<any>;
unit.events$.subscribe(e => (event = e as EventListUnitSplice<any>));
const newLength = unit.insert(startIndex, ...newItems);
normalArray.splice(startIndex, 0, ...newItems);
if (newItems.length) {
const normalStartIndex = normalizeIndex(startIndex, normalArray.length);
expect(normalArray[normalStartIndex]).toEqual(unit.get(startIndex));
expect(event).toBeInstanceOf(EventListUnitSplice);
const normalEvent = new EventListUnitSplice(startIndex, 0, [], newItems);
expect(event).toEqual(normalEvent);
expect(unit.emitCount).toBe(emitCount + 1);
} else {
expect(event).toBe(undefined);
expect(unit.emitCount).toBe(emitCount);
}
expect(unit.length).toBe(newLength);
expect(unit.rawValue()).toEqual(normalArray);
});
it('checks "push" method', () => {
const items = randomArray(1);
let event;
unit.events$.subscribe(e => (event = e));
const newLength = unit.push(...items);
normalArray.push(...items);
if (items.length) {
expect(event).toBeInstanceOf(EventListUnitPush);
expect(event).toEqual(new EventListUnitPush(items));
expect(unit.emitCount).toBe(emitCount + 1);
} else {
expect(event).toBe(undefined);
expect(unit.emitCount).toBe(emitCount);
}
expect(unit.length).toBe(newLength);
expect(unit.rawValue()).toEqual(normalArray);
});
it('checks "unshift" method', () => {
const items = randomArray(1);
let event;
unit.events$.subscribe(e => (event = e));
const newLength = unit.unshift(...items);
normalArray.unshift(...items);
if (items.length) {
expect(event).toBeInstanceOf(EventListUnitUnshift);
expect(event).toEqual(new EventListUnitUnshift(items));
expect(unit.emitCount).toBe(emitCount + 1);
} else {
expect(event).toBe(undefined);
expect(unit.emitCount).toBe(emitCount);
}
expect(unit.length).toBe(newLength);
expect(unit.rawValue()).toEqual(normalArray);
});
it('checks "pop" method', () => {
let event;
unit.events$.subscribe(e => (event = e));
unit.pop();
const poppedItem = normalArray.pop();
if (listLength) {
expect(event).toBeInstanceOf(EventListUnitPop);
expect(event).toEqual(new EventListUnitPop(poppedItem));
expect(unit.emitCount).toBe(emitCount + 1);
} else {
expect(event).toBe(undefined);
expect(unit.emitCount).toBe(emitCount);
}
expect(unit.rawValue()).toEqual(normalArray);
});
it('checks "shift" method', () => {
let event;
unit.events$.subscribe(e => (event = e));
unit.shift();
const shiftedItem = normalArray.shift();
if (listLength) {
expect(event).toBeInstanceOf(EventListUnitShift);
expect(event).toEqual(new EventListUnitShift(shiftedItem));
expect(unit.emitCount).toBe(emitCount + 1);
} else {
expect(event).toBe(undefined);
expect(unit.emitCount).toBe(emitCount);
}
expect(unit.rawValue()).toEqual(normalArray);
});
it('checks "reverse" method', () => {
let event;
unit.events$.subscribe(e => (event = e));
unit.reverse();
normalArray.reverse();
if (listLength) {
expect(event).toBeInstanceOf(EventListUnitReverse);
expect(unit.emitCount).toBe(emitCount + 1);
} else {
expect(event).toBe(undefined);
expect(unit.emitCount).toBe(emitCount);
}
expect(unit.rawValue()).toEqual(normalArray);
});
it('checks "fill" method', () => {
const startIndex = randomValue(1) as number;
const endIndex = randomValue(1) as number;
const fillValue = randomValue(1);
let event;
unit.events$.subscribe(e => (event = e));
unit.fill(fillValue, startIndex, endIndex);
normalArray.fill(fillValue, startIndex, endIndex);
if (listLength) {
expect(event).toBeInstanceOf(EventListUnitFill);
expect(event).toEqual(new EventListUnitFill(fillValue, startIndex, endIndex));
expect(unit.emitCount).toBe(emitCount + 1);
} else {
expect(event).toBe(undefined);
expect(unit.emitCount).toBe(emitCount);
}
expect(unit.rawValue()).toEqual(normalArray);
});
it('checks "copyWithin" method', () => {
const startIndex = randomValue(1) as number;
const endIndex = randomValue(1) as number;
const targetIndex = randomValue(1) as number;
let event;
unit.events$.subscribe(e => (event = e));
unit.copyWithin(targetIndex, startIndex, endIndex);
normalArray.copyWithin(targetIndex, startIndex, endIndex);
if (listLength) {
expect(event).toBeInstanceOf(EventListUnitCopyWithin);
expect(event).toEqual(new EventListUnitCopyWithin(targetIndex, startIndex, endIndex));
expect(unit.emitCount).toBe(emitCount + 1);
} else {
expect(event).toBe(undefined);
expect(unit.emitCount).toBe(emitCount);
}
expect(unit.rawValue()).toEqual(normalArray);
});
it('checks "sort" method', () => {
const sortPredicate = randomBoolean() ? randomValuePureFn() : randomSortPredicate();
let event;
unit.events$.subscribe(e => (event = e));
if (randomBoolean(0.7)) {
unit.sort(sortPredicate);
normalArray.sort(sortPredicate);
} else {
unit.sort();
normalArray.sort();
}
if (listLength) {
expect(event).toBeInstanceOf(EventListUnitSort);
expect(unit.emitCount).toBe(emitCount + 1);
} else {
expect(event).toBe(undefined);
expect(unit.emitCount).toBe(emitCount);
}
expect(unit.rawValue()).toEqual(normalArray);
});
it('checks "splice" method', () => {
const startIndex = randomValue(1) as number;
const deleteCount = randomValue(1) as number;
const newItems = randomArray(1);
let event;
unit.events$.subscribe(e => (event = e));
unit.splice(startIndex, deleteCount, ...newItems);
const removedItems = normalArray.splice(startIndex, deleteCount, ...newItems);
// tslint:disable-next-line:triple-equals
if ((deleteCount != 0 && listLength) || newItems.length) {
expect(event).toBeInstanceOf(EventListUnitSplice);
expect(event).toEqual(
new EventListUnitSplice(startIndex, deleteCount, removedItems, newItems)
);
expect(unit.emitCount).toBe(emitCount + 1);
} else {
expect(event).toBe(undefined);
expect(unit.emitCount).toBe(emitCount);
}
expect(unit.rawValue()).toEqual(normalArray);
});
it('checks "remove" and "removeIf" method', () => {
const predicate = randomValuePureFn();
let validIndices;
let event;
unit.events$.subscribe(e => (event = e));
if (randomBoolean()) {
// for "removeIf" method
unit.removeIf((item, i) => predicate(i));
validIndices = [...Array(listLength).keys()].filter(i => predicate(i));
} else {
// for "remove" method
const indices = randomBoolean() ? multipleOf(() => randomNumber(1, 10)) : randomArray(1);
unit.remove(...indices);
validIndices = sanitizeIndices(indices, normalArray.length);
}
const removedItems = [];
validIndices
.sort()
.reverse()
.forEach(index => removedItems.push(...normalArray.splice(index, 1)));
removedItems.reverse();
if (validIndices.length && listLength) {
expect(event).toBeInstanceOf(EventListUnitRemove);
expect(event).toEqual(new EventListUnitRemove(validIndices, removedItems));
expect(unit.emitCount).toBe(emitCount + 1);
} else {
expect(event).toBe(undefined);
expect(unit.emitCount).toBe(emitCount);
}
expect(unit.rawValue()).toEqual(normalArray);
});
it('checks "delete" and "deleteIf" method', () => {
const predicate = randomValuePureFn();
let validIndices;
let event;
unit.events$.subscribe(e => (event = e));
if (randomBoolean()) {
// for deleteIf" method
unit.deleteIf((item, i) => predicate(i));
validIndices = [...Array(listLength).keys()].filter(i => predicate(i));
} else {
// for "remove" method
const indices = randomArray(1);
unit.delete(...indices);
validIndices = sanitizeIndices(indices, normalArray.length);
}
const deletedItems = [];
validIndices.forEach(index => {
deletedItems.push(normalArray[index]);
delete normalArray[index];
});
if (validIndices.length && listLength) {
expect(event).toBeInstanceOf(EventListUnitDelete);
expect(event).toEqual(new EventListUnitDelete(validIndices, deletedItems));
expect(unit.emitCount).toBe(emitCount + 1);
} else {
expect(event).toBe(undefined);
expect(unit.emitCount).toBe(emitCount);
}
expect(unit.rawValue()).toEqual(normalArray);
});
});
})
); | the_stack |
declare namespace spreedly {
type SpreedlyField = 'number' | 'cvv';
type SpreedlyFieldType = 'number' | 'text' | 'tel';
type SpreedlyNumberFormat = 'prettyFormat' | 'maskedFormat' | 'toggleMask';
type SpreedlyCardType = 'alelo' |
'alia' |
'american_express' |
'cabal' |
'carnet' |
'dankort' |
'diners_club' |
'discover' |
'elo' |
'jcb' |
'maestro' |
'master' |
'naranja' |
'olimpica' |
'sodexo' |
'visa' |
'vr';
type SpreedlyErrorKey = 'errors.account_inactive' |
'errors.environment_key_parameter_required' |
'errors.invalid_environment_key_parameter' |
'errors.blank' |
'errors.invalid' |
'errors.blank_card_type' |
'errors.expired' |
'errors.unknown_referrer' |
'errors.invalid_referrer' |
'errors.configuration';
type SpreedlyFieldEventType = 'focus' | 'blur' | 'mouseover' | 'mouseout' | 'input' | 'enter' | 'escape' | 'tab' | 'shiftTab';
interface InitOptions {
numberEl: string;
cvvEl: string;
}
interface TokenizeCreditCardAdditionalFields {
month?: string;
year?: string;
email?: string;
address1?: string;
address2?: string;
city?: string;
state?: string;
zip?: string;
country?: string;
phone_number?: string;
company?: string;
shipping_address1?: string;
shipping_address2?: string;
shipping_city?: string;
shipping_state?: string;
shipping_zip?: string;
shipping_country?: string;
shipping_phone_number?: string;
metadata?: { [key: string]: string };
}
interface TokenizeCreditCardAdditionalFieldsFullName extends TokenizeCreditCardAdditionalFields {
full_name: string;
}
interface TokenizeCreditCardAdditionalFieldsFirstLastNames extends TokenizeCreditCardAdditionalFields {
first_name: string;
last_name: string;
}
interface SetRecacheOptions {
card_type: SpreedlyCardType;
last_four_digits: string;
}
interface SpreedlyConsoleError {
msg: string;
url: string;
line: string;
col: string;
}
interface SpreedlyError {
attribute: string;
key: SpreedlyErrorKey;
message: string;
}
interface SpreedlyFieldEventInputProperties {
activeElement?: SpreedlyField;
cardType?: SpreedlyCardType | null;
cvvLength?: number;
numberLength?: number;
validCvv?: boolean;
validNumber?: boolean;
}
// TODO: Validate this
interface SpreedlyPaymentMethod {
token: string;
created_at: string;
updated_at: string;
email: string | null;
data: null;
storage_state: 'cached' | 'retained' | 'redacted';
test: boolean;
metadata: { [key: string]: string };
callback_url: string | null;
last_four_digits: string | null;
first_six_digits: string | null;
card_type: SpreedlyCardType;
first_name: string | null;
last_name: string | null;
month: number | null;
year: number | null;
address1: string | null;
address2: string | null;
city: string | null;
state: string | null;
zip: string | null;
country: string | null;
phone_number: string | null;
company: string | null;
full_name: string | null;
eligible_for_card_updater: boolean;
shipping_address1: string | null;
shipping_address2: string | null;
shipping_city: string | null;
shipping_state: string | null;
shipping_zip: string | null;
shipping_country: string | null;
shipping_phone_number: string | null;
payment_method_type: 'credit_card' | 'bank_account' | 'apple_pay' | 'google_pay' | 'third_party_token';
errors: any[];
fingerprint: string | null;
verification_value: string | null;
number: string | null;
}
}
/**
* Create a new, independent, instance of the iFrame. It will be created alongside the default instance, already exposed as Spreedly.
* @see https://docs.spreedly.com/reference/iframe/v1/#spreedlypaymentframe
*/
declare class SpreedlyPaymentFrame {
/**
* Initialize the iFrame library. This must be the first call made to iFrame and will trigger the loading of the iFrame fields.
* Triggers `ready` when the iFrame is ready for more configurartion.
* @see https://docs.spreedly.com/reference/iframe/v1/#init
*
* @param environmentKey - The key of the Spreedly environment where the payment method should be tokenized.
* @param options - Map of initialization options. HTML `id`s where iFrames should be rendered.
*/
init(environmentKey: string, options: spreedly.InitOptions): void;
/**
* Reload the iFrame library. This resets and re-initializes all iFrame elements and state.
* @see https://docs.spreedly.com/reference/iframe/v1/#reload
*/
reload(): void;
/**
* Remove all event handlers currently registered via the on function.
* @see https://docs.spreedly.com/reference/iframe/v1/#removehandlers
*/
removeHandlers(): void;
/**
* Trigger tokenization of the entered credit card.
* On successful tokenization, the `paymentMethod` event will be triggered. On failure, the `errors` event will be triggered.
* @see https://docs.spreedly.com/reference/iframe/v1/#tokenizecreditcard
*
* @param additionalFields - Map of additional payment method fields to store alongside tokenized card.
*/
tokenizeCreditCard(additionalFields: spreedly.TokenizeCreditCardAdditionalFieldsFullName | spreedly.TokenizeCreditCardAdditionalFieldsFirstLastNames): void;
/**
* Request iFrame fields to report their validation status.
* Triggers `validation`.
* @see https://docs.spreedly.com/reference/iframe/v1/#validate
*/
validate(): void;
/**
* Configure the iFrame to operate in recache mode.
* When iFrame has received and displayed the existing payment method information, the `recacheReady` event will be fired.
* @see https://docs.spreedly.com/reference/iframe/v1/#setrecache
*
* @param token - Token of existing payment method in Spreedly environment
* @param options - Map of display options for existing payment method.
*/
setRecache(token: string, options: spreedly.SetRecacheOptions): void;
/**
* Trigger recache on existing payment method. Requires that setRecache has already been called.
* On successful recache, the `recache` event will be triggered. On failure, the `errors` event will be triggered.
* @see https://docs.spreedly.com/reference/iframe/v1/#setrecache
*/
recache(): void;
/**
* Set the input type of the iFrame fields.
* @see https://docs.spreedly.com/reference/iframe/v1/#setfieldtype
*
* @param field - The iFrame field to set the type.
* @param type - The input field type.
*/
setFieldType(field: spreedly.SpreedlyField, type: spreedly.SpreedlyFieldType): void;
/**
* Style iFrame fields’ label. Although the label for each iFrame field is not displayed, it is still used by screen readers and other accessibility devices.
* @see https://docs.spreedly.com/reference/iframe/v1/#setlabel
*
* @param field - The iFrame field to set the label.
* @param label - The label text value.
*/
setLabel(field: spreedly.SpreedlyField, label: string): void;
/**
* Set the card number format.
* @see https://docs.spreedly.com/reference/iframe/v1/#setnumberformat
*
* @param format - The field's number format.
*/
setNumberFormat(format: spreedly.SpreedlyNumberFormat): void;
/**
* Style iFrame fields’ placeholder text.
* @see https://docs.spreedly.com/reference/iframe/v1/#setplaceholder
*
* @param field - The iFrame field to set the placeholder.
* @param placeholder - The placeholder text value
*/
setPlaceholder(field: spreedly.SpreedlyField, placeholder: string): void;
/**
* Style iFrame fields using CSS.
* @see https://docs.spreedly.com/reference/iframe/v1/#setstyle
*
* @param field - The iFrame field to apply the CSS to. Can be one of number or cvv.
* @param css - The CSS to apply. Should be vanilla CSS, constructed as a single string.
*/
setStyle(field: spreedly.SpreedlyField, css: string): void;
/**
* Set the cursor focus to one of the iFrame fields.
* @see https://docs.spreedly.com/reference/iframe/v1/#transferfocus
*
* @param field - The iFrame field to give focus to.
*/
transferFocus(field: spreedly.SpreedlyField): void;
/**
* Triggered when a javascript error occurs within the iFrame.
* @see https://docs.spreedly.com/reference/iframe/v1/#consoleerror
*
* @param event - Event to listen on.
* @param callback - Event callback.
*/
on(event: 'consoleError', callback: (error: spreedly.SpreedlyConsoleError) => void): void;
/**
* Triggered when a payment method is not successfully tokenized or recached.
* @see https://docs.spreedly.com/reference/iframe/v1/#errors
*
* @param event - Event to listen on.
* @param callback - Event callback.
*/
on(event: 'errors', callback: (errors: spreedly.SpreedlyError[]) => void): void;
/**
* Triggered when an input event occurs in either iFrame field.
* @see https://docs.spreedly.com/reference/iframe/v1/#fieldevent
*
* @param event - Event to listen on.
* @param callback - Event callback.
*/
on(
event: 'fieldEvent',
callback: (name: spreedly.SpreedlyField, type: spreedly.SpreedlyFieldEventType, activeEl: spreedly.SpreedlyField, inputProperties: spreedly.SpreedlyFieldEventInputProperties) => void
): void;
/**
* Triggered when a payment method is successfully tokenized or recached by Spreedly.
* @see https://docs.spreedly.com/reference/iframe/v1/#paymentmethod
*
* @param event - Event to listen on.
* @param callback - Event callback.
*/
on(event: 'paymentMethod' | 'recache', callback: (token: string, paymentMethod: spreedly.SpreedlyPaymentMethod) => void): void;
/**
* Triggered when the iFrame is initialized and ready for configuration or is properly configured for recache.
* @see https://docs.spreedly.com/reference/iframe/v1/#ready
*
* @param event - Event to listen on.
* @param callback - Event callback.
*/
on(event: 'ready' | 'recacheReady', callback: () => void): void;
/**
* Triggered when validation of the iFrame is requested.
* @see https://docs.spreedly.com/reference/iframe/v1/#validation
*
* @param event - Event to listen on.
* @param callback - Event callback.
*/
on(event: 'validation', callback: (inputProperties: spreedly.SpreedlyFieldEventInputProperties) => void): void;
}
declare var Spreedly: SpreedlyPaymentFrame; | the_stack |
import { getTags } from '@linode/api-v4/lib/tags';
import classNames from 'classnames';
import { withSnackbar, WithSnackbarProps } from 'notistack';
import { clone } from 'ramda';
import * as React from 'react';
import { compose } from 'recompose';
import Plus from 'src/assets/icons/plusSign.svg';
import CircleProgress from 'src/components/CircleProgress';
import {
createStyles,
Theme,
withStyles,
WithStyles,
} from 'src/components/core/styles';
import Typography from 'src/components/core/Typography';
import Select from 'src/components/EnhancedSelect/Select';
import { isRestrictedUser } from 'src/features/Profile/permissionsHelpers';
import Tag from 'src/components/Tag';
import { getErrorStringOrDefault } from 'src/utilities/errorUtils';
type ClassNames =
| 'root'
| 'tag'
| 'addButtonWrapper'
| 'hasError'
| 'errorNotice'
| 'addTagButton'
| 'tagsPanelItemWrapper'
| 'selectTag'
| 'progress'
| 'loading';
const styles = (theme: Theme) =>
createStyles({
'@keyframes fadeIn': {
from: {
opacity: 0,
},
to: {
opacity: 1,
},
},
tag: {
marginTop: theme.spacing(1) / 2,
marginRight: 4,
},
addButtonWrapper: {
display: 'flex',
justifyContent: 'flex-start',
width: '100%',
},
hasError: {
marginTop: 0,
},
errorNotice: {
animation: '$fadeIn 225ms linear forwards',
borderLeft: `5px solid ${theme.palette.status.errorDark}`,
'& .noticeText': {
...theme.typography.body1,
fontFamily: '"LatoWeb", sans-serif',
},
marginTop: 20,
paddingLeft: 10,
textAlign: 'left',
},
addTagButton: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
backgroundColor: theme.color.tagButton,
border: 'none',
borderRadius: 3,
color: theme.cmrTextColors.linkActiveLight,
cursor: 'pointer',
fontFamily: theme.font.normal,
fontSize: '0.875rem',
fontWeight: 'bold',
padding: '7px 10px',
whiteSpace: 'nowrap',
'& svg': {
color: theme.color.tagIcon,
marginLeft: 10,
height: 10,
width: 10,
},
},
tagsPanelItemWrapper: {
marginBottom: theme.spacing(),
position: 'relative',
},
selectTag: {
animation: '$fadeIn .3s ease-in-out forwards',
marginTop: -3.5,
minWidth: 275,
position: 'relative',
textAlign: 'left',
width: '100%',
zIndex: 3,
'& .error-for-scroll > div': {
flexDirection: 'row',
flexWrap: 'wrap-reverse',
},
'& .input': {
'& p': {
color: theme.color.grey1,
borderLeft: 'none',
fontSize: '.9rem',
},
},
'& .react-select__input': {
backgroundColor: 'transparent',
color: theme.palette.text.primary,
fontSize: '.9rem',
},
'& .react-select__value-container': {
padding: '6px',
},
},
progress: {
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
position: 'absolute',
height: '100%',
width: '100%',
zIndex: 2,
},
loading: {
opacity: 0.4,
},
});
interface Item {
label: string;
value: string;
}
interface Tag {
label: string;
}
interface ActionMeta {
action: string;
}
interface State {
tagsToSuggest?: Item[];
tagError: string;
isCreatingTag: boolean;
tagInputValue: string;
listDeletingTags: string[];
loading?: boolean;
}
export interface Props {
align?: 'left' | 'right';
tags: string[];
updateTags: (tags: string[]) => Promise<any>;
disabled?: boolean;
}
type CombinedProps = Props & WithStyles<ClassNames> & WithSnackbarProps;
class TagsPanel extends React.Component<CombinedProps, State> {
state: State = {
tagsToSuggest: [],
tagError: '',
isCreatingTag: false,
tagInputValue: '',
listDeletingTags: [],
loading: false,
};
componentDidMount() {
const { tags } = this.props;
if (!isRestrictedUser()) {
getTags()
.then((response) => {
/*
* The end goal is to display to the user a list of auto-suggestions
* when they start typing in a new tag, but we don't want to display
* tags that are already applied because there cannot
* be duplicates.
*/
const filteredTags = response.data.filter((thisTag: Tag) => {
return !tags.some((alreadyAppliedTag: string) => {
return alreadyAppliedTag === thisTag.label;
});
});
/*
* reshaping them for the purposes of being passed to the Select component
*/
const reshapedTags = filteredTags.map((thisTag: Tag) => {
return {
label: thisTag.label,
value: thisTag.label,
};
});
this.setState({ tagsToSuggest: reshapedTags });
})
.catch((e) => e);
}
}
toggleTagInput = () => {
if (!this.props.disabled) {
this.setState({
tagError: '',
isCreatingTag: !this.state.isCreatingTag,
});
}
};
handleDeleteTag = (label: string) => {
const { tags, updateTags } = this.props;
/*
* Add this tag to the current list of tags that are queued for deletion
*/
this.setState(
{
listDeletingTags: [...this.state.listDeletingTags, label],
loading: true,
},
() => {
/*
* Update the new list of tags (which is the previous list but
* with the deleted tag filtered out). It's important to note that the Tag is *not*
* being deleted here - it's just being removed from the list
*/
const tagsWithoutDeletedTag = tags.filter((thisTag: string) => {
return this.state.listDeletingTags.indexOf(thisTag) === -1;
});
updateTags(tagsWithoutDeletedTag)
.then(() => {
/*
* Remove this tag from the current list of tags that are queued for deletion
*/
const cloneTagSuggestions = clone(this.state.tagsToSuggest) || [];
this.setState({
tagsToSuggest: [
{
value: label,
label,
},
...cloneTagSuggestions,
],
listDeletingTags: this.state.listDeletingTags.filter(
(thisTag) => thisTag !== label
),
loading: false,
tagError: '',
});
})
.catch((_) => {
this.props.enqueueSnackbar(`Could not delete Tag: ${label}`, {
variant: 'error',
});
/*
* Remove this tag from the current list of tags that are queued for deletion
*/
this.setState({
listDeletingTags: this.state.listDeletingTags.filter(
(thisTag) => thisTag !== label
),
loading: false,
});
});
}
);
};
handleCreateTag = (value: Item, actionMeta: ActionMeta) => {
const { tagsToSuggest } = this.state;
const { tags, updateTags } = this.props;
const inputValue = value && value.value;
/*
* This comes from the react-select API
* basically, we only want to make a request if the user is either
* hitting the enter button or choosing a selection from the dropdown
*/
if (
actionMeta.action !== 'select-option' &&
actionMeta.action !== 'create-option'
) {
return;
}
const tagExists = (tag: string) => {
return tags.some((el) => {
return el === tag;
});
};
this.toggleTagInput();
if (inputValue.length < 3 || inputValue.length > 50) {
this.setState({
tagError: `Tag "${inputValue}" length must be 3-50 characters`,
});
} else if (tagExists(inputValue)) {
this.setState({
tagError: `Tag "${inputValue}" is a duplicate`,
});
} else {
this.setState({
loading: true,
});
updateTags([...tags, value.label])
.then(() => {
// set the input value to blank on submit
this.setState({ tagInputValue: '' });
/*
* Filter out the new tag out of the auto-suggestion list
* since we can't attach this tag anymore
*/
const cloneTagSuggestions = clone(tagsToSuggest) || [];
const filteredTags = cloneTagSuggestions.filter((thisTag: Item) => {
return thisTag.label !== value.label;
});
this.setState({
tagsToSuggest: filteredTags,
loading: false,
});
})
.catch((e) => {
const tagError = getErrorStringOrDefault(
e,
'Error while creating tag'
);
this.setState({ loading: false, tagError });
});
}
};
render() {
const { tags, classes, disabled } = this.props;
const {
isCreatingTag,
tagsToSuggest,
tagInputValue,
tagError,
loading,
} = this.state;
return (
<>
{isCreatingTag ? (
<Select
onChange={this.handleCreateTag}
options={tagsToSuggest}
variant="creatable"
onBlur={this.toggleTagInput}
placeholder="Create or Select a Tag"
label="Create or Select a Tag"
hideLabel
value={tagInputValue}
createOptionPosition="first"
className={classes.selectTag}
escapeClearsValue
blurInputOnSelect
// eslint-disable-next-line
autoFocus
/>
) : (
<div
className={classNames({
[classes.addButtonWrapper]: true,
[classes.hasError]: tagError,
})}
>
<button
className={classes.addTagButton}
title="Add a tag"
onClick={this.toggleTagInput}
>
Add a tag
<Plus />
</button>
</div>
)}
<div className={classes.tagsPanelItemWrapper}>
{loading && (
<div className={classes.progress}>
<CircleProgress mini />
</div>
)}
{tags.map((thisTag) => {
return (
<Tag
key={`tag-item-${thisTag}`}
className={classNames({
[classes.tag]: true,
[classes.loading]: loading,
})}
colorVariant="lightBlue"
label={thisTag}
maxLength={30}
onDelete={
disabled ? undefined : () => this.handleDeleteTag(thisTag)
}
/>
);
})}
{tagError && (
<Typography className={classes.errorNotice}>{tagError}</Typography>
)}
</div>
</>
);
}
}
const styled = withStyles(styles);
export default compose<CombinedProps, Props>(styled, withSnackbar)(TagsPanel); | the_stack |
import { ValidationErrors, ValidatorFn, AbstractControl, FormGroup, FormControl, Validators } from '@angular/forms';
import { NumericValueType, RxwebValidators, ReactiveFormConfig, RxFormBuilder, FormGroupExtension, RxFormControl, RxFormArray } from '@rxweb/reactive-form-validators';
import { tick, fakeAsync } from '@angular/core/testing';
describe('Validator', () => {
beforeEach(() => {
ReactiveFormConfig.set({
"validationMessage": {
"alphaNumeric": "Only alphanumerics are allowed.",
"required": "This field is required",
"digit": "Only digits are allowed"
}
});
});
describe('rx_form_builder_spec', () => {
it("should not error, alphaNumeric validator with rxFormBuilder",
() => {
let formBuilder = new RxFormBuilder();
let formGroup = formBuilder.group({
'areaName': ['Mumbai', RxwebValidators.alphaNumeric()]
})
expect(formGroup.controls.areaName.errors).toBeNull();
});
it("should error ,alphaNumeric validator with rxFormBuilder",
() => {
let formBuilder = new RxFormBuilder();
let formGroup = formBuilder.group({
'areaName': ['@Mumbai', RxwebValidators.alphaNumeric()]
})
expect(formGroup.controls.areaName.errors).toEqual({ 'alphaNumeric': { message: 'Only alphanumerics are allowed.', refValues: ['@Mumbai'] } });
});
it("should not error ,alphaNumeric validator with rxFormBuilder allowWhiteSpace true.",
() => {
let formBuilder = new RxFormBuilder();
let formGroup = formBuilder.group({
'flatAddress': ['', RxwebValidators.alphaNumeric({ allowWhiteSpace: true })]
});
formGroup.controls.flatAddress.setValue('Victoria Park');
expect(formGroup.controls.flatAddress.errors).toBeNull();
});
it("Should not error, alphaNumeric validator Conditional Expression with type 'function' using rxFormbuilder",
() => {
let formBuilder = new RxFormBuilder();
let formGroup = formBuilder.group({
'areaName': [''],
'countryCode': ['', RxwebValidators.alphaNumeric({ conditionalExpression: (x, y) => x.areaName == "Delhi" })]
});
formGroup.controls.areaName.setValue('Mumbai')
formGroup.controls.countryCode.setValue("@AU")
expect(formGroup.controls.countryCode.errors).toBeNull();
});
it("Should not error, alphaNumeric validator Conditional Expression with type 'string' using rxFormbuilder",
() => {
let formBuilder = new RxFormBuilder();
let formGroup = formBuilder.group({
'areaName': [''],
'countryCode': ['', RxwebValidators.alphaNumeric({ conditionalExpression: 'x => x.areaName == "Delhi"' })]
});
formGroup.controls.areaName.setValue('Mumbai');
formGroup.controls.countryCode.setValue("@AU")
expect(formGroup.controls.countryCode.errors).toBeNull();
});
it("Should not error, alphaNumeric validator Conditional Expression with type 'function' using rxFormbuilder",
() => {
let formBuilder = new RxFormBuilder();
let formGroup = formBuilder.group({
'areaName': '',
'countryCode': ['', RxwebValidators.alphaNumeric({ conditionalExpression: (x, y) => x.areaName == "Delhi" })]
});
formGroup.controls.areaName.setValue('Delhi')
formGroup.controls.countryCode.setValue("AU")
expect(formGroup.controls.countryCode.errors).toBeNull();
});
it("Should not error, alphaNumeric validator Conditional Expression with type 'string' using rxFormbuilder",
() => {
let formBuilder = new RxFormBuilder();
let formGroup = formBuilder.group({
'areaName': 'Delhi',
'countryCode': ['', RxwebValidators.alphaNumeric({ conditionalExpression: 'x => x.areaName == "Delhi"' })]
});
formGroup.controls.countryCode.setValue("AU");
expect(formGroup.controls.countryCode.errors).toBeNull();
});
it("Should error, alphaNumeric validator Conditional Expression with type 'function' using rxFormbuilder",
() => {
let formBuilder = new RxFormBuilder();
let formGroup = formBuilder.group({
'areaName': 'Delhi',
'countryCode': ['', RxwebValidators.alphaNumeric({ conditionalExpression: (x, y) => x.areaName == "Delhi" })]
});
formGroup.controls.countryCode.setValue('@AU');
expect(formGroup.controls.countryCode.errors).toEqual({ 'alphaNumeric': { message: 'Only alphanumerics are allowed.', refValues: ['@AU'] } });
});
it("Should error, alphaNumeric validator Conditional Expression with type 'string' using rxFormbuilder",
() => {
let formBuilder = new RxFormBuilder();
let formGroup = formBuilder.group({
'areaName': [''],
'countryCode': ['', RxwebValidators.alphaNumeric({ conditionalExpression: 'x => x.areaName == "Delhi"' })]
});
formGroup.controls.areaName.setValue('Delhi');
formGroup.controls.countryCode.setValue('@AU');
expect(formGroup.controls.countryCode.errors).toEqual({ 'alphaNumeric': { message: 'Only alphanumerics are allowed.', refValues: ['@AU'] } });
});
it("Should error, alphaNumeric validator Shows custom message using rxFormbuilder",
() => {
let formBuilder = new RxFormBuilder();
let formGroup = formBuilder.group({
postalAddress: ['', RxwebValidators.alphaNumeric({ message: 'Please enter only alphanumerics, special characters are not allowed.' })],
});
formGroup.controls.postalAddress.setValue('16 amphi-theatre');
expect(formGroup.controls.postalAddress.errors).toEqual({ 'alphaNumeric': { message: 'Please enter only alphanumerics, special characters are not allowed.', refValues: ['16 amphi-theatre'] } });
});
it("should be valid, validators of angular using rxFormbuilder",
() => {
let formBuilder = new RxFormBuilder();
let formGroup = formBuilder.group({
firstName: ['', Validators.required],
});
formGroup.controls.firstName.setValue('ajay');
expect(formGroup.controls.firstName.valid).toBe(true);
})
it("should be invalid, validators of angular using rxFormbuilder",
() => {
let formBuilder = new RxFormBuilder();
let formGroup = formBuilder.group({
firstName: ['', Validators.required],
});
formGroup.controls.firstName.setValue('');
expect(formGroup.controls.firstName.valid).toBe(false);
})
it("should be valid, validators of angular using rxFormbuilder",
() => {
let formBuilder = new RxFormBuilder();
let formGroup = formBuilder.group({
firstName: ['', Validators.pattern('^[A-Za-z]+$')],
});
formGroup.controls.firstName.setValue('ajay');
expect(formGroup.controls.firstName.valid).toBe(true);
})
it("should be invalid, validators of angular using rxFormbuilder",
() => {
let formBuilder = new RxFormBuilder();
let formGroup = formBuilder.group({
firstName: ['', Validators.pattern('^[A-Za-z]+$')],
});
formGroup.controls.firstName.setValue('ajay@123');
expect(formGroup.controls.firstName.valid).toBe(false);
})
it("should be valid, validators of angular using rxFormbuilder",
() => {
let formBuilder = new RxFormBuilder();
let formGroup = formBuilder.group({
firstName: ['', Validators.minLength(5)],
});
formGroup.controls.firstName.setValue('samanthaRuthPrabhu');
expect(formGroup.controls.firstName.valid).toBe(true);
})
it("should be invalid, validators of angular using rxFormbuilder",
() => {
let formBuilder = new RxFormBuilder();
let formGroup = formBuilder.group({
firstName: ['', Validators.minLength(5)],
});
formGroup.controls.firstName.setValue('ajay');
expect(formGroup.controls.firstName.valid).toBe(false);
})
it("should be valid, validators of angular using rxFormbuilder",
() => {
let formBuilder = new RxFormBuilder();
let formGroup = formBuilder.group({
firstName: ['', Validators.minLength(5)],
lastName: ['', Validators.min(5)]
});
formGroup.controls.firstName.setValue('samanthaRuthPrabhu');
formGroup.controls.lastName.setValue('Khandelwal')
expect(formGroup.controls.firstName.valid).toBe(true);
})
it("should be invalid, validators of angular using rxFormbuilder",
() => {
let formBuilder = new RxFormBuilder();
let formGroup = formBuilder.group({
firstName: ['', Validators.minLength(5)],
lastName: ['', Validators.min(5)]
});
formGroup.controls.firstName.setValue('ajay');
formGroup.controls.lastName.setValue('ojha')
expect(formGroup.controls.firstName.valid).toBe(false);
})
it("should be valid, validators of angular using rxFormbuilder",
() => {
let formBuilder = new RxFormBuilder();
let formGroup = formBuilder.group({
firstName: ['', Validators.maxLength(10)],
lastName: ['', Validators.max(5)]
});
formGroup.controls.firstName.setValue('Bharat');
formGroup.controls.lastName.setValue('Patel')
expect(formGroup.controls.firstName.valid).toBe(true);
})
it("should be invalid, validators of angular using rxFormbuilder",
() => {
let formBuilder = new RxFormBuilder();
let formGroup = formBuilder.group({
firstName: ['', Validators.maxLength(10)],
lastName: ['', Validators.max(5)]
});
formGroup.controls.firstName.setValue('samanthaRuthPrabhu');
formGroup.controls.lastName.setValue('Khandelwal')
expect(formGroup.controls.firstName.valid).toBe(false);
})
it("should be valid, validators of angular using rxFormbuilder",
() => {
let formBuilder = new RxFormBuilder();
let formGroup = formBuilder.group({
email: ['', Validators.email]
});
formGroup.controls.email.setValue('bharatpatel@gmail.com');
expect(formGroup.controls.email.valid).toBe(true);
})
it("should be invalid, validators of angular using rxFormbuilder",
() => {
let formBuilder = new RxFormBuilder();
let formGroup = formBuilder.group({
email: ['', Validators.email]
});
formGroup.controls.email.setValue('bharatpatelgmail.com');
expect(formGroup.controls.email.valid).toBe(false);
});
it("should not error using nested formGroup in rxFormBuilder", () => {
let formBuilder = new RxFormBuilder();
let formGroup = formBuilder.group({
firstName: new FormControl('', RxwebValidators.required()),
lastName: new FormControl('', RxwebValidators.required()),
addressFormGroup: formBuilder.group({
street: new FormControl('', RxwebValidators.alphaNumeric()),
zipcode: new FormControl('', RxwebValidators.digit())
})
})
formGroup.controls.firstName.setValue('Bharat');
expect(formGroup.controls.firstName.errors).toBeNull();
formGroup.controls.lastName.setValue('Patel');
expect(formGroup.controls.lastName.errors).toBeNull();
let address = formGroup.controls.addressFormGroup['controls'];
address.street.setValue('VictoriaLake');
expect(address.street.errors).toBeNull();
address.zipcode.setValue('10001');
expect(address.zipcode.errors).toBeNull();
});
it("should error using nested formGroup in rxFormBuilder", () => {
let formBuilder = new RxFormBuilder();
let formGroup = formBuilder.group({
firstName: new FormControl('', RxwebValidators.required()),
lastName: new FormControl('', RxwebValidators.required()),
addressFormGroup: formBuilder.group({
street: new FormControl('', RxwebValidators.alphaNumeric()),
zipcode: new FormControl('', RxwebValidators.digit())
})
})
formGroup.controls.firstName.setValue('');
expect(formGroup.controls.firstName.errors).toEqual({ 'required': { message: 'This field is required', refValues: [] } });
formGroup.controls.lastName.setValue('');
expect(formGroup.controls.lastName.errors).toEqual({ 'required': { message: 'This field is required', refValues: [] } });
let address = formGroup.controls.addressFormGroup['controls'];
address.street.setValue('Victoria-Lake');
expect(address.street.errors).toEqual({ 'alphaNumeric': { message: 'Only alphanumerics are allowed.', refValues: ['Victoria-Lake'] } });
address.zipcode.setValue('A10001');
expect(address.zipcode.errors).toEqual({ 'digit': { message: 'Only digits are allowed', refValues: ['A10001'] } });
})
it("should display error", () => {
let formBuilder = new RxFormBuilder();
let formGroup = formBuilder.group({
firstName: ['', RxwebValidators.required()],
lastName: ['', RxwebValidators.required()]
});
let errorobject = { firstName: "This field is required", lastName: "This field is required" };
formGroup.controls.firstName.setValue('');
formGroup.controls.lastName.setValue('');
let errorObject = (<FormGroupExtension>formGroup).getErrorSummary(true);
expect(errorObject).toEqual(errorobject);
})
it("should defined dob",
() => {
let formBuilder = new RxFormBuilder();
let formGroup = formBuilder.group({
dob: new Date()
})
expect(formGroup.controls.dob instanceof RxFormControl).toBe(true);
});
//issue : https://github.com/rxweb/rxweb/issues/161
it("should validate nested formgroup, formcontrol with conditional expression",
fakeAsync(() => {
let formBuilder = new RxFormBuilder();
let formGroup = formBuilder.group({
nested: formBuilder.group({
typeValue: [''],
value: ['', [
RxwebValidators.numeric({
conditionalExpression: (x, y) => {
return x.typeValue === '1';
},
acceptValue: NumericValueType.PositiveNumber,
allowDecimal: false,
message: 'Positive Integer'
}),
RxwebValidators.numeric({
conditionalExpression: (x, y) => {
return x.typeValue === '2';
},
isFormat: true,
digitsInfo: '1.0-2',
allowDecimal: true,
message: 'Positive Decimal',
}),
RxwebValidators.required({
conditionalExpression: (x, y) => {
return y.nested.typeValue === '3';
},
message: 'Field Required'
})]]
})
})
let nestedFormGroup = formGroup.controls.nested as FormGroup;
expect(nestedFormGroup.controls.value.errors).toBeNull();
nestedFormGroup.controls.typeValue.setValue('3');
tick(1000);
expect(nestedFormGroup.controls.value.errors != null).toBeTruthy();
}));
//issue : https://github.com/rxweb/rxweb/issues/269
it("should defined Date",
() => {
let date = new Date();
let formBuilder = new RxFormBuilder();
let formGroup = formBuilder.group({
date: [new Date(), [RxwebValidators.required()]]
})
expect(formGroup.controls.date instanceof RxFormControl).toBe(true);
expect(formGroup.controls.date.value).toEqual(date);
});
//issue : https://github.com/rxweb/rxweb/issues/276
it("should define nested formarray with zero controls",
() => {
let date = new Date();
let formBuilder = new RxFormBuilder();
let formGroup = formBuilder.group({
addresses: []
})
let formArray = formGroup.controls.addresses as RxFormArray;
expect(formGroup.controls.addresses instanceof RxFormArray).toBe(true);
expect(formArray.controls.length).toEqual(0);
});
//issue : https://github.com/rxweb/rxweb/issues/332
it("bind validators at FormGroup level.",
() => {
let globalValidator = (): ValidatorFn => {
return (c: AbstractControl): ValidationErrors => {
return { global: true };
}
}
let date = new Date();
let formBuilder = new RxFormBuilder();
let formGroup = formBuilder.group({
addresses: []
}, {
baseAbstractControlOptions: {
global: {
validators: [globalValidator()]
}
}
})
expect(formGroup.errors).toEqual({ global: true });
});
});
}); | the_stack |
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import {
IEmployee,
IOrganization,
IOrganizationContact,
IOrganizationProject,
ProjectBillingEnum,
ITag,
ProjectOwnerEnum,
TaskListTypeEnum,
ContactType,
ICurrency,
OrganizationProjectBudgetTypeEnum
} from '@gauzy/contracts';
import { TranslateService } from '@ngx-translate/core';
import { Router } from '@angular/router';
import { uniq } from 'underscore';
import { debounceTime, filter, tap } from 'rxjs/operators';
import { distinctUntilChange } from '@gauzy/common-angular';
import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy';
import { TranslationBaseComponent } from '../../../@shared/language-base/translation-base.component';
import { patterns } from '../../../@shared/regex/regex-patterns.const';
import { environment as ENV } from './../../../../environments/environment';
import { ErrorHandlingService, OrganizationContactService, Store, ToastrService } from '../../../@core/services';
import { DUMMY_PROFILE_IMAGE } from '../../../@core/constants';
import { CompareDateValidator } from '../../../@core/validators';
import { FormHelpers } from '../../../@shared/forms/helpers';
import { ckEditorConfig } from "../../../@shared/ckeditor.config";
@UntilDestroy({ checkProperties: true })
@Component({
selector: 'ga-projects-mutation',
templateUrl: './projects-mutation.component.html',
styleUrls: ['./projects-mutation.component.scss']
})
export class ProjectsMutationComponent
extends TranslationBaseComponent
implements OnInit {
/*
* Getter & Setter for dynamic project element
*/
_project: IOrganizationProject;
get project(): IOrganizationProject {
return this._project;
}
@Input() set project(project: IOrganizationProject) {
this._project = project;
}
@Output()
canceled = new EventEmitter();
@Output()
addOrEditProject = new EventEmitter();
@Input()
organizationContacts: Object[] = [];
OrganizationProjectBudgetTypeEnum = OrganizationProjectBudgetTypeEnum;
TaskListTypeEnum = TaskListTypeEnum;
members: string[] = [];
selectedEmployeeIds: string[] = [];
billings: string[] = Object.values(ProjectBillingEnum);
owners: ProjectOwnerEnum[] = Object.values(ProjectOwnerEnum);
taskViewModeTypes: TaskListTypeEnum[] = Object.values(TaskListTypeEnum);
showSprintManage = false;
ckConfig: any = ckEditorConfig;
public organization: IOrganization;
employees: IEmployee[] = [];
FormHelpers: typeof FormHelpers = FormHelpers;
/*
* Project Mutation Form
*/
public form: FormGroup = ProjectsMutationComponent.buildForm(this.fb);
static buildForm(fb: FormBuilder): FormGroup {
return fb.group({
tags: [],
public: [],
billable: [],
name: ['', Validators.required],
organizationContact: [],
billing: [ProjectBillingEnum.RATE],
currency: [ENV.DEFAULT_CURRENCY],
startDate: [],
endDate: [],
owner: [ProjectOwnerEnum.CLIENT],
taskViewMode: [TaskListTypeEnum.GRID],
description: [],
code: [],
color: [],
budget: [],
budgetType: [OrganizationProjectBudgetTypeEnum.HOURS],
openSource: [],
projectUrl: ['', Validators.compose([
Validators.pattern(new RegExp(patterns.websiteUrl))
])
],
openSourceProjectUrl: ['', Validators.compose([
Validators.pattern(new RegExp(patterns.websiteUrl))
])
]
}, {
validators: [
CompareDateValidator.validateDate('startDate', 'endDate')
]
});
}
constructor(
private readonly fb: FormBuilder,
private readonly organizationContactService: OrganizationContactService,
private readonly toastrService: ToastrService,
public readonly translateService: TranslateService,
private readonly errorHandler: ErrorHandlingService,
private readonly router: Router,
private readonly store: Store
) {
super(translateService);
}
ngOnInit() {
this.store.selectedOrganization$
.pipe(
filter((organization) => !!organization),
distinctUntilChange(),
debounceTime(100),
tap((organization: IOrganization) => this.organization = organization),
tap(() => this._loadDefaultCurrency()),
tap(() => this._syncProject()),
tap(() => this._getOrganizationContacts()),
untilDestroyed(this)
)
.subscribe();
}
/**
* Load default organization currency
*/
private _loadDefaultCurrency() {
if (!this.organization) {
return;
}
const { currency = ENV.DEFAULT_CURRENCY } = this.organization;
if (currency) {
this.form.get('currency').setValue(currency);
this.form.get('currency').updateValueAndValidity();
}
}
private async _getOrganizationContacts() {
const { tenantId } = this.store.user;
const { id: organizationId } = this.organization;
const { items } = await this.organizationContactService.getAll([], {
organizationId,
tenantId
});
items.forEach((i) => {
this.organizationContacts = uniq([
...this.organizationContacts,
{ name: i.name, organizationContactId: i.id, id: i.id }
], 'id');
});
}
changeProjectOwner(owner: ProjectOwnerEnum) {
const clientControl = this.form.get('client');
if (owner === ProjectOwnerEnum.INTERNAL && clientControl) {
clientControl.setValue('');
}
}
/**
* Sync edit organization project
*
* @param project
*/
private _syncProject() {
if (!this.project) {
return;
}
const project: IOrganizationProject = this.project;
this.selectedEmployeeIds = project.members.map(
(member: IEmployee) => member.id
);
this.members = this.selectedEmployeeIds;
this.form.patchValue({
tags: project.tags || [],
public: project.public || false,
billable: project.billable || false,
name: project.name || null,
organizationContact: project.organizationContact || null,
billing: project.billing || ProjectBillingEnum.RATE,
currency: project.currency,
startDate: project.startDate ? new Date(project.startDate) : null,
endDate: project.endDate ? new Date(project.endDate) : null,
owner: project.owner || ProjectOwnerEnum.CLIENT,
taskViewMode: project.taskListType || TaskListTypeEnum.GRID,
description: project.description || null,
code: project.code || null,
color: project.color || null,
budget: project.budget || null,
budgetType: project.budgetType || OrganizationProjectBudgetTypeEnum.HOURS,
openSource: project.openSource || null,
projectUrl: project.projectUrl || null,
openSourceProjectUrl: project.openSourceProjectUrl || null,
});
this.form.updateValueAndValidity();
}
/**
* Public toggle action
* @param state
*/
togglePublic(state: boolean) {
this.form.get('public').setValue(state);
this.form.get('public').updateValueAndValidity();
}
/**
* Billable toggle action
* @param state
*/
toggleBillable(state: boolean) {
this.form.get('billable').setValue(state);
this.form.get('billable').updateValueAndValidity();
}
/**
* Open source toggle action
* @param state
*/
toggleOpenSource(state: boolean) {
this.form.get('openSource').setValue(state);
this.form.get('openSource').updateValueAndValidity();
}
onMembersSelected(members: string[]) {
this.members = members;
}
cancel() {
this.canceled.emit();
}
/**
* On submit project mutation form
*
* @returns
*/
onSubmit() {
if (this.form.invalid) {
return;
}
const { tenantId } = this.store.user;
const { id: organizationId } = this.organization;
const { name, code, projectUrl, owner, organizationContact, startDate, endDate } = this.form.getRawValue();
const { description, tags } = this.form.getRawValue();
const { billing, currency } = this.form.getRawValue();
const { budget, budgetType } = this.form.getRawValue();
const { openSource, openSourceProjectUrl } = this.form.getRawValue();
const { color, taskListType, public: isPublic, billable } = this.form.getRawValue();
this.addOrEditProject.emit({
action: !this.project ? 'add' : 'edit',
project: {
id: this.project ? this.project.id : undefined,
// Main Step
name: name,
code: code,
projectUrl: projectUrl,
owner: owner,
organizationContactId: organizationContact ? organizationContact.id : null,
startDate: startDate,
endDate: endDate,
members: this.members.map((id) => this.employees.find((e) => e.id === id)).filter((e) => !!e),
// Description Step
description: description,
tags: tags || [],
// Billing Step
billing: billing,
billingFlat: (billing === ProjectBillingEnum.RATE) || (billing === ProjectBillingEnum.FLAT_FEE) ? true : false,
currency: currency,
// Budget Step
budget: budget,
budgetType: budgetType,
// Open Source Step
openSource: openSource,
openSourceProjectUrl: openSourceProjectUrl,
// Setting Step
color: color,
taskListType: taskListType,
public: isPublic,
billable: billable,
organizationId,
tenantId
}
});
}
selectedTagsEvent(selectedTags: ITag[]) {
this.form.get('tags').setValue(selectedTags);
this.form.get('tags').updateValueAndValidity();
}
addNewOrganizationContact = (
name: string
): Promise<IOrganizationContact> => {
try {
this.toastrService.success(
'NOTES.ORGANIZATIONS.EDIT_ORGANIZATIONS_CONTACTS.ADD_CONTACT',
{
name: name
}
);
const { id: organizationId } = this.organization;
const { tenantId } = this.store.user;
return this.organizationContactService.create({
name,
organizationId,
tenantId,
contactType: ContactType.CLIENT,
imageUrl: DUMMY_PROFILE_IMAGE
});
} catch (error) {
this.errorHandler.handleError(error);
}
};
openTasksSettings(): void {
this.router.navigate(['/pages/tasks/settings', this.project.id], {
state: this.project
});
}
/*
* On Changed Currency Event Emitter
*/
currencyChanged($event: ICurrency) { }
/**
* Load employees from multiple selected employees
*
* @param employees
*/
public onLoadEmployees(employees: IEmployee[]) {
this.employees = employees;
}
} | the_stack |
import { Constants } from './Constants';
import { Day } from './Day';
import { Locales } from './Locale';
import { Op } from './Operation';
import { Units } from './Units';
/**
* The calculated bounds of a DaySpan relative to a given day.
*/
export interface DaySpanBounds
{
/**
* The top of the span within the rectangle of the given day.
*/
top: number;
/**
* The bottom of the span within the rectangle of the givne day.
*/
bottom: number;
/**
* The height of the span within the rectangle of the given day. This is
* equivalent by `bottom - top`.
*/
height: number;
/**
* The left of the span within the rectangle of the given day.
*/
left: number;
/**
* The right of the span within the rectangle of the given day.
*/
right: number;
/**
* The width of the span within the rectangle of the given day. This is
* equivalent by `right - left`.
*/
width: number;
}
/**
* A class for a range of time between two [[Day]] timestamps.
*/
export class DaySpan
{
/**
* The starting timestamp of the span (inclusive).
*/
public start: Day;
/**
* The endind timestamp of the span (inclusive).
*/
public end: Day;
/**
* Creates a new span of time.
*
* @param start The starting timestamp.
* @param end The ending timestamp.
*/
public constructor(start: Day, end: Day)
{
this.start = start;
this.end = end;
}
/**
* Whether this span starts and ends on the same timestamp.
*/
public get isPoint(): boolean
{
return this.start.time === this.end.time;
}
/**
* Determines whether the given timestamp lies between the start and end
* timestamp.
*
* @param day The timestamp to test.
* @returns True if the day is >= the start and <= the end of this span.
*/
public contains(day: Day): boolean
{
return day.time >= this.start.time && day.time <= this.end.time;
}
/**
* Compares the given timestamp to this span. If the timestamp is before this
* span then `-1` is returned, if the timestamp is after this span then `1`
* us returned, otherwise `0` is returned when the timestamp is in this span.
*
* @param day The timestamp to compare to.
* @returns `-1`, `0`, or `1` depending on the given timestamp relative to
* this span.
*/
public compareTo(day: Day): number
{
return day.time < this.start.time ? -1 : (day.time > this.end.time ? 1 : 0);
}
/**
* Determines whether the given timestamp is between the start and end
* timestamp or lies on the same day as the start or end timestamp.
*
* @param day The timestamp to test.
* @see [[Day.sameDay]]
*/
public matchesDay(day: Day): boolean
{
return this.contains( day ) || day.sameDay( this.start ) || day.sameDay( this.end );
}
/**
* Determines whether the given timestamp is between the start and end
* timestamp or lies on the same week as the start or end timestamp.
*
* @param day The timestamp to test.
* @see [[Day.sameWeek]]
*/
public matchesWeek(day: Day): boolean
{
return this.contains( day ) || day.sameWeek( this.start ) || day.sameWeek( this.end );
}
/**
* Determines whether the given timestamp is between the start and end
* timestamp or lies on the same month as the start or end timestamp.
*
* @param day The timestamp to test.
* @see [[Day.sameMonth]]
*/
public matchesMonth(day: Day): boolean
{
return this.contains( day ) || day.sameMonth( this.start ) || day.sameMonth( this.end );
}
/**
* Determines whether the given timestamp is between the start and end
* timestamp or lies on the same year as the start or end timestamp.
*
* @param day The timestamp to test.
* @see [[Day.sameYear]]
*/
public matchesYear(day: Day): boolean
{
return this.contains( day ) || day.sameYear( this.start ) || day.sameYear( this.end );
}
/**
* Calculates the number of milliseconds between the start and end timestamp.
*
* @param op The operation to perform on the result.
* @param absolute Whether the result should always be positive.
* @returns The time between the start and end timestamp.
* @see [[Day.millisBetween]]
*/
public millis(op: Op = Op.DOWN, absolute: boolean = true): number
{
return this.start.millisBetween(this.end, op, absolute);
}
/**
* Calculates the number of seconds between the start and end timestamp.
*
* @param op The operation to perform on the result.
* @param absolute Whether the result should always be positive.
* @returns The time between the start and end timestamp.
* @see [[Day.secondsBetween]]
*/
public seconds(op: Op = Op.DOWN, absolute: boolean = true): number
{
return this.start.secondsBetween(this.end, op, absolute);
}
/**
* Calculates the number of minutes between the start and end timestamp.
*
* @param op The operation to perform on the result.
* @param absolute Whether the result should always be positive.
* @returns The time between the start and end timestamp.
* @see [[Day.minutesBetween]]
*/
public minutes(op: Op = Op.DOWN, absolute: boolean = true): number
{
return this.start.minutesBetween(this.end, op, absolute);
}
/**
* Calculates the number of hours between the start and end timestamp.
*
* @param op The operation to perform on the result.
* @param absolute Whether the result should always be positive.
* @returns The time between the start and end timestamp.
* @see [[Day.hoursBetween]]
*/
public hours(op: Op = Op.DOWN, absolute: boolean = true): number
{
return this.start.hoursBetween(this.end, op, absolute);
}
/**
* Calculates the number of days between the start and end timestamp.
*
* @param op The operation to perform on the result.
* @param absolute Whether the result should always be positive.
* @returns The time between the start and end timestamp.
* @see [[Day.daysBetween]]
*/
public days(op: Op = Op.DOWN, absolute: boolean = true): number
{
return this.start.daysBetween(this.end, op, absolute);
}
/**
* Calculates the number of weeks between the start and end timestamp.
*
* @param op The operation to perform on the result.
* @param absolute Whether the result should always be positive.
* @returns The time between the start and end timestamp.
* @see [[Day.weeksBetween]]
*/
public weeks(op: Op = Op.DOWN, absolute: boolean = true): number
{
return this.start.weeksBetween(this.end, op, absolute);
}
/**
* Calculates the number of months between the start and end timestamp.
*
* @param op The operation to perform on the result.
* @param absolute Whether the result should always be positive.
* @returns The time between the start and end timestamp.
* @see [[Day.monthsBetween]]
*/
public months(op: Op = Op.DOWN, absolute: boolean = true): number
{
return this.start.monthsBetween(this.end, op, absolute);
}
/**
* Calculates the number of years between the start and end timestamp.
*
* @param op The operation to perform on the result.
* @param absolute Whether the result should always be positive.
* @returns The time between the start and end timestamp.
* @see [[Day.yearsBetween]]
*/
public years(op: Op = Op.DOWN, absolute: boolean = true): number
{
return this.start.yearsBetween(this.end, op, absolute);
}
/**
* Returns a delta value between 0 and 1 which represents where the
* [[DaySpan.start]] is relative to the given day. The delta value would
* be less than 0 if the start of the event is before the given day.
*
* @param relativeTo The day to find the start delta relative to.
* @return A number between 0 and 1 if the start of this span is in the
* 24-hour period starting at the given timestamp, otherwise the value
* returned may be less than 0 or greater than 1.
*/
public startDelta(relativeTo: Day): number
{
return (this.start.time - relativeTo.time) / Constants.MILLIS_IN_DAY;
}
/**
* Returns a delta value between 0 and 1 which represents where the
* [[DaySpan.end]] is relative to the given day. The delta value would
* be greater than 1 if the end of the event is after the given day.
*
* @param relativeTo The day to find the end delta relative to.
* @return A number between 0 and 1 if the end of this span is in the
* 24-hour period starting at the given timestamp, otherwise the value
* returned may be less than 0 or greater than 1.
*/
public endDelta(relativeTo: Day): number
{
return (this.end.time - relativeTo.time) / Constants.MILLIS_IN_DAY;
}
/**
* Calculates the bounds for span event if it were placed in a rectangle which
* represents a day (24 hour period). By default the returned values are
* between 0 and 1 and can be scaled by the proper rectangle dimensions or the
* rectangle dimensions can be passed to this function.
*
* @param relativeTo The day to find the bounds relative to. If this is not the
* start of the day the returned bounds is relative to the given time.
* @param dayHeight The height of the rectangle of the day.
* @param dayWidth The width of the rectangle of the day.
* @param columnOffset The offset in the rectangle of the day to adjust this
* span by. This also reduces the width of the returned bounds to keep the
* bounds in the rectangle of the day.
* @param clip `true` if the bounds should stay in the day rectangle, `false`
* and the bounds may go outside the rectangle of the day for multi-day
* spans.
* @param offsetX How much to translate the left & right properties by.
* @param offsetY How much to translate the top & bottom properties by.
* @returns The calculated bounds for this span.
*/
public getBounds(relativeTo: Day, dayHeight: number = 1, dayWidth: number = 1, columnOffset: number = 0, clip: boolean = true, offsetX: number = 0, offsetY: number = 0): DaySpanBounds
{
const startRaw: number = this.startDelta( relativeTo );
const endRaw: number = this.endDelta( relativeTo );
const start: number = clip ? Math.max(0, startRaw) : startRaw;
const end: number = clip ? Math.min(1, endRaw) : endRaw;
const left: number = columnOffset;
const right: number = dayWidth - left;
const top: number = start * dayHeight;
const bottom: number = end * dayHeight;
return {
top: top + offsetY,
bottom: bottom + offsetY,
height: bottom - top,
left: left + offsetX,
right: right + offsetX,
width: right
};
}
/**
* Summarizes this span given an approximate unit of time and a few other
* options. If the start and end are on the same unit, a single value will
* be returned. Otherwise a start and end will be returned with a `delimiter`.
*
* @param type The unit of time this span is for.
* @param dayOfWeek When `true` the weekday of the start and end are included.
* @param short When `true` the short form of weekdays and months will be used.
* @param repeat When `true` the year will be repeated on the start and end
* timestamp even if they are the same year.
* @param contextual When `true` the year will be hidden if it's the current
* year.
* @param delimiter The string to separate the start and end timestamps with.
* @returns The summary of this span.
*/
public summary(type: Units, dayOfWeek: boolean = true, short: boolean = false, repeat: boolean = false, contextual: boolean = true, delimiter: string = ' - '): string
{
const formats = [Locales.current.summaryDay, Locales.current.summaryWeek, Locales.current.summaryMonth, Locales.current.summaryYear];
const formatter = formats[ type ];
const today: Day = Day.today();
const showStartYear: boolean = !contextual || !this.start.sameYear( today );
const showEndYear: boolean = !contextual || !this.end.sameYear( today );
const start: string = this.start.format( formatter(short, dayOfWeek, showStartYear) );
const end: string = this.end.format( formatter(short, dayOfWeek, showEndYear) );
let summary: string = start;
if (start !== end)
{
if (!repeat)
{
summary = this.start.format( formatter(short, dayOfWeek, !this.start.sameYear(this.end)) );
}
summary += delimiter;
summary += end;
}
else
{
summary = start;
}
return summary;
}
/**
* Determines whether the gven span intersects with this span.
*
* @param span The span to test.
* @returns `true` if the spans intersect, otherwise `false`.
*/
public intersects(span: DaySpan): boolean
{
return !(
this.end.time < span.start.time ||
this.start.time > span.end.time
);
}
/**
* Calculates the intersection between this span and the given span. If there
* is no intersection between the two spans then `null` is returned.
*
* @param span The span to calculate the intersection with.
* @returns The intersection or `null` if none exists.
*/
public intersection(span: DaySpan): DaySpan
{
const start: Day = this.start.max( span.start );
const end: Day = this.end.min( span.end );
return start.isAfter( end ) ? null : new DaySpan(start, end);
}
/**
* Calculates the union between this span and the given span.
*
* @param span The span to calculate the union with.
* @returns The union of the two spans.
*/
public union(span: DaySpan): DaySpan
{
const start: Day = this.start.min( span.start );
const end: Day = this.end.max( span.end );
return new DaySpan(start, end);
}
/**
* Returns a point [[DaySpan]] with the same start and end timestamp.
*
* @param day The timestamp which will be the start and end.
* @returns The new instance.
* @see [[DaySpan.isPoint]]
*/
public static point(day: Day): DaySpan
{
return new DaySpan( day, day );
}
} | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { Factories } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { DataFactoryManagementClient } from "../dataFactoryManagementClient";
import {
Factory,
FactoriesListNextOptionalParams,
FactoriesListOptionalParams,
FactoriesListByResourceGroupNextOptionalParams,
FactoriesListByResourceGroupOptionalParams,
FactoriesListResponse,
FactoryRepoUpdate,
FactoriesConfigureFactoryRepoOptionalParams,
FactoriesConfigureFactoryRepoResponse,
FactoriesListByResourceGroupResponse,
FactoriesCreateOrUpdateOptionalParams,
FactoriesCreateOrUpdateResponse,
FactoryUpdateParameters,
FactoriesUpdateOptionalParams,
FactoriesUpdateResponse,
FactoriesGetOptionalParams,
FactoriesGetResponse,
FactoriesDeleteOptionalParams,
GitHubAccessTokenRequest,
FactoriesGetGitHubAccessTokenOptionalParams,
FactoriesGetGitHubAccessTokenResponse,
UserAccessPolicy,
FactoriesGetDataPlaneAccessOptionalParams,
FactoriesGetDataPlaneAccessResponse,
FactoriesListNextResponse,
FactoriesListByResourceGroupNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing Factories operations. */
export class FactoriesImpl implements Factories {
private readonly client: DataFactoryManagementClient;
/**
* Initialize a new instance of the class Factories class.
* @param client Reference to the service client
*/
constructor(client: DataFactoryManagementClient) {
this.client = client;
}
/**
* Lists factories under the specified subscription.
* @param options The options parameters.
*/
public list(
options?: FactoriesListOptionalParams
): PagedAsyncIterableIterator<Factory> {
const iter = this.listPagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listPagingPage(options);
}
};
}
private async *listPagingPage(
options?: FactoriesListOptionalParams
): AsyncIterableIterator<Factory[]> {
let result = await this._list(options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listNext(continuationToken, options);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listPagingAll(
options?: FactoriesListOptionalParams
): AsyncIterableIterator<Factory> {
for await (const page of this.listPagingPage(options)) {
yield* page;
}
}
/**
* Lists factories.
* @param resourceGroupName The resource group name.
* @param options The options parameters.
*/
public listByResourceGroup(
resourceGroupName: string,
options?: FactoriesListByResourceGroupOptionalParams
): PagedAsyncIterableIterator<Factory> {
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?: FactoriesListByResourceGroupOptionalParams
): AsyncIterableIterator<Factory[]> {
let result = await this._listByResourceGroup(resourceGroupName, options);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByResourceGroupNext(
resourceGroupName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByResourceGroupPagingAll(
resourceGroupName: string,
options?: FactoriesListByResourceGroupOptionalParams
): AsyncIterableIterator<Factory> {
for await (const page of this.listByResourceGroupPagingPage(
resourceGroupName,
options
)) {
yield* page;
}
}
/**
* Lists factories under the specified subscription.
* @param options The options parameters.
*/
private _list(
options?: FactoriesListOptionalParams
): Promise<FactoriesListResponse> {
return this.client.sendOperationRequest({ options }, listOperationSpec);
}
/**
* Updates a factory's repo information.
* @param locationId The location identifier.
* @param factoryRepoUpdate Update factory repo request definition.
* @param options The options parameters.
*/
configureFactoryRepo(
locationId: string,
factoryRepoUpdate: FactoryRepoUpdate,
options?: FactoriesConfigureFactoryRepoOptionalParams
): Promise<FactoriesConfigureFactoryRepoResponse> {
return this.client.sendOperationRequest(
{ locationId, factoryRepoUpdate, options },
configureFactoryRepoOperationSpec
);
}
/**
* Lists factories.
* @param resourceGroupName The resource group name.
* @param options The options parameters.
*/
private _listByResourceGroup(
resourceGroupName: string,
options?: FactoriesListByResourceGroupOptionalParams
): Promise<FactoriesListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, options },
listByResourceGroupOperationSpec
);
}
/**
* Creates or updates a factory.
* @param resourceGroupName The resource group name.
* @param factoryName The factory name.
* @param factory Factory resource definition.
* @param options The options parameters.
*/
createOrUpdate(
resourceGroupName: string,
factoryName: string,
factory: Factory,
options?: FactoriesCreateOrUpdateOptionalParams
): Promise<FactoriesCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, factoryName, factory, options },
createOrUpdateOperationSpec
);
}
/**
* Updates a factory.
* @param resourceGroupName The resource group name.
* @param factoryName The factory name.
* @param factoryUpdateParameters The parameters for updating a factory.
* @param options The options parameters.
*/
update(
resourceGroupName: string,
factoryName: string,
factoryUpdateParameters: FactoryUpdateParameters,
options?: FactoriesUpdateOptionalParams
): Promise<FactoriesUpdateResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, factoryName, factoryUpdateParameters, options },
updateOperationSpec
);
}
/**
* Gets a factory.
* @param resourceGroupName The resource group name.
* @param factoryName The factory name.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
factoryName: string,
options?: FactoriesGetOptionalParams
): Promise<FactoriesGetResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, factoryName, options },
getOperationSpec
);
}
/**
* Deletes a factory.
* @param resourceGroupName The resource group name.
* @param factoryName The factory name.
* @param options The options parameters.
*/
delete(
resourceGroupName: string,
factoryName: string,
options?: FactoriesDeleteOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ resourceGroupName, factoryName, options },
deleteOperationSpec
);
}
/**
* Get GitHub Access Token.
* @param resourceGroupName The resource group name.
* @param factoryName The factory name.
* @param gitHubAccessTokenRequest Get GitHub access token request definition.
* @param options The options parameters.
*/
getGitHubAccessToken(
resourceGroupName: string,
factoryName: string,
gitHubAccessTokenRequest: GitHubAccessTokenRequest,
options?: FactoriesGetGitHubAccessTokenOptionalParams
): Promise<FactoriesGetGitHubAccessTokenResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, factoryName, gitHubAccessTokenRequest, options },
getGitHubAccessTokenOperationSpec
);
}
/**
* Get Data Plane access.
* @param resourceGroupName The resource group name.
* @param factoryName The factory name.
* @param policy Data Plane user access policy definition.
* @param options The options parameters.
*/
getDataPlaneAccess(
resourceGroupName: string,
factoryName: string,
policy: UserAccessPolicy,
options?: FactoriesGetDataPlaneAccessOptionalParams
): Promise<FactoriesGetDataPlaneAccessResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, factoryName, policy, options },
getDataPlaneAccessOperationSpec
);
}
/**
* ListNext
* @param nextLink The nextLink from the previous successful call to the List method.
* @param options The options parameters.
*/
private _listNext(
nextLink: string,
options?: FactoriesListNextOptionalParams
): Promise<FactoriesListNextResponse> {
return this.client.sendOperationRequest(
{ nextLink, options },
listNextOperationSpec
);
}
/**
* ListByResourceGroupNext
* @param resourceGroupName The resource group name.
* @param nextLink The nextLink from the previous successful call to the ListByResourceGroup method.
* @param options The options parameters.
*/
private _listByResourceGroupNext(
resourceGroupName: string,
nextLink: string,
options?: FactoriesListByResourceGroupNextOptionalParams
): Promise<FactoriesListByResourceGroupNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, nextLink, options },
listByResourceGroupNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const listOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/Microsoft.DataFactory/factories",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.FactoryListResponse
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.$host, Parameters.subscriptionId],
headerParameters: [Parameters.accept],
serializer
};
const configureFactoryRepoOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/providers/Microsoft.DataFactory/locations/{locationId}/configureFactoryRepo",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.Factory
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.factoryRepoUpdate,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.locationId
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const listByResourceGroupOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.FactoryListResponse
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName
],
headerParameters: [Parameters.accept],
serializer
};
const createOrUpdateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.Factory
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.factory,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.factoryName
],
headerParameters: [
Parameters.accept,
Parameters.contentType,
Parameters.ifMatch
],
mediaType: "json",
serializer
};
const updateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}",
httpMethod: "PATCH",
responses: {
200: {
bodyMapper: Mappers.Factory
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.factoryUpdateParameters,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.factoryName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const getOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.Factory
},
304: {},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.factoryName
],
headerParameters: [Parameters.accept, Parameters.ifNoneMatch],
serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}",
httpMethod: "DELETE",
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.factoryName
],
headerParameters: [Parameters.accept],
serializer
};
const getGitHubAccessTokenOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/getGitHubAccessToken",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.GitHubAccessTokenResponse
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.gitHubAccessTokenRequest,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.factoryName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const getDataPlaneAccessOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/getDataPlaneAccess",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.AccessPolicyResponse
},
default: {
bodyMapper: Mappers.CloudError
}
},
requestBody: Parameters.policy,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.factoryName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const listNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.FactoryListResponse
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.nextLink,
Parameters.subscriptionId
],
headerParameters: [Parameters.accept],
serializer
};
const listByResourceGroupNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.FactoryListResponse
},
default: {
bodyMapper: Mappers.CloudError
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.nextLink,
Parameters.subscriptionId,
Parameters.resourceGroupName
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import { ILogger, nextId, onResolve, resolveAll, Task, TaskStatus } from '@aurelia/kernel';
import { BindingMode, LifecycleFlags, Scope } from '@aurelia/runtime';
import { bindable } from '../../bindable.js';
import { INode, IRenderLocation } from '../../dom.js';
import { IPlatform } from '../../platform.js';
import { IInstruction } from '../../renderer.js';
import {
Controller,
ICustomAttributeController,
ICustomAttributeViewModel,
IHydratableController,
IHydratedController,
IHydratedParentController,
ISyntheticView
} from '../../templating/controller.js';
import { IViewFactory } from '../../templating/view.js';
import { attributePattern, AttrSyntax } from '../attribute-pattern.js';
import { templateController } from '../custom-attribute.js';
@templateController('promise')
export class PromiseTemplateController implements ICustomAttributeViewModel {
public readonly id: number = nextId('au$component');
public readonly $controller!: ICustomAttributeController<this>; // This is set by the controller after this instance is constructed
private view!: ISyntheticView;
@bindable public value!: Promise<unknown>;
public pending?: PendingTemplateController;
public fulfilled?: FulfilledTemplateController;
public rejected?: RejectedTemplateController;
private viewScope!: Scope;
private preSettledTask: Task<void | Promise<void>> | null = null;
private postSettledTask: Task<void | Promise<void>> | null = null;
private postSettlePromise!: Promise<void>;
/** @internal */ private readonly logger: ILogger;
public constructor(
/** @internal */ @IViewFactory private readonly _factory: IViewFactory,
/** @internal */ @IRenderLocation private readonly _location: IRenderLocation,
/** @internal */ @IPlatform private readonly _platform: IPlatform,
@ILogger logger: ILogger,
) {
this.logger = logger.scopeTo('promise.resolve');
}
public link(
_controller: IHydratableController,
_childController: ICustomAttributeController,
_target: INode,
_instruction: IInstruction,
): void {
this.view = this._factory.create(this.$controller).setLocation(this._location);
}
public attaching(initiator: IHydratedController, parent: IHydratedParentController, flags: LifecycleFlags): void | Promise<void> {
const view = this.view;
const $controller = this.$controller;
return onResolve(
view.activate(initiator, $controller, flags, this.viewScope = Scope.fromParent($controller.scope, {})),
() => this.swap(initiator, flags)
);
}
public valueChanged(_newValue: boolean, _oldValue: boolean, flags: LifecycleFlags): void {
if (!this.$controller.isActive) { return; }
this.swap(null, flags);
}
private swap(initiator: IHydratedController | null, flags: LifecycleFlags): void {
const value = this.value;
if (!(value instanceof Promise)) {
this.logger.warn(`The value '${String(value)}' is not a promise. No change will be done.`);
return;
}
const q = this._platform.domWriteQueue;
const fulfilled = this.fulfilled;
const rejected = this.rejected;
const pending = this.pending;
const s = this.viewScope;
let preSettlePromise: Promise<void>;
const defaultQueuingOptions = { reusable: false };
const $swap = () => {
// Note that the whole thing is not wrapped in a q.queueTask intentionally.
// Because that would block the app till the actual promise is resolved, which is not the goal anyway.
void resolveAll(
// At first deactivate the fulfilled and rejected views, as well as activate the pending view.
// The order of these 3 should not necessarily be sequential (i.e. order-irrelevant).
preSettlePromise = (this.preSettledTask = q.queueTask(() => {
return resolveAll(
fulfilled?.deactivate(initiator, flags),
rejected?.deactivate(initiator, flags),
pending?.activate(initiator, flags, s)
);
}, defaultQueuingOptions)).result,
value
.then(
(data) => {
if (this.value !== value) {
return;
}
const fulfill = () => {
// Deactivation of pending view and the activation of the fulfilled view should not necessarily be sequential.
this.postSettlePromise = (this.postSettledTask = q.queueTask(() => resolveAll(
pending?.deactivate(initiator, flags),
rejected?.deactivate(initiator, flags),
fulfilled?.activate(initiator, flags, s, data),
), defaultQueuingOptions)).result;
};
if (this.preSettledTask!.status === TaskStatus.running) {
void preSettlePromise.then(fulfill);
} else {
this.preSettledTask!.cancel();
fulfill();
}
},
(err) => {
if (this.value !== value) {
return;
}
const reject = () => {
// Deactivation of pending view and the activation of the rejected view should also not necessarily be sequential.
this.postSettlePromise = (this.postSettledTask = q.queueTask(() => resolveAll(
pending?.deactivate(initiator, flags),
fulfilled?.deactivate(initiator, flags),
rejected?.activate(initiator, flags, s, err),
), defaultQueuingOptions)).result;
};
if (this.preSettledTask!.status === TaskStatus.running) {
void preSettlePromise.then(reject);
} else {
this.preSettledTask!.cancel();
reject();
}
},
));
};
if (this.postSettledTask?.status === TaskStatus.running) {
void this.postSettlePromise.then($swap);
} else {
this.postSettledTask?.cancel();
$swap();
}
}
public detaching(initiator: IHydratedController, parent: IHydratedParentController, flags: LifecycleFlags): void | Promise<void> {
this.preSettledTask?.cancel();
this.postSettledTask?.cancel();
this.preSettledTask = this.postSettledTask = null;
return this.view.deactivate(initiator, this.$controller, flags);
}
public dispose(): void {
this.view?.dispose();
this.view = (void 0)!;
}
}
@templateController('pending')
export class PendingTemplateController implements ICustomAttributeViewModel {
public readonly id: number = nextId('au$component');
public readonly $controller!: ICustomAttributeController<this>; // This is set by the controller after this instance is constructed
@bindable({ mode: BindingMode.toView }) public value!: Promise<unknown>;
public view: ISyntheticView;
public constructor(
@IViewFactory private readonly factory: IViewFactory,
@IRenderLocation location: IRenderLocation,
) {
this.view = this.factory.create().setLocation(location);
}
public link(
controller: IHydratableController,
_childController: ICustomAttributeController,
_target: INode,
_instruction: IInstruction,
): void {
getPromiseController(controller).pending = this;
}
public activate(initiator: IHydratedController | null, flags: LifecycleFlags, scope: Scope): void | Promise<void> {
const view = this.view;
if (view.isActive) { return; }
return view.activate(view, this.$controller, flags, scope);
}
public deactivate(initiator: IHydratedController | null, flags: LifecycleFlags): void | Promise<void> {
const view = this.view;
if (!view.isActive) { return; }
return view.deactivate(view, this.$controller, flags);
}
public detaching(initiator: IHydratedController, parent: IHydratedParentController, flags: LifecycleFlags): void | Promise<void> {
return this.deactivate(initiator, flags);
}
public dispose(): void {
this.view?.dispose();
this.view = (void 0)!;
}
}
@templateController('then')
export class FulfilledTemplateController implements ICustomAttributeViewModel {
public readonly id: number = nextId('au$component');
public readonly $controller!: ICustomAttributeController<this>; // This is set by the controller after this instance is constructed
@bindable({ mode: BindingMode.fromView }) public value!: unknown;
public view: ISyntheticView;
public constructor(
@IViewFactory private readonly factory: IViewFactory,
@IRenderLocation location: IRenderLocation,
) {
this.view = this.factory.create().setLocation(location);
}
public link(
controller: IHydratableController,
_childController: ICustomAttributeController,
_target: INode,
_instruction: IInstruction,
): void {
getPromiseController(controller).fulfilled = this;
}
public activate(initiator: IHydratedController | null, flags: LifecycleFlags, scope: Scope, resolvedValue: unknown): void | Promise<void> {
this.value = resolvedValue;
const view = this.view;
if (view.isActive) { return; }
return view.activate(view, this.$controller, flags, scope);
}
public deactivate(initiator: IHydratedController | null, flags: LifecycleFlags): void | Promise<void> {
const view = this.view;
if (!view.isActive) { return; }
return view.deactivate(view, this.$controller, flags);
}
public detaching(initiator: IHydratedController, parent: IHydratedParentController, flags: LifecycleFlags): void | Promise<void> {
return this.deactivate(initiator, flags);
}
public dispose(): void {
this.view?.dispose();
this.view = (void 0)!;
}
}
@templateController('catch')
export class RejectedTemplateController implements ICustomAttributeViewModel {
public readonly id: number = nextId('au$component');
public readonly $controller!: ICustomAttributeController<this>; // This is set by the controller after this instance is constructed
@bindable({ mode: BindingMode.fromView }) public value!: unknown;
public view: ISyntheticView;
public constructor(
@IViewFactory private readonly factory: IViewFactory,
@IRenderLocation location: IRenderLocation,
) {
this.view = this.factory.create().setLocation(location);
}
public link(
controller: IHydratableController,
_childController: ICustomAttributeController,
_target: INode,
_instruction: IInstruction,
): void {
getPromiseController(controller).rejected = this;
}
public activate(initiator: IHydratedController | null, flags: LifecycleFlags, scope: Scope, error: unknown): void | Promise<void> {
this.value = error;
const view = this.view;
if (view.isActive) { return; }
return view.activate(view, this.$controller, flags, scope);
}
public deactivate(initiator: IHydratedController | null, flags: LifecycleFlags): void | Promise<void> {
const view = this.view;
if (!view.isActive) { return; }
return view.deactivate(view, this.$controller, flags);
}
public detaching(initiator: IHydratedController, parent: IHydratedParentController, flags: LifecycleFlags): void | Promise<void> {
return this.deactivate(initiator, flags);
}
public dispose(): void {
this.view?.dispose();
this.view = (void 0)!;
}
}
function getPromiseController(controller: IHydratableController) {
const promiseController: IHydratedParentController = (controller as Controller).parent! as IHydratedParentController;
const $promise = promiseController?.viewModel;
if ($promise instanceof PromiseTemplateController) {
return $promise;
}
if (__DEV__)
throw new Error('The parent promise.resolve not found; only `*[promise.resolve] > *[pending|then|catch]` relation is supported.');
else
throw new Error('AUR0813');
}
@attributePattern({ pattern: 'promise.resolve', symbols: '' })
export class PromiseAttributePattern {
public 'promise.resolve'(name: string, value: string, _parts: string[]): AttrSyntax {
return new AttrSyntax(name, value, 'promise', 'bind');
}
}
@attributePattern({ pattern: 'then', symbols: '' })
export class FulfilledAttributePattern {
public 'then'(name: string, value: string, _parts: string[]): AttrSyntax {
return new AttrSyntax(name, value, 'then', 'from-view');
}
}
@attributePattern({ pattern: 'catch', symbols: '' })
export class RejectedAttributePattern {
public 'catch'(name: string, value: string, _parts: string[]): AttrSyntax {
return new AttrSyntax(name, value, 'catch', 'from-view');
}
} | the_stack |
import {
AppUserConfig, AppConfig, ServerAppPromptConfig,
ConfigIntegrationKind, ServerAppConfig } from "../models/AppConfig";
import { WindowEnvironmentKind } from "../models/WindowEnvironmentKind";
import { SdkInitError, SdkInitErrorKind } from "../errors/SdkInitError";
import SdkEnvironment from "../managers/SdkEnvironment";
import OneSignalUtils from "../utils/OneSignalUtils";
import Utils from "../context/shared/utils/Utils";
import {
SERVER_CONFIG_DEFAULTS_SESSION,
SERVER_CONFIG_DEFAULTS_PROMPT_DELAYS,
SERVER_CONFIG_DEFAULTS_SLIDEDOWN,
CONFIG_DEFAULTS_SLIDEDOWN_OPTIONS
} from "../config";
import {
AppUserConfigCustomLinkOptions,
AppUserConfigPromptOptions,
DelayedPromptType,
} from '../models/Prompts';
import TagUtils from '../../src/utils/TagUtils';
import PromptsHelper from './PromptsHelper';
import { ConverterHelper } from "./ConverterHelper";
export enum IntegrationConfigurationKind {
/**
* Configuration comes from the dashboard only.
*/
Dashboard,
/**
* Configuration comes from user-provided JavaScript code only.
*/
JavaScript
}
export interface IntegrationCapabilities {
configuration: IntegrationConfigurationKind;
}
const MAX_CATEGORIES = 10;
export class ConfigHelper {
public static async getAppConfig(userConfig: AppUserConfig,
downloadServerAppConfig: (appId: string) => Promise<ServerAppConfig>): Promise<AppConfig> {
try {
if (!userConfig || !userConfig.appId || !OneSignalUtils.isValidUuid(userConfig.appId))
throw new SdkInitError(SdkInitErrorKind.InvalidAppId);
const serverConfig = await downloadServerAppConfig(userConfig.appId);
ConverterHelper.upgradeConfigToVersionTwo(userConfig);
const appConfig = this.getMergedConfig(userConfig, serverConfig);
this.checkRestrictedOrigin(appConfig);
return appConfig;
}
catch (e) {
if (e) {
if (e.code === 1)
throw new SdkInitError(SdkInitErrorKind.InvalidAppId);
else if (e.code === 2)
throw new SdkInitError(SdkInitErrorKind.AppNotConfiguredForWebPush);
}
throw e;
}
}
public static checkRestrictedOrigin(appConfig: AppConfig) {
if (appConfig.restrictedOriginEnabled) {
if (SdkEnvironment.getWindowEnv() !== WindowEnvironmentKind.ServiceWorker) {
if (window.top === window &&
!Utils.contains(window.location.hostname, ".os.tc") &&
!Utils.contains(window.location.hostname, ".onesignal.com") &&
!this.doesCurrentOriginMatchConfigOrigin(appConfig.origin)) {
throw new SdkInitError(SdkInitErrorKind.WrongSiteUrl, {
siteUrl: appConfig.origin
});
}
}
}
}
public static doesCurrentOriginMatchConfigOrigin(configOrigin: string): boolean {
try {
return location.origin === new URL(configOrigin).origin;
} catch (e) {
return false;
}
}
public static getIntegrationCapabilities(integration: ConfigIntegrationKind): IntegrationCapabilities {
switch (integration) {
case ConfigIntegrationKind.Custom:
case ConfigIntegrationKind.WordPress:
return { configuration: IntegrationConfigurationKind.JavaScript };
default:
return { configuration: IntegrationConfigurationKind.Dashboard };
}
}
public static getMergedConfig(userConfig: AppUserConfig, serverConfig: ServerAppConfig): AppConfig {
const configIntegrationKind = this.getConfigIntegrationKind(serverConfig);
const subdomain = this.getSubdomainForConfigIntegrationKind(configIntegrationKind, userConfig, serverConfig);
const allowLocalhostAsSecureOrigin = (
serverConfig.config.setupBehavior ?
serverConfig.config.setupBehavior.allowLocalhostAsSecureOrigin :
userConfig.allowLocalhostAsSecureOrigin
);
const isUsingSubscriptionWorkaround = OneSignalUtils.internalIsUsingSubscriptionWorkaround(
subdomain,
allowLocalhostAsSecureOrigin
);
const mergedUserConfig = this.getUserConfigForConfigIntegrationKind(
configIntegrationKind, userConfig, serverConfig, isUsingSubscriptionWorkaround);
return {
appId: serverConfig.app_id,
subdomain,
siteName: serverConfig.config.siteInfo.name,
origin: serverConfig.config.origin,
httpUseOneSignalCom: serverConfig.config.http_use_onesignal_com,
restrictedOriginEnabled: serverConfig.features.restrict_origin && serverConfig.features.restrict_origin.enable,
metrics: {
enable: serverConfig.features.metrics.enable,
mixpanelReportingToken: serverConfig.features.metrics.mixpanel_reporting_token
},
safariWebId: serverConfig.config.safari_web_id,
vapidPublicKey: serverConfig.config.vapid_public_key,
onesignalVapidPublicKey: serverConfig.config.onesignal_vapid_public_key,
userConfig: mergedUserConfig,
// default confirmed deliveries feature to off
receiveReceiptsEnable: serverConfig.features.receive_receipts_enable || false,
enableOnSession: Utils.valueOrDefault(
serverConfig.features.enable_on_session,
SERVER_CONFIG_DEFAULTS_SESSION.enableOnSessionForUnsubcribed
),
sessionThreshold: Utils.valueOrDefault(
serverConfig.features.session_threshold,
SERVER_CONFIG_DEFAULTS_SESSION.reportingThreshold
),
enableSessionDuration: Utils.valueOrDefault(
serverConfig.features.web_on_focus_enabled,
SERVER_CONFIG_DEFAULTS_SESSION.enableOnFocus
)
};
}
public static getConfigIntegrationKind(serverConfig: ServerAppConfig): ConfigIntegrationKind {
if (serverConfig.config.integration)
return serverConfig.config.integration.kind;
return ConfigIntegrationKind.Custom;
}
public static getCustomLinkConfig(serverConfig: ServerAppConfig): AppUserConfigCustomLinkOptions {
const initialState: AppUserConfigCustomLinkOptions = {
enabled: false,
style: "button",
size: "medium",
unsubscribeEnabled: false,
text: {
explanation: "",
subscribe: "",
unsubscribe: "",
},
color: {
button: "",
text: "",
}
};
if (!serverConfig || !serverConfig.config ||
!serverConfig.config.staticPrompts || !serverConfig.config.staticPrompts.customlink ||
!serverConfig.config.staticPrompts.customlink.enabled) {
return initialState;
}
const customlink = serverConfig.config.staticPrompts.customlink;
return {
enabled: customlink.enabled,
style: customlink.style,
size: customlink.size,
unsubscribeEnabled: customlink.unsubscribeEnabled,
text: customlink.text ? {
subscribe: customlink.text.subscribe,
unsubscribe: customlink.text.unsubscribe,
explanation: customlink.text.explanation,
} : initialState.text,
color: customlink.color ? {
button: customlink.color.button,
text: customlink.color.text,
} : initialState.color,
};
}
/**
* Used for Custom Code Integration Type
* @param {AppUserConfigPromptOptions|undefined} promptOptions
* @param {ServerAppPromptConfig} defaultsFromServer
* @param {AppUserConfig} wholeUserConfig
* @param {boolean=false} isUsingSubscriptionWorkaround
* @returns AppUserConfigPromptOptions
*/
public static injectDefaultsIntoPromptOptions(
promptOptions: AppUserConfigPromptOptions | undefined,
defaultsFromServer: ServerAppPromptConfig,
wholeUserConfig: AppUserConfig,
isUsingSubscriptionWorkaround: boolean = false,
): AppUserConfigPromptOptions | undefined {
let customlinkUser: AppUserConfigCustomLinkOptions = { enabled: false };
if (promptOptions && promptOptions.customlink) {
customlinkUser = promptOptions.customlink;
}
const customlinkDefaults = defaultsFromServer.customlink;
const promptOptionsConfig: AppUserConfigPromptOptions = {
...promptOptions,
customlink: {
enabled: Utils.getValueOrDefault(customlinkUser.enabled, customlinkDefaults.enabled),
style: Utils.getValueOrDefault(customlinkUser.style, customlinkDefaults.style),
size: Utils.getValueOrDefault(customlinkUser.size, customlinkDefaults.size),
unsubscribeEnabled: Utils.getValueOrDefault(customlinkUser.unsubscribeEnabled,
customlinkDefaults.unsubscribeEnabled),
text: {
subscribe: Utils.getValueOrDefault(customlinkUser.text ? customlinkUser.text.subscribe : undefined,
customlinkDefaults.text.subscribe),
unsubscribe: Utils.getValueOrDefault(customlinkUser.text ? customlinkUser.text.unsubscribe: undefined,
customlinkDefaults.text.unsubscribe),
explanation: Utils.getValueOrDefault(customlinkUser.text ? customlinkUser.text.explanation : undefined,
customlinkDefaults.text.explanation),
},
color: {
button: Utils.getValueOrDefault(customlinkUser.color ? customlinkUser.color.button : undefined,
customlinkDefaults.color.button),
text: Utils.getValueOrDefault(customlinkUser.color ? customlinkUser.color.text : undefined,
customlinkDefaults.color.text),
},
}
};
if (promptOptionsConfig.slidedown) {
promptOptionsConfig.slidedown.prompts = promptOptionsConfig.slidedown?.prompts?.map(promptOption => {
promptOption.type = Utils.getValueOrDefault(promptOption.type, DelayedPromptType.Push);
if (promptOption.type === DelayedPromptType.Category) {
promptOption.text = {
...promptOption.text,
positiveUpdateButton: Utils.getValueOrDefault(promptOption.text?.positiveUpdateButton,
SERVER_CONFIG_DEFAULTS_SLIDEDOWN.categoryDefaults.positiveUpdateButton),
negativeUpdateButton: Utils.getValueOrDefault(promptOption.text?.negativeUpdateButton,
SERVER_CONFIG_DEFAULTS_SLIDEDOWN.categoryDefaults.negativeUpdateButton),
updateMessage: Utils.getValueOrDefault(promptOption.text?.updateMessage,
SERVER_CONFIG_DEFAULTS_SLIDEDOWN.categoryDefaults.updateMessage),
};
}
promptOption.text = {
...promptOption.text,
actionMessage: Utils.getValueOrDefault(promptOption.text?.actionMessage,
SERVER_CONFIG_DEFAULTS_SLIDEDOWN.actionMessage),
acceptButton: Utils.getValueOrDefault(promptOption.text?.acceptButton,
SERVER_CONFIG_DEFAULTS_SLIDEDOWN.acceptButton),
cancelButton: Utils.getValueOrDefault(promptOption.text?.cancelButton,
SERVER_CONFIG_DEFAULTS_SLIDEDOWN.cancelButton),
confirmMessage: Utils.getValueOrDefault(promptOption.text?.confirmMessage,
SERVER_CONFIG_DEFAULTS_SLIDEDOWN.confirmMessage)
};
// default autoPrompt to true iff slidedown config exists but omitted the autoPrompt setting
promptOption.autoPrompt = Utils.getValueOrDefault(promptOption.autoPrompt, true);
promptOption.delay = {
pageViews: Utils.getValueOrDefault(promptOption.delay?.pageViews,
SERVER_CONFIG_DEFAULTS_PROMPT_DELAYS.pageViews),
timeDelay: Utils.getValueOrDefault(promptOption.delay?.timeDelay,
SERVER_CONFIG_DEFAULTS_PROMPT_DELAYS.timeDelay)
};
if (promptOption.categories) {
const { categories } = promptOption;
promptOption.categories = TagUtils.limitCategoriesToMaxCount(categories, MAX_CATEGORIES);
}
return promptOption;
});
} else {
promptOptionsConfig.slidedown = { prompts: [] };
promptOptionsConfig.slidedown.prompts = [ CONFIG_DEFAULTS_SLIDEDOWN_OPTIONS ];
}
if (promptOptionsConfig.native) {
promptOptionsConfig.native.enabled = !!promptOptionsConfig.native.enabled;
promptOptionsConfig.native.autoPrompt = promptOptionsConfig.native.hasOwnProperty("autoPrompt") ?
!!promptOptionsConfig.native.enabled && !!promptOptionsConfig.native.autoPrompt :
!!promptOptionsConfig.native.enabled;
promptOptionsConfig.native.pageViews = Utils.getValueOrDefault(promptOptionsConfig.native.pageViews,
SERVER_CONFIG_DEFAULTS_PROMPT_DELAYS.pageViews);
promptOptionsConfig.native.timeDelay = Utils.getValueOrDefault(promptOptionsConfig.native.timeDelay,
SERVER_CONFIG_DEFAULTS_PROMPT_DELAYS.timeDelay);
} else {
promptOptionsConfig.native = {
enabled: false,
autoPrompt: false,
pageViews: SERVER_CONFIG_DEFAULTS_PROMPT_DELAYS.pageViews,
timeDelay: SERVER_CONFIG_DEFAULTS_PROMPT_DELAYS.timeDelay
};
}
/**
* If autoRegister is true, show native prompt for https and slidedown for http ignoring any other related
* prompt options.
*/
if (wholeUserConfig.autoRegister === true) {
if (isUsingSubscriptionWorkaround) {
// disable native prompt
promptOptionsConfig.native.enabled = false;
promptOptionsConfig.native.autoPrompt = false;
// enable slidedown & make it autoPrompt
const text = {
actionMessage : SERVER_CONFIG_DEFAULTS_SLIDEDOWN.actionMessage,
acceptButton : SERVER_CONFIG_DEFAULTS_SLIDEDOWN.acceptButton,
cancelButton : SERVER_CONFIG_DEFAULTS_SLIDEDOWN.cancelButton,
};
promptOptionsConfig.slidedown.prompts = [{ type: DelayedPromptType.Push, autoPrompt: true, text }];
} else {
//enable native prompt & make it autoPrompt
promptOptionsConfig.native.enabled = true;
promptOptionsConfig.native.autoPrompt = true;
//leave slidedown settings without change
}
}
// sets top level `autoPrompt` to trigger autoprompt codepath in initialization / prompting flow
promptOptionsConfig.autoPrompt = promptOptionsConfig.native.autoPrompt ||
PromptsHelper.isSlidedownAutoPromptConfigured(promptOptionsConfig.slidedown.prompts);
return promptOptionsConfig;
}
/**
* Used only with Dashboard Configuration
* @param {ServerAppConfig} serverConfig
* @returns AppUserConfigPromptOptions
*/
private static getPromptOptionsForDashboardConfiguration(serverConfig: ServerAppConfig): AppUserConfigPromptOptions {
const staticPrompts = serverConfig.config.staticPrompts;
const native = staticPrompts.native ? {
enabled: staticPrompts.native.enabled,
autoPrompt: staticPrompts.native.enabled && staticPrompts.native.autoPrompt !== false,
pageViews: Utils.getValueOrDefault(staticPrompts.native.pageViews,
SERVER_CONFIG_DEFAULTS_PROMPT_DELAYS.pageViews),
timeDelay: Utils.getValueOrDefault(staticPrompts.native.timeDelay,
SERVER_CONFIG_DEFAULTS_PROMPT_DELAYS.timeDelay)
} : {
enabled: false,
autoPrompt: false,
pageViews: SERVER_CONFIG_DEFAULTS_PROMPT_DELAYS.pageViews,
timeDelay: SERVER_CONFIG_DEFAULTS_PROMPT_DELAYS.timeDelay
};
const { prompts } = staticPrompts.slidedown;
return {
autoPrompt: native.autoPrompt || PromptsHelper.isSlidedownAutoPromptConfigured(prompts),
native,
slidedown: {
prompts
},
fullscreen: {
enabled: staticPrompts.fullscreen.enabled,
actionMessage: staticPrompts.fullscreen.actionMessage,
acceptButton: staticPrompts.fullscreen.acceptButton,
cancelButton: staticPrompts.fullscreen.cancelButton,
title: staticPrompts.fullscreen.title,
message: staticPrompts.fullscreen.message,
caption: staticPrompts.fullscreen.caption,
autoAcceptTitle: staticPrompts.fullscreen.autoAcceptTitle,
},
customlink: this.getCustomLinkConfig(serverConfig),
};
}
public static getUserConfigForConfigIntegrationKind(
configIntegrationKind: ConfigIntegrationKind,
userConfig: AppUserConfig,
serverConfig: ServerAppConfig,
isUsingSubscriptionWorkaround: boolean = false,
): AppUserConfig {
const integrationCapabilities = this.getIntegrationCapabilities(configIntegrationKind);
switch (integrationCapabilities.configuration) {
case IntegrationConfigurationKind.Dashboard:
/*
Ignores code-based initialization configuration and uses dashboard configuration only.
*/
return {
appId: serverConfig.app_id,
autoRegister: false,
autoResubscribe: serverConfig.config.autoResubscribe,
path: serverConfig.config.serviceWorker.path,
serviceWorkerPath: serverConfig.config.serviceWorker.workerName,
serviceWorkerUpdaterPath: serverConfig.config.serviceWorker.updaterWorkerName,
serviceWorkerParam: { scope: serverConfig.config.serviceWorker.registrationScope },
subdomainName: serverConfig.config.siteInfo.proxyOrigin,
promptOptions: this.getPromptOptionsForDashboardConfiguration(serverConfig),
welcomeNotification: {
disable: !serverConfig.config.welcomeNotification.enable,
title: serverConfig.config.welcomeNotification.title,
message: serverConfig.config.welcomeNotification.message,
url: serverConfig.config.welcomeNotification.url
},
notifyButton: {
enable: serverConfig.config.staticPrompts.bell.enabled,
displayPredicate: serverConfig.config.staticPrompts.bell.hideWhenSubscribed ?
() => {
return OneSignal.isPushNotificationsEnabled()
.then((isPushEnabled: boolean) => {
/* The user is subscribed, so we want to return "false" to hide the notify button */
return !isPushEnabled;
});
} :
null,
size: serverConfig.config.staticPrompts.bell.size,
position: serverConfig.config.staticPrompts.bell.location,
showCredit: false,
offset: {
bottom: `${serverConfig.config.staticPrompts.bell.offset.bottom}px`,
left: `${serverConfig.config.staticPrompts.bell.offset.left}px`,
right: `${serverConfig.config.staticPrompts.bell.offset.right}px`
},
colors: {
'circle.background': serverConfig.config.staticPrompts.bell.color.main,
'circle.foreground': serverConfig.config.staticPrompts.bell.color.accent,
'badge.background': 'black',
'badge.foreground': 'white',
'badge.bordercolor': 'black',
'pulse.color': serverConfig.config.staticPrompts.bell.color.accent,
'dialog.button.background.hovering': serverConfig.config.staticPrompts.bell.color.main,
'dialog.button.background.active': serverConfig.config.staticPrompts.bell.color.main,
'dialog.button.background': serverConfig.config.staticPrompts.bell.color.main,
'dialog.button.foreground': 'white',
},
text: {
'tip.state.unsubscribed': serverConfig.config.staticPrompts.bell.tooltip.unsubscribed,
'tip.state.subscribed': serverConfig.config.staticPrompts.bell.tooltip.subscribed,
'tip.state.blocked': serverConfig.config.staticPrompts.bell.tooltip.blocked,
'message.prenotify': serverConfig.config.staticPrompts.bell.tooltip.unsubscribed,
'message.action.subscribing': serverConfig.config.staticPrompts.bell.message.subscribing,
'message.action.subscribed': serverConfig.config.staticPrompts.bell.message.subscribing,
'message.action.resubscribed': serverConfig.config.staticPrompts.bell.message.subscribing,
'message.action.unsubscribed': serverConfig.config.staticPrompts.bell.message.unsubscribing,
'dialog.main.title': serverConfig.config.staticPrompts.bell.dialog.main.title,
'dialog.main.button.subscribe': serverConfig.config.staticPrompts.bell.dialog.main.subscribeButton,
'dialog.main.button.unsubscribe': serverConfig.config.staticPrompts.bell.dialog.main.unsubscribeButton,
'dialog.blocked.title': serverConfig.config.staticPrompts.bell.dialog.blocked.title,
'dialog.blocked.message': serverConfig.config.staticPrompts.bell.dialog.blocked.message,
},
},
persistNotification: serverConfig.config.notificationBehavior ?
serverConfig.config.notificationBehavior.display.persist : undefined,
webhooks: {
cors: serverConfig.config.webhooks.corsEnable,
'notification.displayed': serverConfig.config.webhooks.notificationDisplayedHook,
'notification.clicked': serverConfig.config.webhooks.notificationClickedHook,
'notification.dismissed': serverConfig.config.webhooks.notificationDismissedHook,
},
notificationClickHandlerMatch: serverConfig.config.notificationBehavior ?
serverConfig.config.notificationBehavior.click.match : undefined,
notificationClickHandlerAction: serverConfig.config.notificationBehavior ?
serverConfig.config.notificationBehavior.click.action : undefined,
allowLocalhostAsSecureOrigin: serverConfig.config.setupBehavior ?
serverConfig.config.setupBehavior.allowLocalhostAsSecureOrigin : undefined,
requiresUserPrivacyConsent: userConfig.requiresUserPrivacyConsent,
outcomes: {
direct: serverConfig.config.outcomes.direct,
indirect: {
enabled: serverConfig.config.outcomes.indirect.enabled,
influencedTimePeriodMin:
serverConfig.config.outcomes.indirect.notification_attribution.minutes_since_displayed,
influencedNotificationsLimit: serverConfig.config.outcomes.indirect.notification_attribution.limit,
},
unattributed: serverConfig.config.outcomes.unattributed,
}
};
case IntegrationConfigurationKind.JavaScript:
/*
Ignores dashboard configuration and uses code-based configuration only.
Except injecting some default values for prompts.
*/
const isTopLevelServiceWorkerParamDefined = typeof OneSignal !== 'undefined' &&
!!OneSignal.SERVICE_WORKER_PARAM;
const isTopLevelServiceWorkerPathDefined = typeof OneSignal !== 'undefined' &&
!!OneSignal.SERVICE_WORKER_PATH;
const isTopLevelServiceWorkerUpdaterPathDefined = typeof OneSignal !== 'undefined' &&
!!OneSignal.SERVICE_WORKER_UPDATER_PATH;
const fallbackServiceWorkerParam = isTopLevelServiceWorkerParamDefined ?
OneSignal.SERVICE_WORKER_PARAM : { scope: '/' };
const fallbackServiceWorkerPath = isTopLevelServiceWorkerPathDefined ?
OneSignal.SERVICE_WORKER_PATH : 'OneSignalSDKWorker.js';
const fallbackServiceWorkerUpdaterPath = isTopLevelServiceWorkerUpdaterPathDefined ?
OneSignal.SERVICE_WORKER_UPDATER_PATH : 'OneSignalSDKUpdaterWorker.js';
const config = {
...userConfig,
promptOptions: this.injectDefaultsIntoPromptOptions(
userConfig.promptOptions,
serverConfig.config.staticPrompts,
userConfig,
isUsingSubscriptionWorkaround
),
...{
serviceWorkerParam: !!userConfig.serviceWorkerParam ?
userConfig.serviceWorkerParam : fallbackServiceWorkerParam,
serviceWorkerPath: !!userConfig.serviceWorkerPath ?
userConfig.serviceWorkerPath : fallbackServiceWorkerPath,
serviceWorkerUpdaterPath: !!userConfig.serviceWorkerUpdaterPath ?
userConfig.serviceWorkerUpdaterPath : fallbackServiceWorkerUpdaterPath,
path: !!userConfig.path ? userConfig.path : '/'
},
outcomes: {
direct: serverConfig.config.outcomes.direct,
indirect: {
enabled: serverConfig.config.outcomes.indirect.enabled,
influencedTimePeriodMin:
serverConfig.config.outcomes.indirect.notification_attribution.minutes_since_displayed,
influencedNotificationsLimit: serverConfig.config.outcomes.indirect.notification_attribution.limit,
},
unattributed: serverConfig.config.outcomes.unattributed,
}
};
if (userConfig.hasOwnProperty("autoResubscribe")) {
config.autoResubscribe = !!userConfig.autoResubscribe;
} else if (userConfig.hasOwnProperty("autoRegister")) {
config.autoResubscribe = !!userConfig.autoRegister;
} else {
config.autoResubscribe = !!serverConfig.config.autoResubscribe;
}
return config;
}
}
/**
* Describes how to merge a dashboard-set subdomain with a/lack of user-supplied subdomain.
*/
public static getSubdomainForConfigIntegrationKind(
configIntegrationKind: ConfigIntegrationKind,
userConfig: AppUserConfig,
serverConfig: ServerAppConfig
): string | undefined {
const integrationCapabilities = this.getIntegrationCapabilities(configIntegrationKind);
const userValue: string | undefined = userConfig.subdomainName;
let serverValue: string | undefined = '';
switch (integrationCapabilities.configuration) {
case IntegrationConfigurationKind.Dashboard:
serverValue = serverConfig.config.siteInfo.proxyOriginEnabled ?
serverConfig.config.siteInfo.proxyOrigin :
undefined;
break;
case IntegrationConfigurationKind.JavaScript:
serverValue = serverConfig.config.subdomain;
break;
}
if (serverValue && !this.shouldUseServerConfigSubdomain(userValue, integrationCapabilities)) {
return undefined;
} else {
return serverValue;
}
}
public static shouldUseServerConfigSubdomain(
userProvidedSubdomain: string | undefined,
capabilities: IntegrationCapabilities
): boolean {
switch (capabilities.configuration) {
case IntegrationConfigurationKind.Dashboard:
/*
Dashboard config using the new web config editor always takes precedence.
*/
return true;
case IntegrationConfigurationKind.JavaScript:
/*
* An HTTPS site may be using either a native push integration or a fallback
* subdomain integration. Our SDK decides the integration based on whether
* init option subdomainName appears and the site's protocol.
*
* To avoid having developers write JavaScript to customize the SDK,
* configuration properties like subdomainName are downloaded on page start.
*
* New developers setting up web push can omit subdomainName, but existing
* developers already having written code to configure OneSignal aren't
* removing their code.
*
* When an HTTPS site is configured with a subdomain on the server-side, we do
* not apply it even though we've downloaded this configuration unless the
* user also declares it manually in their initialization code.
*/
switch (location.protocol) {
case 'https:':
return !!userProvidedSubdomain;
case 'http:':
return true;
default:
return false;
}
}
}
} | the_stack |
import { $TSContext, JSONUtilities, pathManager } from 'amplify-cli-core';
import { DeploymentOp, DeploymentStep, DEPLOYMENT_META } from '../iterative-deployment';
import { DiffChanges, DiffableProject, getGQLDiff } from './utils';
import { DynamoDB, Template } from 'cloudform-types';
import { GSIChange, getGSIDiffs } from './gsi-diff-helpers';
import { GSIRecord, TemplateState, getPreviousDeploymentRecord, getTableNames } from '../utils/amplify-resource-state-utils';
import { ROOT_APPSYNC_S3_KEY, hashDirectory } from '../upload-appsync-files';
import { addGSI, getGSIDetails, removeGSI } from './dynamodb-gsi-helpers';
import {
cantAddAndRemoveGSIAtSameTimeRule,
cantBatchMutateGSIAtUpdateTimeRule,
cantEditGSIKeySchemaRule,
cantHaveMoreThan500ResourcesRule,
sanityCheckDiffs,
} from 'graphql-transformer-core';
import { CloudFormation } from 'aws-sdk';
import { Diff } from 'deep-diff';
import _ from 'lodash';
import { loadConfiguration } from '../configuration-manager';
import fs from 'fs-extra';
import path from 'path';
export type GQLResourceManagerProps = {
cfnClient: CloudFormation;
resourceMeta?: ResourceMeta;
backendDir: string;
cloudBackendDir: string;
rebuildAllTables?: boolean;
};
export type ResourceMeta = {
category: string;
providerPlugin: string;
resourceName: string;
service: string;
output: any;
providerMetadata: {
s3TemplateURL: string;
logicalId: string;
};
stackId: string;
DeploymentBucketName: string;
[key: string]: any;
};
// TODO: Add unit testing
export class GraphQLResourceManager {
static serviceName: string = 'AppSync';
static categoryName: string = 'api';
private cfnClient: CloudFormation;
private resourceMeta: ResourceMeta;
private cloudBackendApiProjectRoot: string;
private backendApiProjectRoot: string;
private templateState: TemplateState;
private rebuildAllTables: boolean = false; // indicates that all underlying model tables should be rebuilt
public static createInstance = async (context: $TSContext, gqlResource: any, StackId: string, rebuildAllTables: boolean = false) => {
try {
const cred = await loadConfiguration(context);
const cfn = new CloudFormation(cred);
const apiStack = await cfn
.describeStackResources({ StackName: StackId, LogicalResourceId: gqlResource.providerMetadata.logicalId })
.promise();
return new GraphQLResourceManager({
cfnClient: cfn,
resourceMeta: { ...gqlResource, stackId: apiStack.StackResources[0].PhysicalResourceId },
backendDir: pathManager.getBackendDirPath(),
cloudBackendDir: pathManager.getCurrentCloudBackendDirPath(),
rebuildAllTables,
});
} catch (err) {
throw err;
}
};
constructor(props: GQLResourceManagerProps) {
if (!props.resourceMeta) {
throw Error('No GraphQL API enabled.');
}
this.cfnClient = props.cfnClient;
this.resourceMeta = props.resourceMeta;
this.backendApiProjectRoot = path.join(props.backendDir, GraphQLResourceManager.categoryName, this.resourceMeta.resourceName);
this.cloudBackendApiProjectRoot = path.join(props.cloudBackendDir, GraphQLResourceManager.categoryName, this.resourceMeta.resourceName);
this.templateState = new TemplateState();
this.rebuildAllTables = props.rebuildAllTables || false;
}
run = async (): Promise<DeploymentStep[]> => {
const gqlDiff = getGQLDiff(this.backendApiProjectRoot, this.cloudBackendApiProjectRoot);
try {
const diffRules = [
// GSI
cantEditGSIKeySchemaRule,
cantBatchMutateGSIAtUpdateTimeRule,
cantAddAndRemoveGSIAtSameTimeRule,
];
const projectRules = [cantHaveMoreThan500ResourcesRule];
sanityCheckDiffs(gqlDiff.diff, gqlDiff.current, gqlDiff.next, diffRules, projectRules);
} catch (err) {
if (err.name !== 'InvalidGSIMigrationError') {
throw err;
}
}
if (!this.rebuildAllTables) {
this.gsiManagement(gqlDiff.diff, gqlDiff.current, gqlDiff.next);
}
this.tableRecreationManagement(gqlDiff.current, gqlDiff.next);
return await this.getDeploymentSteps();
};
// save states to build with a copy of build on every deploy
getDeploymentSteps = async (): Promise<DeploymentStep[]> => {
if (this.templateState.isEmpty()) return [];
let count = 1;
const gqlSteps = new Array<DeploymentStep>();
const cloudBuildDir = path.join(this.cloudBackendApiProjectRoot, 'build');
const stateFileDir = this.getStateFilesDirectory();
const tableNameMap = await getTableNames(this.cfnClient, this.templateState.getKeys(), this.resourceMeta.stackId);
const { parameters, capabilities } = await getPreviousDeploymentRecord(this.cfnClient, this.resourceMeta.stackId);
const buildHash = await hashDirectory(this.backendApiProjectRoot);
// copy the last deployment state as current state
let previousStepPath = cloudBuildDir;
let previousStep: DeploymentOp = await this.getCurrentlyDeployedStackStep();
let previousMetaKey = previousStep.previousMetaKey;
while (!this.templateState.isEmpty()) {
const stepNumber = count.toString().padStart(2, '0');
const stepPath = path.join(stateFileDir, stepNumber);
fs.copySync(previousStepPath, stepPath);
previousStepPath = stepPath;
const tables = this.templateState.getKeys();
const tableNames = [];
tables.forEach(tableName => {
tableNames.push(tableNameMap.get(tableName));
const tableNameStackFilePath = path.join(stepPath, 'stacks', `${tableName}.json`);
fs.ensureDirSync(path.dirname(tableNameStackFilePath));
JSONUtilities.writeJson(tableNameStackFilePath, this.templateState.pop(tableName));
});
const deploymentRootKey = `${ROOT_APPSYNC_S3_KEY}/${buildHash}/states/${stepNumber}`;
const deploymentStep: DeploymentOp = {
stackTemplatePathOrUrl: `${deploymentRootKey}/cloudformation-template.json`,
previousMetaKey: previousMetaKey,
parameters: { ...parameters, S3DeploymentRootKey: deploymentRootKey },
stackName: this.resourceMeta.stackId,
tableNames: tableNames,
capabilities,
// clientRequestToken: `${buildHash}-step-${stepNumber}`,
};
// save the current deployment step in the state
const deploymentStepStatePath = path.join(stepPath, DEPLOYMENT_META);
JSONUtilities.writeJson(deploymentStepStatePath, deploymentStep);
gqlSteps.push({
deployment: deploymentStep,
rollback: previousStep,
});
// Current deployment step is the rollback step for next step
previousStep = deploymentStep;
previousMetaKey = `${deploymentRootKey}/${DEPLOYMENT_META}`;
count++;
}
return gqlSteps;
};
/**
* get a copy of last deployed API nested stack to rollback to incase deployment fails
*/
public getCurrentlyDeployedStackStep = async (): Promise<DeploymentOp> => {
const cloudBuildDir = path.join(this.cloudBackendApiProjectRoot, 'build');
const stateFileDir = this.getStateFilesDirectory();
const { parameters, capabilities } = await getPreviousDeploymentRecord(this.cfnClient, this.resourceMeta.stackId);
const buildHash = await hashDirectory(this.backendApiProjectRoot);
const stepNumber = 'initial-stack';
const stepPath = path.join(stateFileDir, `${stepNumber}`);
fs.copySync(cloudBuildDir, stepPath);
const deploymentRootKey = `${ROOT_APPSYNC_S3_KEY}/${buildHash}/states/${stepNumber}`;
const currentDeployedStep: DeploymentOp = {
stackTemplatePathOrUrl: `${deploymentRootKey}/cloudformation-template.json`,
previousMetaKey: `${deploymentRootKey}/${DEPLOYMENT_META}`,
parameters: { ...parameters, S3DeploymentRootKey: deploymentRootKey },
stackName: this.resourceMeta.stackId,
capabilities,
tableNames: [],
};
// save the current deployment step in the state
const deploymentStateStep = path.join(stepPath, DEPLOYMENT_META);
JSONUtilities.writeJson(deploymentStateStep, currentDeployedStep);
return currentDeployedStep;
};
public getStateFilesDirectory = (): string => {
const buildDir = path.join(this.backendApiProjectRoot, 'build');
return path.join(buildDir, 'states');
};
public getCloudStateFilesDirectory = async (): Promise<string> => {
const buildHash = await hashDirectory(this.backendApiProjectRoot);
return `${ROOT_APPSYNC_S3_KEY}/${buildHash}/states`;
};
private gsiManagement = (diffs: DiffChanges<DiffableProject>, currentState: DiffableProject, nextState: DiffableProject) => {
const gsiChanges = _.filter(diffs, diff => {
return diff.path.includes('GlobalSecondaryIndexes');
});
const tableWithGSIChanges = _.uniqBy(gsiChanges, diff => diff.path?.slice(0, 3).join('/')).map(gsiChange => {
const tableName = gsiChange.path[3] as string;
const stackName = gsiChange.path[1].split('.')[0] as string;
const currentTable = this.getTable(gsiChange, currentState);
const nextTable = this.getTable(gsiChange, nextState);
return {
tableName,
stackName,
currentTable,
nextTable,
};
});
for (const gsiChange of tableWithGSIChanges) {
const changeSteps = getGSIDiffs(gsiChange.currentTable, gsiChange.nextTable);
const stackName = gsiChange.stackName;
const tableName = gsiChange.tableName;
for (const changeStep of changeSteps) {
const ddbResource = this.templateState.getLatest(stackName) || this.getStack(stackName, currentState);
let gsiRecord;
switch (changeStep.type) {
case GSIChange.Add:
gsiRecord = getGSIDetails(changeStep.indexName, gsiChange.nextTable);
this.addGSI(gsiRecord, tableName, ddbResource);
this.templateState.add(stackName, JSONUtilities.stringify(ddbResource));
break;
case GSIChange.Delete:
this.deleteGSI(changeStep.indexName, tableName, ddbResource);
this.templateState.add(stackName, JSONUtilities.stringify(ddbResource));
break;
case GSIChange.Update:
this.deleteGSI(changeStep.indexName, tableName, ddbResource);
this.templateState.add(stackName, JSONUtilities.stringify(ddbResource));
gsiRecord = getGSIDetails(changeStep.indexName, gsiChange.nextTable);
this.addGSI(gsiRecord, tableName, ddbResource);
this.templateState.add(stackName, JSONUtilities.stringify(ddbResource));
break;
default:
assertUnreachable(changeStep.type);
}
}
}
};
private tableRecreationManagement = (currentState: DiffableProject, nextState: DiffableProject) => {
this.getTablesBeingReplaced().forEach(tableMeta => {
const ddbStack = this.getStack(tableMeta.stackName, currentState);
this.dropTemplateResources(ddbStack);
// clear any other states created by GSI updates as dropping and recreating supercedes those changes
this.clearTemplateState(tableMeta.stackName);
this.templateState.add(tableMeta.stackName, JSONUtilities.stringify(ddbStack));
this.templateState.add(tableMeta.stackName, JSONUtilities.stringify(this.getStack(tableMeta.stackName, nextState)));
});
};
getTablesBeingReplaced = () => {
const gqlDiff = getGQLDiff(this.backendApiProjectRoot, this.cloudBackendApiProjectRoot);
const [diffs, currentState] = [gqlDiff.diff, gqlDiff.current];
const getTablesRequiringReplacement = () => {
if (!diffs) {
return [];
}
return _.uniq(
diffs
// diff.path looks like [ "stacks", "ModelName.json", "Resources", "TableName", "Properties", "KeySchema", 0, "AttributeName"]
.filter(
diff =>
(diff.kind === 'E' && diff.path.length === 8 && diff.path[5] === 'KeySchema') || diff.path.includes('LocalSecondaryIndexes'),
) // filter diffs with changes that require replacement
.map(diff => ({
// extract table name and stack name from diff path
tableName: diff.path?.[3] as string,
stackName: diff.path[1].split('.')[0] as string,
})),
) as { tableName: string; stackName: string }[];
};
const getAllTables = () =>
Object.entries(currentState.stacks)
.map(([name, template]) => ({
tableName: this.getTableNameFromTemplate(template),
stackName: path.basename(name, '.json'),
}))
.filter(meta => !!meta.tableName);
return this.rebuildAllTables ? getAllTables() : getTablesRequiringReplacement();
};
private getTable = (gsiChange: Diff<any, any>, proj: DiffableProject): DynamoDB.Table => {
return proj.stacks[gsiChange.path[1]].Resources[gsiChange.path[3]] as DynamoDB.Table;
};
private getStack(stackName: string, proj: DiffableProject): Template {
return proj.stacks[`${stackName}.json`];
}
private addGSI = (gsiRecord: GSIRecord, tableName: string, template: Template): void => {
const table = template.Resources[tableName] as DynamoDB.Table;
template.Resources[tableName] = addGSI(gsiRecord, table);
};
private deleteGSI = (indexName: string, tableName: string, template: Template): void => {
const table = template.Resources[tableName] as DynamoDB.Table;
template.Resources[tableName] = removeGSI(indexName, table);
};
private dropTemplateResources = (template: Template): void => {
// remove all resources from table stack except one placeholder resource
template.Resources = {};
// CloudFormation requires at least one resource so setting a placeholder
// https://stackoverflow.com/a/62991447/5283094
template.Resources.PlaceholderNullResource = { Type: 'AWS::CloudFormation::WaitConditionHandle' };
template.Outputs = {};
};
private clearTemplateState = (stackName: string) => {
while (this.templateState.has(stackName)) {
this.templateState.pop(stackName);
}
};
private getTableNameFromTemplate = (template: Template): string | undefined =>
Object.entries(template?.Resources || {}).find(([_, resource]) => resource.Type === 'AWS::DynamoDB::Table')?.[0];
}
// https://stackoverflow.com/questions/39419170/how-do-i-check-that-a-switch-block-is-exhaustive-in-typescript
export const assertUnreachable = (_: never): never => {
throw new Error('Default case should never reach');
}; | the_stack |
import {ElementRef, NgZone} from '@angular/core';
import {Platform, normalizePassiveListenerOptions} from '@angular/cdk/platform';
import {isFakeMousedownFromScreenReader, isFakeTouchstartFromScreenReader} from '@angular/cdk/a11y';
import {coerceElement} from '@angular/cdk/coercion';
import {RippleRef, RippleState, RippleConfig} from './ripple-ref';
/**
* Interface that describes the target for launching ripples.
* It defines the ripple configuration and disabled state for interaction ripples.
* @docs-private
*/
export interface RippleTarget {
/** Configuration for ripples that are launched on pointer down. */
rippleConfig: RippleConfig;
/** Whether ripples on pointer down should be disabled. */
rippleDisabled: boolean;
}
/** Interfaces the defines ripple element transition event listeners. */
interface RippleEventListeners {
onTransitionEnd: EventListener;
onTransitionCancel: EventListener;
}
// TODO: import these values from `@material/ripple` eventually.
/**
* Default ripple animation configuration for ripples without an explicit
* animation config specified.
*/
export const defaultRippleAnimationConfig = {
enterDuration: 225,
exitDuration: 150,
};
/**
* Timeout for ignoring mouse events. Mouse events will be temporary ignored after touch
* events to avoid synthetic mouse events.
*/
const ignoreMouseEventsTimeout = 800;
/** Options that apply to all the event listeners that are bound by the ripple renderer. */
const passiveEventOptions = normalizePassiveListenerOptions({passive: true});
/** Events that signal that the pointer is down. */
const pointerDownEvents = ['mousedown', 'touchstart'];
/** Events that signal that the pointer is up. */
const pointerUpEvents = ['mouseup', 'mouseleave', 'touchend', 'touchcancel'];
/**
* Helper service that performs DOM manipulations. Not intended to be used outside this module.
* The constructor takes a reference to the ripple directive's host element and a map of DOM
* event handlers to be installed on the element that triggers ripple animations.
* This will eventually become a custom renderer once Angular support exists.
* @docs-private
*/
export class RippleRenderer implements EventListenerObject {
/** Element where the ripples are being added to. */
private _containerElement: HTMLElement;
/** Element which triggers the ripple elements on mouse events. */
private _triggerElement: HTMLElement | null;
/** Whether the pointer is currently down or not. */
private _isPointerDown = false;
/**
* Map of currently active ripple references.
* The ripple reference is mapped to its element event listeners.
* The reason why `| null` is used is that event listeners are added only
* when the condition is truthy (see the `_startFadeOutTransition` method).
*/
private _activeRipples = new Map<RippleRef, RippleEventListeners | null>();
/** Latest non-persistent ripple that was triggered. */
private _mostRecentTransientRipple: RippleRef | null;
/** Time in milliseconds when the last touchstart event happened. */
private _lastTouchStartEvent: number;
/** Whether pointer-up event listeners have been registered. */
private _pointerUpEventsRegistered = false;
/**
* Cached dimensions of the ripple container. Set when the first
* ripple is shown and cleared once no more ripples are visible.
*/
private _containerRect: ClientRect | null;
constructor(
private _target: RippleTarget,
private _ngZone: NgZone,
elementOrElementRef: HTMLElement | ElementRef<HTMLElement>,
platform: Platform,
) {
// Only do anything if we're on the browser.
if (platform.isBrowser) {
this._containerElement = coerceElement(elementOrElementRef);
}
}
/**
* Fades in a ripple at the given coordinates.
* @param x Coordinate within the element, along the X axis at which to start the ripple.
* @param y Coordinate within the element, along the Y axis at which to start the ripple.
* @param config Extra ripple options.
*/
fadeInRipple(x: number, y: number, config: RippleConfig = {}): RippleRef {
const containerRect = (this._containerRect =
this._containerRect || this._containerElement.getBoundingClientRect());
const animationConfig = {...defaultRippleAnimationConfig, ...config.animation};
if (config.centered) {
x = containerRect.left + containerRect.width / 2;
y = containerRect.top + containerRect.height / 2;
}
const radius = config.radius || distanceToFurthestCorner(x, y, containerRect);
const offsetX = x - containerRect.left;
const offsetY = y - containerRect.top;
const enterDuration = animationConfig.enterDuration;
const ripple = document.createElement('div');
ripple.classList.add('mat-ripple-element');
ripple.style.left = `${offsetX - radius}px`;
ripple.style.top = `${offsetY - radius}px`;
ripple.style.height = `${radius * 2}px`;
ripple.style.width = `${radius * 2}px`;
// If a custom color has been specified, set it as inline style. If no color is
// set, the default color will be applied through the ripple theme styles.
if (config.color != null) {
ripple.style.backgroundColor = config.color;
}
ripple.style.transitionDuration = `${enterDuration}ms`;
this._containerElement.appendChild(ripple);
// By default the browser does not recalculate the styles of dynamically created
// ripple elements. This is critical to ensure that the `scale` animates properly.
// We enforce a style recalculation by calling `getComputedStyle` and *accessing* a property.
// See: https://gist.github.com/paulirish/5d52fb081b3570c81e3a
const computedStyles = window.getComputedStyle(ripple);
const userTransitionProperty = computedStyles.transitionProperty;
const userTransitionDuration = computedStyles.transitionDuration;
// Note: We detect whether animation is forcibly disabled through CSS by the use of
// `transition: none`. This is technically unexpected since animations are controlled
// through the animation config, but this exists for backwards compatibility. This logic does
// not need to be super accurate since it covers some edge cases which can be easily avoided by users.
const animationForciblyDisabledThroughCss =
userTransitionProperty === 'none' ||
// Note: The canonical unit for serialized CSS `<time>` properties is seconds. Additionally
// some browsers expand the duration for every property (in our case `opacity` and `transform`).
userTransitionDuration === '0s' ||
userTransitionDuration === '0s, 0s';
// Exposed reference to the ripple that will be returned.
const rippleRef = new RippleRef(this, ripple, config, animationForciblyDisabledThroughCss);
// Start the enter animation by setting the transform/scale to 100%. The animation will
// execute as part of this statement because we forced a style recalculation before.
// Note: We use a 3d transform here in order to avoid an issue in Safari where
// the ripples aren't clipped when inside the shadow DOM (see #24028).
ripple.style.transform = 'scale3d(1, 1, 1)';
rippleRef.state = RippleState.FADING_IN;
if (!config.persistent) {
this._mostRecentTransientRipple = rippleRef;
}
let eventListeners: RippleEventListeners | null = null;
// Do not register the `transition` event listener if fade-in and fade-out duration
// are set to zero. The events won't fire anyway and we can save resources here.
if (!animationForciblyDisabledThroughCss && (enterDuration || animationConfig.exitDuration)) {
this._ngZone.runOutsideAngular(() => {
const onTransitionEnd = () => this._finishRippleTransition(rippleRef);
const onTransitionCancel = () => this._destroyRipple(rippleRef);
ripple.addEventListener('transitionend', onTransitionEnd);
// If the transition is cancelled (e.g. due to DOM removal), we destroy the ripple
// directly as otherwise we would keep it part of the ripple container forever.
// https://www.w3.org/TR/css-transitions-1/#:~:text=no%20longer%20in%20the%20document.
ripple.addEventListener('transitioncancel', onTransitionCancel);
eventListeners = {onTransitionEnd, onTransitionCancel};
});
}
// Add the ripple reference to the list of all active ripples.
this._activeRipples.set(rippleRef, eventListeners);
// In case there is no fade-in transition duration, we need to manually call the transition
// end listener because `transitionend` doesn't fire if there is no transition.
if (animationForciblyDisabledThroughCss || !enterDuration) {
this._finishRippleTransition(rippleRef);
}
return rippleRef;
}
/** Fades out a ripple reference. */
fadeOutRipple(rippleRef: RippleRef) {
// For ripples already fading out or hidden, this should be a noop.
if (rippleRef.state === RippleState.FADING_OUT || rippleRef.state === RippleState.HIDDEN) {
return;
}
const rippleEl = rippleRef.element;
const animationConfig = {...defaultRippleAnimationConfig, ...rippleRef.config.animation};
// This starts the fade-out transition and will fire the transition end listener that
// removes the ripple element from the DOM.
rippleEl.style.transitionDuration = `${animationConfig.exitDuration}ms`;
rippleEl.style.opacity = '0';
rippleRef.state = RippleState.FADING_OUT;
// In case there is no fade-out transition duration, we need to manually call the
// transition end listener because `transitionend` doesn't fire if there is no transition.
if (rippleRef._animationForciblyDisabledThroughCss || !animationConfig.exitDuration) {
this._finishRippleTransition(rippleRef);
}
}
/** Fades out all currently active ripples. */
fadeOutAll() {
this._getActiveRipples().forEach(ripple => ripple.fadeOut());
}
/** Fades out all currently active non-persistent ripples. */
fadeOutAllNonPersistent() {
this._getActiveRipples().forEach(ripple => {
if (!ripple.config.persistent) {
ripple.fadeOut();
}
});
}
/** Sets up the trigger event listeners */
setupTriggerEvents(elementOrElementRef: HTMLElement | ElementRef<HTMLElement>) {
const element = coerceElement(elementOrElementRef);
if (!element || element === this._triggerElement) {
return;
}
// Remove all previously registered event listeners from the trigger element.
this._removeTriggerEvents();
this._triggerElement = element;
this._registerEvents(pointerDownEvents);
}
/**
* Handles all registered events.
* @docs-private
*/
handleEvent(event: Event) {
if (event.type === 'mousedown') {
this._onMousedown(event as MouseEvent);
} else if (event.type === 'touchstart') {
this._onTouchStart(event as TouchEvent);
} else {
this._onPointerUp();
}
// If pointer-up events haven't been registered yet, do so now.
// We do this on-demand in order to reduce the total number of event listeners
// registered by the ripples, which speeds up the rendering time for large UIs.
if (!this._pointerUpEventsRegistered) {
this._registerEvents(pointerUpEvents);
this._pointerUpEventsRegistered = true;
}
}
/** Method that will be called if the fade-in or fade-in transition completed. */
private _finishRippleTransition(rippleRef: RippleRef) {
if (rippleRef.state === RippleState.FADING_IN) {
this._startFadeOutTransition(rippleRef);
} else if (rippleRef.state === RippleState.FADING_OUT) {
this._destroyRipple(rippleRef);
}
}
/**
* Starts the fade-out transition of the given ripple if it's not persistent and the pointer
* is not held down anymore.
*/
private _startFadeOutTransition(rippleRef: RippleRef) {
const isMostRecentTransientRipple = rippleRef === this._mostRecentTransientRipple;
const {persistent} = rippleRef.config;
rippleRef.state = RippleState.VISIBLE;
// When the timer runs out while the user has kept their pointer down, we want to
// keep only the persistent ripples and the latest transient ripple. We do this,
// because we don't want stacked transient ripples to appear after their enter
// animation has finished.
if (!persistent && (!isMostRecentTransientRipple || !this._isPointerDown)) {
rippleRef.fadeOut();
}
}
/** Destroys the given ripple by removing it from the DOM and updating its state. */
private _destroyRipple(rippleRef: RippleRef) {
const eventListeners = this._activeRipples.get(rippleRef) ?? null;
this._activeRipples.delete(rippleRef);
// Clear out the cached bounding rect if we have no more ripples.
if (!this._activeRipples.size) {
this._containerRect = null;
}
// If the current ref is the most recent transient ripple, unset it
// avoid memory leaks.
if (rippleRef === this._mostRecentTransientRipple) {
this._mostRecentTransientRipple = null;
}
rippleRef.state = RippleState.HIDDEN;
if (eventListeners !== null) {
rippleRef.element.removeEventListener('transitionend', eventListeners.onTransitionEnd);
rippleRef.element.removeEventListener('transitioncancel', eventListeners.onTransitionCancel);
}
rippleRef.element.remove();
}
/** Function being called whenever the trigger is being pressed using mouse. */
private _onMousedown(event: MouseEvent) {
// Screen readers will fire fake mouse events for space/enter. Skip launching a
// ripple in this case for consistency with the non-screen-reader experience.
const isFakeMousedown = isFakeMousedownFromScreenReader(event);
const isSyntheticEvent =
this._lastTouchStartEvent &&
Date.now() < this._lastTouchStartEvent + ignoreMouseEventsTimeout;
if (!this._target.rippleDisabled && !isFakeMousedown && !isSyntheticEvent) {
this._isPointerDown = true;
this.fadeInRipple(event.clientX, event.clientY, this._target.rippleConfig);
}
}
/** Function being called whenever the trigger is being pressed using touch. */
private _onTouchStart(event: TouchEvent) {
if (!this._target.rippleDisabled && !isFakeTouchstartFromScreenReader(event)) {
// Some browsers fire mouse events after a `touchstart` event. Those synthetic mouse
// events will launch a second ripple if we don't ignore mouse events for a specific
// time after a touchstart event.
this._lastTouchStartEvent = Date.now();
this._isPointerDown = true;
// Use `changedTouches` so we skip any touches where the user put
// their finger down, but used another finger to tap the element again.
const touches = event.changedTouches;
for (let i = 0; i < touches.length; i++) {
this.fadeInRipple(touches[i].clientX, touches[i].clientY, this._target.rippleConfig);
}
}
}
/** Function being called whenever the trigger is being released. */
private _onPointerUp() {
if (!this._isPointerDown) {
return;
}
this._isPointerDown = false;
// Fade-out all ripples that are visible and not persistent.
this._getActiveRipples().forEach(ripple => {
// By default, only ripples that are completely visible will fade out on pointer release.
// If the `terminateOnPointerUp` option is set, ripples that still fade in will also fade out.
const isVisible =
ripple.state === RippleState.VISIBLE ||
(ripple.config.terminateOnPointerUp && ripple.state === RippleState.FADING_IN);
if (!ripple.config.persistent && isVisible) {
ripple.fadeOut();
}
});
}
/** Registers event listeners for a given list of events. */
private _registerEvents(eventTypes: string[]) {
this._ngZone.runOutsideAngular(() => {
eventTypes.forEach(type => {
this._triggerElement!.addEventListener(type, this, passiveEventOptions);
});
});
}
private _getActiveRipples(): RippleRef[] {
return Array.from(this._activeRipples.keys());
}
/** Removes previously registered event listeners from the trigger element. */
_removeTriggerEvents() {
if (this._triggerElement) {
pointerDownEvents.forEach(type => {
this._triggerElement!.removeEventListener(type, this, passiveEventOptions);
});
if (this._pointerUpEventsRegistered) {
pointerUpEvents.forEach(type => {
this._triggerElement!.removeEventListener(type, this, passiveEventOptions);
});
}
}
}
}
/**
* Returns the distance from the point (x, y) to the furthest corner of a rectangle.
*/
function distanceToFurthestCorner(x: number, y: number, rect: ClientRect) {
const distX = Math.max(Math.abs(x - rect.left), Math.abs(x - rect.right));
const distY = Math.max(Math.abs(y - rect.top), Math.abs(y - rect.bottom));
return Math.sqrt(distX * distX + distY * distY);
} | the_stack |
import { ITelemetryLogger, IEvent } from "@fluidframework/common-definitions";
import { assert, performance, Deferred, TypedEventEmitter } from "@fluidframework/common-utils";
import { DocumentDeltaConnection } from "@fluidframework/driver-base";
import { DriverError } from "@fluidframework/driver-definitions";
import { OdspError } from "@fluidframework/odsp-driver-definitions";
import { LoggingError } from "@fluidframework/telemetry-utils";
import {
IClient,
IConnect,
INack,
ISequencedDocumentMessage,
ISignalMessage,
} from "@fluidframework/protocol-definitions";
import { v4 as uuid } from "uuid";
import { IOdspSocketError, IGetOpsResponse, IFlushOpsResponse } from "./contracts";
import { EpochTracker } from "./epochTracker";
import { errorObjectFromSocketError } from "./odspError";
const protocolVersions = ["^0.4.0", "^0.3.0", "^0.2.0", "^0.1.0"];
const feature_get_ops = "api_get_ops";
const feature_flush_ops = "api_flush_ops";
export interface FlushResult {
lastPersistedSequenceNumber?: number;
retryAfter?: number;
}
// How long to wait before disconnecting the socket after the last reference is removed
// This allows reconnection after receiving a nack to be smooth
const socketReferenceBufferTime = 2000;
export interface ISocketEvents extends IEvent {
(event: "server_disconnect", listener: (error: LoggingError & OdspError) => void);
}
class SocketReference extends TypedEventEmitter<ISocketEvents> {
private references: number = 1;
private delayDeleteTimeout: ReturnType<typeof setTimeout> | undefined;
private _socket: SocketIOClient.Socket | undefined;
// When making decisions about socket reuse, we do not reuse disconnected socket.
// But we want to differentiate the following case from disconnected case:
// Socket that never connected and never failed, it's in "attempting to connect" mode
// such sockets should be reused, despite socket.disconnected === true
private isPendingInitialConnection = true;
// Map of all existing socket io sockets. [url, tenantId, documentId] -> socket
private static readonly socketIoSockets: Map<string, SocketReference> = new Map();
public static find(key: string, logger: ITelemetryLogger) {
const socketReference = SocketReference.socketIoSockets.get(key);
// Verify the socket is healthy before reusing it
if (socketReference && socketReference.disconnected) {
// The socket is in a bad state. fully remove the reference
socketReference.closeSocket();
return undefined;
}
if (socketReference) {
// Clear the pending deletion if there is one
socketReference.clearTimer();
socketReference.references++;
}
return socketReference;
}
/**
* Removes a reference for the given key
* Once the ref count hits 0, the socket is disconnected and removed
* @param key - socket reference key
* @param isFatalError - true if the socket reference should be removed immediately due to a fatal error
*/
public removeSocketIoReference(isFatalError: boolean) {
assert(this.references > 0, 0x09f /* "No more socketIO refs to remove!" */);
this.references--;
// see comment in disconnected() getter
this.isPendingInitialConnection = false;
if (isFatalError || this.disconnected) {
this.closeSocket();
return;
}
if (this.references === 0 && this.delayDeleteTimeout === undefined) {
this.delayDeleteTimeout = setTimeout(() => {
// We should not get here with active users.
assert(this.references === 0, 0x0a0 /* "Unexpected socketIO references on timeout" */);
this.closeSocket();
}, socketReferenceBufferTime);
}
}
public get socket() {
if (!this._socket) {
throw new Error(`Invalid socket for key "${this.key}`);
}
return this._socket;
}
public constructor(public readonly key: string, socket: SocketIOClient.Socket) {
super();
this._socket = socket;
assert(!SocketReference.socketIoSockets.has(key), 0x220 /* "socket key collision" */);
SocketReference.socketIoSockets.set(key, this);
// The server always closes the socket after sending this message
// fully remove the socket reference now
socket.on("server_disconnect", (socketError: IOdspSocketError) => {
// Treat all errors as recoverable, and rely on joinSession / reconnection flow to
// filter out retryable vs. non-retryable cases.
const error = errorObjectFromSocketError(socketError, "server_disconnect");
error.canRetry = true;
// see comment in disconnected() getter
// Setting it here to ensure socket reuse does not happen if new request to connect
// comes in from "disconnect" listener below, before we close socket.
this.isPendingInitialConnection = false;
this.emit("server_disconnect", error);
this.closeSocket();
});
}
private clearTimer() {
if (this.delayDeleteTimeout !== undefined) {
clearTimeout(this.delayDeleteTimeout);
this.delayDeleteTimeout = undefined;
}
}
private closeSocket() {
if (!this._socket) { return; }
this.clearTimer();
assert(SocketReference.socketIoSockets.get(this.key) === this,
0x0a1 /* "Socket reference set unexpectedly does not point to this socket!" */);
SocketReference.socketIoSockets.delete(this.key);
const socket = this._socket;
this._socket = undefined;
// Delay closing socket, to make sure all users of socket observe the same event that causes
// this instance to close, and thus properly record reason for closure.
// All event raising is synchronous, so clients will have a chance to react before socket is
// closed without any extra data on why it was closed.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
Promise.resolve().then(() => { socket.disconnect(); });
}
private get disconnected() {
if (this._socket === undefined) { return true; }
if (this.socket.connected) { return false; }
// We have a socket that is not connected. Possible cases:
// 1) It was connected some time ago and lost connection. We do not want to reuse it.
// 2) It failed to connect (was never connected).
// 3) It was just created and never had a chance to connect - connection is in process.
// We have to differentiate 1 from 2-3 (specifically 1 & 3) in order to be able to reuse socket in #3.
// We will use the fact that socket had some activity. I.e. if socket disconnected, or client stopped using
// socket, then removeSocketIoReference() will be called for it, and it will be the indiction that it's not #3.
return !this.isPendingInitialConnection;
}
}
/**
* Represents a connection to a stream of delta updates
*/
export class OdspDocumentDeltaConnection extends DocumentDeltaConnection {
/**
* Create a OdspDocumentDeltaConnection
* If url #1 fails to connect, will try url #2 if applicable.
*
* @param tenantId - the ID of the tenant
* @param documentId - document ID
* @param token - authorization token for storage service
* @param io - websocket library
* @param client - information about the client
* @param mode - mode of the client
* @param url - websocket URL
* @param telemetryLogger - optional telemetry logger
* @param timeoutMs - time limit on making the connection
* @param epochTracker - track epoch changes
* @param socketReferenceKeyPrefix - (optional) prefix to isolate socket reuse cache
*/
public static async create(
tenantId: string,
documentId: string,
token: string | null,
io: SocketIOClientStatic,
client: IClient,
url: string,
telemetryLogger: ITelemetryLogger,
timeoutMs: number,
epochTracker: EpochTracker,
socketReferenceKeyPrefix: string | undefined): Promise<OdspDocumentDeltaConnection> {
// enable multiplexing when the websocket url does not include the tenant/document id
const parsedUrl = new URL(url);
const enableMultiplexing = !parsedUrl.searchParams.has("documentId") && !parsedUrl.searchParams.has("tenantId");
// do not include the specific tenant/doc id in the ref key when multiplexing
// this will allow multiple documents to share the same websocket connection
const key = socketReferenceKeyPrefix ? `${socketReferenceKeyPrefix},${url}` : url;
const socketReferenceKey = enableMultiplexing ? key : `${key},${tenantId},${documentId}`;
const socketReference = OdspDocumentDeltaConnection.getOrCreateSocketIoReference(
io, timeoutMs, socketReferenceKey, url, enableMultiplexing, tenantId, documentId, telemetryLogger);
const socket = socketReference.socket;
const connectMessage: IConnect = {
client,
id: documentId,
mode: client.mode,
tenantId,
token, // Token is going to indicate tenant level information, etc...
versions: protocolVersions,
nonce: uuid(),
epoch: epochTracker.fluidEpoch,
};
// Reference to this client supporting get_ops flow.
// back-compat: remove cast to any once new definition of IConnect comes through.
(connectMessage as any).supportedFeatures = { [feature_get_ops]: true };
const deltaConnection = new OdspDocumentDeltaConnection(
socket,
documentId,
socketReference,
telemetryLogger,
enableMultiplexing);
try {
await deltaConnection.initialize(connectMessage, timeoutMs);
await epochTracker.validateEpochFromPush(deltaConnection.details);
} catch (errorObject) {
if (errorObject !== null && typeof errorObject === "object") {
// We have to special-case error types here in terms of what is re-triable.
// These errors have to re-retried, we just need new joinSession result to connect to right server:
// 400: Invalid tenant or document id. The WebSocket is connected to a different document
// Document is full (with retryAfter)
// 404: Invalid document. The document \"local/w1-...\" does not exist
// But this has to stay not-retriable:
// 406: Unsupported client protocol. This path is the only gatekeeper, have to fail!
// 409: Epoch Version Mismatch. Client epoch and server epoch does not match, so app needs
// to be refreshed.
// This one is fine either way
// 401/403: Code will retry once with new token either way, then it becomes fatal - on this path
// and on join Session path.
// 501: (Fluid not enabled): this is fine either way, as joinSession is gatekeeper
if (errorObject.statusCode === 400 || errorObject.statusCode === 404) {
errorObject.canRetry = true;
}
}
throw errorObject;
}
return deltaConnection;
}
private socketReference: SocketReference | undefined;
private readonly requestOpsNoncePrefix: string;
private pushCallCounter = 0;
private readonly getOpsMap: Map<string, { start: number, from: number, to: number }> = new Map();
private flushOpNonce: string | undefined;
private flushDeferred: Deferred<FlushResult> | undefined;
/**
* Error raising for socket.io issues
*/
protected createErrorObject(handler: string, error?: any, canRetry = true): DriverError {
// Note: we suspect the incoming error object is either:
// - a socketError: add it to the OdspError object for driver to be able to parse it and reason over it.
// - anything else: let base class handle it
if (canRetry && Number.isInteger(error?.code) && typeof error?.message === "string") {
return errorObjectFromSocketError(error as IOdspSocketError, handler) as DriverError;
} else {
return super.createErrorObject(handler, error, canRetry);
}
}
/**
* Gets or create a socket io connection for the given key
*/
private static getOrCreateSocketIoReference(
io: SocketIOClientStatic,
timeoutMs: number,
key: string,
url: string,
enableMultiplexing: boolean,
tenantId: string,
documentId: string,
logger: ITelemetryLogger,
): SocketReference {
const existingSocketReference = SocketReference.find(key, logger);
if (existingSocketReference) {
return existingSocketReference;
}
const query = enableMultiplexing ? undefined : { documentId, tenantId };
const socket = io(
url,
{
multiplex: false, // Don't rely on socket.io built-in multiplexing
query,
reconnection: false,
transports: ["websocket"],
timeout: timeoutMs,
});
return new SocketReference(key, socket);
}
/**
* @param socket - websocket to be used
* @param documentId - ID of the document
* @param details - details of the websocket connection
* @param socketReferenceKey - socket reference key
* @param enableMultiplexing - If the websocket is multiplexing multiple documents
*/
private constructor(
socket: SocketIOClient.Socket,
documentId: string,
socketReference: SocketReference,
logger: ITelemetryLogger,
private readonly enableMultiplexing?: boolean,
) {
super(socket, documentId, logger);
this.socketReference = socketReference;
this.requestOpsNoncePrefix = `${uuid()}-`;
}
/**
* Retrieves ops from PUSH
* @param from - inclusive
* @param to - exclusive
* @returns ops retrieved
*/
public requestOps(from: number, to: number) {
// Given that to is exclusive, we should be asking for at least something!
assert(to > from, 0x272 /* "empty request" */);
// PUSH may disable this functionality
// back-compat: remove cast to any once latest version of IConnected is consumed
if ((this.details as any).supportedFeatures?.[feature_get_ops] !== true) {
return;
}
this.pushCallCounter++;
const nonce = `${this.requestOpsNoncePrefix}${this.pushCallCounter}`;
const start = performance.now();
// We may keep keep accumulating memory for nothing, if we are not getting responses.
// Note that we should not have overlapping requests, as DeltaManager allows only one
// outstanding request to storage, and that's the only way to get here.
// But requests could be cancelled, and thus overlapping requests might be in the picture
// If it happens, we do not care about stale requests.
// So track some number of requests, but log if we get too many in flight - that likely
// indicates an error somewhere.
if (this.getOpsMap.size >= 5) {
let time = start;
let key: string | undefined;
for (const [keyCandidate, value] of this.getOpsMap.entries()) {
if (value.start <= time || key === undefined) {
time = value.start;
key = keyCandidate;
}
}
const payloadToDelete = this.getOpsMap.get(key!)!;
this.logger.sendErrorEvent({
eventName: "GetOpsTooMany",
from: payloadToDelete.from,
to: payloadToDelete.to,
length: payloadToDelete.to - payloadToDelete.from,
duration: performance.now() - payloadToDelete.start,
});
this.getOpsMap.delete(key!);
}
this.getOpsMap.set(
nonce,
{
start,
from,
to,
},
);
this.socket.emit("get_ops", this.clientId, {
nonce,
from,
to: to - 1,
});
}
public async flush(): Promise<FlushResult> {
// back-compat: remove cast to any once latest version of IConnected is consumed
if ((this.details as any).supportedFeatures?.[feature_flush_ops] !== true) {
// Once single-commit summary is enabled end-to-end, flush support is a must!
// The only alternative is change in design where SPO fetches ops from PUSH OR
// summary includes required ops and SPO has some validation mechanism to ensure
// they are not forged by client.
// If design changes, we can reconsider it, but right now it's non-recoverable failure.
this.logger.sendErrorEvent({ eventName: "FlushOpsNotSupported" });
throw new Error("flush() API is not supported by PUSH, required for single-commit summaries");
}
this.pushCallCounter++;
const nonce = `${this.requestOpsNoncePrefix}${this.pushCallCounter}`;
// There should be only one flush ops in flight, kicked out by upload summary workflow
// That said, it could timeout, and request could be repeated, so theoretically we can
// get overlapping requests, but it should be very rare
if (this.flushDeferred !== undefined) {
this.logger.sendErrorEvent({ eventName: "FlushOpsTooMany" });
this.flushDeferred.reject("process involving flush() was cancelled OR unsupported concurrency");
}
this.socket.emit("flush_ops", this.clientId, { nonce });
this.flushOpNonce = nonce;
this.flushDeferred = new Deferred<FlushResult>();
return this.flushDeferred.promise;
}
protected serverDisconnectHandler = (error: LoggingError & OdspError) => {
this.disposeCore(true, error);
};
protected async initialize(connectMessage: IConnect, timeout: number) {
if (this.enableMultiplexing) {
// multiplex compatible early handlers
this.earlyOpHandler = (messageDocumentId: string, msgs: ISequencedDocumentMessage[]) => {
if (this.documentId === messageDocumentId) {
this.queuedMessages.push(...msgs);
}
};
this.earlySignalHandler = (msg: ISignalMessage, messageDocumentId?: string) => {
if (messageDocumentId === undefined || messageDocumentId === this.documentId) {
this.queuedSignals.push(msg);
}
};
}
this.socketReference!.once("server_disconnect", this.serverDisconnectHandler);
this.socket.on("get_ops_response", (result: IGetOpsResponse) => {
const messages = result.messages;
const data = this.getOpsMap.get(result.nonce);
// Due to socket multiplexing, this client may not have asked for any data
// If so, there it most likely does not need these ops (otherwise it already asked for them)
if (data !== undefined) {
this.getOpsMap.delete(result.nonce);
const common = {
eventName: "GetOps",
code: result.code,
from: data.from,
to: data.to,
duration: performance.now() - data.start,
};
if (messages !== undefined && messages.length > 0) {
this.logger.sendPerformanceEvent({
...common,
first: messages[0].sequenceNumber,
last: messages[messages.length - 1].sequenceNumber,
length: messages.length,
});
this.emit("op", this.documentId, messages);
} else {
this.logger.sendPerformanceEvent({
...common,
length: 0,
});
}
}
});
this.socket.on("flush_ops_response", (result: IFlushOpsResponse) => {
if (this.flushOpNonce === result.nonce) {
const seq = result.lastPersistedSequenceNumber;
let category: "generic" | "error" = "generic";
if (result.lastPersistedSequenceNumber === undefined || result.code !== 200) {
switch (result.code) {
case 409:
case 429:
category = "error";
break;
case 204:
break;
default:
category = "error";
break;
}
}
this.logger.sendTelemetryEvent({
eventName: "FlushResult",
code: result.code,
sequenceNumber: seq,
category,
});
this.flushDeferred!.resolve(result);
this.flushDeferred = undefined;
this.flushOpNonce = undefined;
}
});
await super.initialize(connectMessage, timeout);
}
protected addTrackedListener(event: string, listener: (...args: any[]) => void) {
// override some event listeners in order to support multiple documents/clients over the same websocket
switch (event) {
case "op":
// per document op handling
super.addTrackedListener(event, (documentId: string, msgs: ISequencedDocumentMessage[]) => {
if (!this.enableMultiplexing || this.documentId === documentId) {
listener(documentId, msgs);
}
});
break;
case "signal":
// per document signal handling
super.addTrackedListener(event, (msg: ISignalMessage, documentId?: string) => {
if (!this.enableMultiplexing || !documentId || documentId === this.documentId) {
listener(msg, documentId);
}
});
break;
case "nack":
// per client / document nack handling
super.addTrackedListener(event, (clientIdOrDocumentId: string, message: INack[]) => {
if (clientIdOrDocumentId.length === 0 ||
clientIdOrDocumentId === this.documentId ||
(this.hasDetails && clientIdOrDocumentId === this.clientId)) {
this.emit("nack", clientIdOrDocumentId, message);
}
});
break;
default:
super.addTrackedListener(event, listener);
break;
}
}
/**
* Disconnect from the websocket
*/
protected disconnect(socketProtocolError: boolean, reason: any) {
const socket = this.socketReference;
assert(socket !== undefined, 0x0a2 /* "reentrancy not supported!" */);
this.socketReference = undefined;
this.socket.off("server_disconnect", this.serverDisconnectHandler);
if (!socketProtocolError && this.hasDetails) {
// tell the server we are disconnecting this client from the document
this.socket.emit("disconnect_document", this.clientId, this.documentId);
}
socket.removeSocketIoReference(socketProtocolError);
this.emit("disconnect", reason);
}
} | the_stack |
import {
ConnectionStatus,
DidChangeConnectionStatusNotificationType,
DidChangeDataNotificationType,
DidChangeDocumentMarkersNotificationType,
DidChangeVersionCompatibilityNotification,
DidChangeVersionCompatibilityNotificationType,
DidEncounterMaintenanceModeNotificationType,
GetDocumentFromMarkerRequestType,
ReportingMessageType,
ReportMessageRequestType,
SetServerUrlRequestType,
TraceLevel
} from "@codestream/protocols/agent";
import { CodemarkType } from "@codestream/protocols/api";
import {
ApplyMarkerRequest,
ApplyMarkerRequestType,
ApplyMarkerResponse,
BootstrapInHostRequestType,
BootstrapInHostResponse,
CompareMarkerRequest,
CompareMarkerRequestType,
CompareMarkerResponse,
EditorContext,
EditorHighlightRangeRequestType,
EditorHighlightRangeResponse,
EditorRevealRangeRequest,
EditorRevealRangeRequestType,
EditorRevealRangeResponse,
EditorScrollToNotification,
EditorScrollToNotificationType,
EditorSelectRangeRequest,
EditorSelectRangeRequestType,
EditorSelectRangeResponse,
GetActiveEditorContextRequestType,
GetActiveEditorContextResponse,
HostDidChangeActiveEditorNotification,
HostDidChangeActiveEditorNotificationType,
HostDidChangeConfigNotificationType,
HostDidChangeEditorSelectionNotificationType,
HostDidChangeEditorVisibleRangesNotificationType,
HostDidChangeFocusNotificationType,
HostDidLogoutNotificationType,
HostDidReceiveRequestNotificationType,
InsertTextRequest,
InsertTextRequestType,
InsertTextResponse,
isIpcRequestMessage,
LogoutRequestType,
LogoutResponse,
NewCodemarkNotificationType,
ReloadWebviewRequestType,
RestartRequestType,
ShellPromptFolderRequestType,
ShellPromptFolderResponse,
ShowCodemarkNotificationType,
ShowPullRequestNotificationType,
StartWorkNotificationType,
UpdateConfigurationRequest,
UpdateConfigurationRequestType,
UpdateConfigurationResponse,
UpdateServerUrlRequestType,
WebviewContext,
WebviewDidChangeContextNotificationType,
WebviewDidInitializeNotificationType,
WebviewIpcNotificationMessage,
WebviewIpcRequestMessage,
WebviewPanels,
OpenUrlRequestType,
OpenUrlRequest
} from "@codestream/protocols/webview";
import { CompositeDisposable, Disposable, Emitter, Point, Range, TextEditor } from "atom";
import { Convert } from "atom-languageclient";
import { remote, shell, WebviewTag } from "electron";
import * as fs from "fs-plus";
import { FileLogger } from "logger";
import { NotificationType } from "vscode-languageserver-protocol";
import { ConfigSchema } from "../configs";
import { asAbsolutePath, createTempFile, Debug, Echo, Editor } from "../utils";
import { Container } from "../workspace/container";
import { EditorObserver } from "../workspace/editor-observer";
import { SessionStatus, SignoutReason, WorkspaceSession } from "../workspace/workspace-session";
import { isViewVisible } from "./controller";
import { debounce } from "lodash-es";
export const CODESTREAM_VIEW_URI = "atom://codestream";
export const DID_CHANGE_STATE = "state-changed";
export const WILL_DESTROY = "will-destroy";
export class CodestreamView {
element: HTMLElement;
private session: WorkspaceSession;
private subscriptions: CompositeDisposable;
private webview: WebviewTag;
private emitter: Emitter;
private webviewContext: any;
private editorSelectionObserver?: EditorObserver;
private logger: FileLogger;
private timestamp = Date.now();
private webviewReadyEmitter = new Echo();
private _webviewInitialized = false;
private readonly _onEditorActiveEditorChangedDebounced: (e: TextEditor | undefined) => void;
private readonly _onSelectionChangedDebounced: (event: {
editor: TextEditor;
range: Range;
cursor: Point;
}) => void;
constructor(session: WorkspaceSession, webviewContext: any) {
this.session = session;
this.webviewContext = webviewContext;
this.logger = new FileLogger("webview");
this.emitter = new Emitter();
this.subscriptions = new CompositeDisposable(
this.logger,
this.emitter,
this.webviewReadyEmitter
);
this.element = document.createElement("div");
this.element.classList.add("codestream-view");
this.webview = document.createElement("webview");
this.webviewReadyEmitter.add(() => {
this._webviewInitialized = true;
this.initialize();
});
this._onEditorActiveEditorChangedDebounced = debounce(this._onEditorActiveEditorChanged, 500);
this._onSelectionChangedDebounced = debounce(this._onSelectionChanged, 250, { maxWait: 250 });
this.initializeWebview();
}
// update-able
getTitle() {
return "CodeStream";
}
// update-able
getIconName() {
return "comment-discussion";
}
getDefaultLocation() {
return "right";
}
getAllowedLocations() {
return ["right", "left"];
}
isPermanentDockItem() {
return false;
}
getPreferredWidth() {
return 300;
}
getURI() {
return CODESTREAM_VIEW_URI;
}
whenWebviewInitialized(cb: () => void) {
if (this._webviewInitialized) cb();
else this.webviewReadyEmitter.once(cb);
}
async show() {
await atom.workspace.open(this, { activatePane: true });
}
async showCodemark(codemarkId: string, sourceUri?: string) {
await this.show();
this.whenWebviewInitialized(() =>
this.sendNotification(ShowCodemarkNotificationType, { codemarkId, sourceUri })
);
}
async showPullRequest(providerId: string, id: string, commentId?: string) {
await this.show();
this.whenWebviewInitialized(() =>
this.sendNotification(ShowPullRequestNotificationType, { providerId, id, commentId })
);
}
private _htmlPath: string | undefined;
private async getWebviewSrc() {
if (!Debug.isDebugging() && this._htmlPath) return this._htmlPath;
return new Promise<string>((resolve, reject) => {
fs.readFile(asAbsolutePath("dist/webview/index.html"), "utf8", async (error, data) => {
if (error) return reject(error);
if (!this._htmlPath) {
const htmlPath = (this._htmlPath = await createTempFile("codestream-atom-webview.html"));
this.subscriptions.add(new Disposable(() => fs.remove(htmlPath, () => {})));
}
fs.writeFile(this._htmlPath, data.replace(/{{root}}/g, asAbsolutePath(".")), () =>
resolve(this._htmlPath)
);
});
});
}
private async initializeWebview() {
this.webview.src = await this.getWebviewSrc();
this.webview.preload = asAbsolutePath("dist/webview/preload.js");
this.webview.plugins = true;
this.webview.classList.add("codestream-webview", "native-key-bindings");
this.webview.addEventListener("dom-ready", async () => {
this.subscriptions.add(
atom.commands.add("atom-workspace", "codestream:open-webview-devtools", () =>
this.webview.openDevTools()
)
);
});
this.webview.addEventListener("ipc-message", async event => {
switch (event.channel) {
case "ready": {
this.webview.send("initialize", {
styles: await Container.styles.getStylesheets(),
isDebugging: Debug.isDebugging()
});
this.subscriptions.add(
Container.styles.onDidChange(styles => {
this.webview.send("did-change-styles", styles);
})
);
break;
}
case "did-keydown": {
this._handleKeydownEvent(event.args[0]);
break;
}
case "did-log": {
const { type, message, args } = event.args[0];
this.logger.log(type, message, JSON.stringify(args));
break;
}
case "did-click-link": {
const url = event.args[0];
shell.openExternal(url);
break;
}
case "codestream-ui": {
const data = event.args[0];
if (isIpcRequestMessage(data)) {
const target = data.method.split("/")[0];
if (target === "host") {
// @ts-ignore
requestIdleCallback(() => {
this.handleWebviewRequest(data)
.then(result => {
if (result) this.webview.send("codestream-ui", { id: data.id, ...result });
})
.catch(error => {
this.webview.send("codestream-ui", { id: data.id, error: error.message });
});
});
} else {
// @ts-ignore
requestIdleCallback(async () => {
this.forwardWebviewRequest(data)
.then(result => {
this.webview.send("codestream-ui", { id: data.id, ...result });
})
.catch(error => {
this.webview.send("codestream-ui", { id: data.id, error: error.message });
});
});
}
} else this.onWebviewNotification(data as WebviewIpcNotificationMessage);
break;
}
}
});
this.element.append(this.webview);
}
private _handleKeydownEvent(event: KeyboardEvent) {
if (["Alt", "Meta", "Control", "Shift", "CapsLock"].includes(event.key)) return;
if (event.shiftKey) {
if (event.metaKey && event.key === "z") {
this.webview.redo();
}
return;
}
if (event.metaKey) {
switch (event.key) {
case "a":
this.webview.selectAll();
break;
case "c":
this.webview.copy();
break;
case "v":
this.webview.paste();
break;
case "x":
this.webview.cut();
break;
case "z":
this.webview.undo();
break;
default:
}
}
const emulatedKeyboardEvent = new KeyboardEvent("keydown", event);
Object.defineProperty(emulatedKeyboardEvent, "target", {
get: () => this.webview
});
// not sure this is worth it
atom.keymaps.handleKeyboardEvent(emulatedKeyboardEvent);
}
private _observeWorkspace() {
this.editorSelectionObserver = new EditorObserver();
this.editorSelectionObserver.onDidChangeSelection(this._onSelectionChangedDebounced);
this.editorSelectionObserver.onDidChangeActiveEditor(
this._onEditorActiveEditorChangedDebounced
);
this.editorSelectionObserver.onDidChangeVisibleRanges(editor => {
this.sendNotification(HostDidChangeEditorVisibleRangesNotificationType, {
uri: Editor.getUri(editor),
selections: Editor.getCSSelections(editor),
visibleRanges: Editor.getVisibleRanges(editor),
lineCount: editor.getLineCount()
});
});
}
private initialize() {
const onBlur = () => {
if (isViewVisible(this.getURI())) {
this.sendNotification(HostDidChangeFocusNotificationType, { focused: false });
}
};
const onFocus = () => {
if (isViewVisible(this.getURI())) {
this.sendNotification(HostDidChangeFocusNotificationType, { focused: true });
}
};
const window = remote.getCurrentWindow();
window.on("focus", onFocus);
window.on("blur", onBlur);
if (this.session.isSignedIn) this._observeWorkspace();
this.subscriptions.add(
new Disposable(() => {
window.removeListener("blur", onBlur);
window.removeListener("focus", onFocus);
}),
this.session.agent.onDidChangeData(data =>
this.sendNotification(DidChangeDataNotificationType, data)
),
this.session.onDidChangeSessionStatus(change => {
if (change.current === SessionStatus.SignedIn) {
this._observeWorkspace();
}
if (
change.current === SessionStatus.SignedOut &&
change.signoutReason === SignoutReason.Extension
) {
this.sendNotification(HostDidLogoutNotificationType, {});
}
}),
this.session.agent.onDidChangeDocumentMarkers(e =>
this.sendNotification(DidChangeDocumentMarkersNotificationType, e)
),
Container.configs.onDidChangeWebviewConfig(changes =>
this.sendNotification(HostDidChangeConfigNotificationType, changes)
),
this.session.agent.onDidChangeConnectionStatus(e => {
switch (e.status) {
case ConnectionStatus.Disconnected: {
break;
}
case ConnectionStatus.Reconnecting: {
this.sendNotification(DidChangeConnectionStatusNotificationType, e);
break;
}
case ConnectionStatus.Reconnected: {
if (e.reset) {
this.destroy();
// atom.workspace.paneForURI(CODESTREAM_VIEW_URI)!.destroy();
atom.workspace.open(CODESTREAM_VIEW_URI);
break;
}
this.sendNotification(DidChangeConnectionStatusNotificationType, e);
break;
}
}
}),
this.session.agent.onDidEncounterMaintenanceMode(e => {
this.sendNotification(DidEncounterMaintenanceModeNotificationType, e);
})
);
}
changeVersionCompatibility(e: DidChangeVersionCompatibilityNotification) {
atom.workspace.open(CODESTREAM_VIEW_URI);
this.sendNotification(DidChangeVersionCompatibilityNotificationType, e);
}
serialize() {
return {
deserializer: "codestream/CodestreamView"
};
}
destroy() {
Container.markerDecorationProvider.enable();
this.emitter.emit(WILL_DESTROY);
this.element.remove();
this.editorSelectionObserver && this.editorSelectionObserver.dispose();
this.subscriptions.dispose();
}
onWillDestroy(cb: () => void) {
return this.emitter.on(WILL_DESTROY, cb);
}
onDidChangeState(cb: (state: WebviewContext) => void) {
return this.emitter.on(DID_CHANGE_STATE, cb);
}
checkToToggleMarkers() {
if (!this.webviewContext || !Container.session.isSignedIn) return;
const configs = Container.configs;
if (configs.get("showMarkers") === true && configs.get("autoHideMarkers") === true) {
if (this.webviewContext.panelStack[0] === WebviewPanels.CodemarksForFile) {
if (isViewVisible(this.getURI())) {
Container.markerDecorationProvider.disable();
} else Container.markerDecorationProvider.enable();
} else Container.markerDecorationProvider.enable();
}
}
private getActiveEditorContext(): EditorContext {
const editor = atom.workspace.getActiveTextEditor();
if (editor) {
const uri = Editor.getUri(editor);
return {
activeFile: Editor.getRelativePath(editor),
textEditorUri: uri,
textEditorVisibleRanges: Editor.getVisibleRanges(editor),
textEditorSelections: Editor.getCSSelections(editor),
textEditorLineCount: editor.getLineCount()
};
}
return {};
}
private async forwardWebviewRequest(request: { id: string; method: string; params?: any }) {
const response = await this.session.agent.sendRequest(request.method, request.params);
return { params: response };
}
private async handleWebviewRequest(
message: WebviewIpcRequestMessage
): Promise<{ params: any } | { error: any } | void> {
switch (message.method) {
case BootstrapInHostRequestType.method: {
try {
// TODO: is this still necessary?
await this.session.ready;
const response: BootstrapInHostResponse = {
...this.session.getBootstrapInfo(),
context: this.webviewContext || {
currentTeamId: this.session.isSignedIn ? this.session.teamId : undefined
}
};
return { params: response };
} catch (error) {
return { error: error.message };
}
}
case ShellPromptFolderRequestType.method: {
const result = await remote.dialog.showOpenDialog({
title: message.params.message,
properties: ["openDirectory"]
});
const response: ShellPromptFolderResponse = {
path: result.filePaths && result.filePaths.length ? result.filePaths[0] : undefined
};
return { params: response };
}
case GetActiveEditorContextRequestType.method: {
return {
params: {
editorContext: this.getActiveEditorContext()
} as GetActiveEditorContextResponse
};
}
case UpdateConfigurationRequestType.method: {
const { name, value }: UpdateConfigurationRequest = message.params;
if (Container.configs.isUserSetting(name)) {
Container.configs.set(name as keyof ConfigSchema, value);
}
this.sendNotification(HostDidChangeConfigNotificationType, { [name]: value });
return { params: {} as UpdateConfigurationResponse };
}
case UpdateServerUrlRequestType.method: {
const { serverUrl, disableStrictSSL } = message.params;
await Container.configs.set("serverUrl", serverUrl);
await Container.configs.set("disableStrictSSL", disableStrictSSL);
await this.session.agent.sendRequest(SetServerUrlRequestType.method, {
serverUrl,
disableStrictSSL
});
return { params: {} };
}
case EditorHighlightRangeRequestType.method: {
const { uri, highlight, range } = message.params;
const success = await Container.editorManipulator.highlight(
highlight,
Convert.uriToPath(uri),
Convert.lsRangeToAtomRange(range)
);
return { params: { success } as EditorHighlightRangeResponse };
}
case EditorSelectRangeRequestType.method: {
const { selection, uri, preserveFocus }: EditorSelectRangeRequest = message.params;
try {
await Container.editorManipulator.select(
Convert.uriToPath(uri),
Convert.lsRangeToAtomRange(selection)
);
if (preserveFocus) {
atom.views.getView(this).focus();
this.webview.focus();
}
return { params: { success: true } as EditorSelectRangeResponse };
} catch (error) {
this.session.agent.request(ReportMessageRequestType, {
message: "Could not select range in buffer",
type: ReportingMessageType.Error,
source: "extension",
extra: error
});
return { params: { success: false } as EditorSelectRangeResponse };
}
}
case EditorRevealRangeRequestType.method: {
const { uri, range } = message.params as EditorRevealRangeRequest;
const success = atom.workspace.getTextEditors().some(editor => {
if (editor.getPath() === Convert.uriToPath(uri)) {
// TODO: compute the scroll position that will make `range.start.row` the first visible line
editor.scrollToBufferPosition(Convert.lsRangeToAtomRange(range).start);
return true;
}
return false;
});
return { params: { success } as EditorRevealRangeResponse };
}
case CompareMarkerRequestType.method: {
const { marker }: CompareMarkerRequest = message.params;
await Container.diffController.showDiff(marker);
return { params: {} as CompareMarkerResponse };
}
case ApplyMarkerRequestType.method: {
const { marker }: ApplyMarkerRequest = message.params;
await Container.diffController.applyPatch(marker);
return { params: {} as ApplyMarkerResponse };
}
case LogoutRequestType.method: {
await this.session.signOut(SignoutReason.User);
return { params: {} as LogoutResponse };
}
case ReloadWebviewRequestType.method: {
// TODO: technically, just the iframe could be replaced
Container.viewController.reload(this.getURI());
return;
}
case RestartRequestType.method: {
await this.session.signOut(SignoutReason.User);
Container.viewController.reload(this.getURI());
return;
}
case InsertTextRequestType.method: {
const { text, marker } = message.params as InsertTextRequest;
let response: InsertTextResponse = false;
const documentMarkerInfo = await Container.session.agent.request(
GetDocumentFromMarkerRequestType,
{
markerId: marker.id
}
);
if (documentMarkerInfo) {
const editor = await Container.editorManipulator.open(
Convert.uriToPath(documentMarkerInfo.textDocument.uri)
);
if (editor) {
const bufferRange = Convert.lsRangeToAtomRange(documentMarkerInfo.range);
editor.setTextInBufferRange(
[[bufferRange.start.row, 0], [bufferRange.start.row, 0]],
text
);
response = true;
}
}
return { params: response as InsertTextResponse };
}
case OpenUrlRequestType.method: {
shell.openExternal((message.params as OpenUrlRequest).url);
return {} as any;
}
default: {
if (Debug.isDebugging()) {
atom.notifications.addWarning(`Unhandled webview message: ${message.method}`);
if (atom.inDevMode() && Container.configs.get("traceLevel") === TraceLevel.Debug) {
atom.notifications.addWarning(`Unhandled webview request: ${message.method}`);
}
} else if (Container.session.isSignedIn) {
Container.session.agent.request(ReportMessageRequestType, {
type: ReportingMessageType.Warning,
message: `Unhandled request from webview: ${message.method}`,
source: "extension"
});
}
return { error: "No handler found" };
}
}
}
private onWebviewNotification(event: WebviewIpcNotificationMessage) {
switch (event.method) {
case WebviewDidInitializeNotificationType.method: {
if (Debug.isDebugging()) {
console.debug(
`CodeStream view created and interactive in ${Date.now() - this.timestamp} `
);
}
this.webviewReadyEmitter.push();
break;
}
case WebviewDidChangeContextNotificationType.method: {
this.webviewContext = event.params.context;
this.emitter.emit(DID_CHANGE_STATE, event.params.context);
this.checkToToggleMarkers();
break;
}
case EditorScrollToNotificationType.method: {
const { atTop, uri, position, deltaPixels }: EditorScrollToNotification = event.params;
const editor = atom.workspace.getTextEditors().find(e => Editor.getUri(e) === uri);
if (!editor) return;
if (atTop) {
editor.setScrollTopRow(editor.screenRowForBufferRow(position.line));
} else {
editor.element.setScrollTop(editor.element.getScrollTop() + deltaPixels!);
}
break;
}
default: {
Container.session.agent.request(ReportMessageRequestType, {
type: ReportingMessageType.Warning,
message: `Unhandled notification from webview: ${event.method}`,
source: "extension"
});
if (atom.inDevMode() && Container.configs.get("traceLevel") === TraceLevel.Debug) {
atom.notifications.addWarning(`Unhandled webview notification: ${event.method}`);
}
}
}
}
sendNotification<ET extends NotificationType<any, any>>(
eventType: ET,
params: ET extends NotificationType<infer P, any> ? P : never
) {
this.webview.send("codestream-ui", { method: eventType.method, params });
}
newCodemarkRequest(type: CodemarkType, source?: string) {
const editor = atom.workspace.getActiveTextEditor();
if (editor === undefined) return;
const uri = Editor.getUri(editor);
const range = Editor.getCurrentSelectionRange(editor);
this.sendNotification(NewCodemarkNotificationType, { type, uri, range, source });
editor.setSelectedBufferRange(Convert.lsRangeToAtomRange(range));
}
startWorkRequest(source?: string) {
const editor = atom.workspace.getActiveTextEditor();
let uri;
if (editor) {
uri = Editor.getUri(editor);
}
this.sendNotification(StartWorkNotificationType, { source, uri });
}
handleProtocolRequest(uri: string) {
this.sendNotification(HostDidReceiveRequestNotificationType, { url: uri });
}
private _onSelectionChanged = (event: { editor: TextEditor; range: Range; cursor: Point }) => {
this.sendNotification(HostDidChangeEditorSelectionNotificationType, {
uri: Editor.getUri(event.editor),
selections: Editor.getCSSelections(event.editor),
visibleRanges: Editor.getVisibleRanges(event.editor),
lineCount: event.editor.getLineCount()
});
};
private _onEditorActiveEditorChanged = (editor?: TextEditor) => {
const notification: HostDidChangeActiveEditorNotification = {};
const fileName = editor && Editor.getRelativePath(editor);
if (editor) {
notification.editor = {
fileName: fileName || "",
uri: Editor.getUri(editor),
visibleRanges: Editor.getVisibleRanges(editor),
selections: Editor.getCSSelections(editor),
metrics: {
lineHeight: editor.getLineHeightInPixels(),
fontSize: atom.config.get("editor.fontSize")
},
lineCount: editor.getLineCount()
};
}
this.sendNotification(HostDidChangeActiveEditorNotificationType, notification);
};
} | the_stack |
import React, { Component } from "react";
import { RouteComponentProps, withRouter } from "react-router";
import styled from "styled-components";
import api from "shared/api";
import { H } from "highlight.run";
import { Context } from "shared/Context";
import { PorterUrl, pushFiltered, pushQueryParams } from "shared/routing";
import { ClusterType, ProjectType } from "shared/types";
import ConfirmOverlay from "components/ConfirmOverlay";
import Loading from "components/Loading";
import ClusterDashboard from "./cluster-dashboard/ClusterDashboard";
import Dashboard from "./dashboard/Dashboard";
import WelcomeForm from "./WelcomeForm";
import Integrations from "./integrations/Integrations";
import Templates from "./launch/Launch";
import ClusterInstructionsModal from "./modals/ClusterInstructionsModal";
import IntegrationsInstructionsModal from "./modals/IntegrationsInstructionsModal";
import IntegrationsModal from "./modals/IntegrationsModal";
import Modal from "./modals/Modal";
import UpdateClusterModal from "./modals/UpdateClusterModal";
import NamespaceModal from "./modals/NamespaceModal";
import Navbar from "./navbar/Navbar";
import NewProject from "./new-project/NewProject";
import ProjectSettings from "./project-settings/ProjectSettings";
import Sidebar from "./sidebar/Sidebar";
import PageNotFound from "components/PageNotFound";
import DeleteNamespaceModal from "./modals/DeleteNamespaceModal";
import { fakeGuardedRoute } from "shared/auth/RouteGuard";
import { withAuth, WithAuthProps } from "shared/auth/AuthorizationHoc";
import EditInviteOrCollaboratorModal from "./modals/EditInviteOrCollaboratorModal";
import AccountSettingsModal from "./modals/AccountSettingsModal";
import discordLogo from "../../assets/discord.svg";
import UsageWarningModal from "./modals/UsageWarningModal";
// Guarded components
const GuardedProjectSettings = fakeGuardedRoute("settings", "", [
"get",
"list",
"update",
"create",
"delete",
])(ProjectSettings);
const GuardedIntegrations = fakeGuardedRoute("integrations", "", [
"get",
"list",
"update",
"create",
"delete",
])(Integrations);
type PropsType = RouteComponentProps &
WithAuthProps & {
logOut: () => void;
currentProject: ProjectType;
currentCluster: ClusterType;
currentRoute: PorterUrl;
};
type StateType = {
forceSidebar: boolean;
showWelcome: boolean;
handleDO: boolean; // Trigger DO infra calls after oauth flow if needed
ghRedirect: boolean;
forceRefreshClusters: boolean; // For updating ClusterSection from modal on deletion
// Track last project id for refreshing clusters on project change
prevProjectId: number | null;
showWelcomeForm: boolean;
};
// TODO: Handle cluster connected but with some failed infras (no successful set)
// TODO: Set up current view / sidebar tab as dynamic Routes
class Home extends Component<PropsType, StateType> {
state = {
forceSidebar: true,
showWelcome: false,
prevProjectId: null as number | null,
forceRefreshClusters: false,
sidebarReady: false,
handleDO: false,
ghRedirect: false,
showWelcomeForm: true,
};
// TODO: Refactor and prevent flash + multiple reload
initializeView = () => {
let { currentProject } = this.props;
if (!currentProject) return;
api
.getInfra(
"<token>",
{},
{
project_id: currentProject.id,
}
)
.then((res) => {
let creating = false;
for (var i = 0; i < res.data.length; i++) {
creating = res.data[i].status === "creating";
}
if (creating) {
pushFiltered(this.props, "/dashboard", ["project_id"], {
tab: "provisioner",
});
} else if (this.state.ghRedirect) {
pushFiltered(this.props, "/integrations", ["project_id"]);
this.setState({ ghRedirect: false });
}
});
};
getMetadata = () => {
api
.getMetadata("<token>", {}, {})
.then((res) => {
this.context.setCapabilities(res.data);
})
.catch((err) => {
console.log(err);
});
};
getProjects = (id?: number) => {
let { user, setProjects, setCurrentProject } = this.context;
let { currentProject } = this.props;
let queryString = window.location.search;
let urlParams = new URLSearchParams(queryString);
let projectId = urlParams.get("project_id");
if (!projectId && currentProject?.id) {
pushQueryParams(this.props, { project_id: currentProject.id.toString() });
}
api
.getProjects("<token>", {}, { id: user.userId })
.then((res) => {
if (res.data) {
if (res.data.length === 0) {
pushFiltered(this.props, "/new-project", ["project_id"]);
} else if (res.data.length > 0 && !currentProject) {
setProjects(res.data);
let foundProject = null;
if (id) {
res.data.forEach((project: ProjectType, i: number) => {
if (project.id === id) {
foundProject = project;
}
});
setCurrentProject(foundProject || res.data[0]);
}
if (!foundProject) {
res.data.forEach((project: ProjectType, i: number) => {
if (
project.id.toString() ===
localStorage.getItem("currentProject")
) {
foundProject = project;
}
});
setCurrentProject(foundProject || res.data[0], () =>
this.initializeView()
);
}
}
}
})
.catch(console.log);
};
provisionDOCR = async (
integrationId: number,
tier: string,
callback?: any
) => {
console.log("Provisioning DOCR...");
await api.createDOCR(
"<token>",
{
do_integration_id: integrationId,
docr_name: this.props.currentProject.name,
docr_subscription_tier: tier,
},
{
project_id: this.props.currentProject.id,
}
);
return callback();
};
provisionDOKS = async (
integrationId: number,
region: string,
clusterName: string
) => {
console.log("Provisioning DOKS...");
await api.createDOKS(
"<token>",
{
do_integration_id: integrationId,
doks_name: clusterName,
do_region: region,
},
{
project_id: this.props.currentProject.id,
}
);
return pushFiltered(this.props, "/dashboard", ["project_id"], {
tab: "provisioner",
});
};
checkDO = () => {
let { currentProject } = this.props;
if (this.state.handleDO && currentProject?.id) {
api
.getOAuthIds(
"<token>",
{},
{
project_id: currentProject.id,
}
)
.then((res) => {
let tgtIntegration = res.data.find((integration: any) => {
return integration.client === "do";
});
let queryString = window.location.search;
let urlParams = new URLSearchParams(queryString);
let tier = urlParams.get("tier");
let region = urlParams.get("region");
let clusterName = urlParams.get("cluster_name");
let infras = urlParams.getAll("infras");
if (infras.length === 2) {
this.provisionDOCR(tgtIntegration.id, tier, () => {
this.provisionDOKS(tgtIntegration.id, region, clusterName);
});
} else if (infras[0] === "docr") {
this.provisionDOCR(tgtIntegration.id, tier, () => {
pushFiltered(this.props, "/dashboard", ["project_id"], {
tab: "provisioner",
});
});
} else {
this.provisionDOKS(tgtIntegration.id, region, clusterName);
}
})
.catch(console.log);
this.setState({ handleDO: false });
}
};
componentDidMount() {
let { match } = this.props;
let params = match.params as any;
let { cluster } = params;
let { user } = this.context;
// Initialize Highlight
if (
window.location.href.includes("dashboard.getporter.dev") &&
!user.email.includes("@getporter.dev")
) {
H.init("y2d13lgr");
H.identify(user.email, { id: user.id });
}
// Handle redirect from DO
let queryString = window.location.search;
let urlParams = new URLSearchParams(queryString);
let err = urlParams.get("error");
if (err) {
this.context.setCurrentError(err);
}
let provision = urlParams.get("provision");
let defaultProjectId = parseInt(urlParams.get("project_id"));
if (provision === "do") {
this.setState({ handleDO: true });
this.checkDO();
}
this.setState({ ghRedirect: urlParams.get("gh_oauth") !== null });
urlParams.delete("gh_oauth");
this.getProjects(defaultProjectId);
this.getMetadata();
}
async checkIfProjectHasBilling(projectId: number) {
if (!projectId) {
return false;
}
try {
const res = await api.getHasBilling(
"<token>",
{},
{ project_id: projectId }
);
this.context.setHasBillingEnabled(res.data?.has_billing);
return res?.data?.has_billing;
} catch (error) {
console.log(error);
}
}
// TODO: Need to handle the following cases. Do a deep rearchitecture (Prov -> Dashboard?) if need be:
// 1. Make sure clicking cluster in drawer shows cluster-dashboard
// 2. Make sure switching projects shows appropriate initial view (dashboard || provisioner)
// 3. Make sure initializing from URL (DO oauth) displays the appropriate initial view
componentDidUpdate(prevProps: PropsType) {
if (prevProps.currentProject?.id !== this.props.currentProject?.id) {
this.checkIfProjectHasBilling(this?.context?.currentProject?.id)
.then((isBillingEnabled) => {
if (isBillingEnabled) {
api
.getUsage(
"<token>",
{},
{ project_id: this.context?.currentProject?.id }
)
.then((res) => {
const usage = res.data;
this.context.setUsage(usage);
if (usage.exceeded) {
this.context.setCurrentModal("UsageWarningModal", {
usage,
});
}
})
.catch(console.log);
}
})
.catch(console.log);
}
if (
prevProps.currentProject !== this.props.currentProject ||
(!prevProps.currentCluster && this.props.currentCluster)
) {
if (this.state.handleDO) {
this.checkDO();
} else {
this.initializeView();
this.getMetadata();
}
}
}
// TODO: move into ClusterDashboard
renderDashboard = () => {
let { currentCluster } = this.context;
if (currentCluster?.id === -1) {
return <Loading />;
} else if (!currentCluster || !currentCluster.name) {
return (
<DashboardWrapper>
<PageNotFound />
</DashboardWrapper>
);
}
return (
<DashboardWrapper>
<ClusterDashboard
currentCluster={currentCluster}
setSidebar={(x: boolean) => this.setState({ forceSidebar: x })}
currentView={this.props.currentRoute}
// setCurrentView={(x: string) => this.setState({ currentView: x })}
/>
</DashboardWrapper>
);
};
renderContents = () => {
let currentView = this.props.currentRoute;
if (this.context.currentProject && currentView !== "new-project") {
if (
currentView === "cluster-dashboard" ||
currentView === "applications" ||
currentView === "jobs" ||
currentView === "env-groups"
) {
return this.renderDashboard();
} else if (currentView === "dashboard") {
return (
<DashboardWrapper>
<Dashboard
projectId={this.context.currentProject?.id}
setRefreshClusters={(x: boolean) =>
this.setState({ forceRefreshClusters: x })
}
/>
</DashboardWrapper>
);
} else if (currentView === "integrations") {
return <GuardedIntegrations />;
} else if (currentView === "project-settings") {
return <GuardedProjectSettings />;
}
return <Templates />;
} else if (currentView === "new-project") {
return <NewProject />;
}
};
renderSidebar = () => {
if (this.context.projects.length > 0) {
return (
<Sidebar
key="sidebar"
forceSidebar={this.state.forceSidebar}
setWelcome={(x: boolean) => this.setState({ showWelcome: x })}
currentView={this.props.currentRoute}
forceRefreshClusters={this.state.forceRefreshClusters}
setRefreshClusters={(x: boolean) =>
this.setState({ forceRefreshClusters: x })
}
/>
);
} else {
return (
<>
<DiscordButton href="https://discord.gg/34n7NN7FJ7" target="_blank">
<Icon src={discordLogo} />
Join Our Discord
</DiscordButton>
{this.state.showWelcomeForm &&
localStorage.getItem("welcomed") != "true" && (
<>
<WelcomeForm
closeForm={() => this.setState({ showWelcomeForm: false })}
/>
<Navbar
logOut={this.props.logOut}
currentView={this.props.currentRoute} // For form feedback
/>
</>
)}
</>
);
}
};
projectOverlayCall = () => {
let { user, setProjects, setCurrentProject } = this.context;
api
.getProjects("<token>", {}, { id: user.userId })
.then((res) => {
if (res.data) {
setProjects(res.data);
if (res.data.length > 0) {
setCurrentProject(res.data[0]);
} else {
setCurrentProject(null, () =>
pushFiltered(this.props, "/new-project", ["project_id"])
);
}
this.context.setCurrentModal(null, null);
}
})
.catch(console.log);
};
handleDelete = () => {
let { setCurrentModal, currentProject } = this.context;
localStorage.removeItem(currentProject.id + "-cluster");
api
.deleteProject("<token>", {}, { id: currentProject.id })
.then(this.projectOverlayCall)
.catch(console.log);
// Loop through and delete infra of all clusters we've provisioned
api
.getClusters("<token>", {}, { id: currentProject.id })
.then((res) => {
// TODO: promise.map
for (var i = 0; i < res.data.length; i++) {
let cluster = res.data[i];
if (!cluster.infra_id) continue;
// Handle destroying infra we've provisioned
api
.destroyInfra(
"<token>",
{ name: cluster.name },
{
project_id: currentProject.id,
infra_id: cluster.infra_id,
}
)
.then(() =>
console.log("destroyed provisioned infra:", cluster.infra_id)
)
.catch(console.log);
}
})
.catch(console.log);
setCurrentModal(null, null);
pushFiltered(this.props, "/dashboard", []);
};
render() {
let {
currentModal,
setCurrentModal,
currentProject,
currentOverlay,
setCurrentOverlay,
} = this.context;
return (
<StyledHome>
{currentModal === "ClusterInstructionsModal" && (
<Modal
onRequestClose={() => setCurrentModal(null, null)}
width="760px"
height="650px"
title="Connecting to an Existing Cluster"
>
<ClusterInstructionsModal />
</Modal>
)}
{/* We should be careful, as this component is named Update but is for deletion */}
{this.props.isAuthorized("cluster", "", ["get", "delete"]) &&
currentModal === "UpdateClusterModal" && (
<Modal
onRequestClose={() => setCurrentModal(null, null)}
width="565px"
height="275px"
title="Cluster Settings"
>
<UpdateClusterModal
setRefreshClusters={(x: boolean) =>
this.setState({ forceRefreshClusters: x })
}
/>
</Modal>
)}
{currentModal === "IntegrationsModal" && (
<Modal
onRequestClose={() => setCurrentModal(null, null)}
width="760px"
height="380px"
title="Add a New Integration"
>
<IntegrationsModal />
</Modal>
)}
{currentModal === "IntegrationsInstructionsModal" && (
<Modal
onRequestClose={() => setCurrentModal(null, null)}
width="760px"
height="650px"
title="Connecting to an Image Registry"
>
<IntegrationsInstructionsModal />
</Modal>
)}
{this.props.isAuthorized("namespace", "", ["get", "create"]) &&
currentModal === "NamespaceModal" && (
<Modal
onRequestClose={() => setCurrentModal(null, null)}
width="600px"
height="220px"
title="Add Namespace"
>
<NamespaceModal />
</Modal>
)}
{this.props.isAuthorized("namespace", "", ["get", "delete"]) &&
currentModal === "DeleteNamespaceModal" && (
<Modal
onRequestClose={() => setCurrentModal(null, null)}
width="700px"
height="280px"
title="Delete Namespace"
>
<DeleteNamespaceModal />
</Modal>
)}
{currentModal === "EditInviteOrCollaboratorModal" && (
<Modal
onRequestClose={() => setCurrentModal(null, null)}
width="600px"
height="250px"
>
<EditInviteOrCollaboratorModal />
</Modal>
)}
{currentModal === "AccountSettingsModal" && (
<Modal
onRequestClose={() => setCurrentModal(null, null)}
width="760px"
height="440px"
title="Account Settings"
>
<AccountSettingsModal />
</Modal>
)}
{currentModal === "UsageWarningModal" && (
<Modal
onRequestClose={() => setCurrentModal(null, null)}
width="760px"
height="530px"
title="Usage Warning"
>
<UsageWarningModal />
</Modal>
)}
{currentOverlay && (
<ConfirmOverlay
show={true}
message={currentOverlay.message}
onYes={currentOverlay.onYes}
onNo={currentOverlay.onNo}
/>
)}
{this.renderSidebar()}
<ViewWrapper>
<Navbar
logOut={this.props.logOut}
currentView={this.props.currentRoute} // For form feedback
/>
{this.renderContents()}
</ViewWrapper>
<ConfirmOverlay
show={currentModal === "UpdateProjectModal"}
message={
currentProject
? `Are you sure you want to delete ${currentProject.name}?`
: ""
}
onYes={this.handleDelete}
onNo={() => setCurrentModal(null, null)}
/>
</StyledHome>
);
}
}
Home.contextType = Context;
export default withRouter(withAuth(Home));
const ViewWrapper = styled.div`
height: 100%;
width: 100vw;
padding-top: 10vh;
overflow-y: auto;
display: flex;
flex: 1;
justify-content: center;
background: #202227;
position: relative;
`;
const DashboardWrapper = styled.div`
width: calc(85%);
min-width: 300px;
`;
const StyledHome = styled.div`
width: 100vw;
height: 100vh;
position: fixed;
top: 0;
left: 0;
margin: 0;
user-select: none;
display: flex;
justify-content: center;
@keyframes floatInModal {
from {
opacity: 0;
transform: translateY(30px);
}
to {
opacity: 1;
transform: translateY(0px);
}
}
`;
const DiscordButton = styled.a`
position: absolute;
z-index: 1;
text-decoration: none;
bottom: 17px;
display: flex;
align-items: center;
width: 170px;
left: 15px;
border: 2px solid #ffffff44;
border-radius: 3px;
color: #ffffff44;
height: 40px;
font-family: Work Sans, sans-serif;
font-size: 14px;
font-weight: bold;
cursor: pointer;
:hover {
> img {
opacity: 60%;
}
color: #ffffff88;
border-color: #ffffff88;
}
`;
const Icon = styled.img`
height: 25px;
width: 25px;
opacity: 30%;
margin-left: 7px;
margin-right: 5px;
`; | the_stack |
import * as React from 'react';
import Positions from './Positions';
import { TNil } from '../../../../types';
type TWrapperProps = {
style: React.CSSProperties;
ref: (elm: HTMLDivElement) => void;
onScroll?: () => void;
};
/**
* @typedef
*/
type TListViewProps = {
/**
* Number of elements in the list.
*/
dataLength: number;
/**
* Convert item index (number) to the key (string). ListView uses both indexes
* and keys to handle the addtion of new rows.
*/
getIndexFromKey: (key: string) => number;
/**
* Convert item key (string) to the index (number). ListView uses both indexes
* and keys to handle the addtion of new rows.
*/
getKeyFromIndex: (index: number) => string;
/**
* Number of items to draw and add to the DOM, initially.
*/
initialDraw?: number;
/**
* The parent provides fallback height measurements when there is not a
* rendered element to measure.
*/
itemHeightGetter: (index: number, key: string) => number;
/**
* Function that renders an item; rendered items are added directly to the
* DOM, they are not wrapped in list item wrapper HTMLElement.
*/
// itemRenderer(itemKey, style, i, attrs)
itemRenderer: (
itemKey: string,
style: Record<string, string | number>,
index: number,
attributes: Record<string, string>
) => React.ReactNode;
/**
* `className` for the HTMLElement that holds the items.
*/
itemsWrapperClassName?: string;
/**
* When adding new items to the DOM, this is the number of items to add above
* and below the current view. E.g. if list is 100 items and is srcolled
* halfway down (so items [46, 55] are in view), then when a new range of
* items is rendered, it will render items `46 - viewBuffer` to
* `55 + viewBuffer`.
*/
viewBuffer: number;
/**
* The minimum number of items offscreen in either direction; e.g. at least
* `viewBuffer` number of items must be off screen above and below the
* current view, or more items will be rendered.
*/
viewBufferMin: number;
/**
* When `true`, expect `_wrapperElm` to have `overflow: visible` and to,
* essentially, be tall to the point the entire page will will end up
* scrolling as a result of the ListView. Similar to react-virtualized
* window scroller.
*
* - Ref: https://bvaughn.github.io/react-virtualized/#/components/WindowScroller
* - Ref:https://github.com/bvaughn/react-virtualized/blob/497e2a1942529560681d65a9ef9f5e9c9c9a49ba/docs/WindowScroller.md
*/
windowScroller?: boolean;
};
const DEFAULT_INITIAL_DRAW = 300;
/**
* Virtualized list view component, for the most part, only renders the window
* of items that are in-view with some buffer before and after. Listens for
* scroll events and updates which items are rendered. See react-virtualized
* for a suite of components with similar, but generalized, functinality.
* https://github.com/bvaughn/react-virtualized
*
* Note: Presently, ListView cannot be a PureComponent. This is because ListView
* is sensitive to the underlying state that drives the list items, but it
* doesn't actually receive that state. So, a render may still be required even
* if ListView's props are unchanged.
*
* @export
* @class ListView
*/
export default class ListView extends React.Component<TListViewProps> {
/**
* Keeps track of the height and y-value of items, by item index, in the
* ListView.
*/
_yPositions: Positions;
/**
* Keep track of the known / measured heights of the rendered items; populated
* with values through observation and keyed on the item key, not the item
* index.
*/
_knownHeights: Map<string, number>;
/**
* The start index of the items currently drawn.
*/
_startIndexDrawn: number;
/**
* The end index of the items currently drawn.
*/
_endIndexDrawn: number;
/**
* The start index of the items currently in view.
*/
_startIndex: number;
/**
* The end index of the items currently in view.
*/
_endIndex: number;
/**
* Height of the visual window, e.g. height of the scroller element.
*/
_viewHeight: number;
/**
* `scrollTop` of the current scroll position.
*/
_scrollTop: number;
/**
* Used to keep track of whether or not a re-calculation of what should be
* drawn / viewable has been scheduled.
*/
_isScrolledOrResized: boolean;
/**
* If `windowScroller` is true, this notes how far down the page the scroller
* is located. (Note: repositioning and below-the-fold views are untested)
*/
_htmlTopOffset: number;
_windowScrollListenerAdded: boolean;
_htmlElm: HTMLElement;
/**
* HTMLElement holding the scroller.
*/
_wrapperElm: HTMLElement | TNil;
/**
* HTMLElement holding the rendered items.
*/
_itemHolderElm: HTMLElement | TNil;
static defaultProps = {
initialDraw: DEFAULT_INITIAL_DRAW,
itemsWrapperClassName: '',
windowScroller: false,
};
constructor(props: TListViewProps) {
super(props);
this._yPositions = new Positions(200);
// _knownHeights is (item-key -> observed height) of list items
this._knownHeights = new Map();
this._startIndexDrawn = 2 ** 20;
this._endIndexDrawn = -(2 ** 20);
this._startIndex = 0;
this._endIndex = 0;
this._viewHeight = -1;
this._scrollTop = -1;
this._isScrolledOrResized = false;
this._htmlTopOffset = -1;
this._windowScrollListenerAdded = false;
// _htmlElm is only relevant if props.windowScroller is true
this._htmlElm = document.documentElement as any;
this._wrapperElm = undefined;
this._itemHolderElm = undefined;
}
componentDidMount() {
if (this.props.windowScroller) {
if (this._wrapperElm) {
const { top } = this._wrapperElm.getBoundingClientRect();
this._htmlTopOffset = top + this._htmlElm.scrollTop;
}
window.addEventListener('scroll', this._onScroll);
this._windowScrollListenerAdded = true;
}
}
componentDidUpdate() {
if (this._itemHolderElm) {
this._scanItemHeights();
}
}
componentWillUnmount() {
if (this._windowScrollListenerAdded) {
window.removeEventListener('scroll', this._onScroll);
}
}
getViewHeight = () => this._viewHeight;
/**
* Get the index of the item at the bottom of the current view.
*/
getBottomVisibleIndex = (): number => {
const bottomY = this._scrollTop + this._viewHeight;
return this._yPositions.findFloorIndex(bottomY, this._getHeight);
};
/**
* Get the index of the item at the top of the current view.
*/
getTopVisibleIndex = (): number => this._yPositions.findFloorIndex(this._scrollTop, this._getHeight);
getRowPosition = (index: number): { height: number; y: number } =>
this._yPositions.getRowPosition(index, this._getHeight);
/**
* Scroll event listener that schedules a remeasuring of which items should be
* rendered.
*/
_onScroll = () => {
if (!this._isScrolledOrResized) {
this._isScrolledOrResized = true;
window.requestAnimationFrame(this._positionList);
}
};
/**
* Returns true is the view height (scroll window) or scroll position have
* changed.
*/
_isViewChanged() {
if (!this._wrapperElm) {
return false;
}
const useRoot = this.props.windowScroller;
const clientHeight = useRoot ? this._htmlElm.clientHeight : this._wrapperElm.clientHeight;
const scrollTop = useRoot ? this._htmlElm.scrollTop : this._wrapperElm.scrollTop;
return clientHeight !== this._viewHeight || scrollTop !== this._scrollTop;
}
/**
* Recalculate _startIndex and _endIndex, e.g. which items are in view.
*/
_calcViewIndexes() {
const useRoot = this.props.windowScroller;
// funky if statement is to satisfy flow
if (!useRoot) {
/* istanbul ignore next */
if (!this._wrapperElm) {
this._viewHeight = -1;
this._startIndex = 0;
this._endIndex = 0;
return;
}
this._viewHeight = this._wrapperElm.clientHeight;
this._scrollTop = this._wrapperElm.scrollTop;
} else {
this._viewHeight = window.innerHeight - this._htmlTopOffset;
this._scrollTop = window.scrollY;
}
const yStart = this._scrollTop;
const yEnd = this._scrollTop + this._viewHeight;
this._startIndex = this._yPositions.findFloorIndex(yStart, this._getHeight);
this._endIndex = this._yPositions.findFloorIndex(yEnd, this._getHeight);
}
/**
* Checked to see if the currently rendered items are sufficient, if not,
* force an update to trigger more items to be rendered.
*/
_positionList = () => {
this._isScrolledOrResized = false;
if (!this._wrapperElm) {
return;
}
this._calcViewIndexes();
// indexes drawn should be padded by at least props.viewBufferMin
const maxStart =
this.props.viewBufferMin > this._startIndex ? 0 : this._startIndex - this.props.viewBufferMin;
const minEnd =
this.props.viewBufferMin < this.props.dataLength - this._endIndex
? this._endIndex + this.props.viewBufferMin
: this.props.dataLength - 1;
if (maxStart < this._startIndexDrawn || minEnd > this._endIndexDrawn) {
this.forceUpdate();
}
};
_initWrapper = (elm: HTMLElement | TNil) => {
this._wrapperElm = elm;
if (!this.props.windowScroller && elm) {
this._viewHeight = elm.clientHeight;
}
};
_initItemHolder = (elm: HTMLElement | TNil) => {
this._itemHolderElm = elm;
this._scanItemHeights();
};
/**
* Go through all items that are rendered and save their height based on their
* item-key (which is on a data-* attribute). If any new or adjusted heights
* are found, re-measure the current known y-positions (via .yPositions).
*/
_scanItemHeights = () => {
const getIndexFromKey = this.props.getIndexFromKey;
if (!this._itemHolderElm) {
return;
}
// note the keys for the first and last altered heights, the `yPositions`
// needs to be updated
let lowDirtyKey = null;
let highDirtyKey = null;
let isDirty = false;
// iterating childNodes is faster than children
// https://jsperf.com/large-htmlcollection-vs-large-nodelist
const nodes = this._itemHolderElm.childNodes;
const max = nodes.length;
for (let i = 0; i < max; i++) {
const node: HTMLElement = nodes[i] as any;
// use `.getAttribute(...)` instead of `.dataset` for jest / JSDOM
const itemKey = node.getAttribute('data-item-key');
if (!itemKey) {
// eslint-disable-next-line no-console
console.warn('itemKey not found');
continue;
}
// measure the first child, if it's available, otherwise the node itself
// (likely not transferable to other contexts, and instead is specific to
// how we have the items rendered)
const measureSrc: Element = node.firstElementChild || node;
const observed = measureSrc.clientHeight;
const known = this._knownHeights.get(itemKey);
if (observed !== known) {
this._knownHeights.set(itemKey, observed);
if (!isDirty) {
isDirty = true;
// eslint-disable-next-line no-multi-assign
lowDirtyKey = highDirtyKey = itemKey;
} else {
highDirtyKey = itemKey;
}
}
}
if (lowDirtyKey != null && highDirtyKey != null) {
// update yPositions, then redraw
const imin = getIndexFromKey(lowDirtyKey);
const imax = highDirtyKey === lowDirtyKey ? imin : getIndexFromKey(highDirtyKey);
this._yPositions.calcHeights(imax, this._getHeight, imin);
this.forceUpdate();
}
};
/**
* Get the height of the element at index `i`; first check the known heigths,
* fallbck to `.props.itemHeightGetter(...)`.
*/
_getHeight = (i: number) => {
const key = this.props.getKeyFromIndex(i);
const known = this._knownHeights.get(key);
// known !== known iff known is NaN
// eslint-disable-next-line no-self-compare
if (known != null && known === known) {
return known;
}
return this.props.itemHeightGetter(i, key);
};
render() {
const {
dataLength,
getKeyFromIndex,
initialDraw = DEFAULT_INITIAL_DRAW,
itemRenderer,
viewBuffer,
viewBufferMin,
} = this.props;
const heightGetter = this._getHeight;
const items = [];
let start;
let end;
this._yPositions.profileData(dataLength);
if (!this._wrapperElm) {
start = 0;
end = (initialDraw < dataLength ? initialDraw : dataLength) - 1;
} else {
if (this._isViewChanged()) {
this._calcViewIndexes();
}
const maxStart = viewBufferMin > this._startIndex ? 0 : this._startIndex - viewBufferMin;
const minEnd =
viewBufferMin < dataLength - this._endIndex ? this._endIndex + viewBufferMin : dataLength - 1;
if (maxStart < this._startIndexDrawn || minEnd > this._endIndexDrawn) {
start = viewBuffer > this._startIndex ? 0 : this._startIndex - viewBuffer;
end = this._endIndex + viewBuffer;
if (end >= dataLength) {
end = dataLength - 1;
}
} else {
start = this._startIndexDrawn;
end = this._endIndexDrawn > dataLength - 1 ? dataLength - 1 : this._endIndexDrawn;
}
}
this._yPositions.calcHeights(end, heightGetter, start || -1);
this._startIndexDrawn = start;
this._endIndexDrawn = end;
items.length = end - start + 1;
for (let i = start; i <= end; i++) {
const { y: top, height } = this._yPositions.getRowPosition(i, heightGetter);
const style = {
height,
top,
position: 'absolute',
};
const itemKey = getKeyFromIndex(i);
const attrs = { 'data-item-key': itemKey };
items.push(itemRenderer(itemKey, style, i, attrs));
}
const wrapperProps: TWrapperProps = {
style: { position: 'relative' },
ref: this._initWrapper,
};
if (!this.props.windowScroller) {
wrapperProps.onScroll = this._onScroll;
wrapperProps.style.height = '100%';
wrapperProps.style.overflowY = 'auto';
}
const scrollerStyle = {
position: 'relative' as 'relative',
height: this._yPositions.getEstimatedHeight(),
};
return (
<div {...wrapperProps}>
<div style={scrollerStyle}>
<div
style={{
position: 'absolute',
top: 0,
margin: 0,
padding: 0,
}}
className={this.props.itemsWrapperClassName}
ref={this._initItemHolder}
>
{items}
</div>
</div>
</div>
);
}
} | the_stack |
import { CreateElement, VNode, VNodeChildren } from 'vue';
import { guessOptionText } from '../utils/inputOptions';
import TRichSelectInterface from '../types/TRichSelect';
import NormalizedOptions from '../types/NormalizedOptions';
import NormalizedOption from '../types/NormalizedOption';
import Key from '../types/Key';
export default class TRichSelectRenderer {
createElement: CreateElement
component: TRichSelectInterface
constructor(createElement: CreateElement, component: TRichSelectInterface) {
this.createElement = createElement;
this.component = component;
}
render(): VNode {
return this.createWrapper();
}
/**
* Div that wraps the whole component
*/
createWrapper(): VNode {
return this.createElement(
'div',
{
ref: 'wrapper',
class: this.component.getElementCssClass('wrapper'),
},
[
this.createSelectButtonWrapper(),
this.createDropdown(),
],
);
}
/**
* Div that wraps the button that is used as a select box
*/
createSelectButtonWrapper(): VNode {
const subElements = [this.createSelectButton()];
const hasSelectedOption = this.component.multiple
? (this.component.selectedOptions as NormalizedOption[]).filter((o) => !o.disabled).length > 0
: !!(this.component.selectedOption && !this.component.selectedOption.disabled);
if (this.component.clearable && hasSelectedOption && !this.component.disabled) {
subElements.push(this.createSelectButtonClearButton());
}
return this.createElement(
'div',
{
ref: 'buttonWrapper',
class: this.component.getElementCssClass('buttonWrapper'),
},
subElements,
);
}
/**
* The button that is used a select box
*/
createSelectButton(): VNode {
const subElements = [];
if (this.component.multiple && this.component.selectedOptions.length) {
if (this.component.$scopedSlots.label) {
subElements.push(this.component.$scopedSlots.label({
query: this.component.query,
options: this.component.selectedOptions,
className: this.component.getElementCssClass('selectButtonLabel'),
}));
} else {
subElements.push(this.createSelectButtonLabel());
}
} else if (!this.component.multiple && this.component.selectedOption) {
if (this.component.$scopedSlots.label) {
subElements.push(this.component.$scopedSlots.label({
query: this.component.query,
option: this.component.selectedOption,
className: this.component.getElementCssClass('selectButtonLabel'),
}));
} else {
subElements.push(this.createSelectButtonLabel());
}
} else {
subElements.push(this.createSelectButtonPlaceholder());
}
const hasSelectedOption = this.component.multiple
? this.component.selectedOptions.length > 0
: !!this.component.selectedOption;
if (!(this.component.clearable && hasSelectedOption) && !this.component.disabled) {
subElements.push(...this.createSelectButtonIcon());
}
if (this.component.multiple) {
const hiddenInputs = (this.component.selectedOptions as NormalizedOptions).map((option) => this.createElement(
'input',
{
attrs: {
type: 'hidden',
value: option.value,
name: this.component.name,
},
},
));
return this.createElement(
'div',
{
ref: 'tagsContainer',
attrs: {
tabindex: this.component.tabindex || 0,
},
class: this.component.getElementCssClass('selectButton'),
on: {
click: this.component.clickHandler,
focus: this.component.focusHandler,
keydown: (e: KeyboardEvent) => {
if (e.keyCode === Key.DOWN) {
this.component.arrowDownHandler(e);
} else if (e.keyCode === Key.UP) {
this.component.arrowUpHandler(e);
} else if (e.keyCode === Key.ENTER) {
this.component.enterHandler(e);
} else if (e.keyCode === Key.ESC) {
this.component.escapeHandler(e);
}
},
blur: this.component.blurHandler,
mousedown: (e: MouseEvent) => {
e.preventDefault();
},
},
},
subElements.concat(hiddenInputs),
);
}
return this.createElement(
'button',
{
ref: 'selectButton',
attrs: {
type: 'button',
value: this.component.localValue,
id: this.component.id,
autofocus: this.component.autofocus,
disabled: this.component.disabled,
name: this.component.name,
},
class: this.component.getElementCssClass('selectButton'),
on: {
click: this.component.clickHandler,
focus: this.component.focusHandler,
keydown: (e: KeyboardEvent) => {
if (e.keyCode === Key.DOWN) {
this.component.arrowDownHandler(e);
} else if (e.keyCode === Key.UP) {
this.component.arrowUpHandler(e);
} else if (e.keyCode === Key.ENTER) {
this.component.enterHandler(e);
} else if (e.keyCode === Key.ESC) {
this.component.escapeHandler(e);
}
},
blur: this.component.blurHandler,
mousedown: (e: MouseEvent) => {
e.preventDefault();
},
},
},
subElements,
);
}
createSelectButtonLabel(): VNode {
if (this.component.multiple) {
return this.createElement(
'div',
{
class: this.component.getElementCssClass('selectButtonTagWrapper'),
},
(this.component.selectedOptions as NormalizedOptions).map((selectedOption, index) => this.createElement(
'button',
{
class: this.component.getElementCssClass('selectButtonTag'),
attrs: {
tabindex: this.component.tagsAreFocusable && !selectedOption.disabled ? '0' : '-1',
type: 'button',
disabled: selectedOption.disabled ? true : undefined,
},
on: {
click: (e: MouseEvent) => {
e.stopPropagation();
if (selectedOption.disabled) {
return;
}
this.component.selectTag(e.currentTarget as HTMLButtonElement);
},
blur: (e: FocusEvent) => {
this.component.unselectTag(e.currentTarget as HTMLButtonElement);
},
focus: (e: FocusEvent) => {
this.component.selectTag(e.currentTarget as HTMLButtonElement);
},
keydown: (e: KeyboardEvent) => {
if (e.keyCode === Key.BACKSPACE) {
this.component.unselectOptionAtIndex(index);
}
},
},
},
[
this.createElement(
'span',
{
class: this.component.getElementCssClass('selectButtonTagText'),
}, (selectedOption ? selectedOption.text : '') as VNodeChildren,
),
[
selectedOption.disabled
? null
: this.createElement(
'span',
{
class: this.component.getElementCssClass('selectButtonTagDeleteButton'),
attrs: {
tabindex: -1,
},
on: {
click: (e: MouseEvent) => {
e.stopPropagation();
this.component.unselectOptionAtIndex(index);
},
},
},
[
this.createElement(
'svg',
{
class: this.component.getElementCssClass('selectButtonTagDeleteButtonIcon'),
attrs: {
fill: 'currentColor',
viewBox: '0 0 20 20',
xmlns: 'http://www.w3.org/2000/svg',
},
},
[
this.createElement(
'path',
{
attrs: {
'fill-rule': 'evenodd',
evenodd: 'evenodd',
d: 'M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z',
},
},
),
],
),
],
),
],
],
)),
);
}
return this.createElement(
'span',
{
ref: 'selectButtonLabel',
class: this.component.getElementCssClass('selectButtonLabel'),
},
(this.component.selectedOption ? this.component.selectedOption.text : '') as VNodeChildren,
);
}
createSelectButtonPlaceholder(): VNode {
const domProps: {innerHTML?: string} = {};
if (!this.component.placeholder) {
domProps.innerHTML = ' ';
}
return this.createElement(
'span',
{
ref: 'selectButtonPlaceholder',
class: this.component.getElementCssClass('selectButtonPlaceholder'),
domProps,
},
this.component.placeholder || undefined,
);
}
createSelectButtonIcon(): VNode[] {
if (this.component.$scopedSlots.arrow) {
return this.component.$scopedSlots.arrow({
className: this.component.getElementCssClass('selectButtonIcon'),
variant: this.component.variant,
value: this.component.localValue,
}) as VNode[];
}
return [this.createElement(
'svg',
{
ref: 'selectButtonIcon',
attrs: {
fill: 'currentColor',
xmlns: 'http://www.w3.org/2000/svg',
viewBox: '0 0 20 20',
},
class: this.component.getElementCssClass('selectButtonIcon'),
},
[
this.createElement('path', {
attrs: {
'clip-rule': 'evenodd',
'fill-rule': 'evenodd',
d: 'M10 3a1 1 0 01.707.293l3 3a1 1 0 01-1.414 1.414L10 5.414 7.707 7.707a1 1 0 01-1.414-1.414l3-3A1 1 0 0110 3zm-3.707 9.293a1 1 0 011.414 0L10 14.586l2.293-2.293a1 1 0 011.414 1.414l-3 3a1 1 0 01-1.414 0l-3-3a1 1 0 010-1.414z',
},
}),
],
)];
}
createSelectButtonClearButton(): VNode {
return this.createElement(
'button',
{
ref: 'selectButtonClearButton',
class: this.component.getElementCssClass('selectButtonClearButton'),
attrs: {
type: 'button',
tabindex: -1,
},
on: {
click: this.component.clearButtonClickHandler,
},
},
[
this.createElement(
'svg',
{
attrs: {
fill: 'currentColor',
xmlns: 'http://www.w3.org/2000/svg',
viewBox: '0 0 20 20',
},
class: this.component.getElementCssClass('selectButtonClearIcon'),
},
[
this.createElement('polygon', {
attrs: {
points: '10 8.58578644 2.92893219 1.51471863 1.51471863 2.92893219 8.58578644 10 1.51471863 17.0710678 2.92893219 18.4852814 10 11.4142136 17.0710678 18.4852814 18.4852814 17.0710678 11.4142136 10 18.4852814 2.92893219 17.0710678 1.51471863 10 8.58578644',
},
}),
],
),
],
);
}
/**
* Div that wraps the search box
*/
createSearchBoxWrapper(): VNode {
return this.createElement(
'div',
{
ref: 'searchWrapper',
class: this.component.getElementCssClass('searchWrapper'),
},
[
this.createSearchBox(),
],
);
}
/**
* Filter search box
*/
createSearchBox() : VNode {
return this.createElement(
'input',
{
ref: 'searchBox',
class: this.component.getElementCssClass('searchBox'),
domProps: {
value: this.component.query,
},
attrs: {
placeholder: this.component.searchBoxPlaceholder,
},
on: {
keydown: (e: KeyboardEvent) => {
if (e.keyCode === Key.DOWN) {
this.component.arrowDownHandler(e);
} else if (e.keyCode === Key.UP) {
this.component.arrowUpHandler(e);
} else if (e.keyCode === Key.ENTER) {
this.component.enterHandler(e);
} else if (e.keyCode === Key.ESC) {
this.component.escapeHandler(e);
}
},
blur: this.component.blurHandler,
input: this.component.searchInputHandler,
},
},
);
}
getMinimumInputLengthText(): string {
if (typeof this.component.minimumInputLengthText === 'function') {
return this.component.minimumInputLengthText(
this.component.minimumInputLength as number,
this.component.query,
);
}
return this.component.minimumInputLengthText;
}
/**
* The div used as dropdown with the options and the search box
*/
createDropdown(): VNode {
const subElements = [];
if (this.component.shouldShowSearchbox) {
subElements.push(this.createSearchBoxWrapper());
}
if (this.component.$scopedSlots.dropdownUp) {
subElements.push(this.component.$scopedSlots.dropdownUp({
query: this.component.query,
selectedOption: this.component.selectedOption,
options: this.component.filteredOptions,
}));
}
if (this.component.searching && !this.component.nextPage) {
if (this.component.$scopedSlots.searchingText) {
subElements.push(this.component.$scopedSlots.searchingText({
text: this.component.searchingText,
query: this.component.query,
className: this.component.getElementCssClass('dropdownFeedback'),
}));
} else {
subElements.push(this.createDropdownFeedback(this.component.searchingText));
}
} else if (this.component.minimumInputLength !== undefined
&& this.component.query.length < this.component.minimumInputLength) {
const minInputLengthText = this.getMinimumInputLengthText();
subElements.push(this.createDropdownFeedback(minInputLengthText));
} else if (!this.component.filteredOptions.length) {
if (this.component.$scopedSlots.noResults) {
subElements.push(this.component.$scopedSlots.noResults({
text: this.component.noResultsText,
query: this.component.query,
className: this.component.getElementCssClass('dropdownFeedback'),
}));
} else {
subElements.push(this.createDropdownFeedback(this.component.noResultsText));
}
}
if (this.component.filteredOptions.length) {
subElements.push(this.createOptionsList(this.component.filteredOptions));
}
if (this.component.searching && this.component.nextPage) {
if (this.component.$scopedSlots.loadingMoreResultsText) {
subElements.push(this.component.$scopedSlots.loadingMoreResultsText({
text: this.component.loadingMoreResultsText,
nextPage: this.component.nextPage,
query: this.component.query,
className: this.component.getElementCssClass('loadingMoreResults'),
}));
} else {
subElements.push(this.createLoadingMoreResults(this.component.loadingMoreResultsText));
}
}
if (this.component.$scopedSlots.dropdownDown) {
subElements.push(this.component.$scopedSlots.dropdownDown({
query: this.component.query,
selectedOption: this.component.selectedOption,
options: this.component.filteredOptions,
}));
}
return this.createElement(
'transition',
{
props: {
enterClass: this.component.getElementCssClass('enterClass'),
enterActiveClass: this.component.getElementCssClass('enterActiveClass'),
enterToClass: this.component.getElementCssClass('enterToClass'),
leaveClass: this.component.getElementCssClass('leaveClass'),
leaveActiveClass: this.component.getElementCssClass('leaveActiveClass'),
leaveToClass: this.component.getElementCssClass('leaveToClass'),
},
},
this.component.show ? [
this.createElement(
'div',
{
ref: 'dropdown',
class: this.component.getElementCssClass('dropdown'),
},
subElements,
),
] : undefined,
);
}
/**
* Options list wrapper
*/
createOptionsList(options: NormalizedOptions): VNode {
return this.createElement(
'ul',
{
ref: 'optionsList',
class: this.component.getElementCssClass('optionsList'),
style: {
maxHeight: this.component.normalizedHeight,
},
on: {
scroll: this.component.listScrollHandler,
},
},
this.createOptions(options),
);
}
/**
* Dropdown feedback
* @param text
*/
createDropdownFeedback(text: string): VNode {
return this.createElement(
'div',
{
ref: 'dropdownFeedback',
class: this.component.getElementCssClass('dropdownFeedback'),
},
text,
);
}
/**
* Dropdown feedback
* @param text
*/
createLoadingMoreResults(text: string): VNode {
return this.createElement(
'div',
{
ref: 'loadingMoreResults',
class: this.component.getElementCssClass('loadingMoreResults'),
},
text,
);
}
/**
* List of options
*/
createOptions(options: NormalizedOptions): VNode[] {
let index = -1;
return options
.map((option: NormalizedOption) => {
if (option.children) {
return [
option,
...option.children,
];
}
return option;
})
.flat()
.map((option: NormalizedOption) => {
if (option.children) {
return this.createOptgroup(option);
}
index += 1;
return this.createOption(option, index);
});
}
/**
* Creates an optgroup element
* @param option
* @param index
*/
createOptgroup(
optgroup: NormalizedOption,
): VNode {
return this.createElement(
'li',
{
attrs: {
'data-type': 'optgroup',
},
class: this.component.getElementCssClass('optgroup'),
},
guessOptionText(optgroup, this.component.textAttribute),
);
}
/**
* Builds an option element
* @param option
* @param index
*/
createOption(
option: NormalizedOption,
index: number,
): VNode {
const isSelected = this.component.optionHasValue(
option, this.component.localValue,
);
const isHighlighted = this.component.highlighted === index;
let className;
if (option.disabled) {
className = this.component.getElementCssClass('disabledOption');
} else if (isHighlighted && isSelected) {
className = this.component.getElementCssClass('selectedHighlightedOption');
} else if (isHighlighted) {
className = this.component.getElementCssClass('highlightedOption');
} else if (isSelected) {
className = this.component.getElementCssClass('selectedOption');
} else {
className = this.component.getElementCssClass('option');
}
const subElements = [];
if (this.component.$scopedSlots.option) {
subElements.push(this.component.$scopedSlots.option({
index,
isHighlighted,
isSelected,
option,
query: this.component.query,
className: this.component.getElementCssClass('optionContent'),
}));
} else {
subElements.push(this.createOptionContent(option, isSelected));
}
return this.createElement(
'li',
{
ref: 'option',
class: className,
attrs: {
'data-type': 'option',
},
on: {
mouseover: () => {
this.component.highlighted = index;
},
mouseleave: () => {
this.component.highlighted = null;
},
mousedown: (e: MouseEvent) => {
e.preventDefault();
},
click: (e: MouseEvent) => {
e.preventDefault();
if (option.disabled) {
return;
}
this.component.selectOption(option);
},
},
},
subElements,
);
}
createOptionContent(option: NormalizedOption, isSelected: boolean): VNode {
const subElements = [
this.createOptionLabel(option),
];
if (isSelected) {
subElements.push(this.createOptionSelectedIcon());
}
return this.createElement(
'div',
{
ref: 'optionContent',
class: this.component.getElementCssClass('optionContent'),
},
subElements,
);
}
createOptionLabel(option: NormalizedOption): VNode {
return this.createElement(
'span',
{
ref: 'optionLabel',
class: this.component.getElementCssClass('optionLabel'),
},
option.text as VNodeChildren,
);
}
createOptionSelectedIcon(): VNode {
return this.createElement(
'svg',
{
ref: 'selectedIcon',
attrs: {
fill: 'currentColor',
xmlns: 'http://www.w3.org/2000/svg',
viewBox: '0 0 20 20',
},
class: this.component.getElementCssClass('selectedIcon'),
},
[
this.createElement('polygon', {
attrs: {
points: '0 11 2 9 7 14 18 3 20 5 7 18',
},
}),
],
);
}
} | the_stack |
import * as chalk from "chalk";
import { assert } from "node-opcua-assert";
import {
AccessLevelFlag,
BrowseDirection,
coerceLocalizedText,
coerceQualifiedName,
LocalizedText,
NodeClass,
ResultMask
} from "node-opcua-data-model";
import { make_warningLog } from "node-opcua-debug";
import { NodeId, resolveNodeId, sameNodeId } from "node-opcua-nodeid";
import { ReferenceDescription } from "node-opcua-types";
import {
IAddressSpace,
UADataType,
UAReferenceType,
ConstructNodeIdOptions,
CloneExtraInfo,
CloneFilter,
BaseNode,
UAVariable,
UAMethod,
UAObject,
UAObjectType,
UAVariableType,
ISessionContext,
UAReference,
CloneOptions
} from "node-opcua-address-space-base";
import { DataValue } from "node-opcua-data-value";
import { UANamespace_process_modelling_rule } from "./namespace_private";
import { ReferenceImpl } from "./reference_impl";
import { BaseNodeImpl, getReferenceType } from "./base_node_impl";
import { AddressSpacePrivate } from "./address_space_private";
import { UAObjectImpl } from "./ua_object_impl";
const g_weakMap = new WeakMap();
const warningLog = make_warningLog(__filename);
interface BaseNodeCache {
__address_space: IAddressSpace | null;
_browseFilter?: (this: BaseNode, context?: ISessionContext) => boolean;
_cache: any;
_description?: LocalizedText;
_displayName: LocalizedText[];
_parent?: BaseNode | null;
_back_referenceIdx: { [key: string]: UAReference };
_referenceIdx: { [key: string]: UAReference };
_subtype_idxVersion: number;
_subtype_idx: any;
}
export function BaseNode_initPrivate(self: BaseNode): BaseNodeCache {
const _private: BaseNodeCache = {
__address_space: null,
_referenceIdx: {},
_back_referenceIdx: {},
_browseFilter: undefined,
_cache: {},
_description: undefined,
_displayName: [],
_parent: undefined,
_subtype_idx: {},
_subtype_idxVersion: 0
};
g_weakMap.set(self, _private);
return _private;
}
export function BaseNode_removePrivate(self: BaseNode): void {
// there is no need to delete object from weak map
// the GC will take care of this in due course
// g_weakMap.delete(self);
const _private = BaseNode_getPrivate(self);
_private._cache = {};
_private.__address_space = null;
_private._back_referenceIdx = {};
_private._referenceIdx = {};
_private._description = undefined;
_private._displayName = [];
}
export function BaseNode_getPrivate(self: BaseNode): BaseNodeCache {
return g_weakMap.get(self);
}
export function BaseNode_getCache(node: BaseNode): any {
return BaseNode_getPrivate(node)._cache;
}
export function BaseNode_clearCache(node: BaseNode): void {
const _private = BaseNode_getPrivate(node);
if (_private && _private._cache) {
_private._cache = {};
}
}
const hasTypeDefinition_ReferenceTypeNodeId = resolveNodeId("HasTypeDefinition");
export interface ToStringOption {
level: number;
cycleDetector: any;
padding: string;
add(someLine: string): void;
indent(a: string, b: string | null): void;
}
export class ToStringBuilder implements ToStringOption {
public level = 0;
public cycleDetector: any = {};
public padding = "";
private str: string[] = [];
constructor() {
//
this.str = [];
}
public add(line: string): void {
this.str.push(line);
}
public toString(): string {
return this.str.join("\n");
}
public indent(str: string, padding: string | null): string {
padding = padding || " ";
return str
.split("\n")
.map((r) => {
return padding + r;
})
.join("\n");
}
}
function set_as_processed(options: ToStringOption, nodeId: NodeId) {
options.cycleDetector[nodeId.toString()] = nodeId;
}
function is_already_processed(options: ToStringOption, nodeId: NodeId): boolean {
return !!options.cycleDetector[nodeId.toString()];
}
export function BaseNode_toString(this: BaseNode, options: ToStringOption): void {
options.level = options.level || 1;
set_as_processed(options, this.nodeId);
options.add("");
options.add(options.padding + chalk.yellow(" nodeId : ") + this.nodeId.toString());
options.add(
options.padding + chalk.yellow(" nodeClass : ") + NodeClass[this.nodeClass] + " (" + this.nodeClass + ")"
);
options.add(options.padding + chalk.yellow(" browseName : ") + this.browseName.toString());
options.add(
options.padding +
chalk.yellow(" displayName : ") +
this.displayName.map((f) => f.locale + " " + f.text).join(" | ")
);
options.add(
options.padding + chalk.yellow(" description : ") + (this.description ? this.description.toString() : "")
);
}
export function BaseNode_References_toString(this: BaseNode, options: ToStringOption): void {
const _private = BaseNode_getPrivate(this);
const displayOptions = {
addressSpace: this.addressSpace
};
const addressSpace = this.addressSpace;
options.add(
options.padding + chalk.yellow(" references : ") + " length =" + Object.keys(_private._referenceIdx).length
);
function dump_reference(follow: boolean, reference: UAReference | null) {
if (!reference) {
return;
}
const o = ReferenceImpl.resolveReferenceNode(addressSpace, reference);
const name = o ? o.browseName.toString() : "<???>";
options.add(
options.padding + chalk.yellow(" +-> ") + reference.toString(displayOptions) + " " + chalk.cyan(name)
);
// ignore HasTypeDefinition as it has been already handled
if (sameNodeId(reference.referenceType, hasTypeDefinition_ReferenceTypeNodeId) && reference.nodeId.namespace === 0) {
return;
}
if (o) {
if (!is_already_processed(options, o.nodeId)) {
set_as_processed(options, o.nodeId);
if (options.level > 1 && follow) {
const rr = (o as any).toString({
cycleDetector: options.cycleDetector,
level: options.level - 1,
padding: options.padding + " "
});
options.add(rr);
}
}
}
}
// direct reference
(Object.values(_private._referenceIdx) as UAReference[]).forEach(dump_reference.bind(null, true));
const br = Object.values(_private._back_referenceIdx).map((x) => x);
options.add(
options.padding +
chalk.yellow(" back_references : ") +
chalk.cyan(" length =") +
br.length +
chalk.grey(" ( references held by other nodes involving this node)")
);
// backward reference
br.forEach(dump_reference.bind(null, false));
}
function _UAType_toString(this: UAReferenceType | UADataType | UAObjectType | UAVariableType, options: ToStringOption): void {
if (this.subtypeOfObj) {
options.add(
options.padding +
chalk.yellow(" subtypeOf : ") +
this.subtypeOfObj.browseName.toString() +
" (" +
this.subtypeOfObj.nodeId.toString() +
")"
);
}
}
function _UAInstance_toString(this: UAVariable | UAMethod | UAObject, options: ToStringOption): void {
if (this.typeDefinitionObj) {
options.add(
options.padding +
chalk.yellow(" typeDefinition : ") +
this.typeDefinitionObj.browseName.toString() +
" (" +
this.typeDefinitionObj.nodeId.toString() +
")"
);
}
}
export function UAVariableType_toString(this: UAVariableType, options: ToStringOption): void {
BaseNode_toString.call(this, options);
_UAType_toString.call(this, options);
VariableOrVariableType_toString.call(this, options);
BaseNode_References_toString.call(this, options);
}
export function UAVariable_toString(this: UAVariable, options: ToStringOption): void {
BaseNode_toString.call(this, options);
_UAInstance_toString.call(this, options);
VariableOrVariableType_toString.call(this, options);
AccessLevelFlags_toString.call(this, options);
BaseNode_References_toString.call(this, options);
}
export function UAObject_toString(this: UAObject, options: ToStringOption): void {
BaseNode_toString.call(this, options);
_UAInstance_toString.call(this, options);
BaseNode_References_toString.call(this, options);
}
export function UAObjectType_toString(this: UAObjectType, options: ToStringOption): void {
BaseNode_toString.call(this, options);
_UAType_toString.call(this, options);
BaseNode_References_toString.call(this, options);
}
export function valueRankToString(valueRank: number): string {
switch (valueRank) {
case 1:
return "OneDimension (1)";
case 0:
return "OneOrMoreDimensions (0)"; // The value is an array with one or more dimensions
case -1:
return "Scalar (-1)";
case -2:
return "Any (-2)"; // The value can be a scalar or an array with any number of dimensions
case -3:
return "ScalarOrOneDimension (2)"; // The value can be a scalar or a one dimensional array.
default:
if (valueRank > 0) {
return "" + valueRank + "-Dimensions";
} else {
return "Invalid (" + valueRank + ")";
}
}
}
function accessLevelFlagToString(flag: AccessLevelFlag): string {
const str: string[] = [];
if (flag & AccessLevelFlag.CurrentRead) {
str.push("CurrentRead");
}
if (flag & AccessLevelFlag.CurrentWrite) {
str.push("CurrentWrite");
}
if (flag & AccessLevelFlag.HistoryRead) {
str.push("HistoryRead");
}
if (flag & AccessLevelFlag.HistoryWrite) {
str.push("HistoryWrite");
}
if (flag & AccessLevelFlag.SemanticChange) {
str.push("SemanticChange");
}
if (flag & AccessLevelFlag.StatusWrite) {
str.push("StatusWrite");
}
if (flag & AccessLevelFlag.TimestampWrite) {
str.push("TimestampWrite");
}
return str.join(" | ");
}
function AccessLevelFlags_toString(this: UAVariable, options: ToStringOption) {
assert(options);
options.add(
options.padding + chalk.yellow(" accessLevel : ") + " " + accessLevelFlagToString(this.accessLevel)
);
if (this.userAccessLevel !== undefined) {
options.add(
options.padding + chalk.yellow(" userAccessLevel : ") + " " + accessLevelFlagToString(this.userAccessLevel)
);
}
}
export function VariableOrVariableType_toString(this: UAVariableType | UAVariable, options: ToStringOption): void {
assert(options);
if (this.dataType) {
const addressSpace = this.addressSpace;
const d = addressSpace.findNode(this.dataType);
const n = d ? "(" + d.browseName.toString() + ")" : " (???)";
options.add(options.padding + chalk.yellow(" dataType : ") + this.dataType + " " + n);
}
if (this.nodeClass === NodeClass.Variable) {
const _dataValue = (<any>this)._dataValue as DataValue | undefined;
if (_dataValue) {
options.add(
options.padding +
chalk.yellow(" value : ") +
"\n" +
options.indent(_dataValue.toString(), options.padding + " | ")
);
}
}
if (Object.prototype.hasOwnProperty.call(this, "valueRank")) {
if (this.valueRank !== undefined) {
options.add(
options.padding + chalk.yellow(" valueRank : ") + " " + valueRankToString(this.valueRank)
);
} else {
options.add(options.padding + chalk.yellow(" valueRank : ") + " undefined");
}
}
if (this.minimumSamplingInterval !== undefined) {
options.add(
options.padding +
chalk.yellow(" minimumSamplingInterval : ") +
" " +
this.minimumSamplingInterval.toString() +
" ms"
);
}
if (this.arrayDimensions) {
options.add(
options.padding +
chalk.yellow(" arrayDimension : ") +
" [" +
this.arrayDimensions.join(",").toString() +
" ]"
);
}
}
/**
* clone properties and methods
* @private
*/
function _clone_collection_new(
newParent: BaseNode,
collectionRef: UAReference[],
copyAlsoModellingRules: boolean,
optionalFilter?: CloneFilter,
extraInfo?: CloneExtraInfo
): void {
const namespace = newParent.namespace;
const addressSpace = newParent.addressSpace;
assert(!optionalFilter || (typeof optionalFilter.shouldKeep === "function" && typeof optionalFilter.filterFor === "function"));
for (const reference of collectionRef) {
const node: BaseNode = ReferenceImpl.resolveReferenceNode(addressSpace, reference);
// ensure node is of the correct type,
// it may happen that the xml nodeset2 file was malformed
// istanbul ignore next
if (typeof (node as any).clone !== "function") {
// tslint:disable-next-line:no-console
warningLog(
chalk.red("Warning : cannot clone node ") +
node.browseName.toString() +
" of class " +
NodeClass[node.nodeClass].toString() +
" while cloning " +
newParent.browseName.toString()
);
continue;
}
if (optionalFilter && node && !optionalFilter.shouldKeep(node)) {
continue; // skip this node
}
assert(reference.isForward);
assert(reference.referenceType instanceof NodeId, "" + reference.referenceType.toString());
const options = {
namespace,
references: [new ReferenceImpl({ referenceType: reference.referenceType, isForward: false, nodeId: newParent.nodeId })],
copyAlsoModellingRules
};
const clone = (node as UAVariable | UAMethod | UAObject).clone(options, optionalFilter, extraInfo);
if (extraInfo) {
extraInfo.registerClonedObject(node, clone);
}
}
}
export function _clone_children_references(
node: BaseNode,
newParent: BaseNode,
copyAlsoModellingRules: boolean,
optionalFilter?: CloneFilter,
extraInfo?: CloneExtraInfo
): void {
// find all reference that derives from the Aggregates
const aggregatesRef = node.findReferencesEx("Aggregates", BrowseDirection.Forward);
_clone_collection_new(newParent, aggregatesRef, copyAlsoModellingRules, optionalFilter, extraInfo);
}
export function _clone_non_hierarchical_references(
node: BaseNode,
newParent: BaseNode,
copyAlsoModellingRules: boolean,
optionalFilter?: CloneFilter,
extraInfo?: CloneExtraInfo
): void {
// clone only some non hierarchical_references that we do want to clone
// such as:
// HasSubStateMachine
// (may be other as well later ... to do )
assert(newParent instanceof BaseNodeImpl);
// find all reference that derives from the HasSubStateMachine
const references = node.findReferencesEx("HasSubStateMachine", BrowseDirection.Forward);
_clone_collection_new(newParent, references, copyAlsoModellingRules, optionalFilter, extraInfo);
}
/**
* @method _clone
* @private
*/
export function _clone<T extends UAObject | UAVariable | UAMethod>(
this: T,
Constructor: new (options: any) => T,
options: CloneOptions,
optionalFilter?: CloneFilter,
extraInfo?: CloneExtraInfo
): T {
assert(typeof Constructor === "function");
assert(options !== null && typeof options === "object");
assert(
!extraInfo || (extraInfo !== null && typeof extraInfo === "object" && typeof extraInfo.registerClonedObject === "function")
);
assert(!(this as any).subtypeOf, "We do not do cloning of Type yet");
const namespace = options.namespace;
const constructorOptions: any = {
...options,
addressSpace: namespace.addressSpace,
browseName: this.browseName,
description: this.description,
displayName: this.displayName,
nodeClass: this.nodeClass
};
constructorOptions.references = options.references || [];
if (this.nodeClass === NodeClass.Variable || this.nodeClass === NodeClass.Object) {
const voThis = this as UAObject | UAVariable;
if (voThis.typeDefinition) {
constructorOptions.references.push(
new ReferenceImpl({
isForward: true,
nodeId: voThis.typeDefinition,
referenceType: resolveNodeId("HasTypeDefinition")
})
);
}
}
if (!constructorOptions.modellingRule) {
if (this.modellingRule && options.copyAlsoModellingRules) {
const modellingRuleNode = this.findReferencesAsObject("HasModellingRule", true)[0];
assert(modellingRuleNode);
constructorOptions.references.push(
new ReferenceImpl({
isForward: true,
nodeId: modellingRuleNode.nodeId,
referenceType: resolveNodeId("HasModellingRule")
})
);
}
} else {
UANamespace_process_modelling_rule(constructorOptions.references, constructorOptions.modellingRule);
}
constructorOptions.nodeId = namespace.constructNodeId(constructorOptions as ConstructNodeIdOptions);
assert(constructorOptions.nodeId instanceof NodeId);
const cloneObj = new Constructor(constructorOptions);
(this.addressSpace as AddressSpacePrivate)._register(cloneObj);
options.copyAlsoModellingRules = options.copyAlsoModellingRules || false;
const newFilter = optionalFilter ? optionalFilter.filterFor(cloneObj) : undefined;
_clone_children_references(this, cloneObj, options.copyAlsoModellingRules, newFilter, extraInfo);
_clone_non_hierarchical_references(this, cloneObj, options.copyAlsoModellingRules, newFilter, extraInfo);
cloneObj.propagate_back_references();
cloneObj.install_extra_properties();
return cloneObj;
}
export function _handle_HierarchicalReference(node: BaseNode, reference: UAReference): void {
const _cache = BaseNode_getCache(node);
if (!reference.isForward) return;
if (_cache._childByNameMap) {
const addressSpace = node.addressSpace;
const referenceType = ReferenceImpl.resolveReferenceType(addressSpace, reference);
if (referenceType) {
const HierarchicalReferencesType = addressSpace.findReferenceType("HierarchicalReferences");
if (referenceType.isSupertypeOf(HierarchicalReferencesType!)) {
assert(reference.isForward);
const targetNode = ReferenceImpl.resolveReferenceNode(addressSpace, reference);
_cache._childByNameMap[targetNode.browseName!.name!.toString()] = targetNode;
}
}
}
}
function _remove_HierarchicalReference(node: BaseNode, reference: UAReference) {
const _cache = BaseNode_getCache(node);
if (_cache._childByNameMap) {
const addressSpace = node.addressSpace;
const referenceType = ReferenceImpl.resolveReferenceType(addressSpace, reference);
if (referenceType) {
const HierarchicalReferencesType = addressSpace.findReferenceType("HierarchicalReferences");
if (referenceType.isSupertypeOf(HierarchicalReferencesType!)) {
assert(reference.isForward);
const targetNode = ReferenceImpl.resolveReferenceNode(addressSpace, reference);
// Xx console.log(" adding object to map");
delete _cache._childByNameMap[targetNode.browseName!.name!.toString()];
}
}
}
}
function _makeReferenceDescription(addressSpace: IAddressSpace, reference: UAReference, resultMask: number): ReferenceDescription {
const isForward = reference.isForward;
const referenceTypeId = ReferenceImpl.resolveReferenceType(addressSpace, reference).nodeId;
assert(referenceTypeId instanceof NodeId);
const obj = ReferenceImpl.resolveReferenceNode(addressSpace, reference) as any;
let data: any = {};
if (!obj) {
// cannot find reference node
data = {
isForward,
nodeId: reference.nodeId,
referenceTypeId: resultMask & ResultMask.ReferenceType ? referenceTypeId : null,
typeDefinition: null
};
} else {
assert(reference.nodeId, " obj.nodeId");
data = {
browseName: resultMask & ResultMask.BrowseName ? coerceQualifiedName(obj.browseName) : null,
displayName: resultMask & ResultMask.DisplayName ? coerceLocalizedText(obj.displayName[0]) : null,
isForward: resultMask & ResultMask.IsForward ? isForward : false,
nodeClass: resultMask & ResultMask.NodeClass ? obj.nodeClass : NodeClass.Unspecified,
nodeId: obj.nodeId,
referenceTypeId: resultMask & ResultMask.ReferenceType ? referenceTypeId : null,
typeDefinition: resultMask & ResultMask.TypeDefinition ? obj.typeDefinition : null
};
}
if (data.typeDefinition === null) {
data.typeDefinition = NodeId.nullNodeId;
}
const referenceDescription = new ReferenceDescription(data);
return referenceDescription;
}
export function _constructReferenceDescription(
addressSpace: IAddressSpace,
references: UAReference[],
resultMask: number
): ReferenceDescription[] {
assert(Array.isArray(references));
return references.map((reference: UAReference) => _makeReferenceDescription(addressSpace, reference, resultMask));
}
export function BaseNode_remove_backward_reference(this: BaseNode, reference: UAReference): void {
const _private = BaseNode_getPrivate(this);
_remove_HierarchicalReference(this, reference);
const h = (<ReferenceImpl>reference).hash;
if (_private._back_referenceIdx && _private._back_referenceIdx[h]) {
// note : h may not exist in _back_referenceIdx since we are not indexing
// _back_referenceIdx to UAObjectType and UAVariableType for performance reasons
(<ReferenceImpl>_private._back_referenceIdx[h]).dispose();
delete _private._back_referenceIdx[h];
}
(<ReferenceImpl>reference).dispose();
}
export function BaseNode_add_backward_reference(this: BaseNode, reference: UAReference): void {
const _private = BaseNode_getPrivate(this);
const h = (<ReferenceImpl>reference).hash;
assert(typeof h === "string");
// istanbul ignore next
if (_private._referenceIdx[h]) {
// the reference exists already in the forward references
// this append for instance when the XML NotSetFile has redundant <UAReference>
// in this case there is nothing to do
return;
}
// istanbul ignore next
if (_private._back_referenceIdx[h]) {
const opts = { addressSpace: this.addressSpace };
// tslint:disable-next-line:no-console
console.warn(" Warning !", this.browseName.toString());
// tslint:disable-next-line:no-console
console.warn(" ", reference.toString(opts));
// tslint:disable-next-line:no-console
console.warn(" already found in ===>");
// tslint:disable-next-line:no-console
console.warn(
(Object.values(_private._back_referenceIdx) as UAReference[]).map((c: UAReference) => c.toString(opts)).join("\n")
);
// tslint:disable-next-line:no-console
console.warn("===>");
throw new Error("reference exists already in _back_references");
}
if (!getReferenceType(reference)) {
const stop_here = 1;
}
// assert(reference._referenceType instanceof ReferenceType);
_private._back_referenceIdx[h] = reference;
_handle_HierarchicalReference(this, reference);
(this as any)._clear_caches();
} | the_stack |
import * as React from 'react';
export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
export interface Position {
x: number;
y: number;
}
export interface BoxModel {
// content + padding + border + margin
marginBox: Rect;
// content + padding + border
borderBox: Rect;
// content + padding
paddingBox: Rect;
// content
contentBox: Rect;
// for your own consumption
border: Spacing;
padding: Spacing;
margin: Spacing;
}
// This is an extension of DOMRect and ClientRect
export interface Rect {
// ClientRect
top: number;
right: number;
bottom: number;
left: number;
width: number;
height: number;
// DOMRect
x: number;
y: number;
// Rect
center: Position;
}
export interface Spacing {
top: number;
right: number;
bottom: number;
left: number;
}
/**
* IDs
*/
export type Id = string;
export type DraggableId = Id;
export type DroppableId = Id;
export type TypeId = Id;
export type ContextId = Id;
export type ElementId = Id;
export type DroppableMode = 'standard' | 'virtual';
export interface DroppableDescriptor {
id: DroppableId;
type: TypeId;
mode: DroppableMode;
}
export interface DraggableDescriptor {
id: DraggableId;
index: number;
// Inherited from Droppable
droppableId: DroppableId;
// This is technically redundant but it avoids
// needing to look up a parent droppable just to get its type
type: TypeId;
}
export interface DraggableOptions {
canDragInteractiveElements: boolean;
shouldRespectForcePress: boolean;
isEnabled: boolean;
}
export type Direction = 'horizontal' | 'vertical';
export interface VerticalAxis {
direction: 'vertical';
line: 'y';
start: 'top';
end: 'bottom';
size: 'height';
crossAxisLine: 'x';
crossAxisStart: 'left';
crossAxisEnd: 'right';
crossAxisSize: 'width';
}
export interface HorizontalAxis {
direction: 'horizontal';
line: 'x';
start: 'left';
end: 'right';
size: 'width';
crossAxisLine: 'y';
crossAxisStart: 'top';
crossAxisEnd: 'bottom';
crossAxisSize: 'height';
}
export type Axis = VerticalAxis | HorizontalAxis;
export interface ScrollSize {
scrollHeight: number;
scrollWidth: number;
}
export interface ScrollDifference {
value: Position;
// The actual displacement as a result of a scroll is in the opposite
// direction to the scroll itself. When scrolling down items are displaced
// upwards. This value is the negated version of the 'value'
displacement: Position;
}
export interface ScrollDetails {
initial: Position;
current: Position;
// the maximum allowable scroll for the frame
max: Position;
diff: ScrollDifference;
}
export interface Placeholder {
client: BoxModel;
tagName: string;
display: string;
}
export interface DraggableDimension {
descriptor: DraggableDescriptor;
// the placeholder for the draggable
placeholder: Placeholder;
// relative to the viewport when the drag started
client: BoxModel;
// relative to the whole page
page: BoxModel;
// how much displacement the draggable causes
// this is the size of the marginBox
displaceBy: Position;
}
export interface Scrollable {
// This is the window through which the droppable is observed
// It does not change during a drag
pageMarginBox: Rect;
// Used for comparision with dynamic recollecting
frameClient: BoxModel;
scrollSize: ScrollSize;
// Whether or not we should clip the subject by the frame
// Is controlled by the ignoreContainerClipping prop
shouldClipSubject: boolean;
scroll: ScrollDetails;
}
export interface PlaceholderInSubject {
// might not actually be increased by
// placeholder if there is no required space
increasedBy?: Position | undefined;
placeholderSize: Position;
// max scroll before placeholder added
// will be null if there was no frame
oldFrameMaxScroll?: Position | undefined;
}
export interface DroppableSubject {
// raw, unchanging
page: BoxModel;
withPlaceholder?: PlaceholderInSubject | undefined;
// The hitbox for a droppable
// - page margin box
// - with scroll changes
// - with any additional droppable placeholder
// - clipped by frame
// The subject will be null if the hit area is completely empty
active?: Rect | undefined;
}
export interface DroppableDimension {
descriptor: DroppableDescriptor;
axis: Axis;
isEnabled: boolean;
isCombineEnabled: boolean;
// relative to the current viewport
client: BoxModel;
// relative to the whole page
isFixedOnPage: boolean;
// relative to the page
page: BoxModel;
// The container of the droppable
frame?: Scrollable | undefined;
// what is visible through the frame
subject: DroppableSubject;
}
export interface DraggableLocation {
droppableId: DroppableId;
index: number;
}
export interface DraggableIdMap {
[id: string]: true;
}
export interface DroppableIdMap {
[id: string]: true;
}
export interface DraggableDimensionMap {
[key: string]: DraggableDimension;
}
export interface DroppableDimensionMap {
[key: string]: DroppableDimension;
}
export interface Displacement {
draggableId: DraggableId;
shouldAnimate: boolean;
}
export interface DisplacementMap {
[key: string]: Displacement;
}
export interface DisplacedBy {
value: number;
point: Position;
}
export type VerticalUserDirection = 'up' | 'down';
export type HorizontalUserDirection = 'left' | 'right';
export interface UserDirection {
vertical: VerticalUserDirection;
horizontal: HorizontalUserDirection;
}
// details of the item that is being combined with
export interface Combine {
draggableId: DraggableId;
droppableId: DroppableId;
}
export interface DisplacementGroups {
all: DraggableId[];
visible: DisplacementMap;
invisible: DraggableIdMap;
}
export interface ReorderImpact {
type: 'REORDER';
destination: DraggableLocation;
}
export interface CombineImpact {
type: 'COMBINE';
whenEntered: UserDirection;
combine: Combine;
}
export type ImpactLocation = ReorderImpact | CombineImpact;
export interface Displaced {
forwards: DisplacementGroups;
backwards: DisplacementGroups;
}
export interface DragImpact {
displaced: DisplacementGroups;
displacedBy: DisplacedBy;
at?: ImpactLocation | undefined;
}
export interface ClientPositions {
// where the user initially selected
// This point is not used to calculate the impact of a dragging item
// It is used to calculate the offset from the initial selection point
selection: Position;
// the current center of the item
borderBoxCenter: Position;
// how far the item has moved from its original position
offset: Position;
}
export interface PagePositions {
selection: Position;
borderBoxCenter: Position;
}
// There are two seperate modes that a drag can be in
// FLUID: everything is done in response to highly granular input (eg mouse)
// SNAP: items move in response to commands (eg keyboard);
export type MovementMode = 'FLUID' | 'SNAP';
export interface DragPositions {
client: ClientPositions;
page: PagePositions;
}
export interface DraggableRubric {
draggableId: DraggableId;
mode: MovementMode;
source: DraggableLocation;
}
export interface DragStart extends BeforeCapture {
type: TypeId;
source: DraggableLocation;
}
// Published in onBeforeCapture
// We cannot give more information as things might change in the
// onBeforeCapture responder!
export interface BeforeCapture {
draggableId: DraggableId;
mode: MovementMode;
}
// published when a drag starts
export interface DragStart extends DraggableRubric {
mode: MovementMode;
}
export interface DragUpdate extends DragStart {
// may not have any destination (drag to nowhere)
destination?: DraggableLocation | undefined;
// populated when a draggable is dragging over another in combine mode
combine?: Combine | undefined;
}
export type DropReason = 'DROP' | 'CANCEL';
export interface DropResult extends DragUpdate {
reason: DropReason;
}
export interface ScrollOptions {
shouldPublishImmediately: boolean;
}
// using the draggable id rather than the descriptor as the descriptor
// may change as a result of the initial flush. This means that the lift
// descriptor may not be the same as the actual descriptor. To avoid
// confusion the request is just an id which is looked up
// in the dimension-marshal post-flush
// Not including droppableId as it might change in a drop flush
export interface LiftRequest {
draggableId: DraggableId;
scrollOptions: ScrollOptions;
}
export interface Critical {
draggable: DraggableDescriptor;
droppable: DroppableDescriptor;
}
export interface Viewport {
// live updates with the latest values
frame: Rect;
scroll: ScrollDetails;
}
export interface LiftEffect {
inVirtualList: boolean;
effected: DraggableIdMap;
displacedBy: DisplacedBy;
}
export interface DimensionMap {
draggables: DraggableDimensionMap;
droppables: DroppableDimensionMap;
}
export interface DroppablePublish {
droppableId: DroppableId;
scroll: Position;
}
export interface Published {
additions: DraggableDimension[];
removals: DraggableId[];
modified: DroppablePublish[];
}
export interface CompletedDrag {
critical: Critical;
result: DropResult;
impact: DragImpact;
afterCritical: LiftEffect;
}
export interface IdleState {
phase: 'IDLE';
completed?: CompletedDrag | undefined;
shouldFlush: boolean;
}
export interface DraggingState {
phase: 'DRAGGING';
isDragging: true;
critical: Critical;
movementMode: MovementMode;
dimensions: DimensionMap;
initial: DragPositions;
current: DragPositions;
userDirection: UserDirection;
impact: DragImpact;
viewport: Viewport;
afterCritical: LiftEffect;
onLiftImpact: DragImpact;
// when there is a fixed list we want to opt out of this behaviour
isWindowScrollAllowed: boolean;
// if we need to jump the scroll (keyboard dragging)
scrollJumpRequest?: Position | undefined;
// whether or not draggable movements should be animated
forceShouldAnimate?: boolean | undefined;
}
// While dragging we can enter into a bulk collection phase
// During this phase no drag updates are permitted.
// If a drop occurs during this phase, it must wait until it is
// completed before continuing with the drop
// TODO: rename to BulkCollectingState
export interface CollectingState extends Omit<DraggingState, 'phase'> {
phase: 'COLLECTING';
}
// If a drop action occurs during a bulk collection we need to
// wait for the collection to finish before performing the drop.
// This is to ensure that everything has the correct index after
// a drop
export interface DropPendingState extends Omit<DraggingState, 'phase'> {
phase: 'DROP_PENDING';
isWaiting: boolean;
reason: DropReason;
}
// An optional phase for animating the drop / cancel if it is needed
export interface DropAnimatingState {
phase: 'DROP_ANIMATING';
completed: CompletedDrag;
newHomeClientOffset: Position;
dropDuration: number;
// We still need to render placeholders and fix the dimensions of the dragging item
dimensions: DimensionMap;
}
export type State = IdleState | DraggingState | CollectingState | DropPendingState | DropAnimatingState;
export type StateWhenUpdatesAllowed = DraggingState | CollectingState;
export type Announce = (message: string) => void;
export type InOutAnimationMode = 'none' | 'open' | 'close';
export interface ResponderProvided {
announce: Announce;
}
export type OnBeforeCaptureResponder = (before: BeforeCapture) => void;
export type OnBeforeDragStartResponder = (start: DragStart) => void;
export type OnDragStartResponder = (start: DragStart, provided: ResponderProvided) => void;
export type OnDragUpdateResponder = (update: DragUpdate, provided: ResponderProvided) => void;
export type OnDragEndResponder = (result: DropResult, provided: ResponderProvided) => void;
export interface Responders {
onBeforeCapture?: OnBeforeCaptureResponder | undefined;
onBeforeDragStart?: OnBeforeDragStartResponder | undefined;
onDragStart?: OnDragStartResponder | undefined;
onDragUpdate?: OnDragUpdateResponder | undefined;
// always required
onDragEnd: OnDragEndResponder;
}
export interface StopDragOptions {
shouldBlockNextClick: boolean;
}
export interface DragActions {
drop: (args?: StopDragOptions) => void;
cancel: (args?: StopDragOptions) => void;
isActive: () => boolean;
shouldRespectForcePress: () => boolean;
}
export interface FluidDragActions extends DragActions {
move: (clientSelection: Position) => void;
}
export interface SnapDragActions extends DragActions {
moveUp: () => void;
moveDown: () => void;
moveRight: () => void;
moveLeft: () => void;
}
export interface PreDragActions {
// discover if the lock is still active
isActive: () => boolean;
// whether it has been indicated if force press should be respected
shouldRespectForcePress: () => boolean;
// lift the current item
fluidLift: (clientSelection: Position) => FluidDragActions;
snapLift: () => SnapDragActions;
// cancel the pre drag without starting a drag. Releases the lock
abort: () => void;
}
export interface TryGetLockOptions {
sourceEvent?: Event | undefined;
}
export type TryGetLock = (
draggableId: DraggableId,
forceStop?: () => void,
options?: TryGetLockOptions,
) => PreDragActions | null;
export interface SensorAPI {
tryGetLock: TryGetLock;
canGetLock: (id: DraggableId) => boolean;
isLockClaimed: () => boolean;
tryReleaseLock: () => void;
findClosestDraggableId: (event: Event) => DraggableId | null;
findOptionsForDraggable: (id: DraggableId) => DraggableOptions | null;
}
export type Sensor = (api: SensorAPI) => void;
/**
* DragDropContext
*/
export interface DragDropContextProps {
children?: React.ReactNode;
onBeforeCapture?(before: BeforeCapture): void;
onBeforeDragStart?(initial: DragStart): void;
onDragStart?(initial: DragStart, provided: ResponderProvided): void;
onDragUpdate?(initial: DragUpdate, provided: ResponderProvided): void;
onDragEnd(result: DropResult, provided: ResponderProvided): void;
sensors?: Sensor[] | undefined;
}
export class DragDropContext extends React.Component<DragDropContextProps> {}
/**
* Droppable
*/
export interface DroppableProvidedProps {
// used for shared global styles
'data-rbd-droppable-context-id': string;
// Used to lookup. Currently not used for drag and drop lifecycle
'data-rbd-droppable-id': DroppableId;
}
export interface DroppableProvided {
innerRef(element: HTMLElement | null): any;
placeholder?: React.ReactElement<HTMLElement> | null | undefined;
droppableProps: DroppableProvidedProps;
}
export interface DroppableStateSnapshot {
isDraggingOver: boolean;
draggingOverWith?: DraggableId | undefined;
draggingFromThisWith?: DraggableId | undefined;
isUsingPlaceholder: boolean;
}
export interface DroppableProps {
droppableId: DroppableId;
type?: TypeId | undefined;
mode?: DroppableMode | undefined;
isDropDisabled?: boolean | undefined;
isCombineEnabled?: boolean | undefined;
direction?: Direction | undefined;
ignoreContainerClipping?: boolean | undefined;
renderClone?: DraggableChildrenFn | undefined;
getContainerForClone?: (() => React.ReactElement<HTMLElement>) | undefined;
children(provided: DroppableProvided, snapshot: DroppableStateSnapshot): React.ReactElement<HTMLElement>;
}
export class Droppable extends React.Component<DroppableProps> {}
/**
* Draggable
*/
export interface DropAnimation {
duration: number;
curve: string;
moveTo: Position;
opacity?: number | undefined;
scale?: number | undefined;
}
export interface NotDraggingStyle {
transform?: string | undefined;
transition?: 'none' | undefined;
}
export interface DraggingStyle {
position: 'fixed';
top: number;
left: number;
boxSizing: 'border-box';
width: number;
height: number;
transition: 'none';
transform?: string | undefined;
zIndex: number;
opacity?: number | undefined;
pointerEvents: 'none';
}
export interface DraggableProvidedDraggableProps {
// inline style
style?: DraggingStyle | NotDraggingStyle | undefined;
// used for shared global styles
'data-rbd-draggable-context-id': string;
'data-rbd-draggable-id': string;
onTransitionEnd?: React.TransitionEventHandler<any> | undefined;
}
export interface DraggableProvidedDragHandleProps {
'data-rbd-drag-handle-draggable-id': DraggableId;
'data-rbd-drag-handle-context-id': ContextId;
'aria-labelledby': ElementId;
tabIndex: number;
draggable: boolean;
onDragStart: React.DragEventHandler<any>;
}
export interface DraggableProvided {
// will be removed after move to react 16
innerRef(element?: HTMLElement | null): any;
draggableProps: DraggableProvidedDraggableProps;
dragHandleProps?: DraggableProvidedDragHandleProps | undefined;
}
export interface DraggableStateSnapshot {
isDragging: boolean;
isDropAnimating: boolean;
dropAnimation?: DropAnimation | undefined;
draggingOver?: DroppableId | undefined;
// the id of a draggable that you are combining with
combineWith?: DraggableId | undefined;
// a combine target is being dragged over by
combineTargetFor?: DraggableId | undefined;
// What type of movement is being done: 'FLUID' or 'SNAP'
mode?: MovementMode | undefined;
}
export type DraggableChildrenFn = (
provided: DraggableProvided,
snapshot: DraggableStateSnapshot,
rubric: DraggableRubric,
) => React.ReactElement<HTMLElement>;
export interface DraggableProps {
draggableId: DraggableId;
index: number;
children: DraggableChildrenFn;
isDragDisabled?: boolean | undefined;
disableInteractiveElementBlocking?: boolean | undefined;
shouldRespectForcePress?: boolean | undefined;
}
export class Draggable extends React.Component<DraggableProps> {}
export function resetServerContext(): void; | the_stack |
import { deepEqual } from 'assert';
import { expect } from 'chai';
import { firstValueFrom } from 'rxjs';
import { take, toArray } from 'rxjs/operators';
import { AccountRepository, MultisigRepository, NamespaceRepository, Order, RepositoryCallError } from '../../src/infrastructure';
import { AccountPaginationStreamer } from '../../src/infrastructure/paginationStreamer';
import { AccountOrderBy } from '../../src/infrastructure/searchCriteria';
import { UInt64 } from '../../src/model';
import { Account, Address } from '../../src/model/account';
import { PlainMessage } from '../../src/model/message';
import { AliasAction, NamespaceId } from '../../src/model/namespace';
import { NetworkType } from '../../src/model/network';
import {
AddressAliasTransaction,
AggregateTransaction,
Deadline,
MultisigAccountModificationTransaction,
NamespaceRegistrationTransaction,
TransferTransaction,
} from '../../src/model/transaction';
import { IntegrationTestHelper } from './IntegrationTestHelper';
describe('AccountHttp', () => {
const helper = new IntegrationTestHelper();
let account: Account;
let account2: Account;
let multisigAccount: Account;
let cosignAccount1: Account;
let cosignAccount2: Account;
let cosignAccount3: Account;
let accountAddress: Address;
let accountPublicKey: string;
let accountRepository: AccountRepository;
let multisigRepository: MultisigRepository;
let namespaceRepository: NamespaceRepository;
let namespaceId: NamespaceId;
let generationHash: string;
let networkType: NetworkType;
before(() => {
return helper.start({ openListener: true }).then(() => {
account = helper.account;
account2 = helper.account2;
multisigAccount = helper.multisigAccount;
cosignAccount1 = helper.cosignAccount1;
cosignAccount2 = helper.cosignAccount2;
cosignAccount3 = helper.cosignAccount3;
accountAddress = helper.account.address;
accountPublicKey = helper.account.publicKey;
generationHash = helper.generationHash;
networkType = helper.networkType;
accountRepository = helper.repositoryFactory.createAccountRepository();
multisigRepository = helper.repositoryFactory.createMultisigRepository();
namespaceRepository = helper.repositoryFactory.createNamespaceRepository();
});
});
after(() => {
return helper.close();
});
/**
* =========================
* Setup test data
* =========================
*/
describe('Make sure test account is not virgin', () => {
it('Announce TransferTransaction', () => {
const transferTransaction = TransferTransaction.create(
Deadline.create(helper.epochAdjustment),
account2.address,
[helper.createCurrency(1, false)],
PlainMessage.create('test-message'),
networkType,
helper.maxFee,
);
const signedTransaction = transferTransaction.signWith(account, generationHash);
return helper.announce(signedTransaction);
});
});
describe('Setup test NamespaceId', () => {
it('Announce NamespaceRegistrationTransaction', () => {
const namespaceName = 'root-test-namespace-' + Math.floor(Math.random() * 10000);
const registerNamespaceTransaction = NamespaceRegistrationTransaction.createRootNamespace(
Deadline.create(helper.epochAdjustment),
namespaceName,
UInt64.fromUint(9),
networkType,
helper.maxFee,
);
namespaceId = new NamespaceId(namespaceName);
const signedTransaction = registerNamespaceTransaction.signWith(account, generationHash);
return helper.announce(signedTransaction);
});
});
describe('Setup test AddressAlias', () => {
it('Announce addressAliasTransaction', () => {
const addressAliasTransaction = AddressAliasTransaction.create(
Deadline.create(helper.epochAdjustment),
AliasAction.Link,
namespaceId,
account.address,
networkType,
helper.maxFee,
);
const signedTransaction = addressAliasTransaction.signWith(account, generationHash);
return helper.announce(signedTransaction);
});
});
describe('Setup test multisig account', () => {
it('Announce MultisigAccountModificationTransaction', () => {
const modifyMultisigAccountTransaction = MultisigAccountModificationTransaction.create(
Deadline.create(helper.epochAdjustment),
2,
1,
[cosignAccount1.address, cosignAccount2.address, cosignAccount3.address],
[],
networkType,
helper.maxFee,
);
const aggregateTransaction = AggregateTransaction.createComplete(
Deadline.create(helper.epochAdjustment),
[modifyMultisigAccountTransaction.toAggregate(multisigAccount.publicAccount)],
networkType,
[],
helper.maxFee,
);
const signedTransaction = aggregateTransaction.signTransactionWithCosignatories(
multisigAccount,
[cosignAccount1, cosignAccount2, cosignAccount3],
generationHash,
);
return helper.announce(signedTransaction);
});
});
/**
* =========================
* Tests
* =========================
*/
describe('getAccountInfo', () => {
it('should return account data given a NEM Address', async () => {
const accountInfo = await firstValueFrom(accountRepository.getAccountInfo(accountAddress));
expect(accountInfo.publicKey).to.be.equal(accountPublicKey);
const merkleInfo = await firstValueFrom(accountRepository.getAccountInfoMerkle(accountInfo.address));
expect(merkleInfo.raw).to.not.be.undefined;
});
});
describe('getAccountsInfo', () => {
it('should return account data given a NEM Address', async () => {
const accountsInfo = await firstValueFrom(accountRepository.getAccountsInfo([accountAddress]));
expect(accountsInfo[0].publicKey).to.be.equal(accountPublicKey);
});
});
describe('searchAccount', () => {
it('should return account info', async () => {
const info = await firstValueFrom(accountRepository.search({}));
expect(info.data.length).to.be.greaterThan(0);
});
});
describe('searchAccount with streamer', () => {
it('should return account info', async () => {
const streamer = new AccountPaginationStreamer(accountRepository);
const infoStreamer = await firstValueFrom(
streamer.search({ pageSize: 20, order: Order.Asc, orderBy: AccountOrderBy.Id }).pipe(take(20), toArray()),
);
const info = await firstValueFrom(accountRepository.search({ pageSize: 20, order: Order.Asc, orderBy: AccountOrderBy.Id }));
expect(infoStreamer.length).to.be.greaterThan(0);
deepEqual(infoStreamer[0], info.data[0]);
});
});
describe('transactions', () => {
it('should not return accounts when account does not exist', () => {
return firstValueFrom(accountRepository.getAccountInfo(Account.generateNewAccount(networkType).address)).then(
() => {
return Promise.reject('should fail!');
},
(err) => {
const error: RepositoryCallError = JSON.parse(err.message);
expect(error.statusCode).to.be.eq(404);
expect(error.statusMessage).to.be.eq('Not Found');
return Promise.resolve();
},
);
});
});
describe('getAddressNames', () => {
it('should call getAddressNames successfully', async () => {
const addressNames = await firstValueFrom(namespaceRepository.getAccountsNames([accountAddress]));
expect(addressNames.length).to.be.greaterThan(0);
});
});
describe('getMultisigAccountGraphInfo', () => {
it('should call getMultisigAccountGraphInfo successfully', async () => {
await new Promise((resolve) => setTimeout(resolve, 3000));
const multisigAccountGraphInfo = await firstValueFrom(
multisigRepository.getMultisigAccountGraphInfo(multisigAccount.publicAccount.address),
);
expect(multisigAccountGraphInfo.multisigEntries.get(0)![0].accountAddress.plain()).to.be.equal(multisigAccount.address.plain());
});
});
describe('getMultisigAccountInfo', () => {
it('should call getMultisigAccountInfo successfully', async () => {
const multisigAccountInfo = await firstValueFrom(
multisigRepository.getMultisigAccountInfo(multisigAccount.publicAccount.address),
);
expect(multisigAccountInfo.accountAddress.plain()).to.be.equal(multisigAccount.address.plain());
});
});
/**
* =========================
* House Keeping
* =========================
*/
describe('Remove test AddressAlias', () => {
it('Announce addressAliasTransaction', () => {
const addressAliasTransaction = AddressAliasTransaction.create(
Deadline.create(helper.epochAdjustment),
AliasAction.Unlink,
namespaceId,
account.address,
networkType,
helper.maxFee,
);
const signedTransaction = addressAliasTransaction.signWith(account, generationHash);
return helper.announce(signedTransaction);
});
});
describe('Restore test multisig Accounts', () => {
it('Announce MultisigAccountModificationTransaction', () => {
const removeCosigner1 = MultisigAccountModificationTransaction.create(
Deadline.create(helper.epochAdjustment),
-1,
0,
[],
[cosignAccount1.address],
networkType,
helper.maxFee,
);
const removeCosigner2 = MultisigAccountModificationTransaction.create(
Deadline.create(helper.epochAdjustment),
0,
0,
[],
[cosignAccount2.address],
networkType,
helper.maxFee,
);
const removeCosigner3 = MultisigAccountModificationTransaction.create(
Deadline.create(helper.epochAdjustment),
-1,
-1,
[],
[cosignAccount3.address],
networkType,
helper.maxFee,
);
const aggregateTransaction = AggregateTransaction.createComplete(
Deadline.create(helper.epochAdjustment),
[
removeCosigner1.toAggregate(multisigAccount.publicAccount),
removeCosigner2.toAggregate(multisigAccount.publicAccount),
removeCosigner3.toAggregate(multisigAccount.publicAccount),
],
networkType,
[],
helper.maxFee,
);
const signedTransaction = aggregateTransaction.signTransactionWithCosignatories(
cosignAccount1,
[cosignAccount2, cosignAccount3],
generationHash,
);
return helper.announce(signedTransaction);
});
});
}); | the_stack |
import React, { useMemo } from 'react';
import PropTypes from 'prop-types';
import { Transition } from 'react-transition-group';
import { createDataProp, OneOf, isComponentType } from '@leafygreen-ui/lib';
import { useUsingKeyboardContext } from '@leafygreen-ui/leafygreen-provider';
import { isComponentGlyph } from '@leafygreen-ui/icon';
import ChevronRight from '@leafygreen-ui/icon/dist/ChevronRight';
import { prefersReducedMotion } from '@leafygreen-ui/a11y';
import { uiColors } from '@leafygreen-ui/palette';
import { css, cx } from '@leafygreen-ui/emotion';
import { spacing } from '@leafygreen-ui/tokens';
import { useIdAllocator } from '@leafygreen-ui/hooks';
import CollapsedSideNavItem from './CollapsedSideNavItem';
import {
ulStyleOverrides,
sideNavItemSidePadding,
getIndentLevelStyle,
} from './styles';
import { useSideNavContext } from './SideNavContext';
const button = createDataProp('side-nav-group-button');
const listItemStyle = css`
display: flex;
flex-direction: column;
position: relative;
& ~ & > ${button.selector} {
padding: 16px ${sideNavItemSidePadding}px 8px ${sideNavItemSidePadding}px;
}
`;
const labelStyle = css`
position: relative;
display: flex;
align-items: center;
justify-content: space-between;
font-size: 12px;
line-height: 1em;
letter-spacing: 0.3px;
font-weight: bold;
text-transform: uppercase;
color: ${uiColors.green.dark2};
min-height: ${spacing[5]}px;
margin-top: 0;
margin-bottom: 0;
padding: 8px 16px;
&:not(:first-of-type) {
margin-top: ${spacing[1]}px;
}
`;
const collapsibleLabelStyle = css`
background-color: transparent;
border: none;
margin: 0px;
transition: border-color 150ms ease-in-out, color 150ms ease-in-out;
cursor: pointer;
border-bottom: 1px solid ${uiColors.gray.light2};
&:hover {
border-color: ${uiColors.green.base};
}
&:focus {
outline: none;
}
`;
const customIconStyles = css`
margin-right: ${spacing[2]}px;
// When the glyph is the last child, we remove the margin
// used to space it from the text. This matters in the navigation
// collapsed state.
&:last-child {
margin-right: 0;
}
`;
const collapsibleHeaderFocusStyle = css`
&:focus {
color: ${uiColors.blue.dark3};
border-color: ${uiColors.focus};
background-color: ${uiColors.blue.light2};
& svg {
color: ${uiColors.blue.base};
}
}
`;
const expandIconStyle = css`
transition: 150ms all ease-in-out;
margin-left: ${spacing[2]}px;
${prefersReducedMotion(`
transition: none;
`)}
`;
const openExpandIconStyle = css`
transform: rotate(90deg);
`;
const defaultStyle = css`
transition: all 150ms ease-in-out;
max-height: 0;
overflow: hidden;
opacity: 1;
${prefersReducedMotion(`
transition: opacity 150ms ease-in-out;
`)}
`;
const transitionStyles = {
entering: css`
opacity: 0;
`,
exiting: css`
opacity: 0;
`,
exited: css`
opacity: 0;
`,
};
interface SideNavGroupBaseProps {
/**
* Class name that will be applied to the root-level element.
*/
className?: string;
/**
* Content that will be rendered as the component's header. If a string is provided,
* it will be rendered with default styling as a header tag.
*/
header?: React.ReactNode;
/**
* Content that will be rendered inside the root-level element.
*/
children?: React.ReactNode;
/**
* Icon that's rendered in the group label.
*/
glyph?: React.ReactNode;
/**
* Manually overrides automatic detection of whether a group contains an active item.
* This is useful for cases when an active item might be wrapped with another component like a Tooltip or routing component.
*/
hasActiveItem?: boolean;
indentLevel?: number;
}
type CollapsedProps = OneOf<
{
/**
* Determines whether or not the Group can be collapsed.
*
* @defaultValue `false`
*/
collapsible: true;
/**
* If collapsible, determines whether or not the group should be expanded or collapsed by default.
*
* @defaultValue `true`
*/
initialCollapsed?: boolean;
},
{
collapsible?: false;
}
>;
export type SideNavGroupProps = CollapsedProps & SideNavGroupBaseProps;
/**
* # SideNavGroup
*
* ```
<SideNavGroup headerText="Section Header">
<SideNavItem href="/">
Back to Home
</SideNavItem>
</SideNavGroup>
* ```
*
* @param props.className Class name that will be applied to the root-level element.
* @param props.header Content that will be rendered as the component's header
* If a string is provided, it will be rendered with default styling as a header tag.
* @param props.children Class name that will be applied to the component's header.
* @param props.collapsible Determines whether or not the Group can be collapsed. @defaultValue false
* @param props.initialCollapsed Determines whether or not the Group is open by default. @defaultValue true
*/
function SideNavGroup({
header,
children,
collapsible = false,
initialCollapsed = true,
glyph,
className,
hasActiveItem,
indentLevel = 0,
...rest
}: SideNavGroupProps) {
const [open, setOpen] = React.useState(!initialCollapsed);
const nodeRef = React.useRef(null);
const ulRef = React.useRef<HTMLUListElement>(null);
const { usingKeyboard: showFocus } = useUsingKeyboardContext();
const menuGroupLabelId = useIdAllocator({ prefix: 'menu-group-label-id' });
const menuId = useIdAllocator({ prefix: 'menu' });
const { width } = useSideNavContext();
const renderedChildren = useMemo(() => {
const checkForNestedGroups = (children: React.ReactNode) => {
return React.Children.map(children, child => {
if (
isComponentType(child, 'SideNavGroup') ||
isComponentType(child, 'SideNavItem')
) {
return React.cloneElement(child, {
indentLevel: indentLevel + 1,
});
} else if ((child as React.ReactElement)?.props?.children) {
checkForNestedGroups((child as React.ReactElement).props.children);
return child;
} else {
return child;
}
});
};
return checkForNestedGroups(children);
}, [children, indentLevel]);
const isActiveGroup: boolean = useMemo(() => {
if (hasActiveItem != null) {
return hasActiveItem;
}
const checkForActiveNestedItems = (children: React.ReactNode): boolean => {
let foundActiveChild = false;
React.Children.forEach(children, child => {
if (isComponentType(child, 'SideNavItem') && child.props.active) {
foundActiveChild = true;
setOpen(true);
} else if ((child as React.ReactElement)?.props?.children) {
checkForActiveNestedItems(
(child as React.ReactElement).props.children,
);
}
});
return foundActiveChild;
};
return checkForActiveNestedItems(children);
}, [hasActiveItem, children]);
const accessibleGlyph =
glyph && (isComponentGlyph(glyph) || isComponentType(glyph, 'Icon'))
? React.cloneElement(glyph, {
className: cx(customIconStyles, glyph.props.className),
role: 'presentation',
'data-testid': 'side-nav-group-header-icon',
})
: null;
const renderedLabelText = (
<div
className={css`
display: inline-flex;
align-items: center;
`}
>
{accessibleGlyph && (
<>
{accessibleGlyph}
<CollapsedSideNavItem active={isActiveGroup}>
{accessibleGlyph}
</CollapsedSideNavItem>
</>
)}
{/** We wrap the text in a span here to allow us to style based
* on the glyph being the last child of its parent.
* Text nodes aren't considered children.
* */}
<span>{header}</span>
</div>
);
const intentedStyle = cx(
getIndentLevelStyle(indentLevel),
css`
padding-top: 16px;
padding-bottom: 8px;
`,
);
if (collapsible) {
return (
<li className={cx(listItemStyle, className)} {...rest}>
<button
{...button.prop}
aria-controls={menuId}
aria-expanded={open}
className={cx(
labelStyle,
collapsibleLabelStyle,
css`
width: ${width}px;
`,
{
[collapsibleHeaderFocusStyle]: showFocus,
[intentedStyle]: indentLevel > 1,
},
)}
onClick={() => setOpen(curr => !curr)}
id={menuGroupLabelId}
data-testid="side-nav-group-header-label"
>
{renderedLabelText}
<ChevronRight
role="presentation"
size={12}
className={cx(expandIconStyle, {
[openExpandIconStyle]: open,
})}
/>
</button>
<Transition
in={open}
appear
timeout={150}
nodeRef={nodeRef}
mountOnEnter
unmountOnExit
>
{(state: string) => (
<div
ref={nodeRef}
className={cx(defaultStyle, {
[transitionStyles.entering]: state === 'entering',
[css`
opacity: 1;
max-height: ${ulRef?.current?.getBoundingClientRect()
.height}px;
border-bottom: 1px solid ${uiColors.gray.light2};
`]: state === 'entered',
[transitionStyles.exiting]: state === 'exiting',
[transitionStyles.exited]: state === 'exited',
})}
>
<ul
ref={ulRef}
id={menuId}
aria-labelledby={menuGroupLabelId}
className={cx(
ulStyleOverrides,
css`
transition: opacity 150ms ease-in-out;
opacity: 0;
`,
{
[css`
opacity: 1;
`]: ['entering', 'entered'].includes(state),
},
)}
>
{renderedChildren}
</ul>
</div>
)}
</Transition>
</li>
);
}
return (
<li className={cx(listItemStyle, className)} {...rest}>
<div
{...button.prop}
data-testid="side-nav-group-header-label"
id={menuGroupLabelId}
className={cx(labelStyle, {
[intentedStyle]: indentLevel > 1,
})}
>
{renderedLabelText}
</div>
<ul aria-labelledby={menuGroupLabelId} className={ulStyleOverrides}>
{renderedChildren}
</ul>
</li>
);
}
SideNavGroup.displayName = 'SideNavGroup';
SideNavGroup.propTypes = {
className: PropTypes.string,
header: PropTypes.oneOfType([
PropTypes.string,
PropTypes.func,
PropTypes.node,
]),
collapsible: PropTypes.bool,
initialCollapsed: PropTypes.bool,
glyph: PropTypes.node,
children: PropTypes.node,
};
export default SideNavGroup; | the_stack |
import { define } from 'elements-sk/define';
import { html } from 'lit-html';
import '../textarea-numbers-sk';
import 'elements-sk/checkbox-sk';
import 'elements-sk/select-sk';
import 'elements-sk/spinner-sk';
import 'elements-sk/icon/play-arrow-icon-sk';
import 'elements-sk/icon/pause-icon-sk';
import '../test-src-sk';
import { fromObject } from 'common-sk/modules/query';
import { jsonOrThrow } from 'common-sk/modules/jsonOrThrow';
import { CheckOrRadio } from 'elements-sk/checkbox-sk/checkbox-sk';
import { SelectSkSelectionChangedEventDetail } from 'elements-sk/select-sk/select-sk';
import { errorMessage } from 'elements-sk/errorMessage';
import 'elements-sk/styles/buttons';
import 'elements-sk/styles/select';
import { SpinnerSk } from 'elements-sk/spinner-sk/spinner-sk';
import { TextareaNumbersSk } from '../textarea-numbers-sk/textarea-numbers-sk';
import { Options, RunResults, FiddleContext } from '../json';
import { ElementSk } from '../../../infra-sk/modules/ElementSk';
// The type for the 'fiddle-success' CustomEvent detail.
export type FiddleSkFiddleSuccessEventDetail = string;
// Config represents the configuration for how the FiddleSk element appears.
export interface Config {
// Should the options be displayed.
display_options: boolean;
// Is this control embedded in another page (as opposed to being on fiddle.skia.org.).
embedded: boolean;
// Should the CPU result be displayed in embedded mode.
cpu_embedded: boolean;
// Should the GPU result be displayed in embedded mode.
gpu_embedded: boolean;
// Should the options details be open, as opposed to just displaying the summary.
options_open: boolean;
// If true then the more esoteric options are removed.
basic_mode: boolean;
// The domain where fiddle is running. Includes scheme, e.g. https://fiddle.skia.org.
domain: string;
// Should a link to create a bug be displayed near the Run button.
bug_link: boolean;
// The ids of the possible input source images.
sources: number[];
// Should animated images continuously loop.
loop: boolean;
// If true then animations are playing, otherwise they're paused.
play: boolean;
}
export class FiddleSk extends ElementSk {
// Private properties.
private _options: Options = {
textOnly: false,
srgb: false,
f16: false,
width: 128,
height: 128,
animated: false,
duration: 5,
offscreen: false,
offscreen_width: 128,
offscreen_height: 128,
offscreen_sample_count: 1,
offscreen_texturable: false,
offscreen_mipmap: false,
source: 0,
source_mipmap: false,
};
private _config: Config = {
display_options: true,
embedded: false,
cpu_embedded: true,
gpu_embedded: true,
options_open: false,
basic_mode: false,
domain: 'https://fiddle.skia.org',
bug_link: false,
sources: [],
loop: true,
play: true,
};
private _runResults: RunResults = {
text: '',
fiddleHash: '',
runtime_error: '',
compile_errors: [],
};
private textarea: TextareaNumbersSk | null = null;
private spinner: SpinnerSk | null = null;
constructor() {
super(FiddleSk.template);
}
private static displayOptions = (ele: FiddleSk) => (!ele._config.display_options
? html``
: html`
<details ?open=${ele._config.options_open}>
<summary>Options</summary>
<div id="options">
<label>
<input
type="number"
min="4"
max="2048"
placeholder="128"
.value=${ele._options.width}
@change=${ele.widthChange}
/>
Width
</label>
<label>
<input
type="number"
min="4"
max="2048"
placeholder="128"
.value=${ele._options.height}
@change=${ele.heightChange}
/>
Height
</label>
<checkbox-sk
id="textonly"
label="Text Only [Use SkDebugf()]"
?checked=${ele._options.textOnly}
?hidden=${ele._config.basic_mode}
@change=${ele.textOnlyChange}
></checkbox-sk>
<checkbox-sk
id="srgb"
label="sRGB"
?checked=${ele._options.srgb}
?disabled=${ele._options.f16}
?hidden=${ele._config.basic_mode}
@change=${ele.srgbChange}
></checkbox-sk>
<checkbox-sk
id="f16"
title="Half floats"
label="F16"
?checked=${ele._options.f16}
?disabled=${!ele._options.srgb}
?hidden=${ele._config.basic_mode}
@change=${ele.f16Change}
>
</checkbox-sk>
<checkbox-sk
id="animated"
label="Animation"
?checked=${ele._options.animated}
@change=${ele.animatedChange}
></checkbox-sk>
<div ?hidden=${!ele._options.animated} id="animated-options">
<label>
<input
type="number"
min="1"
max="300"
.value=${ele._options.duration}
?disabled=${!ele._options.animated}
@change=${ele.durationChange}
/>
Duration (seconds)
</label>
<div ?hidden=${!ele._options.animated}>
<h4>These globals are now defined:</h4>
<pre class="source-select">
double duration; // The requested duration of the animation.
double frame; // A value in [0, 1] of where we are in the animation.</pre
>
</div>
</div>
<!-- Add offscreen opts here-->
<checkbox-sk
id="offscreen"
title="Create an offscreen render target on the GPU."
label="Offscreen Render Target"
?checked=${ele._options.offscreen}
@change=${ele.offscreenChange}
?hidden=${ele._config.basic_mode}
>
</checkbox-sk>
<div ?hidden=${!ele._options.offscreen} id="offscreen-options">
<label>
<input
type="number"
min="4"
max="2048"
value=${ele._options.offscreen_width}
@change=${ele.offscreenWidthChange}
/>
Width
</label>
<label>
<input
type="number"
min="4"
max="2048"
value=${ele._options.offscreen_height}
@change=${ele.offscreenHeightChange}
/>
Height
</label>
<label>
<input
type="number"
value=${ele._options.offscreen_sample_count}
@change=${ele.offscreenSampleCountChange}
/>
Sample Count
</label>
<checkbox-sk
id="texturable"
label="Texturable"
title="The offscreen render target can be used as a texture."
?checked=${ele._options.offscreen_texturable}
@change=${ele.offscreenTexturableChange}
></checkbox-sk>
<div class="indent">
<checkbox-sk
id="offscreen_mipmap"
label="MipMap"
title="The offscreen render target can be used as a texture that is mipmapped."
?checked=${ele._options.offscreen_mipmap}
?disabled=${!ele._options.offscreen_texturable}
@change=${ele.offscreenMipMapChange}
></checkbox-sk>
</div>
<h4>This global is now defined:</h4>
<pre
class="source-select"
?hidden=${ele._options.offscreen_texturable}
>
GrBackendRenderTarget backEndRenderTarget;</pre
>
<pre
class="source-select"
?hidden=${!ele._options.offscreen_texturable}
>
GrBackendTexture backEndTextureRenderTarget;</pre
>
</div>
<h3>Optional source image</h3>
<select-sk @selection-changed=${ele.sourceChange}>
${ele._config.sources.map((source) => html`
<img
width="64"
height="64"
?selected=${source === ele._options.source}
name=${source}
src="${ele._config.domain}/s/${source}"
class="imgsrc"
/>
`)}
</select-sk>
<div ?hidden=${!ele._options.source} class="offset">
<checkbox-sk
label="MipMap"
title="The backEndTexture is mipmapped."
?checked=${ele._options.source_mipmap}
@change=${ele.sourceMipMapChange}
></checkbox-sk>
<h4>These globals are now defined:</h4>
<pre class="source-select">
SkBitmap source;
sk_sp<SkImage> image;
GrBackendTexture backEndTexture; // GPU Only.</pre
>
</div>
</div>
</details>
`);
private static actions = (ele: FiddleSk) => html`
<div id="submit">
<button class="action" @click=${ele.run}>Run</button>
<spinner-sk></spinner-sk>
<a
?hidden=${!ele._config.embedded}
href="https://fiddle.skia.org/c/${ele._runResults.fiddleHash}"
target="_blank"
>Pop-out</a
>
<a
id="bug"
?hidden=${!ele._config.bug_link}
target="_blank"
href=${ele.bugReportingURL(ele._runResults.fiddleHash)}
>File Bug</a
>
<details id="embed" ?hidden=${ele._config.basic_mode}>
<summary>Embed</summary>
<h3>Embed as an image with a backlink:</h3>
<input
type="text"
readonly
size="150"
value="<a href='https://fiddle.skia.org/c/${ele._runResults
.fiddleHash}'><img src='https://fiddle.skia.org/i/${ele
._runResults.fiddleHash}_raster.png'></a>"
/>
<h3>Embed as custom element (skia.org only):</h3>
<input
type="text"
readonly
size="150"
value="<fiddle-embed name='${ele._runResults
.fiddleHash}'></fiddle-embed> "
/>
</details>
</div>
`;
private static textOnlyResults = (ele: FiddleSk) => {
if (!ele._options.textOnly) {
return html``;
}
return html`
<h2 ?hidden=${ele._config.embedded}>Output</h2>
<div class="textoutput">
<test-src-sk .src=${ele.textURL()}></test-src-sk>
</div>
`;
};
private static runDetails = (ele: FiddleSk) => {
if (ele._config.embedded || !ele.hasImages()) {
return html``;
}
return html`
<details>
<summary>Run Details</summary>
<test-src-sk id="glinfo" .src=${ele.glinfoURL()}></test-src-sk>
</details>
`;
};
private static results = (ele: FiddleSk) => {
if (!ele.hasImages()) {
return html``;
}
return html`
<div id="results">
<div ?hidden=${!ele.showCPU()}>
<img
class="result_image cpu"
?hidden=${ele._options.animated}
title="CPU"
src="${ele._config.domain}/i/${ele._runResults.fiddleHash}_raster.png"
width=${ele._options.width}
height=${ele._options.height}
/>
<video
?hidden=${!ele._options.animated}
title="CPU"
@ended=${ele.playEnded}
?autoplay=${ele._config.play} muted
?loop=${ele._config.loop}
src="${ele._config.domain}/i/${ele._runResults.fiddleHash}_cpu.webm"
width=${ele._options.width}
height=${ele._options.height}
>
</video>
<p ?hidden=${ele._config.embedded}> CPU </p>
</div>
<div ?hidden=${!ele.showGPU()}>
<img
class="result_image gpu"
?hidden=${ele._options.animated}
title="GPU"
src="${ele._config.domain}/i/${ele._runResults.fiddleHash}_gpu.png"
width=${ele._options.width}
height=${ele._options.height}
/>
<video
?hidden=${!ele._options.animated}
title="GPU"
?loop=${ele._config.loop}
?autoplay=${ele._config.play} muted
src="${ele._config.domain}/i/${ele._runResults.fiddleHash}_gpu.webm"
width=${ele._options.width}
height=${ele._options.height}
></video>
<p ?hidden=${ele._config.embedded}> GPU </p>
</div>
<div ?hidden=${!ele.showLinks()}>
<div>
<a href="${ele._config.domain}/i/${ele._runResults.fiddleHash}.pdf"
>PDF</a
>
</div>
<div>
<a href="${ele._config.domain}/i/${ele._runResults.fiddleHash}.skp"
>SKP</a
>
</div>
<div>
<a
href="https://debugger.skia.org?url=https://fiddle.skia.org/i/${
ele._runResults.fiddleHash
}.skp"
>Debug</a
>
</div>
</div>
<div ?hidden=${!ele._options.animated} id="controls">
<button @click=${ele.playClick} title="Play the animation.">
<play-arrow-icon-sk ?hidden=${
ele._config.play
}></play-arrow-icon-sk>
<pause-icon-sk ?hidden=${!ele._config.play} ><pause-icon-sk>
</button>
<checkbox-sk
id="loop"
?checked=${ele._config.loop}
label="Loop"
title="Run animations in a loop"
@change=${ele.loopChange}
></checkbox-sk>
<select id="speed" @change=${ele.speedChange} size="1">
<option value="0.25">0.25</option>
<option value="0.5">0.5</option>
<option value="0.75">0.75</option>
<option value="1" selected>Normal speed</option>
<option value="1.25">1.25</option>
<option value="1.5">1.5</option>
<option value="2">2</option>
</select>
</div>
</div>
`;
};
private static errors = (ele: FiddleSk) => html`
<div @click=${ele.compilerErrorLineClick} ?hidden=${!ele.hasCompileWarningsOrErrors()}>
<h2>Compilation Warnings/Errors</h2>
${ele._runResults.compile_errors?.map(
(err) => html`<pre
class="compile-error ${err.line > 0 ? 'clickable' : ''}"
data-line=${err.line}
data-col=${err.col}
>
${err.text}</pre
>`,
)}
</div>
<div ?hidden=${!ele._runResults.runtime_error}>
<h2>Runtime Errors</h2>
<div>${ele._runResults.runtime_error}</div>
</template>
`;
private static template = (ele: FiddleSk) => html`
${FiddleSk.displayOptions(ele)}
<textarea-numbers-sk .value=${ele._runResults.text}></textarea-numbers-sk>
${FiddleSk.actions(ele)}
${FiddleSk.errors(ele)}
${FiddleSk.results(ele)}
${FiddleSk.textOnlyResults(ele)}
${FiddleSk.runDetails(ele)}
`;
connectedCallback(): void {
super.connectedCallback();
this._render();
this.textarea = this.querySelector('textarea-numbers-sk');
this.spinner = this.querySelector('spinner-sk');
this._upgradeProperty('options');
this._upgradeProperty('config');
this._upgradeProperty('runResults');
this._upgradeProperty('context');
}
// Properties
/** The results from running a fiddle. */
get runResults(): RunResults {
return this._runResults;
}
set runResults(val: RunResults) {
this.textarea!.clearErrors();
this._runResults = val;
this._render();
if (!val.compile_errors) {
return;
}
val.compile_errors.forEach((err) => {
if (err.line === 0) {
return;
}
this.textarea!.setErrorLine(err.line);
});
}
/** The options for the fiddle. */
get options(): Options {
return this._options;
}
set options(val: Options) {
this._options = val;
this._render();
}
/** The configuration of the element. */
get config(): Config {
return this._config;
}
set config(val: Config) {
this._config = val;
this._render();
}
set context(val: FiddleContext | null) {
if (!val) {
return;
}
this.options = val.options;
this.runResults.text = val.code;
this.runResults.fiddleHash = val.fiddlehash;
this._render();
}
// Event listeners.
private sourceMipMapChange(e: Event) {
this._options.source_mipmap = (e.target as CheckOrRadio).checked;
}
private sourceChange(e: CustomEvent<SelectSkSelectionChangedEventDetail>) {
this._options.source = this._config.sources[e.detail.selection];
this._render();
}
private offscreenMipMapChange(e: Event) {
this._options.offscreen_mipmap = (e.target as CheckOrRadio).checked;
}
private offscreenTexturableChange(e: Event) {
this._options.offscreen_texturable = (e.target as CheckOrRadio).checked;
this._render();
}
private offscreenSampleCountChange(e: Event) {
this._options.offscreen_sample_count = +(e.target as HTMLInputElement)
.value;
}
private offscreenWidthChange(e: Event) {
this._options.offscreen_width = +(e.target as HTMLInputElement).value;
}
private offscreenHeightChange(e: Event) {
this._options.offscreen_height = +(e.target as HTMLInputElement).value;
}
private offscreenChange(e: Event) {
this._options.offscreen = (e.target as CheckOrRadio).checked;
this._render();
}
private durationChange(e: Event) {
this._options.duration = +(e.target as HTMLInputElement).value;
}
private animatedChange(e: Event) {
this._options.animated = (e.target as CheckOrRadio).checked;
this._render();
}
private widthChange(e: Event) {
this._options.width = +(e.target as HTMLInputElement).value;
}
private heightChange(e: Event) {
this._options.height = +(e.target as HTMLInputElement).value;
}
private f16Change(e: Event) {
this._options.f16 = (e.target as CheckOrRadio).checked;
this._render();
}
private textOnlyChange(e: Event) {
this._options.textOnly = (e.target as CheckOrRadio).checked;
}
private srgbChange(e: Event) {
this._options.srgb = (e.target as CheckOrRadio).checked;
this._render();
}
private loopChange() {
this._config.loop = !this._config.loop;
this._render();
}
private speedChange(e: Event) {
const speed = (e.target! as HTMLSelectElement).value;
this.querySelectorAll<HTMLVideoElement>('video').forEach((ele) => {
ele.playbackRate = +speed;
});
}
private playClick() {
this._config.play = !this._config.play;
this._render();
this.querySelectorAll<HTMLVideoElement>('video').forEach((e) => {
if (this._config.play) {
e.play();
} else {
e.pause();
}
});
}
private playEnded() {
this._config.play = false;
this._render();
}
private hasImages(): boolean {
return (
!this._options.textOnly
&& this._runResults.fiddleHash !== ''
&& this._runResults.runtime_error === ''
&& !this.hasCompileErrors()
);
}
private hasCompileErrors() {
return !!this._runResults.compile_errors?.some((e) => e.text.includes('error:'));
}
private hasCompileWarningsOrErrors(): boolean {
return (this._runResults!.compile_errors?.length || 0) > 0;
}
private compilerErrorLineClick(e: MouseEvent) {
const ele = e.target! as HTMLElement;
if (ele.nodeName === 'PRE') {
this.textarea!.setCursor(+ele.dataset!.line!, +ele.dataset!.col!);
}
}
private bugReportingURL(fiddleHash: string): string {
const comment = `Visit this link to see the issue on fiddle:\n\n https://fiddle.skia.org/c/${
fiddleHash}`;
return (
`https://bugs.chromium.org/p/skia/issues/entry?${
fromObject({
comment: comment,
})}`
);
}
private async run() {
try {
this._runResults.fiddleHash = '';
this.spinner!.active = true;
const body: FiddleContext = {
version: '',
sources: '',
fiddlehash: '',
name: '',
overwrite: false,
fast: false,
code: this.textarea!.value,
options: this._options,
};
const request = await fetch(`${this._config.domain}/_/run`, {
method: 'POST',
body: JSON.stringify(body),
});
const results = (await jsonOrThrow(request)) as RunResults;
// The .text field returned is empty, so repopulate it with the value we
// stored in body.
results.text = body.code;
this.runResults = results;
this._render();
this.dispatchEvent(
new CustomEvent<FiddleSkFiddleSuccessEventDetail>('fiddle-success', {
detail: this._runResults.fiddleHash,
bubbles: true,
}),
);
} catch (error) {
errorMessage(error);
} finally {
this.spinner!.active = false;
}
}
private glinfoURL(): string {
if (this._runResults.fiddleHash === '') {
return '';
}
return (
`${this._config.domain}/i/${this._runResults.fiddleHash}_glinfo.txt`
);
}
private textURL(): string {
if (this._runResults.fiddleHash === '') {
return '';
}
return `${this._config.domain}/i/${this._runResults.fiddleHash}.txt`;
}
private showCPU(): boolean {
if (!this._config.embedded) {
return true;
}
return this._config.cpu_embedded || !this._config.gpu_embedded;
}
private showGPU(): boolean {
if (!this._config.embedded) {
return true;
}
return this._config.gpu_embedded;
}
private showLinks(): boolean {
return (
!this._options.animated
&& !this._config.embedded
&& !this._config.basic_mode
);
}
}
define('fiddle-sk', FiddleSk); | the_stack |
import classNames from "classnames";
import * as React from "react";
import { polyfill } from "react-lifecycles-compat";
import { IconName } from "@blueprintjs/icons";
import {
AbstractPureComponent2,
Classes,
DISPLAYNAME_PREFIX,
HTMLInputProps,
IntentProps,
Intent,
Props,
IRef,
Keys,
MaybeElement,
Position,
refHandler,
removeNonHTMLProps,
setRef,
Utils,
} from "../../common";
import * as Errors from "../../common/errors";
import { ButtonGroup } from "../button/buttonGroup";
import { Button } from "../button/buttons";
import { ControlGroup } from "./controlGroup";
import { InputGroup } from "./inputGroup";
import {
clampValue,
getValueOrEmptyValue,
isValidNumericKeyboardEvent,
isValueNumeric,
parseStringToStringNumber,
sanitizeNumericInput,
toLocaleString,
toMaxPrecision,
} from "./numericInputUtils";
// eslint-disable-next-line deprecation/deprecation
export type NumericInputProps = INumericInputProps;
/** @deprecated use NumericInputProps */
export interface INumericInputProps extends IntentProps, Props {
/**
* Whether to allow only floating-point number characters in the field,
* mimicking the native `input[type="number"]`.
*
* @default true
*/
allowNumericCharactersOnly?: boolean;
/**
* Set this to `true` if you will be controlling the `value` of this input with asynchronous updates.
* These may occur if you do not immediately call setState in a parent component with the value from
* the `onChange` handler.
*/
asyncControl?: boolean;
/**
* The position of the buttons with respect to the input field.
*
* @default Position.RIGHT
*/
buttonPosition?: typeof Position.LEFT | typeof Position.RIGHT | "none";
/**
* Whether the value should be clamped to `[min, max]` on blur.
* The value will be clamped to each bound only if the bound is defined.
* Note that native `input[type="number"]` controls do *NOT* clamp on blur.
*
* @default false
*/
clampValueOnBlur?: boolean;
/**
* In uncontrolled mode, this sets the default value of the input.
* Note that this value is only used upon component instantiation and changes to this prop
* during the component lifecycle will be ignored.
*
* @default ""
*/
defaultValue?: number | string;
/**
* Whether the input is non-interactive.
*
* @default false
*/
disabled?: boolean;
/** Whether the numeric input should take up the full width of its container. */
fill?: boolean;
/**
* Ref handler that receives HTML `<input>` element backing this component.
*/
inputRef?: IRef<HTMLInputElement>;
/**
* If set to `true`, the input will display with larger styling.
* This is equivalent to setting `Classes.LARGE` via className on the
* parent control group and on the child input group.
*
* @default false
*/
large?: boolean;
/**
* Name of a Blueprint UI icon (or an icon element) to render on the left side of input.
*/
leftIcon?: IconName | MaybeElement;
/**
* The locale name, which is passed to the component to format the number and allowing to type the number in the specific locale.
* [See MDN documentation for more info about browser locale identification](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation).
*
* @default ""
*/
locale?: string;
/**
* The increment between successive values when <kbd>shift</kbd> is held.
* Pass explicit `null` value to disable this interaction.
*
* @default 10
*/
majorStepSize?: number | null;
/** The maximum value of the input. */
max?: number;
/** The minimum value of the input. */
min?: number;
/**
* The increment between successive values when <kbd>alt</kbd> is held.
* Pass explicit `null` value to disable this interaction.
*
* @default 0.1
*/
minorStepSize?: number | null;
/** The placeholder text in the absence of any value. */
placeholder?: string;
/**
* Element to render on right side of input.
* For best results, use a minimal button, tag, or small spinner.
*/
rightElement?: JSX.Element;
/**
* Whether the entire text field should be selected on focus.
*
* @default false
*/
selectAllOnFocus?: boolean;
/**
* Whether the entire text field should be selected on increment.
*
* @default false
*/
selectAllOnIncrement?: boolean;
/**
* The increment between successive values when no modifier keys are held.
*
* @default 1
*/
stepSize?: number;
/**
* The value to display in the input field.
*/
value?: number | string;
/** The callback invoked when the value changes due to a button click. */
onButtonClick?(valueAsNumber: number, valueAsString: string): void;
/** The callback invoked when the value changes due to typing, arrow keys, or button clicks. */
onValueChange?(valueAsNumber: number, valueAsString: string, inputElement: HTMLInputElement | null): void;
}
export interface INumericInputState {
currentImeInputInvalid: boolean;
prevMinProp?: number;
prevMaxProp?: number;
shouldSelectAfterUpdate: boolean;
stepMaxPrecision: number;
value: string;
}
enum IncrementDirection {
DOWN = -1,
UP = +1,
}
const NON_HTML_PROPS: Array<keyof NumericInputProps> = [
"allowNumericCharactersOnly",
"buttonPosition",
"clampValueOnBlur",
"className",
"defaultValue",
"majorStepSize",
"minorStepSize",
"onButtonClick",
"onValueChange",
"selectAllOnFocus",
"selectAllOnIncrement",
"stepSize",
];
type ButtonEventHandlers = Required<Pick<React.HTMLAttributes<Element>, "onKeyDown" | "onMouseDown">>;
@polyfill
export class NumericInput extends AbstractPureComponent2<HTMLInputProps & NumericInputProps, INumericInputState> {
public static displayName = `${DISPLAYNAME_PREFIX}.NumericInput`;
public static VALUE_EMPTY = "";
public static VALUE_ZERO = "0";
public static defaultProps: NumericInputProps = {
allowNumericCharactersOnly: true,
buttonPosition: Position.RIGHT,
clampValueOnBlur: false,
defaultValue: NumericInput.VALUE_EMPTY,
large: false,
majorStepSize: 10,
minorStepSize: 0.1,
selectAllOnFocus: false,
selectAllOnIncrement: false,
stepSize: 1,
};
public static getDerivedStateFromProps(props: NumericInputProps, state: INumericInputState) {
const nextState = {
prevMaxProp: props.max,
prevMinProp: props.min,
};
const didMinChange = props.min !== state.prevMinProp;
const didMaxChange = props.max !== state.prevMaxProp;
const didBoundsChange = didMinChange || didMaxChange;
// in controlled mode, use props.value
// in uncontrolled mode, if state.value has not been assigned yet (upon initial mount), use props.defaultValue
const value = props.value?.toString() ?? state.value;
const stepMaxPrecision = NumericInput.getStepMaxPrecision(props);
const sanitizedValue =
value !== NumericInput.VALUE_EMPTY
? NumericInput.roundAndClampValue(value, stepMaxPrecision, props.min, props.max, 0, props.locale)
: NumericInput.VALUE_EMPTY;
// if a new min and max were provided that cause the existing value to fall
// outside of the new bounds, then clamp the value to the new valid range.
if (didBoundsChange && sanitizedValue !== state.value) {
return { ...nextState, stepMaxPrecision, value: sanitizedValue };
}
return { ...nextState, stepMaxPrecision, value };
}
private static CONTINUOUS_CHANGE_DELAY = 300;
private static CONTINUOUS_CHANGE_INTERVAL = 100;
// Value Helpers
// =============
private static getStepMaxPrecision(props: HTMLInputProps & NumericInputProps) {
if (props.minorStepSize != null) {
return Utils.countDecimalPlaces(props.minorStepSize);
} else {
return Utils.countDecimalPlaces(props.stepSize!);
}
}
private static roundAndClampValue(
value: string,
stepMaxPrecision: number,
min: number | undefined,
max: number | undefined,
delta = 0,
locale: string | undefined,
) {
if (!isValueNumeric(value, locale)) {
return NumericInput.VALUE_EMPTY;
}
const currentValue = parseStringToStringNumber(value, locale);
const nextValue = toMaxPrecision(Number(currentValue) + delta, stepMaxPrecision);
const clampedValue = clampValue(nextValue, min, max);
return toLocaleString(clampedValue, locale);
}
public state: INumericInputState = {
currentImeInputInvalid: false,
shouldSelectAfterUpdate: false,
stepMaxPrecision: NumericInput.getStepMaxPrecision(this.props),
value: getValueOrEmptyValue(this.props.value ?? this.props.defaultValue),
};
// updating these flags need not trigger re-renders, so don't include them in this.state.
private didPasteEventJustOccur = false;
private delta = 0;
public inputElement: HTMLInputElement | null = null;
private inputRef: IRef<HTMLInputElement> = refHandler(this, "inputElement", this.props.inputRef);
private intervalId?: number;
private incrementButtonHandlers = this.getButtonEventHandlers(IncrementDirection.UP);
private decrementButtonHandlers = this.getButtonEventHandlers(IncrementDirection.DOWN);
public render() {
const { buttonPosition, className, fill, large } = this.props;
const containerClasses = classNames(Classes.NUMERIC_INPUT, { [Classes.LARGE]: large }, className);
const buttons = this.renderButtons();
return (
<ControlGroup className={containerClasses} fill={fill}>
{buttonPosition === Position.LEFT && buttons}
{this.renderInput()}
{buttonPosition === Position.RIGHT && buttons}
</ControlGroup>
);
}
public componentDidUpdate(prevProps: NumericInputProps, prevState: INumericInputState) {
super.componentDidUpdate(prevProps, prevState);
if (prevProps.inputRef !== this.props.inputRef) {
setRef(prevProps.inputRef, null);
this.inputRef = refHandler(this, "inputElement", this.props.inputRef);
setRef(this.props.inputRef, this.inputElement);
}
if (this.state.shouldSelectAfterUpdate) {
this.inputElement?.setSelectionRange(0, this.state.value.length);
}
const didMinChange = this.props.min !== prevProps.min;
const didMaxChange = this.props.max !== prevProps.max;
const didBoundsChange = didMinChange || didMaxChange;
const didLocaleChange = this.props.locale !== prevProps.locale;
const didValueChange = this.state.value !== prevState.value;
if ((didBoundsChange && didValueChange) || (didLocaleChange && prevState.value !== NumericInput.VALUE_EMPTY)) {
// we clamped the value due to a bounds change, so we should fire the change callback
const valueToParse = didLocaleChange ? prevState.value : this.state.value;
const valueAsString = parseStringToStringNumber(valueToParse, prevProps.locale);
const localizedValue = toLocaleString(+valueAsString, this.props.locale);
this.props.onValueChange?.(+valueAsString, localizedValue, this.inputElement);
}
}
protected validateProps(nextProps: HTMLInputProps & NumericInputProps) {
const { majorStepSize, max, min, minorStepSize, stepSize, value } = nextProps;
if (min != null && max != null && min > max) {
console.error(Errors.NUMERIC_INPUT_MIN_MAX);
}
if (stepSize! <= 0) {
console.error(Errors.NUMERIC_INPUT_STEP_SIZE_NON_POSITIVE);
}
if (minorStepSize && minorStepSize <= 0) {
console.error(Errors.NUMERIC_INPUT_MINOR_STEP_SIZE_NON_POSITIVE);
}
if (majorStepSize && majorStepSize <= 0) {
console.error(Errors.NUMERIC_INPUT_MAJOR_STEP_SIZE_NON_POSITIVE);
}
if (minorStepSize && minorStepSize > stepSize!) {
console.error(Errors.NUMERIC_INPUT_MINOR_STEP_SIZE_BOUND);
}
if (majorStepSize && majorStepSize < stepSize!) {
console.error(Errors.NUMERIC_INPUT_MAJOR_STEP_SIZE_BOUND);
}
// controlled mode
if (value != null) {
const stepMaxPrecision = NumericInput.getStepMaxPrecision(nextProps);
const sanitizedValue = NumericInput.roundAndClampValue(
value.toString(),
stepMaxPrecision,
min,
max,
0,
this.props.locale,
);
const valueDoesNotMatch = sanitizedValue !== value.toString();
const localizedValue = toLocaleString(
Number(parseStringToStringNumber(value, this.props.locale)),
this.props.locale,
);
const isNotLocalized = sanitizedValue !== localizedValue;
if (valueDoesNotMatch && isNotLocalized) {
console.warn(Errors.NUMERIC_INPUT_CONTROLLED_VALUE_INVALID);
}
}
}
// Render Helpers
// ==============
private renderButtons() {
const { intent, max, min, locale } = this.props;
const value = parseStringToStringNumber(this.state.value, locale);
const disabled = this.props.disabled || this.props.readOnly;
const isIncrementDisabled = max !== undefined && value !== "" && +value >= max;
const isDecrementDisabled = min !== undefined && value !== "" && +value <= min;
return (
<ButtonGroup className={Classes.FIXED} key="button-group" vertical={true}>
<Button
aria-label="increment"
disabled={disabled || isIncrementDisabled}
icon="chevron-up"
intent={intent}
{...this.incrementButtonHandlers}
/>
<Button
aria-label="decrement"
disabled={disabled || isDecrementDisabled}
icon="chevron-down"
intent={intent}
{...this.decrementButtonHandlers}
/>
</ButtonGroup>
);
}
private renderInput() {
const inputGroupHtmlProps = removeNonHTMLProps(this.props, NON_HTML_PROPS, true);
return (
<InputGroup
asyncControl={this.props.asyncControl}
autoComplete="off"
{...inputGroupHtmlProps}
intent={this.state.currentImeInputInvalid ? Intent.DANGER : this.props.intent}
inputRef={this.inputRef}
large={this.props.large}
leftIcon={this.props.leftIcon}
onFocus={this.handleInputFocus}
onBlur={this.handleInputBlur}
onChange={this.handleInputChange}
onCompositionEnd={this.handleCompositionEnd}
onCompositionUpdate={this.handleCompositionUpdate}
onKeyDown={this.handleInputKeyDown}
onKeyPress={this.handleInputKeyPress}
onPaste={this.handleInputPaste}
rightElement={this.props.rightElement}
value={this.state.value}
/>
);
}
// Callbacks - Buttons
// ===================
private getButtonEventHandlers(direction: IncrementDirection): ButtonEventHandlers {
return {
// keydown is fired repeatedly when held so it's implicitly continuous
onKeyDown: evt => {
// eslint-disable-next-line deprecation/deprecation
if (!this.props.disabled && Keys.isKeyboardClick(evt.keyCode)) {
this.handleButtonClick(evt, direction);
}
},
onMouseDown: evt => {
if (!this.props.disabled) {
this.handleButtonClick(evt, direction);
this.startContinuousChange();
}
},
};
}
private handleButtonClick = (e: React.MouseEvent | React.KeyboardEvent, direction: IncrementDirection) => {
const delta = this.updateDelta(direction, e);
const nextValue = this.incrementValue(delta);
this.props.onButtonClick?.(Number(parseStringToStringNumber(nextValue, this.props.locale)), nextValue);
};
private startContinuousChange() {
// The button's onMouseUp event handler doesn't fire if the user
// releases outside of the button, so we need to watch all the way
// from the top.
document.addEventListener("mouseup", this.stopContinuousChange);
// Initial delay is slightly longer to prevent the user from
// accidentally triggering the continuous increment/decrement.
this.setTimeout(() => {
this.intervalId = window.setInterval(this.handleContinuousChange, NumericInput.CONTINUOUS_CHANGE_INTERVAL);
}, NumericInput.CONTINUOUS_CHANGE_DELAY);
}
private stopContinuousChange = () => {
this.delta = 0;
this.clearTimeouts();
clearInterval(this.intervalId);
document.removeEventListener("mouseup", this.stopContinuousChange);
};
private handleContinuousChange = () => {
// If either min or max prop is set, when reaching the limit
// the button will be disabled and stopContinuousChange will be never fired,
// hence the need to check on each iteration to properly clear the timeout
if (this.props.min !== undefined || this.props.max !== undefined) {
const min = this.props.min ?? -Infinity;
const max = this.props.max ?? Infinity;
const valueAsNumber = Number(parseStringToStringNumber(this.state.value, this.props.locale));
if (valueAsNumber <= min || valueAsNumber >= max) {
this.stopContinuousChange();
return;
}
}
const nextValue = this.incrementValue(this.delta);
this.props.onButtonClick?.(Number(parseStringToStringNumber(nextValue, this.props.locale)), nextValue);
};
// Callbacks - Input
// =================
private handleInputFocus = (e: React.FocusEvent<HTMLInputElement>) => {
// update this state flag to trigger update for input selection (see componentDidUpdate)
this.setState({ shouldSelectAfterUpdate: this.props.selectAllOnFocus! });
this.props.onFocus?.(e);
};
private handleInputBlur = (e: React.FocusEvent<HTMLInputElement>) => {
// always disable this flag on blur so it's ready for next time.
this.setState({ shouldSelectAfterUpdate: false });
if (this.props.clampValueOnBlur) {
const { value } = e.target as HTMLInputElement;
this.handleNextValue(this.roundAndClampValue(value));
}
this.props.onBlur?.(e);
};
private handleInputKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (this.props.disabled || this.props.readOnly) {
return;
}
// eslint-disable-next-line deprecation/deprecation
const { keyCode } = e;
let direction: IncrementDirection | undefined;
if (keyCode === Keys.ARROW_UP) {
direction = IncrementDirection.UP;
} else if (keyCode === Keys.ARROW_DOWN) {
direction = IncrementDirection.DOWN;
}
if (direction !== undefined) {
// when the input field has focus, some key combinations will modify
// the field's selection range. we'll actually want to select all
// text in the field after we modify the value on the following
// lines. preventing the default selection behavior lets us do that
// without interference.
e.preventDefault();
const delta = this.updateDelta(direction, e);
this.incrementValue(delta);
}
this.props.onKeyDown?.(e);
};
private handleCompositionEnd = (e: React.CompositionEvent<HTMLInputElement>) => {
if (this.props.allowNumericCharactersOnly) {
this.handleNextValue(sanitizeNumericInput(e.data, this.props.locale));
this.setState({ currentImeInputInvalid: false });
}
};
private handleCompositionUpdate = (e: React.CompositionEvent<HTMLInputElement>) => {
if (this.props.allowNumericCharactersOnly) {
const { data } = e;
const sanitizedValue = sanitizeNumericInput(data, this.props.locale);
if (sanitizedValue.length === 0 && data.length > 0) {
this.setState({ currentImeInputInvalid: true });
} else {
this.setState({ currentImeInputInvalid: false });
}
}
};
private handleInputKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
// we prohibit keystrokes in onKeyPress instead of onKeyDown, because
// e.key is not trustworthy in onKeyDown in all browsers.
if (this.props.allowNumericCharactersOnly && !isValidNumericKeyboardEvent(e, this.props.locale)) {
e.preventDefault();
}
this.props.onKeyPress?.(e);
};
private handleInputPaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
this.didPasteEventJustOccur = true;
this.props.onPaste?.(e);
};
private handleInputChange = (e: React.FormEvent) => {
const { value } = e.target as HTMLInputElement;
let nextValue = value;
if (this.props.allowNumericCharactersOnly && this.didPasteEventJustOccur) {
this.didPasteEventJustOccur = false;
nextValue = sanitizeNumericInput(value, this.props.locale);
}
this.handleNextValue(nextValue);
this.setState({ shouldSelectAfterUpdate: false });
};
// Data logic
// ==========
private handleNextValue(valueAsString: string) {
if (this.props.value == null) {
this.setState({ value: valueAsString });
}
this.props.onValueChange?.(
Number(parseStringToStringNumber(valueAsString, this.props.locale)),
valueAsString,
this.inputElement,
);
}
private incrementValue(delta: number) {
// pretend we're incrementing from 0 if currValue is empty
const currValue = this.state.value === NumericInput.VALUE_EMPTY ? NumericInput.VALUE_ZERO : this.state.value;
const nextValue = this.roundAndClampValue(currValue, delta);
if (nextValue !== this.state.value) {
this.handleNextValue(nextValue);
this.setState({ shouldSelectAfterUpdate: this.props.selectAllOnIncrement! });
}
// return value used in continuous change updates
return nextValue;
}
private getIncrementDelta(direction: IncrementDirection, isShiftKeyPressed: boolean, isAltKeyPressed: boolean) {
const { majorStepSize, minorStepSize, stepSize } = this.props;
if (isShiftKeyPressed && majorStepSize != null) {
return direction * majorStepSize;
} else if (isAltKeyPressed && minorStepSize != null) {
return direction * minorStepSize;
} else {
return direction * stepSize!;
}
}
private roundAndClampValue(value: string, delta = 0) {
return NumericInput.roundAndClampValue(
value,
this.state.stepMaxPrecision,
this.props.min,
this.props.max,
delta,
this.props.locale,
);
}
private updateDelta(direction: IncrementDirection, e: React.MouseEvent | React.KeyboardEvent) {
this.delta = this.getIncrementDelta(direction, e.shiftKey, e.altKey);
return this.delta;
}
} | the_stack |
import testifm = require('vso-node-api/interfaces/TestInterfaces');
import ctxm = require('./context');
import cm = require('./common');
import utilities = require('./utilities');
import buildifm = require('vso-node-api/interfaces/BuildInterfaces');
import fc = require('./filecontainerhelper');
import Q = require('q');
import fs = require('fs');
var shell = require('shelljs');
var path = require('path');
export class CodeCoveragePublisher {
constructor(executionContext: cm.IExecutionContext, command: cm.ITaskCommand, reader: ICodeCoverageReader) {
this.executionContext = executionContext;
this.command = command;
this.codeCoverageReader = reader;
this.buildId = parseInt(this.executionContext.variables[ctxm.WellKnownVariables.buildId]);
this.project = this.executionContext.variables[ctxm.WellKnownVariables.projectId];
}
private executionContext: cm.IExecutionContext;
private command: cm.ITaskCommand;
private codeCoverageReader: ICodeCoverageReader;
private buildId: number;
private project: string;
//-----------------------------------------------------
// Publish code coverage
//-----------------------------------------------------
public publishCodeCoverageSummary(): Q.Promise<any> {
var defer = Q.defer<any>();
var _this = this;
var summaryFile = _this.command.properties["summaryfile"];
_this.readCodeCoverageSummary(summaryFile).then(function(codeCoverageData) {
if (codeCoverageData && codeCoverageData.coverageStats && codeCoverageData.coverageStats.length > 0) {
_this.executionContext.service.publishCodeCoverageSummary(codeCoverageData, _this.project, _this.buildId)
.then(function(result) {
_this.command.info("PublishCodeCoverageSummary : Code coverage summary published successfully.");
defer.resolve(null);
}).fail(function(error) {
_this.command.warning("PublishCodeCoverageSummary : Error occured while publishing code coverage summary. Error: " + error);
defer.reject(error);
});
}
else {
_this.command.warning("PublishCodeCoverageSummary : No code coverage data found to publish.");
defer.resolve(null);
}
}).fail(function(err) {
_this.command.warning("PublishCodeCoverageSummary : Error occured while reading code coverage summary. Error : " + err);
defer.reject(err);
});
return defer.promise;
}
//-----------------------------------------------------
// publish code coverage files to server
// - reportDirectory: code coverage report directory
// - additionalCodeCoverageFiles: additional code coverage files
//-----------------------------------------------------
public publishCodeCoverageFiles(): Q.Promise<any> {
var defer = Q.defer();
var _this = this;
var containerId = parseInt(_this.executionContext.variables[ctxm.WellKnownVariables.containerId]);
var summaryFile = _this.command.properties["summaryfile"];
var reportDirectory = _this.command.properties["reportdirectory"];
var additionalCodeCoverageFiles = _this.command.properties["additionalcodecoveragefiles"];
var codeCoverageArtifactName = "Code Coverage Report_" + _this.buildId;
var reportDirectoryExists = false;
var newReportDirectory = reportDirectory;
if (reportDirectory && reportDirectory.length > 0) {
if (utilities.isDirectoryExists(reportDirectory)) {
reportDirectoryExists = true;
}
else {
_this.command.warning("Report directory '" + reportDirectory + "' doesnot exist or it is not a directory.");
}
}
if (!reportDirectoryExists) {
newReportDirectory = path.join(shell.tempdir(), "CodeCoverageReport_" + _this.buildId);
shell.mkdir('-p', newReportDirectory);
}
// copy the summary file into report directory
shell.cp(summaryFile, newReportDirectory);
_this.command.info("PublishCodeCoverageFiles : Publishing code coverage report '" + newReportDirectory + "'");
_this.uploadArtifact(newReportDirectory, codeCoverageArtifactName, containerId, _this.isReportDirectoryBrowsable(newReportDirectory)).then(function() {
try {
_this.command.info("PublishCodeCoverageFiles : Code coverage report published successfully.");
// clean the temporary report directory created.
if (!reportDirectoryExists) {
shell.rm('-rf', newReportDirectory);
}
if (!additionalCodeCoverageFiles || !(additionalCodeCoverageFiles.split(",")) || additionalCodeCoverageFiles.split(",").length <= 0) {
_this.command.info("PublishCodeCoverageFiles : No additional codecoverage files found to publish.");
defer.resolve(null);
return defer.promise;
}
var rawFiles: string[] = additionalCodeCoverageFiles.split(",");
var rawFilesDirectory = path.join(shell.tempdir(), "CodeCoverageFiles_" + _this.buildId);
shell.mkdir('-p', rawFilesDirectory);
_this.copyRawFiles(rawFiles, rawFilesDirectory);
var rawFilesArtifactName = "Code Coverage Files_" + _this.buildId;
_this.command.info("PublishCodeCoverageFiles : Publishing additional code coverage files '" + rawFilesDirectory + "'");
_this.uploadArtifact(rawFilesDirectory, rawFilesArtifactName, containerId, "False").then(function() {
// clean the temporary additional files folder created.
shell.rm('-rf', rawFilesDirectory);
_this.command.info("PublishCodeCoverageFiles : Additional code coverage files published successfully.");
defer.resolve(null);
}).fail(function(error) {
defer.reject(error);
});
}
catch (err) {
defer.reject(err);
}
}).fail(function(error) {
defer.reject(error);
});
return defer.promise;
}
//-----------------------------------------------------
// copies all the additionalcodecoveragefiles into rawFilesDirectory
// if there are files with the same name both are copied by maintaining distinguishing directory structure
// For example, usr/admin/a.xml and usr/admin2/a.xml are copied as admin/a.xml and admin2/a.xml into rawFilesDirectory
//-----------------------------------------------------
private copyRawFiles(additionalCodeCoverageFiles: string[], rawFilesDirectory: string) {
if (additionalCodeCoverageFiles.length > 1) {
additionalCodeCoverageFiles = utilities.sortStringArray(additionalCodeCoverageFiles);
var numberOfFiles = additionalCodeCoverageFiles.length;
var commonPath = utilities.sharedSubString(additionalCodeCoverageFiles[0], additionalCodeCoverageFiles[numberOfFiles - 1])
}
additionalCodeCoverageFiles.forEach(file => {
if (commonPath) {
var newFile: string = file.replace(commonPath, "");
}
else {
var newFile: string = path.basename(file);
}
newFile = path.join(rawFilesDirectory, newFile);
shell.mkdir('-p', path.dirname(newFile));
shell.cp('-f', file, newFile)
});
}
//-----------------------------------------------------
// Helper function to upload artifact to server
// - path: Path of the directory to uploaded to server
// - artifactName: name of teh artifact
// - containerId: containerId
//-----------------------------------------------------
private uploadArtifact(path: string, artifactName: string, containerId: number, browsable: string): Q.Promise<any> {
var defer = Q.defer();
var properties = {};
properties["browsable"] = browsable;
fc.copyToFileContainer(this.executionContext, path, containerId, "/" + artifactName).then((artifactLocation: string) => {
try {
this.command.info('Associating artifact ' + artifactLocation + ' ...');
var artifact: buildifm.BuildArtifact = <buildifm.BuildArtifact>{
name: artifactName,
resource: {
type: "container",
data: artifactLocation,
properties: properties
},
};
this.executionContext.service.postArtifact(this.project, this.buildId, artifact).fail(function(err) {
defer.reject(err);
return defer.promise;
})
defer.resolve(null);
}
catch (error) {
defer.reject(error);
}
}).fail(function(err) {
defer.reject(err);
});
return defer.promise;
}
//-----------------------------------------------------
// Finds if the report directory has index.html
// - reportDirectory: string - report directory
//-----------------------------------------------------
private isReportDirectoryBrowsable(reportDirectory: string): string {
var defaultIndexFile = path.join(reportDirectory, "index.html");
if(utilities.isFileExists(defaultIndexFile)){
return "True";
}
return "False";
}
//-----------------------------------------------------
// Read code coverage results from summary file.
// - codeCoverageSummaryFile: string - location of the code coverage summary file
//-----------------------------------------------------
private readCodeCoverageSummary(codeCoverageSummaryFile: string): Q.Promise<testifm.CodeCoverageData> {
var defer = Q.defer<testifm.CodeCoverageData>();
var _this = this;
if (codeCoverageSummaryFile) {
_this.codeCoverageReader.getCodeCoverageSummary(codeCoverageSummaryFile).then(function(codeCoverageStatistics) {
defer.resolve(codeCoverageStatistics);
}).fail(function(err) {
defer.reject(err);
});
}
else {
defer.resolve(null);
}
return defer.promise;
}
}
//-----------------------------------------------------
// Interface to be implemented by all code coverage result readers
//-----------------------------------------------------
export interface ICodeCoverageReader {
// reads code coverage results from summary file
getCodeCoverageSummary(summaryFilePath: string): Q.Promise<testifm.CodeCoverageData>;
} | the_stack |
import { FilePlanComponentBodyUpdate } from '../model/filePlanComponentBodyUpdate';
import { RMNodeBodyCreateWithRelativePath } from '../model/rMNodeBodyCreateWithRelativePath';
import { RecordCategoryChildEntry } from '../model/recordCategoryChildEntry';
import { RecordCategoryChildPaging } from '../model/recordCategoryChildPaging';
import { RecordCategoryEntry } from '../model/recordCategoryEntry';
import { BaseApi } from './base.api';
import { buildCollectionParam } from '../../../alfrescoApiClient';
import { throwIfNotDefined } from '../../../assert';
/**
* Recordcategories service.
* @module RecordCategoriesApi
*/
export class RecordCategoriesApi extends BaseApi {
/**
* Create a record category or a record folder
*
* Create a record category or a record folder as a primary child of **recordCategoryId**.
You can set the **autoRename** boolean field to automatically resolve name clashes. If there is a name clash, then
the API method tries to create
a unique name using an integer suffix.
This API method also supports record category or record folder creation using application/json.
You must specify at least a **name** and **nodeType**.
You can create a category like this:
JSON
{
\"name\":\"My Record Category\",
\"nodeType\":\"rma:recordCategory\"
}
You can create a record folder like this:
JSON
{
\"name\":\"My Record Folder\",
\"nodeType\":\"rma:recordFolder\"
}
You can create a record folder inside a container hierarchy (applies to record categories as well):
JSON
{
\"name\":\"My Fileplan Component\",
\"nodeType\":\"rma:recordFolder\",
\"relativePath\":\"X/Y/Z\"
}
The **relativePath** specifies the container structure to create relative to the node (record category or record folder). Containers in the
**relativePath** that do not exist are created before the node is created. The container type is decided considering
the type of the parent container and the type of the node to be created.
You can set properties when creating a record category (applies to record folders as well):
JSON
{
\"name\":\"My Record Category\",
\"nodeType\":\"rma:recordCategory\",
\"properties\":
{
\"rma:vitalRecordIndicator\":\"true\",
\"rma:reviewPeriod\":\"month|1\"
}
}
Any missing aspects are applied automatically. You can set aspects explicitly, if needed, using an **aspectNames** field.
**Note:** You can create more than one child by
specifying a list of nodes in the JSON body. For example, the following JSON
body creates a record category and a record folder inside the specified **categoryId**:
JSON
[
{
\"name\":\"My Record Category\",
\"nodeType\":\"rma:recordCategory\"
},
{
\"name\":\"My Record Folder\",
\"nodeType\":\"rma:recordFolder\"
}
]
If you specify a list as input, then a paginated list rather than an entry is returned in the response body. For example:
JSON
{
\"list\": {
\"pagination\": {
\"count\": 2,
\"hasMoreItems\": false,
\"totalItems\": 2,
\"skipCount\": 0,
\"maxItems\": 100
},
\"entries\": [
{
\"entry\": {
...
}
},
{
\"entry\": {
...
}
}
]
}
}
*
* @param recordCategoryId The identifier of a record category.
* @param nodeBodyCreate The node information to create.
* @param opts Optional parameters
* @param opts.autoRename If true, then a name clash will cause an attempt to auto rename by finding a unique name using an integer suffix.
* @param opts.include Returns additional information about the record category. Any optional field from the response model can be requested. For example:
* allowableOperations
* hasRetentionSchedule
* path
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<RecordCategoryChildEntry>
*/
createRecordCategoryChild(recordCategoryId: string, nodeBodyCreate: RMNodeBodyCreateWithRelativePath, opts?: any): Promise<RecordCategoryChildEntry> {
throwIfNotDefined(recordCategoryId, 'recordCategoryId');
throwIfNotDefined(nodeBodyCreate, 'nodeBodyCreate');
opts = opts || {};
let postBody = nodeBodyCreate;
let pathParams = {
'recordCategoryId': recordCategoryId
};
let queryParams = {
'autoRename': opts['autoRename'],
'include': buildCollectionParam(opts['include'], 'csv'),
'fields': buildCollectionParam(opts['fields'], 'csv')
};
let headerParams = {
};
let formParams = {
};
let contentTypes = ['application/json', 'multipart/form-data'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/record-categories/{recordCategoryId}/children', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, RecordCategoryChildEntry);
}
/**
* Delete a record category
*
* Deletes record category **recordCategoryId**.
*
* @param recordCategoryId The identifier of a record category.
* @return Promise<{}>
*/
deleteRecordCategory(recordCategoryId: string): Promise<any> {
throwIfNotDefined(recordCategoryId, 'recordCategoryId');
let postBody = null;
let pathParams = {
'recordCategoryId': recordCategoryId
};
let queryParams = {
};
let headerParams = {
};
let formParams = {
};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/record-categories/{recordCategoryId}', 'DELETE',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts);
}
/**
* Get a record category
*
* Gets information for record category **recordCategoryId**
Mandatory fields and the record category's aspects and properties are returned by default.
You can use the **include** parameter (include=allowableOperations) to return additional information.
*
* @param recordCategoryId The identifier of a record category.
* @param opts Optional parameters
* @param opts.include Returns additional information about the record category. Any optional field from the response model can be requested. For example:
* allowableOperations
* hasRetentionSchedule
* path
* @param opts.relativePath Return information on children in the record category resolved by this path. The path is relative to **recordCategoryId**.
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<RecordCategoryEntry>
*/
getRecordCategory(recordCategoryId: string, opts?: any): Promise<RecordCategoryEntry> {
throwIfNotDefined(recordCategoryId, 'recordCategoryId');
opts = opts || {};
let postBody = null;
let pathParams = {
'recordCategoryId': recordCategoryId
};
let queryParams = {
'include': buildCollectionParam(opts['include'], 'csv'),
'relativePath': opts['relativePath'],
'fields': buildCollectionParam(opts['fields'], 'csv')
};
let headerParams = {
};
let formParams = {
};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/record-categories/{recordCategoryId}', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, RecordCategoryEntry);
}
/**
* List record category's children
*
* Returns a list of record categories and/or record folders.
Minimal information for each child is returned by default.
You can use the **include** parameter (include=allowableOperations) to return additional information.
The list of child nodes includes primary children and secondary children, if there are any.
*
* @param recordCategoryId The identifier of a record category.
* @param opts Optional parameters
* @param opts.skipCount The number of entities that exist in the collection before those included in this list.
* @param opts.maxItems The maximum number of items to return in the list.
* @param opts.where Optionally filter the list. Here are some examples:
* where=(nodeType='rma:recordFolder')
* where=(nodeType='rma:recordCategory')
* where=(isRecordFolder=true AND isClosed=false)
* @param opts.include Returns additional information about the record category child. Any optional field from the response model can be requested. For example:
* allowableOperations
* aspectNames
* hasRetentionSchedule
* isClosed
* isRecordCategory
* isRecordFolder
* path
* properties
* @param opts.relativePath Return information on children in the record category resolved by this path. The path is relative to **recordCategoryId**.
* @param opts.includeSource Also include **source** (in addition to **entries**) with folder information on the parent node – either the specified parent **recordCategoryId**, or as resolved by **relativePath**.
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<RecordCategoryChildPaging>
*/
listRecordCategoryChildren(recordCategoryId: string, opts?: any): Promise<RecordCategoryChildPaging> {
throwIfNotDefined(recordCategoryId, 'recordCategoryId');
opts = opts || {};
let postBody = null;
let pathParams = {
'recordCategoryId': recordCategoryId
};
let queryParams = {
'skipCount': opts['skipCount'],
'maxItems': opts['maxItems'],
'where': opts['where'],
'include': buildCollectionParam(opts['include'], 'csv'),
'relativePath': opts['relativePath'],
'includeSource': opts['includeSource'],
'fields': buildCollectionParam(opts['fields'], 'csv')
};
let headerParams = {
};
let formParams = {
};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/record-categories/{recordCategoryId}/children', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, RecordCategoryChildPaging);
}
/**
* Update a record category
*
* Updates record category **recordCategoryId**. For example, you can rename a record category:
JSON
{
\"name\":\"My new name\"
}
You can also set or update one or more properties:
JSON
{
\"properties\":
{
\"rma:vitalRecordIndicator\": true,
\"rma:reviewPeriod\":\"month|6\"
}
}
**Note:** If you want to add or remove aspects, then you must use **GET /record-categories/{recordCategoryId}** first to get the complete set of *aspectNames*.
**Note:** Currently there is no optimistic locking for updates, so they are applied in \"last one wins\" order.
*
* @param recordCategoryId The identifier of a record category.
* @param recordCategoryBodyUpdate The record category information to update.
* @param opts Optional parameters
* @param opts.include Returns additional information about the record category. Any optional field from the response model can be requested. For example:
* allowableOperations
* hasRetentionSchedule
* path
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<RecordCategoryEntry>
*/
updateRecordCategory(recordCategoryId: string, recordCategoryBodyUpdate: FilePlanComponentBodyUpdate, opts?: any): Promise<RecordCategoryEntry> {
throwIfNotDefined(recordCategoryId, 'recordCategoryId');
throwIfNotDefined(recordCategoryBodyUpdate, 'recordCategoryBodyUpdate');
opts = opts || {};
let postBody = recordCategoryBodyUpdate;
let pathParams = {
'recordCategoryId': recordCategoryId
};
let queryParams = {
'include': buildCollectionParam(opts['include'], 'csv'),
'fields': buildCollectionParam(opts['fields'], 'csv')
};
let headerParams = {
};
let formParams = {
};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/record-categories/{recordCategoryId}', 'PUT',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, RecordCategoryEntry);
}
} | the_stack |
import { AirGapWalletStatus, MoonbaseProtocol } from '../../../src'
import * as keccak from '../../../src/dependencies/src/keccak-1.0.2/js'
import * as secp256k1 from '../../../src/dependencies/src/secp256k1-4.0.2/elliptic'
import { SubstrateNetwork } from '../../../src/protocols/substrate/SubstrateNetwork'
import { TestProtocolSpec } from '../implementations'
import { MoonbaseProtocolStub } from '../stubs/moonbase.stub'
/*
* Test Mnemonic: leopard crouch simple blind castle they elder enact slow rate mad blanket saddle tail silk fury quarter obscure interest exact veteran volcano fabric cherry
*
*/
// Test Mnemonic: food talent voyage degree siege clever account medal film remind good kind
// Derivation path: m/44'/60'/0'/0/0
// Private Key: 548cef3b36e24a05870d80354900cab73082491907f162b1453f8b14bbf6f61f
// Public Key: 031bbd0cdadbef925d173e592c80c86d7917076d5b07ce79537867755f5d1dcc57
// Hex Seed: 55decc156b78772b5ae97cc4a7a4780c4b299d866abed355a8a6649905eadef4d28f76ff7491526addff6c03f3b200ebaa81dacd9f24def6ec88339a19562b91
// Address: 0xB6bC7946dFd3B9128777414c02296273ee6bBd0e
export class MoonbaseTestProtocolSpec extends TestProtocolSpec {
public name = 'Moonbeam'
public lib = new MoonbaseProtocol()
public stub = new MoonbaseProtocolStub()
public validAddresses = [
'0x8925639D43eB0298E95FfEfC792E8d23b7d06cbD',
'0x944e005444aafFE1bC57C9869b51033b7a7630C1',
'0x16dE158cfCF64aa409500F2C82E5305211e0D4e1',
'0xaABa95105e402eD13AB4B44738e7279fEDaDd686',
'0x8C44c6169d10E5E422C28364c4deeEaD83d72B52',
'0xB97224C27b232Dcf150C1f683d3bd01b1817f821',
'0xE0f749Bde03E3a2185e51A5A489948Eb371aD53C',
'0xdc065b9dcC4E20289A2869ce02Ea039f4c0f252E',
'0x82b54235abb1bb90D197437D504Adf07fb93F7D5',
'0xe6DFC410C539FEB97D2A1070fedf00dA575c5786',
'0xFE73fb832eCD3ad4284D3CafA9265FE836521aB6'
]
public wallet = {
privateKey: '548cef3b36e24a05870d80354900cab73082491907f162b1453f8b14bbf6f61f',
publicKey: '031bbd0cdadbef925d173e592c80c86d7917076d5b07ce79537867755f5d1dcc57',
addresses: ['0xB6bC7946dFd3B9128777414c02296273ee6bBd0e'],
masterFingerprint: 'f4e222fd',
status: AirGapWalletStatus.ACTIVE
}
public txs = [
{
from: this.wallet.addresses,
to: this.wallet.addresses,
amount: '1000000000000',
fee: '1000000000',
unsignedTx: {
encoded:
// tslint:disable-next-line: prefer-template
'04' + // number of txs
'5105' + // tx length
'01' + // optional type (specVersion)
'1e000000' + // specVersion
'00' + // type
'02286bee' + // fee
// transaction
'd901' + // length
'84' + // signed flag (not signed)
'B6bC7946dFd3B9128777414c02296273ee6bBd0e'.toLowerCase() + // AccountId signer
'00000000000000000000000000000000000000000000000000000000000000000' + // signature
'00000000000000000000000000000000000000000000000000000000000000000' + // signature
'8503' + // era
'04' + // nonce
'00' + // tip
'0300' + // moduleId + callId
'B6bC7946dFd3B9128777414c02296273ee6bBd0e'.toLowerCase() + // AccountId destination
'070010a5d4e8' + // value
// payload
'4103' + // payload length
Buffer.from(
'0300' + // moduleId + callId
'B6bC7946dFd3B9128777414c02296273ee6bBd0e' + // AccountId destination
'070010a5d4e8' + // value
'8503' + // era
'04' + // nonce
'00' + // tip
'1e000000' + // specVersion
'01000000' + // transactionVersion
'd51522c9ef7ba4e0990f7a4527de79afcac992ab97abbbc36722f8a27189b170' + // genesis hash
'33a7a745849347ce3008c07268be63d8cefd3ef61de0c7318e88a577fb7d26a9' // block hash
).toString('hex') // payload
},
signedTx:
// tslint:disable-next-line: prefer-template
'04' + // number of txs
'5105' + // tx length
'01' + // optional type (specVersion)
'1e000000' + // specVersion
'00' + // type
'02286bee' + // fee
// transaction
'd901' + // length
'84' + // signed flag (signed)
'B6bC7946dFd3B9128777414c02296273ee6bBd0e'.toLowerCase() + // AccountId signer
'6e015cfa75bbeb40b9555fb3e63fc8065f8888adae35d6776029435da40e5926a' + // signature
'f2f4b7ffb23b359aa9431c3a6d479d3afc03360fd919c9f88c57847c79278d700' + // signature
'8503' + // era
'04' + // nonce
'00' + // tip
'0300' + // moduleId + callId
'B6bC7946dFd3B9128777414c02296273ee6bBd0e'.toLowerCase() + // AccountId destination
'070010a5d4e8' + // value
// payload
'4103' + // payload length
Buffer.from(
'0300' + // moduleId + callId
'B6bC7946dFd3B9128777414c02296273ee6bBd0e' + // AccountId destination
'070010a5d4e8' + // value
'8503' + // era
'04' + // nonce
'00' + // tip
'1e000000' + // specVersion
'01000000' + // transactionVersion
'd51522c9ef7ba4e0990f7a4527de79afcac992ab97abbbc36722f8a27189b170' + // genesis hash
'33a7a745849347ce3008c07268be63d8cefd3ef61de0c7318e88a577fb7d26a9' // block hash
).toString('hex') // payload
}
]
public verifySignature = async (publicKey: string, tx: any): Promise<boolean> => {
const decoded = this.lib.options.transactionController.decodeDetails(tx)[0]
const signature = decoded.transaction.signature.signature.value
const message = keccak('keccak256').update(Buffer.from(decoded.payload, 'hex')).digest()
const publicKeyBuffer = Buffer.from(publicKey, 'hex')
return secp256k1.ecdsaVerify(signature.slice(0, 64), message, publicKeyBuffer)
}
public seed(): string {
return '55decc156b78772b5ae97cc4a7a4780c4b299d866abed355a8a6649905eadef4d28f76ff7491526addff6c03f3b200ebaa81dacd9f24def6ec88339a19562b91'
}
public mnemonic(): string {
return 'food talent voyage degree siege clever account medal film remind good kind'
}
public messages = []
public encryptAES = []
public transactionResult = {
transactions: [
{
protocolIdentifier: 'moonbeam',
network: {
name: 'Mainnet',
type: 'MAINNET',
rpcUrl: 'https://rpc.testnet.moonbeam.network',
blockExplorer: { blockExplorer: 'https://moonbase.subscan.io/' },
extras: { apiUrl: 'https://moonbase.subscan.io/api/scan', network: SubstrateNetwork.MOONBEAM }
},
from: ['0x8925639D43eB0298E95FfEfC792E8d23b7d06cbD'],
to: ['EEWyMLHgwtemr48spFNnS3U2XjaYswqAYAbadx2jr9ppp4X'],
isInbound: true,
amount: '99977416667634',
fee: '2583332366',
timestamp: 1601036370,
hash: '0x33482af443df63c3b0c9b5920b0723256a1e69602bba0bbe50cae3cb469084a5',
blockHeight: 4200705,
status: 'applied'
},
{
protocolIdentifier: 'moonbeam',
network: {
name: 'Mainnet',
type: 'MAINNET',
rpcUrl: 'https://rpc.testnet.moonbeam.network',
blockExplorer: { blockExplorer: 'https://moonbase.subscan.io/' },
extras: { apiUrl: 'https://moonbase.subscan.io/api/scan', network: SubstrateNetwork.MOONBEAM }
},
from: ['0x8925639D43eB0298E95FfEfC792E8d23b7d06cbD'],
to: ['0x944e005444aafFE1bC57C9869b51033b7a7630C1'],
isInbound: false,
amount: '1020000000000',
fee: '2583332366',
timestamp: 1601034570,
hash: '0xffef69ea4dbceef33bd904a2aaf92129cca4435642d7f71e85dbccb91d53c3af',
blockHeight: 4200409,
status: 'applied'
}
],
cursor: { page: 1 }
}
public nextTransactionResult = {
transactions: [
{
protocolIdentifier: 'moonbeam',
network: {
name: 'Mainnet',
type: 'MAINNET',
rpcUrl: 'https://rpc.testnet.moonbeam.network',
blockExplorer: { blockExplorer: 'https://moonbase.subscan.io/' },
extras: { apiUrl: 'https://moonbase.subscan.io/api/scan', network: SubstrateNetwork.MOONBEAM }
},
from: ['0x8925639D43eB0298E95FfEfC792E8d23b7d06cbD'],
to: ['0x944e005444aafFE1bC57C9869b51033b7a7630C1'],
isInbound: false,
amount: '15966000000000',
fee: '2599999026',
timestamp: 1601030652,
hash: '0xd02429787c9f28692018a2147ad093222857e686563c1166a1338fa9b624b9d3',
blockHeight: 4199759,
status: 'applied'
},
{
protocolIdentifier: 'moonbeam',
network: {
name: 'Mainnet',
type: 'MAINNET',
rpcUrl: 'https://rpc.testnet.moonbeam.network',
blockExplorer: { blockExplorer: 'https://moonbase.subscan.io/' },
extras: { apiUrl: 'https://moonbase.subscan.io/api/scan', network: SubstrateNetwork.MOONBEAM }
},
from: ['0x8925639D43eB0298E95FfEfC792E8d23b7d06cbD'],
to: ['0x944e005444aafFE1bC57C9869b51033b7a7630C1'],
isInbound: false,
amount: '3800000000000',
fee: '2599999026',
timestamp: 1601030412,
hash: '0x898a890d48861039715bd8d0671593ddf62c539f4b566fcab02859ff2b172c64',
blockHeight: 4199719,
status: 'applied'
}
],
cursor: { page: 2 }
}
}
/*
-045105011e0000000002286beed90184b6bc7946dfd3b9128777414c02296273ee6bbd0e6e015cfa75bbeb40b9555fb3e63fc8065f8888adae35d6776029435da40e592650d0b48004dc4ca6556bce3c592b862b0aeea985b1b7039c370ce64508a3c86a1c850304000300b6bc7946dfd3b9128777414c02296273ee6bbd0e070010a5d4e8410330333030423662433739343664466433423931323837373734313463303232393632373365653662426430653037303031306135643465383835303330343030316530303030303030313030303030306435313532326339656637626134653039393066376134353237646537396166636163393932616239376162626263333637323266386132373138396231373033336137613734353834393334376365333030386330373236386265363364386365666433656636316465306337333138653838613537376662376432366139
+045105011e0000000002286beed90184b6bc7946dfd3b9128777414c02296273ee6bbd0e6e015cfa75bbeb40b9555fb3e63fc8065f8888adae35d6776029435da40e5926af2f4b7ffb23b359aa9431c3a6d479d3afc03360fd919c9f88c57847c79278d700850304000300b6bc7946dfd3b9128777414c02296273ee6bbd0e070010a5d4e8410330333030423662433739343664466433423931323837373734313463303232393632373365653662426430653037303031306135643465383835303330343030316530303030303030313030303030306435313532326339656637626134653039393066376134353237646537396166636163393932616239376162626263333637323266386132373138396231373033336137613734353834393334376365333030386330373236386265363364386365666433656636316465306337333138653838613537376662376432366139
*/ | the_stack |
import { test } from '@japa/runner'
import 'reflect-metadata'
import { join } from 'path'
import { types } from 'util'
import { Filesystem } from '@poppinss/dev-utils'
import { Ioc } from '../src/Ioc'
import { inject } from '../src/decorators'
const fs = new Filesystem(join(__dirname, './app'))
test.group('Ioc', () => {
test('raise error when bind callback is not a function', ({ assert }) => {
const ioc = new Ioc()
const fn = () => (ioc as any).bind('App/Foo', 'hello')
assert.throws(fn, 'E_RUNTIME_EXCEPTION: "ioc.bind" expect 2nd argument to be a function')
})
test('add binding to the container', ({ assert }) => {
const ioc = new Ioc()
ioc.bind('App/Foo', () => {
return 'foo'
})
assert.deepEqual(ioc.lookup('App/Foo'), { namespace: 'App/Foo', type: 'binding' })
})
test('add singleton binding to the container', ({ assert }) => {
const ioc = new Ioc()
ioc.singleton('App/Foo', () => {
return 'foo'
})
assert.deepEqual(ioc.lookup('App/Foo'), { namespace: 'App/Foo', type: 'binding' })
})
test('register import alias', ({ assert }) => {
const ioc = new Ioc()
ioc.alias(join(__dirname, './app'), 'App')
assert.deepEqual(ioc.lookup('App/Foo'), { namespace: 'App/Foo', type: 'alias' })
assert.isNull(ioc.lookup('Apple/Foo'))
assert.deepEqual(ioc.importAliases, { App: join(__dirname, './app') })
})
test('register fake', ({ assert }) => {
const ioc = new Ioc()
ioc.fake('App/Foo', () => {})
assert.isTrue(ioc.hasFake('App/Foo'))
})
test('return true from "hasBinding" when binding exists', ({ assert }) => {
const ioc = new Ioc()
ioc.bind('App/Foo', () => {
return { foo: true }
})
assert.isTrue(ioc.hasBinding('App/Foo'))
assert.isFalse(ioc.hasBinding('Foo'))
})
test('return true from "isAliasPath" when namespace is part of import aliases', ({ assert }) => {
const ioc = new Ioc()
ioc.alias(join(__dirname, './app'), 'App')
assert.isTrue(ioc.isAliasPath('App/Foo'))
assert.isFalse(ioc.isAliasPath('Foo'))
})
test('return false from "isAliasPath" when import alias has a conflict with binding', ({
assert,
}) => {
const ioc = new Ioc()
ioc.alias(join(__dirname, './app'), 'App')
ioc.bind('App/Foo', () => {
return { foo: true }
})
assert.isFalse(ioc.isAliasPath('App/Foo'))
assert.isFalse(ioc.isAliasPath('Foo'))
})
test('return true from "hasFake" when fake exists', ({ assert }) => {
const ioc = new Ioc()
ioc.fake('App/Foo', () => {})
assert.isTrue(ioc.hasFake('App/Foo'))
})
})
test.group('Ioc | lookup', () => {
test('lookup namespace', ({ assert }) => {
const ioc = new Ioc()
ioc.bind('App/Foo', () => {
return 'foo'
})
assert.deepEqual(ioc.lookup('App/Foo'), {
namespace: 'App/Foo',
type: 'binding',
})
})
test('lookup absolute namespace', ({ assert }) => {
const ioc = new Ioc()
ioc.bind('App/Foo', () => {
return 'foo'
})
assert.deepEqual(ioc.lookup('/App/Foo'), {
namespace: 'App/Foo',
type: 'binding',
})
})
test('lookup namespace with a prefix', ({ assert }) => {
const ioc = new Ioc()
ioc.bind('App/Foo', () => {
return 'foo'
})
assert.deepEqual(ioc.lookup('Foo', 'App'), {
namespace: 'App/Foo',
type: 'binding',
})
})
test('lookup absolute namespace with a prefix', ({ assert }) => {
const ioc = new Ioc()
ioc.bind('App/Foo', () => {
return 'foo'
})
assert.deepEqual(ioc.lookup('/App/Foo', 'App'), {
namespace: 'App/Foo',
type: 'binding',
})
})
test('lookup namespace from aliases', ({ assert }) => {
const ioc = new Ioc()
ioc.alias(join(__dirname, './app'), 'App')
assert.deepEqual(ioc.lookup('App/Foo'), {
namespace: 'App/Foo',
type: 'alias',
})
})
test('lookup namespace from aliases with a prefix', ({ assert }) => {
const ioc = new Ioc()
ioc.alias(join(__dirname, './app'), 'App')
assert.deepEqual(ioc.lookup('Foo', 'App'), {
namespace: 'App/Foo',
type: 'alias',
})
})
test('lookup absolute namespace from aliases with a prefix', ({ assert }) => {
const ioc = new Ioc()
ioc.alias(join(__dirname, './app'), 'App')
assert.deepEqual(ioc.lookup('/App/Foo', 'App'), {
namespace: 'App/Foo',
type: 'alias',
})
})
test('give preference to binding when alias and binding namespace has a conflict', ({
assert,
}) => {
const ioc = new Ioc()
ioc.alias(join(__dirname, './app'), 'App')
ioc.bind('App/Foo', () => {
return 'foo'
})
assert.deepEqual(ioc.lookup('App/Foo'), { namespace: 'App/Foo', type: 'binding' })
})
test('return null when namespace is not a binding and neither part of import aliases', ({
assert,
}) => {
const ioc = new Ioc()
assert.isNull(ioc.lookup('App/Foo'))
})
})
test.group('Ioc | resolveBinding', () => {
test('resolve binding', ({ assert }) => {
const ioc = new Ioc()
ioc.bind('App/Foo', () => {
return 'foo'
})
assert.equal(ioc.resolveBinding('App/Foo'), 'foo')
})
test('do not resolve import alias', ({ assert }) => {
const ioc = new Ioc()
ioc.alias(join(__dirname, './app'), 'App')
assert.throws(
() => ioc.resolveBinding('App/Foo'),
'E_IOC_LOOKUP_FAILED: Cannot resolve "App/Foo" namespace from the IoC Container'
)
})
test('raise exception when binding is not registered', ({ assert }) => {
const ioc = new Ioc()
assert.throws(
() => ioc.resolveBinding('App/Foo'),
'E_IOC_LOOKUP_FAILED: Cannot resolve "App/Foo" namespace from the IoC Container'
)
})
test('resolve binding on every call', ({ assert }) => {
const ioc = new Ioc()
ioc.bind('App/Foo', () => {
return Symbol('foo')
})
assert.notStrictEqual(ioc.resolveBinding('App/Foo'), ioc.resolveBinding('App/Foo'))
})
test('do not resolve singleton in subsequent calls', ({ assert }) => {
const ioc = new Ioc()
ioc.singleton('App/Foo', () => {
return Symbol('foo')
})
assert.strictEqual(ioc.resolveBinding('App/Foo'), ioc.resolveBinding('App/Foo'))
})
test('wrap output "object" inside proxy when fake is registered', ({ assert }) => {
const ioc = new Ioc()
ioc.bind('App/Foo', () => {
return { foo: true }
})
ioc.useProxies()
ioc.fake('App/Foo', () => {
return { foo: false }
})
assert.deepEqual(ioc.resolveBinding('App/Foo'), { foo: false })
})
test('wrap output "class constructor" inside proxy when fake is registered', ({ assert }) => {
const ioc = new Ioc()
class User {
public username = 'user'
}
class FakeUser {
public username = 'fakeuser'
}
ioc.bind('App/Foo', () => {
return User
})
ioc.useProxies()
ioc.fake('App/Foo', () => {
return FakeUser
})
assert.equal(new (ioc.resolveBinding('App/Foo'))().username, 'fakeuser')
})
test('instantiating class without defining the fake should work fine', ({ assert }) => {
const ioc = new Ioc()
@inject(['App/Bar'])
class User {
public username = 'virk'
}
ioc.bind('App/Bar', () => {
return {}
})
ioc.bind('App/Foo', () => {
return User
})
ioc.useProxies(true)
assert.equal(ioc.make(ioc.resolveBinding('App/Foo')).username, 'virk')
})
test('class "static properties" must point to fake class', ({ assert }) => {
const ioc = new Ioc()
class User {
public static userName = 'virk'
}
class FakeUser {
public static userName = 'nikk'
}
ioc.bind('App/Foo', () => {
return User
})
ioc.useProxies()
ioc.fake('App/Foo', () => {
return FakeUser
})
assert.equal(ioc.resolveBinding('App/Foo').userName, 'nikk')
})
test('class non configurable properties should point to original object', ({ assert }) => {
const ioc = new Ioc()
class User {
public static userName = 'virk'
}
class FakeUser {
public static userName = 'nikk'
}
ioc.bind('App/Foo', () => {
return User
})
ioc.useProxies()
ioc.fake('App/Foo', () => {
return FakeUser
})
const Foo = ioc.resolveBinding('App/Foo')
const foo = new Foo()
assert.equal(foo.constructor.userName, 'virk')
})
test('class "constructor" must point to the original object, when "no fake is defined"', ({
assert,
}) => {
const ioc = new Ioc()
class User {
public static userName = 'virk'
}
ioc.bind('App/Foo', () => {
return User
})
ioc.useProxies()
const Foo = ioc.resolveBinding('App/Foo')
const foo = new Foo()
assert.equal(foo.constructor.userName, 'virk')
})
test('super class "constructor" must point to the fake class', ({ assert }) => {
const ioc = new Ioc()
class User {
public static userName = 'virk'
public username = 'virk'
}
class FakeUser {
public static userName = 'romain'
public username = 'romain'
}
ioc.bind('App/Foo', () => {
return User
})
ioc.useProxies()
ioc.fake('App/Foo', () => {
return FakeUser
})
class Bar extends ioc.resolveBinding('App/Foo') {
public static userName = 'nikk'
public username = 'nikk'
}
const bar = new Bar()
assert.deepEqual(bar.constructor, Bar)
assert.deepEqual(bar.constructor['userName'], 'nikk')
assert.deepEqual(bar.username, 'nikk')
assert.deepEqual(Object.getPrototypeOf(bar.constructor)['userName'], 'romain')
})
test('super class "constructor" must point to the original class, when "no fake is defined"', ({
assert,
}) => {
const ioc = new Ioc()
class User {
public static userName = 'virk'
public username = 'virk'
}
ioc.bind('App/Foo', () => {
return User
})
ioc.useProxies()
class Bar extends ioc.resolveBinding('App/Foo') {
public static userName = 'nikk'
public username = 'nikk'
}
const bar = new Bar()
assert.deepEqual(bar.constructor, Bar)
assert.deepEqual(bar.constructor['userName'], 'nikk')
assert.deepEqual(bar.username, 'nikk')
assert.deepEqual(Object.getPrototypeOf(bar.constructor)['userName'], 'virk')
})
test('do not wrap "literal" values inside proxy', ({ assert }) => {
const ioc = new Ioc()
class FakeUser {
public static userName = 'nikk'
}
ioc.bind('App/Foo', () => {
return 'foo'
})
ioc.useProxies()
ioc.fake('App/Foo', () => {
return FakeUser
})
assert.equal(ioc.resolveBinding('App/Foo'), 'foo')
})
test('trap "ioc.use" statement when binding is defined', ({ assert }) => {
const ioc = new Ioc()
ioc.bind('App/Foo', () => {
return 'foo'
})
ioc.trap(() => {
return { name: 'foo' }
})
assert.deepEqual(ioc.use('App/Foo'), { name: 'foo' })
})
test('trap "ioc.use" statement when binding is not defined', ({ assert }) => {
const ioc = new Ioc()
ioc.trap(() => {
return { name: 'foo' }
})
assert.deepEqual(ioc.use('App/Foo'), { name: 'foo' })
})
})
test.group('Ioc | require', (group) => {
group.each.teardown(async () => {
await fs.cleanup()
})
test('import "esm ts" module', async ({ assert }) => {
await fs.add(
'app/User.ts',
`
export default class User {
public username = 'virk'
}
`
)
const ioc = new Ioc()
ioc.alias(join(fs.basePath, './app'), 'App')
const resolved = ioc.require('App/User')
assert.property(resolved, 'default')
assert.equal(new resolved.default().username, 'virk')
})
test('handle path subsitions carefully', async ({ assert }) => {
await fs.add(
'app/User/App/User.ts',
`
export default class User {
public username = 'virk'
}
`
)
const ioc = new Ioc()
ioc.alias(join(fs.basePath, './app'), 'App')
const resolved = ioc.require('App/User/App/User')
assert.property(resolved, 'default')
assert.equal(new resolved.default().username, 'virk')
})
test('import "cjs js" module', async ({ assert }) => {
await fs.add(
'app/User.cjs.js',
`
module.exports = class User {
constructor() {
this.username = 'virk'
}
}
`
)
const ioc = new Ioc()
ioc.alias(join(fs.basePath, './app'), 'App')
const resolved = ioc.require('App/User.cjs')
assert.equal(new resolved().username, 'virk')
})
test('raise exception when module is missing', async ({ assert }) => {
assert.plan(1)
const ioc = new Ioc()
ioc.alias(join(fs.basePath, './app'), 'App')
try {
ioc.require('App/Foo')
} catch (error) {
assert.match(error.message, /Cannot find module/)
}
})
test('wrap output "object" inside proxy when fake is registered', async ({ assert }) => {
await fs.add(
'app/User.ts',
`
const user = {
username: 'virk'
}
export default user
`
)
await fs.add(
'app/User.cjs.js',
`
module.exports = {
username: 'virk'
}
`
)
const ioc = new Ioc()
ioc.alias(join(fs.basePath, './app'), 'App')
ioc.useProxies()
ioc.fake('App/User', () => {
return { username: 'romain' }
})
ioc.fake('App/User.cjs', () => {
return { username: 'romain' }
})
assert.deepEqual(ioc.require('App/User').default, { username: 'romain' })
assert.isTrue(ioc.require('App/User').__esModule)
assert.deepEqual(ioc.require('App/User.cjs'), { username: 'romain' })
ioc.useProxies(false)
assert.deepEqual(ioc.require('App/User').default, { username: 'virk' })
assert.isTrue(ioc.require('App/User').__esModule)
assert.deepEqual(ioc.require('App/User.cjs'), { username: 'virk' })
})
test('wrap output "class constructor" inside proxy when fake is registered', async ({
assert,
}) => {
await fs.add(
'app/User.ts',
`
export default class User {
public username = 'virk'
}
`
)
await fs.add(
'app/User.cjs.js',
`
module.exports = class User {
constructor() {
this.username = 'virk'
}
}
`
)
const ioc = new Ioc()
ioc.alias(join(fs.basePath, './app'), 'App')
ioc.useProxies()
ioc.fake('App/User', () => {
return class FakeUser {
public username = 'romain'
}
})
ioc.fake('App/User.cjs', () => {
return class FakeUser {
public username = 'romain'
}
})
assert.equal(new (ioc.require('App/User').default)().username, 'romain')
assert.isTrue(ioc.require('App/User').__esModule)
assert.equal(new (ioc.require('App/User.cjs'))().username, 'romain')
ioc.useProxies(false)
assert.equal(new (ioc.require('App/User').default)().username, 'virk')
assert.isTrue(ioc.require('App/User').__esModule)
assert.equal(new (ioc.require('App/User.cjs'))().username, 'virk')
})
test('class "static properties" must point to fake class', async ({ assert }) => {
await fs.add(
'app/User.ts',
`
export default class User {
public static userName = 'virk'
}
`
)
await fs.add(
'app/User.cjs.js',
`
module.exports = class User {
static get userName() {
return 'virk'
}
}
`
)
const ioc = new Ioc()
ioc.alias(join(fs.basePath, './app'), 'App')
ioc.useProxies()
ioc.fake('App/User', () => {
return class FakeUser {
public static userName = 'romain'
}
})
ioc.fake('App/User.cjs', () => {
return class FakeUser {
public static userName = 'romain'
}
})
ioc.useProxies()
assert.equal(ioc.require('App/User').default.userName, 'romain')
assert.equal(ioc.require('App/User.cjs').userName, 'romain')
ioc.useProxies(false)
assert.equal(ioc.require('App/User').default.userName, 'virk')
assert.equal(ioc.require('App/User.cjs').userName, 'virk')
})
test('class non configurable properties should point to original object', async ({ assert }) => {
await fs.add(
'app/User.ts',
`
export default class User {
public static userName = 'virk'
}
`
)
await fs.add(
'app/User.cjs.js',
`
module.exports = class User {
static get userName() {
return 'virk'
}
}
`
)
const ioc = new Ioc()
ioc.alias(join(fs.basePath, './app'), 'App')
ioc.useProxies()
ioc.fake('App/User', () => {
return class FakeUser {
public static userName = 'romain'
}
})
ioc.fake('App/User.cjs', () => {
return class FakeUser {
public static userName = 'romain'
}
})
ioc.useProxies()
const fakeUser = new (ioc.require('App/User').default)()
assert.equal(fakeUser.constructor.userName, 'virk')
const fakeUserCjs = new (ioc.require('App/User.cjs'))()
assert.equal(fakeUserCjs.constructor.userName, 'virk')
ioc.useProxies(false)
const user = new (ioc.require('App/User').default)()
assert.equal(user.constructor.userName, 'virk')
const userCjs = new (ioc.require('App/User.cjs'))()
assert.equal(userCjs.constructor.userName, 'virk')
})
test('class "constructor" must point to the original object, when "no fake is defined"', async ({
assert,
}) => {
await fs.add(
'app/User.ts',
`
export default class User {
public static userName = 'virk'
}
`
)
await fs.add(
'app/User.cjs.js',
`
module.exports = class User {
static get userName() {
return 'virk'
}
}
`
)
const ioc = new Ioc()
ioc.alias(join(fs.basePath, './app'), 'App')
ioc.useProxies()
const user = new (ioc.require('App/User').default)()
assert.equal(user.constructor.userName, 'virk')
const userCjs = new (ioc.require('App/User.cjs'))()
assert.equal(userCjs.constructor.userName, 'virk')
})
test('super class "constructor" must point to the fake class', async ({ assert }) => {
await fs.add(
'app/User.ts',
`export default class User {
public static userName = 'virk'
public username = 'virk'
}`
)
const ioc = new Ioc()
ioc.alias(join(fs.basePath, './app'), 'App')
ioc.useProxies()
ioc.fake('App/User', () => {
return class FakeUser {
public static userName = 'romain'
public username = 'romain'
}
})
const User = ioc.require('App/User').default
class Bar extends User {
public static userName = 'nikk'
public username = 'nikk'
}
const bar = new Bar()
assert.deepEqual(bar.constructor, Bar)
assert.deepEqual(bar.constructor['userName'], 'nikk')
assert.deepEqual(bar.username, 'nikk')
assert.deepEqual(Object.getPrototypeOf(bar.constructor)['userName'], 'romain')
})
test('super class "constructor" must point to the original class, when "no fake is defined"', async ({
assert,
}) => {
await fs.add(
'app/User.ts',
`export default class User {
public static userName = 'virk'
public username = 'virk'
}`
)
const ioc = new Ioc()
ioc.alias(join(fs.basePath, './app'), 'App')
ioc.useProxies()
const User = ioc.require('App/User').default
class Bar extends User {
public static userName = 'nikk'
public username = 'nikk'
}
const bar = new Bar()
assert.deepEqual(bar.constructor, Bar)
assert.deepEqual(bar.constructor['userName'], 'nikk')
assert.deepEqual(bar.username, 'nikk')
assert.deepEqual(Object.getPrototypeOf(bar.constructor)['userName'], 'virk')
})
test('do not wrap "literal" values inside proxy', async ({ assert }) => {
await fs.add(
'app/User.ts',
`const name = 'virk'
export default name
`
)
const ioc = new Ioc()
ioc.alias(join(fs.basePath, './app'), 'App')
ioc.useProxies()
ioc.fake('App/User', () => {
return class FakeUser {
public static userName = 'nikk'
}
})
assert.equal(ioc.require('App/User').default, 'virk')
})
test('trap "ioc.use" statement when binding is defined', ({ assert }) => {
const ioc = new Ioc()
ioc.bind('App/Foo', () => {
return 'foo'
})
ioc.trap(() => {
return { name: 'foo' }
})
assert.deepEqual(ioc.use('App/Foo'), { name: 'foo' })
})
test('trap "ioc.use" statement when binding is not defined', ({ assert }) => {
const ioc = new Ioc()
ioc.trap(() => {
return { name: 'foo' }
})
assert.deepEqual(ioc.use('App/Foo'), { name: 'foo' })
})
})
test.group('Ioc | make', (group) => {
group.each.teardown(async () => {
await fs.cleanup()
})
test('make instance of a class', ({ assert }) => {
const ioc = new Ioc()
class Foo {}
assert.instanceOf(ioc.make(Foo), Foo)
})
test('make instance and inject dependencies', ({ assert }) => {
const ioc = new Ioc()
class Bar {}
ioc.bind('App/Bar', () => {
return new Bar()
})
class Foo {
constructor(public bar: Bar) {}
/**
* Class injections
*/
public static get inject() {
return {
instance: ['App/Bar'],
}
}
}
assert.instanceOf(ioc.make(Foo).bar, Bar)
})
test('make instance of a class and inject dependencies with runtime dependencies', ({
assert,
}) => {
const ioc = new Ioc()
class Bar {}
class Baz {}
ioc.bind('App/Bar', () => {
return new Bar()
})
class Foo {
constructor(public bar: Bar, public foo: any) {}
/**
* Class injections
*/
public static get inject() {
return {
instance: ['App/Bar'],
}
}
}
assert.equal(ioc.make(Foo, [new Bar(), 'foo']).foo, 'foo')
assert.instanceOf(ioc.make(Foo, [new Bar(), 'foo']).bar, Bar)
assert.instanceOf(ioc.make(Foo, [new Baz(), 'foo']).bar, Baz)
})
test('do not make instance when makePlain is set to true', ({ assert }) => {
const ioc = new Ioc()
class Foo {
constructor(public bar: Bar) {}
public static get makePlain(): true {
return true
}
public static get inject() {
return ['App/Bar']
}
}
class Bar {}
ioc.bind('App/Bar', () => {
return new Bar()
})
assert.deepEqual(ioc.make(Foo), Foo)
})
test('do not make instance when namespace is a binding', ({ assert }) => {
const ioc = new Ioc()
class Bar {}
ioc.bind('App/Bar', () => {
return Bar
})
assert.deepEqual(ioc.make('App/Bar'), Bar)
})
test('make instance when namespace is part of directory aliases', async ({ assert }) => {
await fs.add(
'Foo.js',
`module.exports = class Foo {
constructor () {
this.name = 'foo'
}
}`
)
const ioc = new Ioc()
ioc.alias(join(fs.basePath), 'Admin')
assert.deepEqual(ioc.make('Admin/Foo').name, 'foo')
})
test('inject dependencies when namespace is part of directory aliases', async ({ assert }) => {
await fs.add(
'Foo.js',
`module.exports = class Foo {
constructor (bar) {
this.bar = bar
}
static get inject() {
return {
instance: ['App/Bar'],
}
}
}`
)
const ioc = new Ioc()
class Bar {}
ioc.bind('App/Bar', () => {
return new Bar()
})
ioc.alias(join(fs.basePath), 'Admin')
assert.instanceOf(ioc.make('Admin/Foo').bar, Bar)
})
test('allow faking directory aliases namespace', async ({ assert }) => {
await fs.add(
'Foo.js',
`module.exports = class Foo {
constructor () {
this.name = 'foo'
}
}`
)
const ioc = new Ioc()
ioc.alias(join(fs.basePath), 'Admin')
ioc.useProxies()
class Bar {
public name = 'bar'
}
ioc.fake('Admin/Foo', () => {
return Bar
})
assert.equal(ioc.make('Admin/Foo').name, 'bar')
assert.isTrue(types.isProxy(ioc.use('Admin/Foo')))
})
test('make instance when namespace is part of directory aliases', async ({ assert }) => {
await fs.add(
'Bar.ts',
`export default class Bar {
constructor () {
this.name = 'bar'
}
}`
)
const ioc = new Ioc()
ioc.alias(join(fs.basePath), 'Admin')
assert.deepEqual(ioc.make('Admin/Bar').name, 'bar')
})
test('inject dependencies when namespace is part of directory aliases', async ({ assert }) => {
await fs.add(
'Bar.ts',
`export default class Bar {
constructor (baz) {
this.baz = baz
}
static get inject() {
return {
instance: ['App/Baz'],
}
}
}`
)
const ioc = new Ioc()
class Baz {}
ioc.bind('App/Baz', () => {
return new Baz()
})
ioc.alias(join(fs.basePath), 'Admin')
assert.instanceOf(ioc.make('Admin/Bar').baz, Baz)
})
test('allow faking directory aliases namespace', async ({ assert }) => {
await fs.add(
'Bar.ts',
`export default class Bar {
constructor () {
this.name = 'bar'
}
}`
)
const ioc = new Ioc()
ioc.alias(join(fs.basePath), 'Admin')
ioc.useProxies()
class Baz {
public name = 'baz'
}
ioc.fake('Admin/Bar', () => {
return Baz
})
assert.equal(ioc.make('Admin/Bar').name, 'baz')
assert.isTrue(types.isProxy(ioc.use('Admin/Bar').default))
})
test('do not make esm named exports', async ({ assert }) => {
await fs.add(
'Bar.ts',
`export class Bar {
public name = 'bar'
}`
)
const ioc = new Ioc()
ioc.alias(fs.basePath, 'App')
assert.equal(ioc.make('App/Bar').Bar.name, 'Bar')
})
test('do not proxy named exports', async ({ assert }) => {
await fs.add(
'Bar.ts',
`export class Bar {
public name = 'bar'
}`
)
const ioc = new Ioc()
ioc.useProxies()
ioc.alias(fs.basePath, 'App')
assert.isFalse(types.isProxy(ioc.make('App/Bar')))
})
test('trap "ioc.make" statement when binding is defined', ({ assert }) => {
const ioc = new Ioc()
ioc.bind('App/Foo', () => {
return 'foo'
})
ioc.trap(() => {
return { name: 'foo' }
})
assert.deepEqual(ioc.make('App/Foo'), { name: 'foo' })
})
test('trap "ioc.make" statement when binding is not defined', ({ assert }) => {
const ioc = new Ioc()
ioc.trap(() => {
return { name: 'foo' }
})
assert.deepEqual(ioc.make('App/Foo'), { name: 'foo' })
})
})
test.group('Ioc | withBindings', () => {
test('execute the callback when all bindings exists', async ({ assert }) => {
assert.plan(2)
const ioc = new Ioc()
ioc.bind('App/Foo', () => {
return 'foo'
})
ioc.bind('App/Bar', () => {
return 'bar'
})
ioc.withBindings(['App/Foo', 'App/Bar'], (foo, bar) => {
assert.equal(foo, 'foo')
assert.equal(bar, 'bar')
})
})
test('do not execute the callback if any bindings is missing', async () => {
const ioc = new Ioc()
ioc.bind('App/Foo', () => {
return 'foo'
})
ioc.withBindings(['App/Foo', 'App/Bar'], () => {
throw new Error('Never expected to be called')
})
})
})
test.group('Ioc | Proxy', (group) => {
group.each.teardown(async () => {
await fs.cleanup()
})
test('ensure proxy traps works fine on class instance', ({ assert }) => {
class Foo {
public name = 'foo'
public getName() {
return this.name
}
}
const ioc = new Ioc()
ioc.useProxies()
ioc.bind('App/Foo', () => {
return new Foo()
})
const value = ioc.use('App/Foo')
assert.equal(value.name, 'foo')
assert.equal(value.getName(), 'foo')
assert.isUndefined(value.nonProp)
value.nonProp = true
assert.isTrue(value.nonProp)
assert.equal(value.constructor.name, 'Foo')
assert.deepEqual(Object.getOwnPropertyNames(Object.getPrototypeOf(value)), [
'constructor',
'getName',
])
})
test('ensure proxy traps works fine with fakes', ({ assert }) => {
class Foo {
public name = 'foo'
public getName() {
return this.name
}
public invoke(...args: any[]) {
return args.concat(['real'])
}
}
class FooFake {
public name = 'foofake'
public getName() {
return this.name
}
}
const ioc = new Ioc()
ioc.bind('App/Foo', () => {
return new Foo()
})
ioc.useProxies()
const value = ioc.use('App/Foo')
/**
* Trap get
*/
assert.equal(value.name, 'foo')
/**
* Trap get (hold scope)
*/
assert.equal(value.getName(), 'foo')
/**
* Trap get (reflect truth)
*/
assert.isUndefined(value.nonProp)
/**
* Trap set
*/
value.nonProp = true
assert.isTrue(value.nonProp)
/**
* Trap get constructor
*/
assert.equal(value.constructor.name, 'Foo')
/**
* Trap getPrototypeOf
*/
assert.deepEqual(Object.getOwnPropertyNames(Object.getPrototypeOf(value)), [
'constructor',
'getName',
'invoke',
])
/**
* Trap ownKeys
*/
assert.deepEqual(Object.getOwnPropertyNames(value), ['name', 'nonProp'])
/**
* Trap isExtensible
*/
assert.isTrue(Object.isExtensible(value))
/**
* Trap deleteProperty
*/
delete value.nonProp
assert.isUndefined(value.nonProp)
/**
* Trap has
*/
assert.isTrue('name' in value)
assert.isFalse('nonProp' in value)
/**
* Trap setPrototypeOf
*/
Object.setPrototypeOf(value, {
getName() {
return 'proto name'
},
})
assert.equal(value.getName(), 'proto name')
Object.setPrototypeOf(value, Foo.prototype)
assert.equal(value.getName(), 'foo')
/**
* Trap preventExtensions
*/
const fn = () => Object.preventExtensions(value)
assert.throws(fn, 'Cannot prevent extensions during a fake')
ioc.fake('App/Foo', () => {
return new FooFake()
})
/**
* Trap get
*/
assert.equal(value.name, 'foofake')
/**
* Trap get (hold scope)
*/
assert.equal(value.getName(), 'foofake')
/**
* Trap get (reflect truth)
*/
assert.isUndefined(value.nonProp)
/**
* Trap set
*/
value.nonProp = true
assert.isTrue(value.nonProp)
/**
* Trap get constructor
*/
assert.equal(value.constructor.name, 'FooFake')
/**
* Trap getPrototypeOf
*/
assert.deepEqual(Object.getOwnPropertyNames(Object.getPrototypeOf(value)), [
'constructor',
'getName',
])
/**
* Trap ownKeys
*/
assert.deepEqual(Object.getOwnPropertyNames(value), ['name', 'nonProp'])
/**
* Trap isExtensible
*/
assert.isTrue(Object.isExtensible(value))
/**
* Trap deleteProperty
*/
delete value.nonProp
assert.isUndefined(value.nonProp)
/**
* Trap has
*/
assert.isTrue('name' in value)
assert.isFalse('nonProp' in value)
/**
* Trap setPrototypeOf
*/
Object.setPrototypeOf(value, {
getName() {
return 'proto name'
},
})
assert.equal(value.getName(), 'proto name')
Object.setPrototypeOf(value, Foo.prototype)
assert.equal(value.getName(), 'foofake')
/**
* Trap preventExtensions
*/
const fn1 = () => Object.preventExtensions(value)
assert.throws(fn1, 'Cannot prevent extensions during a fake')
})
test('ensure proxy traps works fine when fake has been restored', ({ assert }) => {
class Foo {
public name = 'foo'
public getName() {
return this.name
}
}
class FooFake {
public name = 'foofake'
public getName() {
return this.name
}
}
const ioc = new Ioc()
ioc.useProxies()
ioc.bind('App/Foo', () => {
return new Foo()
})
const value = ioc.use('App/Foo')
assert.equal(value.name, 'foo')
assert.equal(value.getName(), 'foo')
assert.isUndefined(value.nonProp)
value.nonProp = true
assert.isTrue(value.nonProp)
assert.equal(value.constructor.name, 'Foo')
assert.deepEqual(Object.getOwnPropertyNames(Object.getPrototypeOf(value)), [
'constructor',
'getName',
])
// Fake added
ioc.fake('App/Foo', () => {
return new FooFake()
})
assert.equal(value.name, 'foofake')
assert.equal(value.getName(), 'foofake')
assert.isUndefined(value.nonProp)
value.nonProp = true
assert.isTrue(value.nonProp)
assert.equal(value.constructor.name, 'FooFake')
assert.deepEqual(Object.getOwnPropertyNames(Object.getPrototypeOf(value)), [
'constructor',
'getName',
])
// Fake restored
ioc.restore('App/Foo')
assert.equal(value.name, 'foo')
assert.equal(value.getName(), 'foo')
assert.equal(value.constructor.name, 'Foo')
assert.deepEqual(Object.getOwnPropertyNames(Object.getPrototypeOf(value)), [
'constructor',
'getName',
])
})
test('proxy class constructor', ({ assert }) => {
class Foo {
public name = 'foo'
public getName() {
return this.name
}
}
class FooFake {
public name = 'foofake'
public getName() {
return this.name
}
}
const ioc = new Ioc()
ioc.useProxies()
ioc.bind('App/Foo', () => {
return Foo
})
const value = ioc.use('App/Foo')
assert.instanceOf(new value(), Foo)
ioc.fake('App/Foo', () => {
return FooFake
})
assert.equal(new value().name, 'foofake')
})
test('proxy class constructor via ioc.make', ({ assert }) => {
class Foo {
public name = 'foo'
public getName() {
return this.name
}
}
class FooFake {
public name = 'foofake'
public getName() {
return this.name
}
}
const ioc = new Ioc()
ioc.useProxies()
ioc.bind('App/Foo', () => {
return Foo
})
const value = ioc.make('App/Foo')
assert.instanceOf(new value(), Foo)
ioc.fake('App/Foo', () => {
return FooFake
})
assert.equal(ioc.make(value).name, 'foofake')
})
test('proxy class constructor when no fake is defined', ({ assert }) => {
class Foo {
public name = 'foo'
public getName() {
return this.name
}
}
const ioc = new Ioc()
ioc.useProxies()
ioc.bind('App/Foo', () => {
return Foo
})
const value = ioc.make('App/Foo')
assert.instanceOf(new value(), Foo)
assert.equal(new value().name, 'foo')
})
test('proxy class constructor via ioc.make when no fake is defined', ({ assert }) => {
class Foo {
public name = 'foo'
public getName() {
return this.name
}
}
const ioc = new Ioc()
ioc.useProxies()
ioc.bind('App/Foo', () => {
return Foo
})
const value = ioc.make('App/Foo')
assert.instanceOf(new value(), Foo)
assert.equal(ioc.make(value).name, 'foo')
})
test('do not proxy literals when using ioc.make', ({ assert }) => {
const ioc = new Ioc()
ioc.useProxies()
ioc.bind('App/Foo', () => {
return 'foo'
})
const value = ioc.make('App/Foo')
assert.equal(value, 'foo')
ioc.fake('App/Foo', () => {
return 'fakefake'
})
assert.equal(value, 'foo')
})
test('do not proxy literals when using ioc.use', ({ assert }) => {
const ioc = new Ioc()
ioc.useProxies()
ioc.bind('App/Foo', () => {
return 'foo'
})
const value = ioc.use('App/Foo')
assert.equal(value, 'foo')
ioc.fake('App/Foo', () => {
return 'fakefake'
})
assert.equal(value, 'foo')
})
test('proxy autoloaded class using use', async ({ assert }) => {
await fs.add(
'Bar.ts',
`export = class Bar {
public name = 'bar'
}`
)
const ioc = new Ioc()
ioc.alias(fs.basePath, 'App')
class BarFake {
public name = 'barfake'
public getName() {
return this.name
}
}
ioc.useProxies()
const value = ioc.use('App/Bar')
assert.equal(new value().name, 'bar')
ioc.fake('App/Bar', () => {
return BarFake
})
assert.equal(new value().name, 'barfake')
})
test('proxy bindings using use', async ({ assert }) => {
const ioc = new Ioc()
ioc.bind('App/Bar', () => {
class Bar {
public name = 'bar'
}
return Bar
})
class FooFake {
public name = 'foofake'
public getName() {
return this.name
}
}
ioc.useProxies()
const value = ioc.use('App/Bar')
assert.equal(new value().name, 'bar')
ioc.fake('App/Bar', () => {
return FooFake
})
assert.equal(new value().name, 'foofake')
})
test('proxy autoloaded class using make', async ({ assert }) => {
await fs.add(
'Bar.ts',
`export default class Bar {
public name = 'bar'
}`
)
const ioc = new Ioc()
ioc.alias(fs.basePath, 'App')
class BarFake {
public name = 'barfake'
public getName() {
return this.name
}
}
ioc.useProxies()
assert.equal(ioc.make('App/Bar').name, 'bar')
ioc.fake('App/Bar', () => {
return BarFake
})
assert.equal(ioc.make('App/Bar').name, 'barfake')
})
test('proxy bindings using make', ({ assert }) => {
class Foo {
public name = 'foo'
public getName() {
return this.name
}
}
class FooFake {
public name = 'foofake'
public getName() {
return this.name
}
}
const ioc = new Ioc()
ioc.useProxies()
ioc.bind('App/Foo', () => {
return new Foo()
})
const value = ioc.make('App/Foo')
assert.equal(value.name, 'foo')
ioc.fake('App/Foo', () => {
return new FooFake()
})
assert.equal(value.name, 'foofake')
})
})
test.group('Ioc | inject decorator', () => {
test('set inject property for constructor injections', ({ assert }) => {
@inject(['App/Bar'])
class Foo {
constructor(public bar: any) {}
}
assert.deepEqual(Foo['inject'], {
instance: ['App/Bar'],
})
})
test('set inject property for constructor injections via reflection', ({ assert }) => {
class Bar {}
@inject()
class Foo {
constructor(public bar: Bar) {}
}
assert.deepEqual(Foo['inject'], {
instance: [Bar],
})
})
test('set inject property for constructor by mix-matching reflection and custom injections', ({
assert,
}) => {
class Bar {}
@inject(['App/Baz'])
class Foo {
constructor(public baz: any, public bar: Bar) {}
}
assert.deepEqual(Foo['inject'], { instance: ['App/Baz', Bar] })
})
test('define custom injections after reflection index', ({ assert }) => {
class Bar {}
@inject([null, 'App/Baz'])
class Foo {
constructor(public bar: Bar, public baz: any) {}
}
assert.deepEqual(Foo['inject'], { instance: [Bar, 'App/Baz'] })
})
test('set injections when parameter has no type', ({ assert }) => {
class Bar {}
@inject()
class Foo {
constructor(public bar: Bar, public baz) {}
}
assert.deepEqual(Foo['inject'], { instance: [Bar, Object] })
})
test('set parameter injections', ({ assert }) => {
class Bar {}
class Foo {
@inject()
public greet(_bar: Bar) {}
}
assert.deepEqual(Foo['inject'], { greet: [Bar] })
})
test('set multiple parameter injections', ({ assert }) => {
class Bar {}
class Foo {
@inject()
public greet(_bar: Bar, _baz: any) {}
}
assert.deepEqual(Foo['inject'], { greet: [Bar, Object] })
})
test('inject constructor dependencies injected via decorator', ({ assert }) => {
const ioc = new Ioc()
class Bar {}
@inject()
class Foo {
constructor(public bar: Bar) {}
}
assert.instanceOf(ioc.make(Foo).bar, Bar)
})
test('inject constructor dependencies with runtime arguments', ({ assert }) => {
const ioc = new Ioc()
class Bar {}
@inject()
class Foo {
constructor(public username: string, public bar: Bar) {}
}
const foo = ioc.make(Foo, ['virk'])
assert.instanceOf(foo.bar, Bar)
assert.equal(foo.username, 'virk')
})
test('raise error when class has primitive or object constructor injections', ({ assert }) => {
const ioc = new Ioc()
@inject()
class Foo {
constructor(public baz: string) {}
}
const fn = () => ioc.make(Foo)
assert.throws(fn, 'Cannot inject "{String Constructor}" to "Foo" at position "1"')
})
test('inject method dependencies injected via decorator', ({ assert }) => {
assert.plan(1)
const ioc = new Ioc()
class Bar {}
class Foo {
@inject()
public greet(bar: Bar) {
assert.instanceOf(bar, Bar)
}
}
ioc.call(ioc.make(Foo), 'greet', [])
})
test('inject method dependencies with runtime arguments', ({ assert }) => {
assert.plan(2)
const ioc = new Ioc()
class Bar {}
class Foo {
@inject()
public greet(username: string, bar: Bar) {
assert.equal(username, 'virk')
assert.instanceOf(bar, Bar)
}
}
ioc.call(ioc.make(Foo), 'greet', ['virk'])
})
test('inject method dependencies with interface type hinting', ({ assert }) => {
assert.plan(2)
const ioc = new Ioc()
interface BarContract {}
class Bar {}
ioc.bind('App/Bar', () => {
return new Bar()
})
class Foo {
@inject([null, 'App/Bar'])
public greet(username: string, bar: BarContract) {
assert.equal(username, 'virk')
assert.instanceOf(bar, Bar)
}
}
ioc.call(ioc.make(Foo), 'greet', ['virk'])
})
test('raise error when method has primitive or object constructor injections', ({ assert }) => {
const ioc = new Ioc()
class Bar {}
class Foo {
@inject()
public greet(_username: string, _bar: Bar) {}
}
const fn = () => ioc.call(ioc.make(Foo), 'greet', [])
assert.throws(fn, 'Cannot inject "{String Constructor}" to "Foo.greet" at position "1"')
})
test('call object method even when it has zero injections', ({ assert }) => {
assert.plan(1)
const ioc = new Ioc()
class Foo {
public greet() {
assert.isTrue(true)
}
}
ioc.call(ioc.make(Foo), 'greet')
})
})
test.group('Ioc | lookup resolve', (group) => {
group.each.teardown(async () => {
await fs.cleanup()
})
test('lookup binding from a lookup node', ({ assert }) => {
const ioc = new Ioc()
ioc.bind('App/Foo', () => {
return 'foo'
})
assert.equal(ioc.use({ type: 'binding', namespace: 'App/Foo' }), 'foo')
})
test('lookup directory alias value from a lookup node', async ({ assert }) => {
await fs.add('Foo.js', "module.exports = 'bar'")
const ioc = new Ioc()
ioc.alias(fs.basePath, 'App')
assert.equal(ioc.use({ type: 'alias', namespace: 'App/Foo' }), 'bar')
})
test('raise exception when unable to resolve lookup namespace', async ({ assert }) => {
await fs.add('Foo.js', "module.exports = 'bar'")
const ioc = new Ioc()
ioc.alias(fs.basePath, 'App')
const fn = () => ioc.use({ type: 'binding', namespace: 'App/Foo' })
assert.throws(
fn,
'E_IOC_LOOKUP_FAILED: Cannot resolve "App/Foo" namespace from the IoC Container'
)
})
test('do not resolve binding for autoload lookup node', async ({ assert }) => {
await fs.add('Foo.js', "module.exports = 'bar'")
const ioc = new Ioc()
ioc.bind('App/Foo', () => {
return 'foo'
})
const fn = () => ioc.use({ type: 'alias', namespace: 'App/Foo' })
assert.throws(
fn,
'E_IOC_LOOKUP_FAILED: Cannot resolve "App/Foo" namespace from the IoC Container'
)
})
test('make binding from binding lookup node', ({ assert }) => {
const ioc = new Ioc()
class Bar {}
ioc.bind('App/Foo', () => {
return Bar
})
assert.equal(ioc.make({ type: 'binding', namespace: 'App/Foo' }), Bar)
})
test('make binding from autoloaded lookup node', async ({ assert }) => {
await fs.add(
'Foo.js',
`
module.exports = class Bar {
constructor () {
this.name = 'bar'
}
}
`
)
const ioc = new Ioc()
ioc.alias(fs.basePath, 'App')
assert.equal(ioc.make({ type: 'alias', namespace: 'App/Foo' }).name, 'bar')
})
test('do not make binding for autoload lookup node', async ({ assert }) => {
await fs.add('Foo.js', "module.exports = 'bar'")
const ioc = new Ioc()
ioc.bind('App/Foo', () => {
return 'foo'
})
const fn = () => ioc.make({ type: 'alias', namespace: 'App/Foo' })
assert.throws(
fn,
'E_IOC_LOOKUP_FAILED: Cannot resolve "App/Foo" namespace from the IoC Container'
)
})
test('raise exception when unable to make lookup namespace', async ({ assert }) => {
await fs.add('Foo.js', "module.exports = 'bar'")
const ioc = new Ioc()
ioc.alias(fs.basePath, 'App')
const fn = () => ioc.make({ type: 'binding', namespace: 'App/Foo' })
assert.throws(
fn,
'E_IOC_LOOKUP_FAILED: Cannot resolve "App/Foo" namespace from the IoC Container'
)
})
}) | the_stack |
import { Rule, RuleProperty, ValidationDisplayNameAccessor } from './rule';
import { ValidationMessageParser } from './validation-message-parser';
import { Rules } from './rules';
import { validationMessages } from './validation-messages';
import { PropertyAccessorParser, PropertyAccessor } from '../property-accessor-parser';
import { isString } from '../util';
/**
* Part of the fluent rule API. Enables customizing property rules.
*/
export class FluentRuleCustomizer<TObject, TValue> {
private rule: Rule<TObject, TValue>;
constructor(
property: RuleProperty,
condition: (value: TValue, object?: TObject) => boolean | Promise<boolean>,
config: object = {},
private fluentEnsure: FluentEnsure<TObject>,
private fluentRules: FluentRules<TObject, TValue>,
private parsers: Parsers
) {
this.rule = {
property,
condition,
config,
when: null,
messageKey: 'default',
message: null,
sequence: fluentRules.sequence
};
this.fluentEnsure._addRule(this.rule);
}
/**
* Validate subsequent rules after previously declared rules have
* been validated successfully. Use to postpone validation of costly
* rules until less expensive rules pass validation.
*/
public then() {
this.fluentRules.sequence++;
return this;
}
/**
* Specifies the key to use when looking up the rule's validation message.
*/
public withMessageKey(key: string) {
this.rule.messageKey = key;
this.rule.message = null;
return this;
}
/**
* Specifies rule's validation message.
*/
public withMessage(message: string) {
this.rule.messageKey = 'custom';
this.rule.message = this.parsers.message.parse(message);
return this;
}
/**
* Specifies a condition that must be met before attempting to validate the rule.
* @param condition A function that accepts the object as a parameter and returns true
* or false whether the rule should be evaluated.
*/
public when(condition: (object: TObject) => boolean) {
this.rule.when = condition;
return this;
}
/**
* Tags the rule instance, enabling the rule to be found easily
* using ValidationRules.taggedRules(rules, tag)
*/
public tag(tag: string) {
this.rule.tag = tag;
return this;
}
///// FluentEnsure APIs /////
/**
* Target a property with validation rules.
* @param property The property to target. Can be the property name or a property accessor function.
*/
public ensure<TValue2>(subject: string | ((model: TObject) => TValue2)) {
return this.fluentEnsure.ensure<TValue2>(subject);
}
/**
* Targets an object with validation rules.
*/
public ensureObject() {
return this.fluentEnsure.ensureObject();
}
/**
* Rules that have been defined using the fluent API.
*/
public get rules() {
return this.fluentEnsure.rules;
}
/**
* Applies the rules to a class or object, making them discoverable by the StandardValidator.
* @param target A class or object.
*/
public on(target: any) {
return this.fluentEnsure.on(target);
}
///////// FluentRules APIs /////////
/**
* Applies an ad-hoc rule function to the ensured property or object.
* @param condition The function to validate the rule.
* Will be called with two arguments, the property value and the object.
* Should return a boolean or a Promise that resolves to a boolean.
*/
public satisfies(condition: (value: TValue, object: TObject) => boolean | Promise<boolean>, config?: object) {
return this.fluentRules.satisfies(condition, config);
}
/**
* Applies a rule by name.
* @param name The name of the custom or standard rule.
* @param args The rule's arguments.
*/
public satisfiesRule(name: string, ...args: any[]) {
return this.fluentRules.satisfiesRule(name, ...args);
}
/**
* Applies the "required" rule to the property.
* The value cannot be null, undefined or whitespace.
*/
public required() {
return this.fluentRules.required();
}
/**
* Applies the "matches" rule to the property.
* Value must match the specified regular expression.
* null, undefined and empty-string values are considered valid.
*/
public matches(regex: RegExp) {
return this.fluentRules.matches(regex);
}
/**
* Applies the "email" rule to the property.
* null, undefined and empty-string values are considered valid.
*/
public email() {
return this.fluentRules.email();
}
/**
* Applies the "minLength" STRING validation rule to the property.
* null, undefined and empty-string values are considered valid.
*/
public minLength(length: number) {
return this.fluentRules.minLength(length);
}
/**
* Applies the "maxLength" STRING validation rule to the property.
* null, undefined and empty-string values are considered valid.
*/
public maxLength(length: number) {
return this.fluentRules.maxLength(length);
}
/**
* Applies the "minItems" ARRAY validation rule to the property.
* null and undefined values are considered valid.
*/
public minItems(count: number) {
return this.fluentRules.minItems(count);
}
/**
* Applies the "maxItems" ARRAY validation rule to the property.
* null and undefined values are considered valid.
*/
public maxItems(count: number) {
return this.fluentRules.maxItems(count);
}
/**
* Applies the "min" NUMBER validation rule to the property.
* Value must be greater than or equal to the specified constraint.
* null and undefined values are considered valid.
*/
public min(value: number) {
return this.fluentRules.min(value);
}
/**
* Applies the "max" NUMBER validation rule to the property.
* Value must be less than or equal to the specified constraint.
* null and undefined values are considered valid.
*/
public max(value: number) {
return this.fluentRules.max(value);
}
/**
* Applies the "range" NUMBER validation rule to the property.
* Value must be between or equal to the specified min and max.
* null and undefined values are considered valid.
*/
public range(min: number, max: number) {
return this.fluentRules.range(min, max);
}
/**
* Applies the "between" NUMBER validation rule to the property.
* Value must be between but not equal to the specified min and max.
* null and undefined values are considered valid.
*/
public between(min: number, max: number) {
return this.fluentRules.between(min, max);
}
/**
* Applies the "equals" validation rule to the property.
* null, undefined and empty-string values are considered valid.
*/
public equals(expectedValue: TValue) {
return this.fluentRules.equals(expectedValue);
}
}
/**
* Part of the fluent rule API. Enables applying rules to properties and objects.
*/
export class FluentRules<TObject, TValue> {
public static customRules: {
[name: string]: {
condition: (value: any, object?: any, ...fluentArgs: any[]) => boolean | Promise<boolean>;
argsToConfig?: (...args: any[]) => any;
}
} = {};
/**
* Current rule sequence number. Used to postpone evaluation of rules until rules
* with lower sequence number have successfully validated. The "then" fluent API method
* manages this property, there's usually no need to set it directly.
*/
public sequence = 0;
constructor(
private fluentEnsure: FluentEnsure<TObject>,
private parsers: Parsers,
private property: RuleProperty
) { }
/**
* Sets the display name of the ensured property.
*/
public displayName(name: string | ValidationDisplayNameAccessor | null) {
this.property.displayName = name;
return this;
}
/**
* Applies an ad-hoc rule function to the ensured property or object.
* @param condition The function to validate the rule.
* Will be called with two arguments, the property value and the object.
* Should return a boolean or a Promise that resolves to a boolean.
*/
public satisfies(condition: (value: TValue, object?: TObject) => boolean | Promise<boolean>, config?: object) {
return new FluentRuleCustomizer<TObject, TValue>(
this.property, condition, config, this.fluentEnsure, this, this.parsers);
}
/**
* Applies a rule by name.
* @param name The name of the custom or standard rule.
* @param args The rule's arguments.
*/
public satisfiesRule(name: string, ...args: any[]): FluentRuleCustomizer<TObject, TValue> {
let rule = FluentRules.customRules[name];
if (!rule) {
// standard rule?
rule = (this as any)[name];
if (rule instanceof Function) {
return rule.call(this, ...args);
}
throw new Error(`Rule with name "${name}" does not exist.`);
}
const config = rule.argsToConfig ? rule.argsToConfig(...args) : undefined;
return this.satisfies((value, obj) => rule.condition.call(this, value, obj, ...args), config)
.withMessageKey(name);
}
/**
* Applies the "required" rule to the property.
* The value cannot be null, undefined or whitespace.
*/
public required() {
return this.satisfies(
value =>
value !== null
&& value !== undefined
&& !(isString(value) && !/\S/.test(value as any))
).withMessageKey('required');
}
/**
* Applies the "matches" rule to the property.
* Value must match the specified regular expression.
* null, undefined and empty-string values are considered valid.
*/
public matches(regex: RegExp) {
return this.satisfies(
value => value === null || value === undefined || (value as any).length === 0 || regex.test(value as any))
.withMessageKey('matches');
}
/**
* Applies the "email" rule to the property.
* null, undefined and empty-string values are considered valid.
*/
public email() {
// regex from https://html.spec.whatwg.org/multipage/forms.html#valid-e-mail-address
/* tslint:disable:max-line-length */
return this.matches(/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/)
/* tslint:enable:max-line-length */
.withMessageKey('email');
}
/**
* Applies the "minLength" STRING validation rule to the property.
* null, undefined and empty-string values are considered valid.
*/
public minLength(length: number) {
return this.satisfies(
(value: any) => value === null || value === undefined || value.length === 0 || value.length >= length,
{ length })
.withMessageKey('minLength');
}
/**
* Applies the "maxLength" STRING validation rule to the property.
* null, undefined and empty-string values are considered valid.
*/
public maxLength(length: number) {
return this.satisfies(
(value: any) => value === null || value === undefined || value.length === 0 || value.length <= length,
{ length })
.withMessageKey('maxLength');
}
/**
* Applies the "minItems" ARRAY validation rule to the property.
* null and undefined values are considered valid.
*/
public minItems(count: number) {
return this.satisfies((value: any) => value === null || value === undefined || value.length >= count, { count })
.withMessageKey('minItems');
}
/**
* Applies the "maxItems" ARRAY validation rule to the property.
* null and undefined values are considered valid.
*/
public maxItems(count: number) {
return this.satisfies((value: any) => value === null || value === undefined || value.length <= count, { count })
.withMessageKey('maxItems');
}
/**
* Applies the "min" NUMBER validation rule to the property.
* Value must be greater than or equal to the specified constraint.
* null and undefined values are considered valid.
*/
public min(constraint: number) {
return this.satisfies((value: any) => value === null || value === undefined || value >= constraint, { constraint })
.withMessageKey('min');
}
/**
* Applies the "max" NUMBER validation rule to the property.
* Value must be less than or equal to the specified constraint.
* null and undefined values are considered valid.
*/
public max(constraint: number) {
return this.satisfies((value: any) => value === null || value === undefined || value <= constraint, { constraint })
.withMessageKey('max');
}
/**
* Applies the "range" NUMBER validation rule to the property.
* Value must be between or equal to the specified min and max.
* null and undefined values are considered valid.
*/
public range(min: number, max: number) {
return this.satisfies((value: any) => value === null || value === undefined || (value >= min && value <= max),
{ min, max })
.withMessageKey('range');
}
/**
* Applies the "between" NUMBER validation rule to the property.
* Value must be between but not equal to the specified min and max.
* null and undefined values are considered valid.
*/
public between(min: number, max: number) {
return this.satisfies((value: any) => value === null || value === undefined || (value > min && value < max),
{ min, max })
.withMessageKey('between');
}
/**
* Applies the "equals" validation rule to the property.
* null and undefined values are considered valid.
*/
public equals(expectedValue: TValue) {
return this.satisfies(
value => value === null || value === undefined || value as any === '' || value === expectedValue,
{ expectedValue })
.withMessageKey('equals');
}
}
/**
* Part of the fluent rule API. Enables targeting properties and objects with rules.
*/
export class FluentEnsure<TObject> {
/**
* Rules that have been defined using the fluent API.
*/
public rules: Rule<TObject, any>[][] = [];
constructor(private parsers: Parsers) { }
/**
* Target a property with validation rules.
* @param property The property to target. Can be the property name or a property accessor
* function.
*/
public ensure<TValue>(property: string | number | PropertyAccessor<TObject, TValue>): FluentRules<TObject, any> {
this.assertInitialized();
const name = this.parsers.property.parse(property);
const fluentRules = new FluentRules<TObject, TValue>(
this,
this.parsers,
{ name, displayName: null });
return this.mergeRules(fluentRules, name);
}
/**
* Targets an object with validation rules.
*/
public ensureObject(): FluentRules<TObject, any> {
this.assertInitialized();
const fluentRules = new FluentRules<TObject, TObject>(
this, this.parsers, { name: null, displayName: null });
return this.mergeRules(fluentRules, null);
}
/**
* Applies the rules to a class or object, making them discoverable by the StandardValidator.
* @param target A class or object.
*/
public on(target: any) {
Rules.set(target, this.rules);
return this;
}
/**
* Adds a rule definition to the sequenced ruleset.
* @internal
*/
public _addRule(rule: Rule<TObject, any>) {
while (this.rules.length < rule.sequence + 1) {
this.rules.push([]);
}
this.rules[rule.sequence].push(rule);
}
private assertInitialized() {
if (this.parsers) {
return;
}
throw new Error(`Did you forget to add ".plugin('aurelia-validation')" to your main.js?`);
}
private mergeRules(fluentRules: FluentRules<TObject, any>, propertyName: string | number | null) {
// tslint:disable-next-line:triple-equals | Use loose equality for property keys
const existingRules = this.rules.find(r => r.length > 0 && r[0].property.name == propertyName);
if (existingRules) {
const rule = existingRules[existingRules.length - 1];
fluentRules.sequence = rule.sequence;
if (rule.property.displayName !== null) {
fluentRules = fluentRules.displayName(rule.property.displayName);
}
}
return fluentRules;
}
}
/**
* Fluent rule definition API.
*/
export class ValidationRules {
private static parsers: Parsers;
public static initialize(messageParser: ValidationMessageParser, propertyParser: PropertyAccessorParser) {
this.parsers = {
message: messageParser,
property: propertyParser
};
}
/**
* Target a property with validation rules.
* @param property The property to target. Can be the property name or a property accessor function.
*/
public static ensure<TObject, TValue>(property: string | number | PropertyAccessor<TObject, TValue>) {
return new FluentEnsure<TObject>(ValidationRules.parsers).ensure(property);
}
/**
* Targets an object with validation rules.
*/
public static ensureObject<TObject>() {
return new FluentEnsure<TObject>(ValidationRules.parsers).ensureObject();
}
/**
* Defines a custom rule.
* @param name The name of the custom rule. Also serves as the message key.
* @param condition The rule function.
* @param message The message expression
* @param argsToConfig A function that maps the rule's arguments to a "config"
* object that can be used when evaluating the message expression.
*/
public static customRule(
name: string,
condition: (value: any, object?: any, ...args: any[]) => boolean | Promise<boolean>,
message: string,
argsToConfig?: (...args: any[]) => any
) {
validationMessages[name] = message;
FluentRules.customRules[name] = { condition, argsToConfig };
}
/**
* Returns rules with the matching tag.
* @param rules The rules to search.
* @param tag The tag to search for.
*/
public static taggedRules(rules: Rule<any, any>[][], tag: string): Rule<any, any>[][] {
return rules.map(x => x.filter(r => r.tag === tag));
}
/**
* Returns rules that have no tag.
* @param rules The rules to search.
*/
public static untaggedRules(rules: Rule<any, any>[][]): Rule<any, any>[][] {
return rules.map(x => x.filter(r => r.tag === undefined));
}
/**
* Removes the rules from a class or object.
* @param target A class or object.
*/
public static off(target: any): void {
Rules.unset(target);
}
}
export interface Parsers {
message: ValidationMessageParser;
property: PropertyAccessorParser;
} | the_stack |
import { TestBed, ComponentFixture, fakeAsync, tick } from '@angular/core/testing';
import { IgxGridModule } from './grid.module';
import { IgxGridComponent } from './grid.component';
import { DebugElement } from '@angular/core';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { IgxColumnComponent } from '../columns/column.component';
import { IgxColumnGroupComponent } from '../columns/column-group.component';
import { SortingDirection } from '../../data-operations/sorting-expression.interface';
import { By } from '@angular/platform-browser';
import { DefaultSortingStrategy } from '../../data-operations/sorting-strategy';
import { IgxStringFilteringOperand } from '../../data-operations/filtering-condition';
import { configureTestSuite } from '../../test-utils/configure-suite';
import { IgxGridHeaderComponent } from '../headers/grid-header.component';
import { GridSummaryFunctions, GridFunctions } from '../../test-utils/grid-functions.spec';
import { wait } from '../../test-utils/ui-interactions.spec';
import { DropPosition } from '../moving/moving.service';
import { OneGroupOneColGridComponent, OneGroupThreeColsGridComponent,
BlueWhaleGridComponent, ColumnGroupTestComponent, ColumnGroupFourLevelTestComponent,
ThreeGroupsThreeColumnsGridComponent,
NestedColGroupsGridComponent, StegosaurusGridComponent,
OneColPerGroupGridComponent, NestedColumnGroupsGridComponent,
DynamicGridComponent, NestedColGroupsWithTemplatesGridComponent,
DynamicColGroupsGridComponent } from '../../test-utils/grid-mch-sample.spec';
const GRID_COL_THEAD_TITLE_CLASS = 'igx-grid-th__title';
const GRID_COL_GROUP_THEAD_TITLE_CLASS = 'igx-grid-thead__title';
const GRID_COL_GROUP_THEAD_GROUP_CLASS = 'igx-grid-thead__group';
/* eslint-disable max-len */
describe('IgxGrid - multi-column headers #grid', () => {
let fixture; let grid: IgxGridComponent; let componentInstance;
configureTestSuite((() => {
TestBed.configureTestingModule({
declarations: [
OneGroupOneColGridComponent,
OneGroupThreeColsGridComponent,
BlueWhaleGridComponent,
ColumnGroupTestComponent,
ColumnGroupFourLevelTestComponent,
ThreeGroupsThreeColumnsGridComponent,
NestedColGroupsGridComponent,
StegosaurusGridComponent,
OneColPerGroupGridComponent,
NestedColumnGroupsGridComponent,
DynamicGridComponent,
NestedColGroupsWithTemplatesGridComponent,
DynamicColGroupsGridComponent
],
imports: [
NoopAnimationsModule,
IgxGridModule
]
});
}));
describe('Initialization and rendering tests: ', () => {
it('should initialize a grid with column groups', () => {
fixture = TestBed.createComponent(ColumnGroupTestComponent);
fixture.detectChanges();
grid = fixture.componentInstance.grid;
const expectedColumnGroups = 5;
const expectedLevel = 2;
const groupHeaders = GridFunctions.getColumnGroupHeaders(fixture);
expect(groupHeaders.length).toEqual(expectedColumnGroups);
expect(grid.getColumnByName('ContactName').level).toEqual(expectedLevel);
});
it('Should render column group headers correctly.', fakeAsync(() => {
fixture = TestBed.createComponent(BlueWhaleGridComponent);
fixture.detectChanges();
componentInstance = fixture.componentInstance;
grid = componentInstance.grid;
const columnWidthPx = parseInt(componentInstance.columnWidth, 10);
// 2 levels of column group and 1 level of columns
const gridHeadersDepth = 3;
const firstGroupChildrenCount = 100;
const secondGroupChildrenCount = 2;
const secondSubGroupChildrenCount = 50;
const secondSubGroupHeadersDepth = 2;
const firstGroup = GridFunctions.getColumnGroupHeaders(fixture)[0];
testColumnGroupHeaderRendering(firstGroup, firstGroupChildrenCount * columnWidthPx,
gridHeadersDepth * grid.defaultRowHeight, componentInstance.firstGroupTitle,
'firstGroupColumn', firstGroupChildrenCount);
let horizontalScroll = grid.headerContainer.getScroll();
let scrollToNextGroup = firstGroupChildrenCount * columnWidthPx + columnWidthPx;
horizontalScroll.scrollLeft = scrollToNextGroup;
tick();
fixture.detectChanges();
const secondGroup = GridFunctions.getColumnGroupHeaders(fixture)[1];
testColumnGroupHeaderRendering(secondGroup,
secondGroupChildrenCount * secondSubGroupChildrenCount * columnWidthPx,
gridHeadersDepth * grid.defaultRowHeight, componentInstance.secondGroupTitle,
'secondSubGroup', 0);
const secondSubGroups = secondGroup.queryAll(By.css('.secondSubGroup'));
testColumnGroupHeaderRendering(secondSubGroups[0],
secondSubGroupChildrenCount * columnWidthPx,
secondSubGroupHeadersDepth * grid.defaultRowHeight, componentInstance.secondSubGroupTitle,
'secondSubGroupColumn', secondSubGroupChildrenCount);
testColumnGroupHeaderRendering(secondSubGroups[1],
secondSubGroupChildrenCount * columnWidthPx,
secondSubGroupHeadersDepth * grid.defaultRowHeight, componentInstance.secondSubGroupTitle,
'secondSubGroupColumn', secondSubGroupChildrenCount);
horizontalScroll = grid.headerContainer.getScroll();
scrollToNextGroup = horizontalScroll.scrollLeft +
secondSubGroupHeadersDepth * secondSubGroupChildrenCount * columnWidthPx;
horizontalScroll.scrollLeft = scrollToNextGroup;
tick();
fixture.detectChanges();
const idColumn = fixture.debugElement.query(By.css('.lonelyId'));
testColumnHeaderRendering(idColumn, columnWidthPx,
gridHeadersDepth * grid.defaultRowHeight, componentInstance.idHeaderTitle);
const companyNameColumn = GridFunctions.getColumnHeader('CompanyName', fixture);
testColumnHeaderRendering(companyNameColumn, columnWidthPx,
2 * grid.defaultRowHeight, componentInstance.companyNameTitle);
const personDetailsColumn = GridFunctions.getColumnGroupHeader('Person Details', fixture);
testColumnGroupHeaderRendering(personDetailsColumn, 2 * columnWidthPx,
2 * grid.defaultRowHeight, componentInstance.personDetailsTitle,
'personDetailsColumn', 2);
}));
it('Should not render empty column group.', () => {
fixture = TestBed.createComponent(ColumnGroupTestComponent);
fixture.detectChanges();
const ci = fixture.componentInstance;
// Empty column group should not be displayed
const emptyColGroup = GridFunctions.getColumnGroupHeader('Empty Header', fixture);
expect(parseInt(ci.emptyColGroup.width, 10)).toBe(0);
expect(emptyColGroup).toBeUndefined();
});
it('Should render headers correctly when having a column per group.', () => {
fixture = TestBed.createComponent(OneColPerGroupGridComponent);
fixture.detectChanges();
const ci = fixture.componentInstance;
grid = ci.grid;
const addressColGroup = GridFunctions.getColumnGroupHeader('Address Group', fixture);
const addressColGroupDepth = 2; // one-level children
const addressColGroupChildrenCount = 1;
testColumnGroupHeaderRendering(addressColGroup, parseInt(ci.columnWidth, 10),
addressColGroupDepth * grid.defaultRowHeight, ci.addressColGroupTitle,
'addressCol', addressColGroupChildrenCount);
const addressCol = GridFunctions.getColumnHeader('Address', fixture);
testColumnHeaderRendering(addressCol, parseInt(ci.columnWidth, 10),
grid.defaultRowHeight, ci.addressColTitle);
const phoneColGroup = GridFunctions.getColumnGroupHeader('Phone Group', fixture);
const phoneColGroupDepth = 2; // one-level children
const phoneColGroupChildrenCount = 1;
testColumnGroupHeaderRendering(phoneColGroup, parseInt(ci.phoneColWidth, 10),
phoneColGroupDepth * grid.defaultRowHeight, ci.phoneColGroupTitle,
'phoneCol', phoneColGroupChildrenCount);
const phoneCol = GridFunctions.getColumnHeader('Phone', fixture);
testColumnHeaderRendering(phoneCol, parseInt(ci.phoneColWidth, 10),
grid.defaultRowHeight, ci.phoneColTitle);
const faxColGroup = GridFunctions.getColumnGroupHeader('Fax Group', fixture);
const faxColGroupDepth = 2; // one-level children
const faxColGroupChildrenCount = 1;
testColumnGroupHeaderRendering(faxColGroup, parseInt(ci.faxColWidth, 10),
faxColGroupDepth * grid.defaultRowHeight, ci.faxColGroupTitle, 'faxCol',
faxColGroupChildrenCount);
const faxCol = GridFunctions.getColumnHeader('Fax', fixture);
testColumnHeaderRendering(faxCol, parseInt(ci.faxColWidth, 10),
grid.defaultRowHeight, ci.faxColTitle);
});
it('Should render headers correctly when having nested column groups.', () => {
fixture = TestBed.createComponent(NestedColumnGroupsGridComponent);
fixture.detectChanges();
NestedColGroupsTests.testHeadersRendering(fixture);
});
it('Should render headers correctly when having nested column groups with huge header text.', () => {
fixture = TestBed.createComponent(NestedColumnGroupsGridComponent);
fixture.detectChanges();
const ci = fixture.componentInstance;
grid = ci.grid;
const title = 'Lorem Ipsum is simply dummy text of the printing and typesetting' +
' industry.Lorem Ipsum has been the industry\'s standard dummy text ever since' +
' the 1500s, when an unknown printer took a galley of type and scrambled it to' +
' make a type specimen book. It has survived not only five centuries, but also the' +
' leap into electronic typesetting, remaining essentially unchanged.It was popularised' +
' in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and' +
' more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.';
ci.masterColGroupTitle = ci.firstSlaveColGroupTitle =
ci.secondSlaveColGroupTitle = ci.addressColTitle = ci.phoneColTitle =
ci.faxColTitle = ci.cityColTitle = title;
fixture.detectChanges();
NestedColGroupsTests.testHeadersRendering(fixture);
});
it('Should correctly initialize column group templates.', () => {
fixture = TestBed.createComponent(NestedColGroupsWithTemplatesGridComponent);
fixture.detectChanges();
const ci = fixture.componentInstance;
const locationColGroup = ci.locationColGroup;
const contactInfoColGroup = ci.contactInfoColGroup;
expect(locationColGroup.headerTemplate).toBeDefined();
expect(contactInfoColGroup.headerTemplate).toBeUndefined();
const headerSpans: DebugElement[] = fixture.debugElement.queryAll(By.css('.col-group-template'));
expect(headerSpans.length).toBe(1);
expect(headerSpans[0].nativeElement.textContent).toMatch('Column group template');
});
it('Should correctly change column group templates dynamically.', () => {
fixture = TestBed.createComponent(NestedColGroupsWithTemplatesGridComponent);
fixture.detectChanges();
componentInstance = fixture.componentInstance;
const locationColGroup = componentInstance.locationColGroup;
const genInfoColGroup = componentInstance.genInfoColGroup;
const headerTemplate = componentInstance.dynamicColGroupTemplate;
locationColGroup.headerTemplate = headerTemplate;
genInfoColGroup.headerTemplate = headerTemplate;
fixture.detectChanges();
let headerSpans: DebugElement[] = fixture.debugElement.queryAll(By.css('.dynamic-col-group-template'));
expect(headerSpans.length).toBe(2);
headerSpans.forEach(headerSpan => {
expect(headerSpan.nativeElement.textContent).toMatch('Dynamic column group template');
});
locationColGroup.headerTemplate = null;
fixture.detectChanges();
headerSpans = fixture.debugElement.queryAll(By.css('.dynamic-col-group-template'));
expect(headerSpans.length).toBe(1);
headerSpans.forEach(headerSpan => {
expect(headerSpan.nativeElement.textContent).toMatch('Dynamic column group template');
});
headerSpans = fixture.debugElement.queryAll(By.css('.col-group-template'));
expect(headerSpans.length).toBe(0);
headerSpans = fixture.debugElement.queryAll(By.css('.' + GRID_COL_GROUP_THEAD_TITLE_CLASS));
expect(headerSpans[1].nativeElement.textContent).toBe('Location');
});
it('There shouldn\'t be any errors when dynamically removing a column group with filtering enabled', () => {
fixture = TestBed.createComponent(DynamicColGroupsGridComponent);
fixture.detectChanges();
grid = fixture.componentInstance.grid;
let columnLength = grid.columnList.length;
let firstColumnGroup = grid.columnList.first;
let expectedColumnName = 'First';
let expectedColumnListLength = 10;
expect(firstColumnGroup.header).toEqual(expectedColumnName);
expect(expectedColumnListLength).toEqual(columnLength);
fixture.componentInstance.columnGroups = fixture.componentInstance.columnGroups.splice(1, fixture.componentInstance.columnGroups.length - 1);
fixture.detectChanges();
fixture.componentInstance.columnGroups = fixture.componentInstance.columnGroups.splice(1, fixture.componentInstance.columnGroups.length - 1);
fixture.detectChanges();
firstColumnGroup = grid.columnList.first;
expectedColumnName = 'Third';
columnLength = grid.columnList.length;
expectedColumnListLength = 3;
expect(firstColumnGroup.header).toEqual(expectedColumnName);
expect(expectedColumnListLength).toEqual(columnLength);
});
it('There shouldn\'t be any errors when dynamically removing or adding a column in column group', () => {
fixture = TestBed.createComponent(DynamicColGroupsGridComponent);
fixture.detectChanges();
grid = fixture.componentInstance.grid;
expect(grid.columnList.length).toEqual(10);
expect(() => {
// Delete column
fixture.componentInstance.columnGroups[0].columns.splice(0, 1);
fixture.detectChanges();
}).not.toThrow();
expect(grid.columnList.length).toEqual(9);
expect(() => {
// Add column
fixture.componentInstance.columnGroups[0].columns.push({ field: 'Fax', type: 'string' });
fixture.detectChanges();
}).not.toThrow();
expect(grid.columnList.length).toEqual(10);
expect(() => {
// Update column
fixture.componentInstance.columnGroups[0].columns[1] = { field: 'City', type: 'string' };
fixture.detectChanges();
}).not.toThrow();
expect(grid.columnList.length).toEqual(10);
});
it('should set title attribute on column group header spans', () => {
fixture = TestBed.createComponent(ColumnGroupTestComponent);
fixture.detectChanges();
grid = fixture.componentInstance.grid;
const generalGroup = grid.columnList.find(c => c.header === 'General Information');
generalGroup.title = 'General Information Title';
fixture.detectChanges();
const headers = fixture.debugElement.queryAll(By.css('.' + GRID_COL_GROUP_THEAD_TITLE_CLASS));
const generalHeader = headers.find(h => h.nativeElement.textContent === 'General Information');
const addressHeader = headers.find(h => h.nativeElement.textContent === 'Address Information');
expect(generalHeader.nativeElement.firstElementChild.title).toBe('General Information Title');
expect(addressHeader.nativeElement.firstElementChild.title).toBe('Address Information');
});
});
describe('Columns widths tests (1 group 1 column) ', () => {
beforeEach(fakeAsync(() => {
fixture = TestBed.createComponent(OneGroupOneColGridComponent);
fixture.detectChanges();
componentInstance = fixture.componentInstance;
grid = fixture.componentInstance.grid;
}));
it('Width should be correct. Column group with column. No width.', () => {
grid.ngAfterViewInit();
fixture.detectChanges();
const locationColGroup = getColGroup(grid, 'Location');
expect(parseInt(locationColGroup.width, 10) + grid.scrollSize).toBe(parseInt(componentInstance.gridWrapperWidthPx, 10));
const cityColumn = grid.getColumnByName('City');
expect(parseInt(cityColumn.width, 10) + grid.scrollSize).toBe(parseInt(componentInstance.gridWrapperWidthPx, 10));
});
it('Width should be correct. Column group with column. Width in px.', () => {
const gridWidth = '600px';
const gridWidthPx = parseInt(gridWidth, 10);
grid.width = gridWidth;
fixture.detectChanges();
const locationColGroup = getColGroup(grid, 'Location');
expect(parseInt(locationColGroup.width, 10) + grid.scrollSize).toBe(gridWidthPx);
const cityColumn = grid.getColumnByName('City');
expect(parseInt(cityColumn.width, 10) + grid.scrollSize).toBe(gridWidthPx);
});
it('Width should be correct. Column group with column. Width in percent.', () => {
const gridWidth = '50%';
grid.width = gridWidth;
fixture.detectChanges();
const locationColGroup = getColGroup(grid, 'Location');
const gridWidthInPx = ((parseInt(gridWidth, 10) / 100) *
parseInt(componentInstance.gridWrapperWidthPx, 10) - grid.scrollSize) + 'px';
expect(locationColGroup.width).toBe(gridWidthInPx);
const cityColumn = grid.getColumnByName('City');
expect(cityColumn.width).toBe(gridWidthInPx);
});
it('Width should be correct. Column group with column. Column width in px.', () => {
const gridColWidth = '200px';
grid.columnWidth = gridColWidth;
fixture.detectChanges();
const locationColGroup = getColGroup(grid, 'Location');
expect(locationColGroup.width).toBe(gridColWidth);
const cityColumn = grid.getColumnByName('City');
expect(cityColumn.width).toBe(gridColWidth);
});
it('Width should be correct. Column group with column. Column width in percent.', () => {
const gridColWidth = '50%';
grid.columnWidth = gridColWidth;
fixture.detectChanges();
const locationColGroup = getColGroup(grid, 'Location');
const expectedWidth = (grid.calcWidth / 2) + 'px';
expect(locationColGroup.width).toBe(expectedWidth);
const cityColumn = grid.getColumnByName('City');
expect(cityColumn.width).toBe(gridColWidth);
});
it('Width should be correct. Column group with column. Column with width in px.', () => {
const columnWidth = '200px';
componentInstance.columnWidth = columnWidth;
fixture.detectChanges();
const locationColGroup = getColGroup(grid, 'Location');
expect(locationColGroup.width).toBe(columnWidth);
const cityColumn = grid.getColumnByName('City');
expect(cityColumn.width).toBe(columnWidth);
});
it('Width should be correct. Column group with column. Column with width in percent.', () => {
const columnWidth = '50%';
componentInstance.columnWidth = columnWidth;
fixture.detectChanges();
const locationColGroup = getColGroup(grid, 'Location');
const expectedWidth = (grid.calcWidth / 2) + 'px';
expect(locationColGroup.width).toBe(expectedWidth);
const cityColumn = grid.getColumnByName('City');
expect(cityColumn.width).toBe(columnWidth);
});
it('Should not throw exception if multi-column header columns width is set as number', () => {
expect(() => {
const cityColumn = grid.getColumnByName('City');
(cityColumn.width as any) = 55;
fixture.detectChanges();
}).not.toThrow();
});
});
describe('Columns widths tests (1 group 3 columns) ', () => {
beforeEach(fakeAsync(() => {
fixture = TestBed.createComponent(OneGroupThreeColsGridComponent);
fixture.detectChanges();
componentInstance = fixture.componentInstance;
grid = fixture.componentInstance.grid;
}));
it('Width should be correct. Column group with three columns. No width.', () => {
const scrWitdh = grid.nativeElement.querySelector('.igx-grid__tbody-scrollbar').getBoundingClientRect().width;
const availableWidth = (parseInt(componentInstance.gridWrapperWidthPx, 10) - scrWitdh).toString();
const locationColGroup = getColGroup(grid, 'Location');
const colWidth = Math.floor(parseInt(availableWidth, 10) / 3);
const colWidthPx = colWidth + 'px';
expect(locationColGroup.width).toBe((Math.round(colWidth) * 3) + 'px');
const countryColumn = grid.getColumnByName('Country');
expect(countryColumn.width).toBe(colWidthPx);
const regionColumn = grid.getColumnByName('Region');
expect(regionColumn.width).toBe(colWidthPx);
const cityColumn = grid.getColumnByName('City');
expect(cityColumn.width).toBe(colWidthPx);
});
it('Width should be correct. Column group with three columns. Width in px.', () => {
const gridWidth = '600px';
grid.width = gridWidth;
fixture.detectChanges();
const scrWitdh = grid.nativeElement.querySelector('.igx-grid__tbody-scrollbar').getBoundingClientRect().width;
const gridWidthInPx = parseInt(gridWidth, 10) - scrWitdh;
const colWidth = Math.floor(gridWidthInPx / 3);
const colWidthPx = colWidth + 'px';
const locationColGroup = getColGroup(grid, 'Location');
expect(locationColGroup.width).toBe((Math.round(colWidth) * 3) + 'px');
const countryColumn = grid.getColumnByName('Country');
expect(countryColumn.width).toBe(colWidthPx);
const regionColumn = grid.getColumnByName('Region');
expect(regionColumn.width).toBe(colWidthPx);
const cityColumn = grid.getColumnByName('City');
expect(cityColumn.width).toBe(colWidthPx);
});
it('Width should be correct. Column group with three columns. Columns with mixed width - px and percent.', async () => {
const col1 = grid.getColumnByName('Country');
const col2 = grid.getColumnByName('Region');
const col3 = grid.getColumnByName('City');
col1.width = '200px';
col2.width = '20%';
col3.width = '50%';
fixture.detectChanges();
// check group has correct size.
let locationColGroup = getColGroup(grid, 'Location');
let expectedWidth = (200 + Math.floor(grid.calcWidth * 0.7)) + 'px';
expect(locationColGroup.width).toBe(expectedWidth);
// check header and content have same size.
const col1Header = grid.getColumnByName('Country').headerCell.nativeElement;
const cell1 = grid.gridAPI.get_row_by_index(0).cells.toArray()[0].nativeElement;
expect(col1Header.offsetWidth).toEqual(cell1.offsetWidth);
let col2Header = grid.getColumnByName('Region').headerCell.nativeElement;
let cell2 = grid.gridAPI.get_row_by_index(0).cells.toArray()[1].nativeElement;
expect(col2Header.offsetWidth - cell2.offsetWidth).toBeLessThanOrEqual(1);
let col3Header = grid.getColumnByName('City').headerCell.nativeElement;
let cell3 = grid.gridAPI.get_row_by_index(0).cells.toArray()[2].nativeElement;
expect(col3Header.offsetWidth).toEqual(cell3.offsetWidth);
// check that if grid is resized, group size is updated.
componentInstance.gridWrapperWidthPx = '500';
fixture.detectChanges();
await wait(100);
fixture.detectChanges();
locationColGroup = getColGroup(grid, 'Location');
expectedWidth = (200 + Math.floor(grid.calcWidth * 0.7)) + 'px';
expect(locationColGroup.width).toBe(expectedWidth);
col2Header = grid.getColumnByName('Region').headerCell.nativeElement;
cell2 = grid.gridAPI.get_row_by_index(0).cells.toArray()[1].nativeElement;
expect(col2Header.offsetWidth - cell2.offsetWidth).toBeLessThanOrEqual(1);
col3Header = grid.getColumnByName('City').headerCell.nativeElement;
cell3 = grid.gridAPI.get_row_by_index(0).cells.toArray()[2].nativeElement;
expect(col3Header.offsetWidth).toEqual(cell3.offsetWidth);
});
it('Width should be correct. Column group with three columns. Columns with mixed width - px, percent and null.', () => {
const col1 = grid.getColumnByName('Country');
const col2 = grid.getColumnByName('Region');
const col3 = grid.getColumnByName('City');
col1.width = '200px';
col2.width = '20%';
col3.width = null;
fixture.detectChanges();
// check group has correct size. Should fill available space in grid since one column has no width.
const locationColGroup = getColGroup(grid, 'Location');
const expectedWidth = grid.calcWidth - 1 + 'px';
expect(locationColGroup.width).toBe(expectedWidth);
// check header and content have same size.
const col1Header = grid.getColumnByName('Country').headerCell.nativeElement;
const cell1 = grid.gridAPI.get_row_by_index(0).cells.toArray()[0].nativeElement;
expect(col1Header.offsetWidth).toEqual(cell1.offsetWidth);
const col2Header = grid.getColumnByName('Region').headerCell.nativeElement;
const cell2 = grid.gridAPI.get_row_by_index(0).cells.toArray()[1].nativeElement;
expect(col2Header.offsetWidth - cell2.offsetWidth).toBeLessThanOrEqual(1);
const col3Header = grid.getColumnByName('City').headerCell.nativeElement;
const cell3 = grid.gridAPI.get_row_by_index(0).cells.toArray()[2].nativeElement;
expect(col3Header.offsetWidth).toEqual(cell3.offsetWidth);
});
it('Width should be correct. Column group with three columns. Width in percent.', () => {
const gridWidth = '50%';
grid.width = gridWidth;
fixture.detectChanges();
const scrWitdh = grid.nativeElement.querySelector('.igx-grid__tbody-scrollbar').getBoundingClientRect().width;
const gridWidthInPx = (parseInt(gridWidth, 10) / 100) *
parseInt(componentInstance.gridWrapperWidthPx, 10) - scrWitdh;
const colWidth = Math.floor(gridWidthInPx / 3);
const colWidthPx = colWidth + 'px';
const locationColGroup = getColGroup(grid, 'Location');
expect(locationColGroup.width).toBe((Math.round(colWidth) * 3) + 'px');
const countryColumn = grid.getColumnByName('Country');
expect(countryColumn.width).toBe(colWidthPx);
const regionColumn = grid.getColumnByName('Region');
expect(regionColumn.width).toBe(colWidthPx);
const cityColumn = grid.getColumnByName('City');
expect(cityColumn.width).toBe(colWidthPx);
});
it('Width should be correct. Column group with three columns. Column width in px.', () => {
const gridColWidth = '200px';
grid.columnWidth = gridColWidth;
fixture.detectChanges();
const locationColGroup = getColGroup(grid, 'Location');
const gridWidth = parseInt(gridColWidth, 10) * 3;
expect(locationColGroup.width).toBe(gridWidth + 'px');
const countryColumn = grid.getColumnByName('Country');
expect(countryColumn.width).toBe(gridColWidth);
const regionColumn = grid.getColumnByName('Region');
expect(regionColumn.width).toBe(gridColWidth);
const cityColumn = grid.getColumnByName('City');
expect(cityColumn.width).toBe(gridColWidth);
});
it('Width should be correct. Colum group with three columns. Column width in percent.', () => {
const gridColWidth = '20%';
grid.columnWidth = gridColWidth;
fixture.detectChanges();
const locationColGroup = getColGroup(grid, 'Location');
const expectedWidth = (Math.floor(grid.calcWidth * 0.2) * 3) + 'px';
expect(locationColGroup.width).toBe(expectedWidth);
const countryColumn = grid.getColumnByName('Country');
expect(countryColumn.width).toBe(gridColWidth);
const regionColumn = grid.getColumnByName('Region');
expect(regionColumn.width).toBe(gridColWidth);
const cityColumn = grid.getColumnByName('City');
expect(cityColumn.width).toBe(gridColWidth);
});
it('Width should be correct. Column group with three columns. Columns with width in px.', () => {
const columnWidth = '200px';
componentInstance.columnWidth = columnWidth;
fixture.detectChanges();
const locationColGroup = getColGroup(grid, 'Location');
const groupWidth = parseInt(columnWidth, 10) * 3;
expect(locationColGroup.width).toBe(groupWidth + 'px');
const countryColumn = grid.getColumnByName('Country');
expect(countryColumn.width).toBe(columnWidth);
const regionColumn = grid.getColumnByName('Region');
expect(regionColumn.width).toBe(columnWidth);
const cityColumn = grid.getColumnByName('City');
expect(cityColumn.width).toBe(columnWidth);
});
it('Width should be correct. Column group with three columns. Columns with width in percent.', () => {
const columnWidth = '20%';
componentInstance.columnWidth = columnWidth;
fixture.detectChanges();
const locationColGroup = getColGroup(grid, 'Location');
const expectedWidth = (Math.floor(grid.calcWidth * 0.2) * 3) + 'px';
expect(locationColGroup.width).toBe(expectedWidth);
const countryColumn = grid.getColumnByName('Country');
expect(countryColumn.width).toBe(columnWidth);
const regionColumn = grid.getColumnByName('Region');
expect(regionColumn.width).toBe(columnWidth);
const cityColumn = grid.getColumnByName('City');
expect(cityColumn.width).toBe(columnWidth);
});
});
describe('Column hiding: ', () => {
beforeEach(fakeAsync(() => {
fixture = TestBed.createComponent(ColumnGroupFourLevelTestComponent);
fixture.detectChanges();
grid = fixture.componentInstance.grid;
}));
it('column hiding - parent level', () => {
const addressGroup = grid.columnList.filter(c => c.header === 'Address Information')[0];
addressGroup.hidden = true;
fixture.detectChanges();
expect(GridFunctions.getColumnHeaders(fixture).length).toEqual(4);
expect(GridFunctions.getColumnGroupHeaders(fixture).length).toEqual(2);
});
it('column hiding - child level', () => {
const addressGroup = fixture.componentInstance.addrInfoColGroup;
addressGroup.children.first.hidden = true;
fixture.detectChanges();
expect(GridFunctions.getColumnGroupHeaders(fixture).length).toEqual(5);
expect(addressGroup.children.first.hidden).toBe(true);
expect(addressGroup.children.first.children.toArray().every(c => c.hidden === true)).toEqual(true);
});
it('column hiding - Verify column hiding of Individual column and Child column', () => {
testGroupsAndColumns(7, 11, fixture);
// Hide individual column
grid.getColumnByName('ID').hidden = true;
fixture.detectChanges();
testGroupsAndColumns(7, 10, fixture);
// Hide column in goup
grid.getColumnByName('CompanyName').hidden = true;
fixture.detectChanges();
expect(GridFunctions.getColumnGroupHeaders(fixture).length).toEqual(7);
expect(GridFunctions.getColumnHeaders(fixture).length).toEqual(9);
grid.getColumnByName('Address').hidden = true;
fixture.detectChanges();
testGroupsAndColumns(7, 8, fixture);
});
it('column hiding - Verify when 2 of 2 child columns are hidden, the Grouped column would be hidden as well.', () => {
testGroupsAndColumns(7, 11, fixture);
// Hide 2 columns in the group
grid.getColumnByName('ContactName').hidden = true;
fixture.detectChanges();
grid.getColumnByName('ContactTitle').hidden = true;
fixture.detectChanges();
testGroupsAndColumns(6, 9, fixture);
expect(getColGroup(grid, 'Person Details').hidden).toEqual(true);
// Show one of the columns
grid.getColumnByName('ContactName').hidden = false;
fixture.detectChanges();
testGroupsAndColumns(7, 10, fixture);
expect(getColGroup(grid, 'Person Details').hidden).toEqual(false);
});
it('column hiding - Verify when 1 child column and 1 group are hidden, the Grouped column would be hidden as well.', () => {
testGroupsAndColumns(7, 11, fixture);
// Hide 2 columns in the group
grid.getColumnByName('CompanyName').hidden = true;
fixture.detectChanges();
getColGroup(grid, 'Person Details').hidden = true;
fixture.detectChanges();
testGroupsAndColumns(5, 8, fixture);
expect(getColGroup(grid, 'General Information').hidden).toEqual(true);
// Show the group
getColGroup(grid, 'Person Details').hidden = false;
fixture.detectChanges();
testGroupsAndColumns(7, 10, fixture);
expect(getColGroup(grid, 'General Information').hidden).toEqual(false);
});
});
describe('API methods tests ', () => {
beforeEach(fakeAsync(() => {
fixture = TestBed.createComponent(ColumnGroupFourLevelTestComponent);
fixture.detectChanges();
grid = fixture.componentInstance.grid;
}));
it('API method level should return correct values', () => {
grid.getColumnByName('Fax').hidden = true;
fixture.detectChanges();
getColGroup(grid, 'Person Details').hidden = true;
fixture.detectChanges();
expect(grid.columnList.filter(col => col.columnGroup).length).toEqual(7);
// Get level of column
expect(grid.getColumnByName('ID').level).toEqual(0);
expect(grid.getColumnByName('CompanyName').level).toEqual(1);
expect(grid.getColumnByName('Country').level).toEqual(2);
expect(grid.getColumnByName('City').level).toEqual(3);
expect(grid.getColumnByName('PostalCode').level).toEqual(2);
// Get level of hidden column
expect(grid.getColumnByName('Fax').level).toEqual(2);
// Get level of column in hidden group
expect(grid.getColumnByName('ContactTitle').level).toEqual(2);
// Get level of grouped column
expect(getColGroup(grid, 'General Information').level).toEqual(0);
expect(getColGroup(grid, 'Location').level).toEqual(1);
expect(getColGroup(grid, 'Location City').level).toEqual(2);
expect(getColGroup(grid, 'Contact Information').level).toEqual(1);
expect(getColGroup(grid, 'Postal Code').level).toEqual(1);
// Get level of hidden group
expect(getColGroup(grid, 'Person Details').level).toEqual(1);
});
it('API method columnGroup should return correct values', () => {
grid.getColumnByName('Fax').hidden = true;
fixture.detectChanges();
getColGroup(grid, 'Person Details').hidden = true;
fixture.detectChanges();
expect(grid.columnList.filter(col => col.columnGroup).length).toEqual(7);
// Get columnGroup of column
expect(grid.getColumnByName('ID').columnGroup).toEqual(false);
expect(grid.getColumnByName('Fax').columnGroup).toEqual(false);
expect(grid.getColumnByName('ContactTitle').columnGroup).toEqual(false);
// Get columnGroup of grouped column
expect(getColGroup(grid, 'General Information').columnGroup).toEqual(true);
expect(getColGroup(grid, 'Location City').columnGroup).toEqual(true);
expect(getColGroup(grid, 'Contact Information').columnGroup).toEqual(true);
expect(getColGroup(grid, 'Postal Code').columnGroup).toEqual(true);
expect(getColGroup(grid, 'Person Details').columnGroup).toEqual(true);
});
it('API method allChildren should return correct values', () => {
grid.getColumnByName('Fax').hidden = true;
fixture.detectChanges();
getColGroup(grid, 'Person Details').hidden = true;
fixture.detectChanges();
expect(grid.columnList.filter(col => col.columnGroup).length).toEqual(7);
// Get allChildren of column
expect(grid.getColumnByName('ID').allChildren.length).toEqual(0);
expect(grid.getColumnByName('PostalCode').allChildren.length).toEqual(0);
// Get allChildren of hidden column
expect(grid.getColumnByName('Fax').allChildren.length).toEqual(0);
// Get allChildren of group
const genInfGroupedColumnAllChildren = getColGroup(grid, 'General Information').allChildren;
expect(genInfGroupedColumnAllChildren.length).toEqual(4);
expect(genInfGroupedColumnAllChildren.indexOf(getColGroup(grid, 'Person Details'))).toBeGreaterThanOrEqual(0);
// Get allChildren of hidden group
expect(getColGroup(grid, 'Person Details').allChildren.length).toEqual(2);
// Get allChildren of group with one column
const postCodeGroupedColumnAllChildren = getColGroup(grid, 'Postal Code').allChildren;
expect(postCodeGroupedColumnAllChildren.length).toEqual(1);
expect(postCodeGroupedColumnAllChildren.indexOf(grid.getColumnByName('PostalCode'))).toEqual(0);
// Get allChildren of group with hidden columns and more levels
const addressGroupedColumnAllChildren = getColGroup(grid, 'Address Information').allChildren;
expect(addressGroupedColumnAllChildren.length).toEqual(11);
expect(addressGroupedColumnAllChildren.indexOf(getColGroup(grid, 'Postal Code'))).toBeGreaterThanOrEqual(0);
expect(addressGroupedColumnAllChildren.indexOf(grid.getColumnByName('PostalCode'))).toBeGreaterThanOrEqual(0);
expect(addressGroupedColumnAllChildren.indexOf(grid.getColumnByName('Address'))).toBeGreaterThanOrEqual(0);
expect(addressGroupedColumnAllChildren.indexOf(grid.getColumnByName('Country'))).toBeGreaterThanOrEqual(0);
expect(addressGroupedColumnAllChildren.indexOf(grid.getColumnByName('Fax'))).toBeGreaterThanOrEqual(0);
expect(addressGroupedColumnAllChildren.indexOf(getColGroup(grid, 'General Information'))).toEqual(-1);
});
it('API method children should return correct values', () => {
grid.getColumnByName('Fax').hidden = true;
fixture.detectChanges();
getColGroup(grid, 'Person Details').hidden = true;
fixture.detectChanges();
expect(grid.columnList.filter(col => col.columnGroup).length).toEqual(7);
// Get children of grouped column
expect(getColGroup(grid, 'General Information').children.length).toEqual(2);
// Get children of hidden group
expect(getColGroup(grid, 'Person Details').children.length).toEqual(2);
// Get children of group with one column
const postCodeGroupedColumnAllChildren = getColGroup(grid, 'Postal Code').children;
expect(postCodeGroupedColumnAllChildren.length).toEqual(1);
// Get children of group with more levels
const addressGroupedColumnAllChildren = getColGroup(grid, 'Address Information').children;
expect(addressGroupedColumnAllChildren.length).toEqual(3);
});
it('API method topLevelParent should return correct values', () => {
grid.getColumnByName('Fax').hidden = true;
fixture.detectChanges();
getColGroup(grid, 'Person Details').hidden = true;
fixture.detectChanges();
expect(grid.columnList.filter(col => col.columnGroup).length).toEqual(7);
// Get topLevelParent of column with no group
expect(grid.getColumnByName('ID').topLevelParent).toBeNull();
// Get topLevelParent of column
const addressGroupedColumn = getColGroup(grid, 'Address Information');
expect(grid.getColumnByName('PostalCode').topLevelParent).toEqual(addressGroupedColumn);
expect(grid.getColumnByName('Fax').topLevelParent).toEqual(addressGroupedColumn);
expect(grid.getColumnByName('Country').topLevelParent).toEqual(addressGroupedColumn);
const genInfGroupedColumn = getColGroup(grid, 'General Information');
expect(grid.getColumnByName('ContactName').topLevelParent).toEqual(genInfGroupedColumn);
expect(grid.getColumnByName('CompanyName').topLevelParent).toEqual(genInfGroupedColumn);
// Get topLevelParent of top group
expect(genInfGroupedColumn.topLevelParent).toBeNull();
expect(addressGroupedColumn.topLevelParent).toBeNull();
// Get topLevelParent of group
expect(getColGroup(grid, 'Person Details').topLevelParent).toEqual(genInfGroupedColumn);
expect(getColGroup(grid, 'Postal Code').topLevelParent).toEqual(addressGroupedColumn);
expect(getColGroup(grid, 'Location City').topLevelParent).toEqual(addressGroupedColumn);
});
it('Should emit "columnInit" event when having multi-column headers.', () => {
fixture = TestBed.createComponent(NestedColumnGroupsGridComponent);
const ci = fixture.componentInstance;
grid = ci.grid;
spyOn(grid.columnInit, 'emit').and.callThrough();
fixture.detectChanges();
const colsCount = 4;
const colGroupsCount = 3;
expect(grid.columnInit.emit).toHaveBeenCalledTimes(colsCount + colGroupsCount);
});
it('Should fire "columnInit" event when adding a multi-column header.', () => {
fixture = TestBed.createComponent(DynamicGridComponent);
componentInstance = fixture.componentInstance;
grid = componentInstance.grid;
fixture.detectChanges();
spyOn(grid.columnInit, 'emit').and.callThrough();
componentInstance.mchCount.push({});
fixture.detectChanges();
const colsCount = 2; // 1 col group and 1 col
expect(grid.columnInit.emit).toHaveBeenCalledTimes(colsCount);
});
});
describe('Column Pinning ', () => {
beforeEach(fakeAsync(() => {
fixture = TestBed.createComponent(ColumnGroupTestComponent);
fixture.detectChanges();
grid = fixture.componentInstance.grid;
}));
it('column pinning - Pin a column in a group using property.', () => {
PinningTests.testColumnGroupPinning((component) => {
component.contactTitleCol.pinned = true;
fixture.detectChanges();
}, (component) => {
component.contactTitleCol.pinned = false;
fixture.detectChanges();
});
});
it('column pinning - Pin a column in a group using grid API.', () => {
PinningTests.testColumnGroupPinning((component) => {
component.grid.pinColumn(component.contactTitleCol);
fixture.detectChanges();
}, (component) => {
component.grid.unpinColumn(component.contactTitleCol);
fixture.detectChanges();
});
});
it('column pinning - Pin an inner column group using property.', () => {
PinningTests.testColumnGroupPinning((component) => {
component.pDetailsColGroup.pinned = true;
fixture.detectChanges();
}, (component) => {
component.pDetailsColGroup.pinned = false;
fixture.detectChanges();
});
});
it('column pinning - Pin an inner column group using grid API.', () => {
PinningTests.testColumnGroupPinning((component) => {
component.grid.pinColumn(component.pDetailsColGroup);
fixture.detectChanges();
}, (component) => {
component.grid.unpinColumn(component.pDetailsColGroup);
fixture.detectChanges();
});
});
it('column pinning - Pin a group using property.', () => {
PinningTests.testColumnGroupPinning((component) => {
component.genInfoColGroup.pinned = true;
fixture.detectChanges();
}, (component) => {
component.genInfoColGroup.pinned = false;
fixture.detectChanges();
});
});
it('column pinning - Pin a group using API.', () => {
PinningTests.testColumnGroupPinning((component) => {
component.grid.pinColumn(component.genInfoColGroup);
fixture.detectChanges();
}, (component) => {
component.grid.unpinColumn(component.genInfoColGroup);
fixture.detectChanges();
});
});
it('column pinning - Verify pin a not fully visble group', () => {
const ci = fixture.componentInstance;
expect(grid.pinnedColumns.length).toEqual(0);
expect(grid.unpinnedColumns.length).toEqual(16);
// Pin a Group which is not fully visble
const grAdressInf = getColGroup(grid, 'Address Information');
grAdressInf.pinned = true;
fixture.detectChanges();
// Verify group and all its children are not pinned
testColumnPinning(grAdressInf, true);
expect(grid.getCellByColumn(0, 'ID')).toBeDefined();
expect(grid.getCellByColumn(0, 'Country')).toBeDefined();
expect(grid.getCellByColumn(0, 'City')).toBeDefined();
expect(grid.getCellByColumn(0, 'ID').value).toEqual('ALFKI');
expect(grid.getCellByColumn(0, 'Country').value).toEqual('Germany');
expect(grid.getCellByColumn(0, 'City').value).toEqual('Berlin');
});
it('Should pin column groups using indexes correctly.', () => {
fixture = TestBed.createComponent(StegosaurusGridComponent);
fixture.detectChanges();
const ci = fixture.componentInstance;
grid = ci.grid;
ci.genInfoColGroup.pinned = true;
fixture.detectChanges();
ci.idCol.pinned = true;
fixture.detectChanges();
ci.postalCodeColGroup.pinned = true;
fixture.detectChanges();
ci.cityColGroup.pinned = true;
fixture.detectChanges();
testColumnsVisibleIndexes(ci.genInfoColList.concat(ci.idCol)
.concat(ci.postalCodeColList).concat(ci.cityColList).concat(ci.countryColList)
.concat(ci.regionColList).concat(ci.addressColList).concat(ci.phoneColList)
.concat(ci.faxColList));
// unpinning with index
expect(grid.unpinColumn(ci.genInfoColGroup, 2)).toBe(true);
fixture.detectChanges();
const postUnpinningColList = [ci.idCol].concat(ci.postalCodeColList).concat(ci.cityColList)
.concat(ci.countryColList).concat(ci.regionColList).concat(ci.genInfoColList)
.concat(ci.addressColList).concat(ci.phoneColList).concat(ci.faxColList);
testColumnsVisibleIndexes(postUnpinningColList);
testColumnPinning(ci.genInfoColGroup, false);
// pinning to non-existent index
expect(grid.pinColumn(ci.genInfoColGroup, 15)).toBe(false);
fixture.detectChanges();
testColumnsVisibleIndexes(postUnpinningColList);
testColumnPinning(ci.genInfoColGroup, false);
// pinning to negative index
expect(grid.pinColumn(ci.genInfoColGroup, -15)).toBe(false);
fixture.detectChanges();
testColumnsVisibleIndexes(postUnpinningColList);
testColumnPinning(ci.genInfoColGroup, false);
// pinning with index
expect(grid.pinColumn(ci.genInfoColGroup, 2)).toBe(true);
fixture.detectChanges();
const postPinningColList = [ci.idCol].concat(ci.postalCodeColList).concat(ci.genInfoColList)
.concat(ci.cityColList).concat(ci.countryColList).concat(ci.regionColList)
.concat(ci.addressColList).concat(ci.phoneColList).concat(ci.faxColList);
testColumnsVisibleIndexes(postPinningColList);
testColumnPinning(ci.genInfoColGroup, true);
// unpinning to non-existent index
expect(grid.unpinColumn(ci.genInfoColGroup, 15)).toBe(false);
testColumnsVisibleIndexes(postPinningColList);
testColumnPinning(ci.genInfoColGroup, true);
// unpinning to negative index
expect(grid.unpinColumn(ci.genInfoColGroup, -15)).toBe(false);
testColumnsVisibleIndexes(postPinningColList);
testColumnPinning(ci.genInfoColGroup, true);
});
it('Should initially pin the whole group when one column of the group is pinned', () => {
fixture = TestBed.createComponent(ThreeGroupsThreeColumnsGridComponent);
fixture.componentInstance.cnPinned = true;
fixture.detectChanges();
const contactTitle = fixture.componentInstance.grid.getColumnByName('ContactTitle');
expect(contactTitle.pinned).toBeTruthy();
});
});
describe('Column moving ', () => {
// configureTestSuite();
beforeEach(fakeAsync(() => {
fixture = TestBed.createComponent(ColumnGroupTestComponent);
fixture.detectChanges();
grid = fixture.componentInstance.grid;
}));
it('Should not allow moving group to another level via API.', () => {
expect(grid.pinnedColumns.length).toEqual(0);
expect(grid.unpinnedColumns.length).toEqual(16);
expect(grid.rowList.first.cells.first.value).toMatch('ALFKI');
expect(grid.rowList.first.cells.toArray()[1].value).toMatch('Alfreds Futterkiste');
expect(grid.rowList.first.cells.toArray()[2].value).toMatch('Maria Anders');
expect(grid.rowList.first.cells.toArray()[3].value).toMatch('Sales Representative');
// Pin a column
const colID = grid.getColumnByName('ID');
colID.pinned = true;
fixture.detectChanges();
expect(grid.pinnedColumns.length).toEqual(1);
expect(grid.unpinnedColumns.length).toEqual(15);
expect(colID.visibleIndex).toEqual(0);
expect(grid.rowList.first.cells.first.value).toMatch('ALFKI');
// Try to move a group column to pinned area, where there is non group column
const contName = grid.getColumnByName('ContactName');
grid.moveColumn(contName, colID);
fixture.detectChanges();
// pinning should be unsuccesfull !
expect(grid.pinnedColumns.length).toEqual(1);
expect(grid.unpinnedColumns.length).toEqual(15);
expect(grid.rowList.first.cells.first.value).toMatch('ALFKI');
// pin grouped column to the pinned area
const genGroup = getColGroup(grid, 'General Information');
genGroup.pinned = true;
fixture.detectChanges();
expect(grid.pinnedColumns.length).toEqual(6);
expect(grid.unpinnedColumns.length).toEqual(10);
expect(genGroup.visibleIndex).toEqual(1);
expect(colID.visibleIndex).toEqual(0);
expect(grid.rowList.first.cells.first.value).toMatch('ALFKI');
expect(grid.rowList.first.cells.toArray()[1].value).toMatch('Alfreds Futterkiste');
expect(grid.rowList.first.cells.toArray()[2].value).toMatch('Maria Anders');
expect(grid.rowList.first.cells.toArray()[3].value).toMatch('Sales Representative');
// pin grouped column to the pinned area
const compName = grid.getColumnByName('CompanyName');
const persDetails = getColGroup(grid, 'Person Details');
const contTitle = grid.getColumnByName('ContactTitle');
grid.moveColumn(colID, genGroup);
grid.moveColumn(compName, persDetails);
grid.moveColumn(contName, contTitle);
fixture.detectChanges();
fixture.detectChanges();
expect(grid.rowList.first.cells.first.value).toMatch('Sales Representative');
expect(grid.rowList.first.cells.toArray()[1].value).toMatch('Maria Anders');
expect(grid.rowList.first.cells.toArray()[2].value).toMatch('Alfreds Futterkiste');
expect(grid.rowList.first.cells.toArray()[3].value).toMatch('ALFKI');
});
it('Should move column group correctly. One level column groups.', () => {
fixture = TestBed.createComponent(ThreeGroupsThreeColumnsGridComponent);
fixture.detectChanges();
const ci = fixture.componentInstance;
grid = ci.grid;
const genInfoCols = [ci.genInfoColGroup, ci.companyNameCol,
ci.contactNameCol, ci.contactTitleCol];
const locCols = [ci.locationColGroup, ci.countryCol, ci.regionCol, ci.cityCol];
const contactInfoCols = [ci.contactInfoColGroup, ci.phoneCol, ci.faxCol, ci.postalCodeCol];
testColumnsOrder(genInfoCols.concat(locCols).concat(contactInfoCols));
// moving last to be first
grid.moveColumn(ci.contactInfoColGroup, ci.genInfoColGroup, DropPosition.BeforeDropTarget);
fixture.detectChanges();
testColumnsOrder(contactInfoCols.concat(genInfoCols).concat(locCols));
// moving first to be last
grid.moveColumn(ci.contactInfoColGroup, ci.locationColGroup);
fixture.detectChanges();
testColumnsOrder(genInfoCols.concat(locCols).concat(contactInfoCols));
// moving inner to be last
grid.moveColumn(ci.locationColGroup, ci.contactInfoColGroup);
fixture.detectChanges();
testColumnsOrder(genInfoCols.concat(contactInfoCols).concat(locCols));
// moving inner to be first
grid.moveColumn(ci.contactInfoColGroup, ci.genInfoColGroup, DropPosition.BeforeDropTarget);
fixture.detectChanges();
testColumnsOrder(contactInfoCols.concat(genInfoCols).concat(locCols));
// moving to the same spot, no change expected
grid.moveColumn(ci.genInfoColGroup, ci.genInfoColGroup);
fixture.detectChanges();
testColumnsOrder(contactInfoCols.concat(genInfoCols).concat(locCols));
// moving column group to the place of a column, no change expected
grid.moveColumn(ci.genInfoColGroup, ci.countryCol);
fixture.detectChanges();
testColumnsOrder(contactInfoCols.concat(genInfoCols).concat(locCols));
});
it('Should move columns within column groups. One level column groups.', () => {
fixture = TestBed.createComponent(ThreeGroupsThreeColumnsGridComponent);
fixture.detectChanges();
const ci = fixture.componentInstance;
grid = ci.grid;
const genInfoAndLocCols = [ci.genInfoColGroup, ci.companyNameCol,
ci.contactNameCol, ci.contactTitleCol, ci.locationColGroup, ci.countryCol,
ci.regionCol, ci.cityCol];
// moving last to be first
grid.moveColumn(ci.postalCodeCol, ci.phoneCol, DropPosition.BeforeDropTarget);
fixture.detectChanges();
testColumnsOrder(genInfoAndLocCols.concat([ci.contactInfoColGroup,
ci.postalCodeCol, ci.phoneCol, ci.faxCol]));
// moving first to be last
grid.moveColumn(ci.postalCodeCol, ci.faxCol);
fixture.detectChanges();
testColumnsOrder(genInfoAndLocCols.concat([ci.contactInfoColGroup,
ci.phoneCol, ci.faxCol, ci.postalCodeCol]));
// moving inner to be last
grid.moveColumn(ci.faxCol, ci.postalCodeCol);
fixture.detectChanges();
testColumnsOrder(genInfoAndLocCols.concat([ci.contactInfoColGroup,
ci.phoneCol, ci.postalCodeCol, ci.faxCol]));
// moving inner to be first
grid.moveColumn(ci.postalCodeCol, ci.phoneCol, DropPosition.BeforeDropTarget);
fixture.detectChanges();
testColumnsOrder(genInfoAndLocCols.concat([ci.contactInfoColGroup,
ci.postalCodeCol, ci.phoneCol, ci.faxCol]));
// moving to the sample spot, no change expected
grid.moveColumn(ci.postalCodeCol, ci.postalCodeCol);
fixture.detectChanges();
testColumnsOrder(genInfoAndLocCols.concat([ci.contactInfoColGroup,
ci.postalCodeCol, ci.phoneCol, ci.faxCol]));
// moving column to the place of its column group, no change expected
grid.moveColumn(ci.postalCodeCol, ci.contactInfoColGroup);
fixture.detectChanges();
testColumnsOrder(genInfoAndLocCols.concat([ci.contactInfoColGroup,
ci.postalCodeCol, ci.phoneCol, ci.faxCol]));
//// moving column to the place of a column group, no change expected
grid.moveColumn(ci.postalCodeCol, ci.genInfoColGroup);
fixture.detectChanges();
testColumnsOrder(genInfoAndLocCols.concat([ci.contactInfoColGroup,
ci.postalCodeCol, ci.phoneCol, ci.faxCol]));
});
it('Should move columns and groups. Two level column groups.', () => {
fixture = TestBed.createComponent(NestedColGroupsGridComponent);
fixture.detectChanges();
const ci = fixture.componentInstance;
grid = ci.grid;
// moving a two-level col
grid.moveColumn(ci.phoneCol, ci.locationColGroup, DropPosition.BeforeDropTarget);
fixture.detectChanges();
testColumnsOrder([ci.contactInfoColGroup, ci.phoneCol, ci.locationColGroup, ci.countryCol,
ci.genInfoColGroup, ci.companyNameCol, ci.cityCol]);
// moving a three-level col
grid.moveColumn(ci.cityCol, ci.contactInfoColGroup, DropPosition.BeforeDropTarget);
fixture.detectChanges();
const colsOrder = [ci.cityCol, ci.contactInfoColGroup, ci.phoneCol,
ci.locationColGroup, ci.countryCol, ci.genInfoColGroup, ci.companyNameCol];
testColumnsOrder(colsOrder);
// moving between different groups, hould stay the same
grid.moveColumn(ci.locationColGroup, ci.companyNameCol);
fixture.detectChanges();
testColumnsOrder(colsOrder);
// moving between different levels, should stay the same
grid.moveColumn(ci.countryCol, ci.phoneCol);
testColumnsOrder(colsOrder);
// moving between different levels, should stay the same
grid.moveColumn(ci.cityCol, ci.phoneCol);
fixture.detectChanges();
testColumnsOrder(colsOrder);
grid.moveColumn(ci.genInfoColGroup, ci.companyNameCol);
fixture.detectChanges();
testColumnsOrder(colsOrder);
grid.moveColumn(ci.locationColGroup, ci.contactInfoColGroup);
fixture.detectChanges();
testColumnsOrder(colsOrder);
});
it('Should move columns and groups. Pinning enabled.', () => {
fixture = TestBed.createComponent(StegosaurusGridComponent);
fixture.detectChanges();
const ci = fixture.componentInstance;
ci.idCol.pinned = true;
fixture.detectChanges();
ci.genInfoColGroup.pinned = true;
fixture.detectChanges();
ci.postalCodeColGroup.pinned = true;
fixture.detectChanges();
ci.cityColGroup.pinned = true;
fixture.detectChanges();
// moving group from unpinned to pinned
ci.grid.moveColumn(ci.phoneColGroup, ci.idCol, DropPosition.BeforeDropTarget);
fixture.detectChanges();
let postMovingOrder = ci.phoneColList.concat([ci.idCol]).concat(ci.genInfoColList)
.concat(ci.postalCodeColList).concat(ci.cityColList).concat(ci.countryColList)
.concat(ci.regionColList).concat(ci.addressColList).concat(ci.faxColList);
testColumnsVisibleIndexes(postMovingOrder);
testColumnPinning(ci.phoneColGroup, true);
testColumnPinning(ci.idCol, true);
// moving sub group to different parent, should not be allowed
ci.grid.moveColumn(ci.pDetailsColGroup, ci.regionCol);
fixture.detectChanges();
testColumnsVisibleIndexes(postMovingOrder);
testColumnPinning(ci.pDetailsColGroup, true);
testColumnPinning(ci.regionCol, false);
// moving pinned group as firstly unpinned
ci.grid.moveColumn(ci.idCol, ci.cityColGroup);
fixture.detectChanges();
ci.idCol.pinned = false;
fixture.detectChanges();
postMovingOrder = ci.phoneColList.concat(ci.genInfoColList)
.concat(ci.postalCodeColList).concat(ci.cityColList).concat([ci.idCol])
.concat(ci.countryColList).concat(ci.regionColList)
.concat(ci.addressColList).concat(ci.faxColList);
testColumnsVisibleIndexes(postMovingOrder);
testColumnPinning(ci.idCol, false);
testColumnPinning(ci.countryColGroup, false);
// moving column to different parent, shound not be allowed
ci.grid.moveColumn(ci.postalCodeCol, ci.cityCol);
fixture.detectChanges();
testColumnsVisibleIndexes(postMovingOrder);
testColumnPinning(ci.postalCodeCol, true);
testColumnPinning(ci.cityCol, true);
});
});
describe('Features integration tests: ', () => {
beforeEach(fakeAsync(() => {
fixture = TestBed.createComponent(ColumnGroupFourLevelTestComponent);
fixture.detectChanges();
grid = fixture.componentInstance.grid;
}));
it('sorting - sort a grouped column by API', () => {
// Verify columns and groups
testGroupsAndColumns(7, 11, fixture);
grid.getColumnByName('CompanyName').sortable = true;
grid.getColumnByName('ContactName').sortable = true;
fixture.detectChanges();
// Sort column
grid.sort({ fieldName: 'CompanyName', dir: SortingDirection.Asc, ignoreCase: true });
fixture.detectChanges();
// Verify columns and groups
testGroupsAndColumns(7, 11, fixture);
// Verify cells
expect(grid.getCellByColumn(0, 'ID').value).toEqual('ALFKI');
expect(grid.getCellByColumn(0, 'ContactTitle').value).toEqual('Sales Representative');
expect(grid.getCellByColumn(0, 'CompanyName').value).toEqual('Alfreds Futterkiste');
expect(grid.getCellByColumn(4, 'ID').value).toEqual('BSBEV');
expect(grid.getCellByColumn(4, 'ContactTitle').value).toEqual('Sales Representative');
expect(grid.getCellByColumn(4, 'Country').value).toEqual('UK');
grid.clearSort();
fixture.detectChanges();
// Verify columns and groups
testGroupsAndColumns(7, 11, fixture);
// Verify cells
expect(grid.getCellByColumn(0, 'ID').value).toEqual('ALFKI');
expect(grid.getCellByColumn(0, 'ContactTitle').value).toEqual('Sales Representative');
expect(grid.getCellByColumn(0, 'CompanyName').value).toEqual('Alfreds Futterkiste');
expect(grid.getCellByColumn(4, 'ID').value).toEqual('BERGS');
expect(grid.getCellByColumn(4, 'Country').value).toEqual('Sweden');
// sort column which is not in the view
grid.sort({ fieldName: 'ContactName', dir: SortingDirection.Asc, ignoreCase: true });
fixture.detectChanges();
// Verify columns and groups
testGroupsAndColumns(7, 11, fixture);
// Verify cells
expect(grid.getCellByColumn(0, 'ID').value).toEqual('ANATR');
expect(grid.getCellByColumn(0, 'ContactTitle').value).toEqual('Owner');
expect(grid.getCellByColumn(0, 'CompanyName').value).toEqual('Ana Trujillo Emparedados y helados');
expect(grid.getCellByColumn(3, 'ID').value).toEqual('FAMIA');
expect(grid.getCellByColumn(3, 'ContactTitle').value).toEqual('Marketing Assistant');
expect(grid.getCellByColumn(3, 'Country').value).toEqual('Brazil');
});
it('sorting - sort a grouped column by clicking on header cell UI', () => {
// Verify columns and groups
testGroupsAndColumns(7, 11, fixture);
grid.getColumnByName('CompanyName').sortable = true;
fixture.detectChanges();
// Sort column by clicking on it
const contactTitleHeaderCell = GridFunctions.getColumnHeaderByIndex(fixture, 3);
contactTitleHeaderCell.triggerEventHandler('click', new Event('click'));
fixture.detectChanges();
// Verify columns and groups
testGroupsAndColumns(7, 11, fixture);
// Verify cells
expect(grid.getCellByColumn(0, 'ID').value).toEqual('ALFKI');
expect(grid.getCellByColumn(0, 'ContactTitle').value).toEqual('Sales Representative');
expect(grid.getCellByColumn(0, 'CompanyName').value).toEqual('Alfreds Futterkiste');
expect(grid.getCellByColumn(4, 'ID').value).toEqual('BERGS');
expect(grid.getCellByColumn(4, 'ContactTitle').value).toEqual('Order Administrator');
expect(grid.getCellByColumn(4, 'Country').value).toEqual('Sweden');
});
it('summaries - verify summaries when there are grouped columns', () => {
const allColumns = grid.columnList;
allColumns.forEach((col) => {
if (!col.columnGroup) {
col.hasSummary = true;
}
});
fixture.detectChanges();
const summaryRow = GridSummaryFunctions.getRootSummaryRow(fixture);
GridSummaryFunctions.verifyColumnSummaries(summaryRow, 0, ['Count'], ['27']);
GridSummaryFunctions.verifyColumnSummaries(summaryRow, 1, ['Count'], ['27']);
GridSummaryFunctions.verifyColumnSummaries(summaryRow, 2, ['Count'], ['27']);
GridSummaryFunctions.verifyColumnSummaries(summaryRow, 3, ['Count'], ['27']);
GridSummaryFunctions.verifyColumnSummaries(summaryRow, 4, ['Count'], ['27']);
GridSummaryFunctions.verifyColumnSummaries(summaryRow, 5, ['Count'], ['27']);
GridSummaryFunctions.verifyColumnSummaries(summaryRow, 6, ['Count'], ['27']);
});
it('filtering - filter a grouped column', fakeAsync(() => {
const initialRowListLenght = grid.rowList.length;
// Verify columns and groups
testGroupsAndColumns(7, 11, fixture);
grid.getColumnByName('ContactTitle').filterable = true;
tick();
grid.getColumnByName('PostalCode').filterable = true;
tick();
fixture.detectChanges();
// Filter column
grid.filter('ContactTitle', 'Accounting Manager',
IgxStringFilteringOperand.instance().condition('equals'), true);
tick();
fixture.detectChanges();
expect(grid.rowList.length).toEqual(2);
// Verify columns and groups
testGroupsAndColumns(7, 11, fixture);
// Filter column
grid.filter('PostalCode', '28', IgxStringFilteringOperand.instance().condition('contains'), true);
tick();
fixture.detectChanges();
expect(grid.rowList.length).toEqual(1);
// Reset filters
grid.clearFilter('ContactTitle');
tick();
grid.clearFilter('PostalCode');
tick();
fixture.detectChanges();
expect(grid.rowList.length).toEqual(initialRowListLenght);
// Verify columns and groups
testGroupsAndColumns(7, 11, fixture);
// Filter column with no match
grid.filter('ContactTitle', 'no items', IgxStringFilteringOperand.instance().condition('equals'), true);
tick();
fixture.detectChanges();
expect(grid.rowList.length).toEqual(0);
// Verify columns and groups
testGroupsAndColumns(7, 11, fixture);
// Clear filter
grid.clearFilter('ContactTitle');
tick();
fixture.detectChanges();
expect(grid.rowList.length).toEqual(initialRowListLenght);
// Verify columns and groups
testGroupsAndColumns(7, 11, fixture);
}));
it('grouping - verify grouping when there are grouped columns', () => {
fixture = TestBed.createComponent(ColumnGroupTestComponent);
fixture.detectChanges();
grid = fixture.componentInstance.grid;
// Verify columns and groups
testGroupsAndColumns(5, 11, fixture);
grid.getColumnByName('ContactTitle').groupable = true;
grid.getColumnByName('Country').groupable = true;
grid.getColumnByName('Phone').groupable = true;
fixture.detectChanges();
grid.groupBy({
fieldName: 'ContactTitle', dir: SortingDirection.Desc, ignoreCase: false,
strategy: DefaultSortingStrategy.instance()
});
fixture.detectChanges();
// verify grouping expressions
const grExprs = grid.groupingExpressions;
expect(grExprs.length).toEqual(1);
expect(grExprs[0].fieldName).toEqual('ContactTitle');
// verify rows
const groupRows = grid.groupsRowList.toArray();
const dataRows = grid.dataRowList.toArray();
expect(groupRows.length).toEqual(1);
expect(dataRows.length).toEqual(6);
// Verify first grouped row
const firstGroupedRow = groupRows[0].groupRow;
expect(firstGroupedRow.value).toEqual('Sales Representative');
expect(firstGroupedRow.records.length).toEqual(6);
});
});
});
const getColGroup = (grid: IgxGridComponent, headerName: string): IgxColumnGroupComponent => {
const colGroups = grid.columnList.filter(c => c.columnGroup && c.header === headerName);
if (colGroups.length === 0) {
return null;
} else if (colGroups.length === 1) {
return colGroups[0];
} else {
throw new Error('More than one column group found.');
}
};
// tests column and column group header rendering
const testColumnGroupHeaderRendering = (column: DebugElement, width: number, height: number,
title: string, descendentColumnCssClass?: string, descendentColumnCount?: number) => {
expect(column.nativeElement.offsetHeight).toBe(height);
expect(column.nativeElement.offsetWidth).toBe(width);
const colHeaderTitle = column.children
.filter(c => c.nativeElement.classList.contains(GRID_COL_GROUP_THEAD_TITLE_CLASS))[0];
expect(colHeaderTitle.nativeElement.textContent).toBe(title);
const colGroupDirectChildren = column.children
.filter(c => c.nativeElement.classList.contains(GRID_COL_GROUP_THEAD_GROUP_CLASS))[0]
.children.filter(c => {
const header = c.query(By.directive(IgxGridHeaderComponent));
return header.nativeElement.classList.contains(descendentColumnCssClass);
});
expect(colGroupDirectChildren.length).toBe(descendentColumnCount);
};
const testColumnHeaderRendering = (column: DebugElement, width: number, height: number,
title: string) => {
expect(column.nativeElement.offsetHeight).toBe(height);
expect(column.nativeElement.offsetWidth).toBe(width);
const colHeaderTitle = column.children
.filter(c => c.nativeElement.classList.contains(GRID_COL_THEAD_TITLE_CLASS))[0];
expect(colHeaderTitle.nativeElement.textContent.trim()).toBe(title);
};
const testColumnsOrder = (columns: IgxColumnComponent[]) => {
testColumnsIndexes(columns);
testColumnsVisibleIndexes(columns);
};
const testColumnsIndexes = (columns: IgxColumnComponent[]) => {
for (let index = 0; index < columns.length; index++) {
expect(columns[index].index).toBe(index);
}
};
const testColumnsVisibleIndexes = (columns: IgxColumnComponent[]) => {
let visibleIndex = 0;
for (const column of columns) {
expect(column.visibleIndex).toBe(visibleIndex);
if (!(column instanceof IgxColumnGroupComponent)) {
visibleIndex++;
}
}
};
const testGroupsAndColumns = (groups: number, columns: number, ci) => {
expect(GridFunctions.getColumnGroupHeaders(ci).length).toEqual(groups);
expect(GridFunctions.getColumnHeaders(ci).length).toEqual(columns);
};
const testColumnPinning = (column: IgxColumnComponent, isPinned: boolean) => {
expect(column.pinned).toBe(isPinned);
expect(column.allChildren.every(c => c.pinned === isPinned)).toEqual(true);
};
type PinUnpinFunc = (component: ColumnGroupFourLevelTestComponent) => void;
class PinningTests {
public static testColumnGroupPinning(pinGenInfoColFunc: PinUnpinFunc, unpinGenInfoColFunc: PinUnpinFunc) {
const fixture = TestBed.createComponent(ColumnGroupFourLevelTestComponent);
fixture.detectChanges();
const ci = fixture.componentInstance;
const grid = ci.grid;
expect(grid.pinnedColumns.length).toEqual(0);
expect(grid.unpinnedColumns.length).toEqual(18);
// Pin a column in a group
pinGenInfoColFunc(ci);
// Verify the topParent group is pinned
testColumnPinning(ci.genInfoColGroup, true);
testColumnPinning(ci.idCol, false);
testColumnPinning(ci.addrInfoColGroup, false);
testColumnsIndexes(ci.colsAndGroupsNaturalOrder);
testColumnsVisibleIndexes(ci.genInfoColsAndGroups.concat(ci.idCol).concat(ci.addrInfoColGroup));
expect(grid.pinnedColumns.length).toEqual(5);
expect(grid.unpinnedColumns.length).toEqual(13);
// Unpin a column
unpinGenInfoColFunc(ci);
// Verify the topParent group is not pinned
testColumnPinning(ci.genInfoColGroup, false);
testColumnPinning(ci.idCol, false);
testColumnPinning(ci.addrInfoColGroup, false);
testColumnsOrder(ci.colsAndGroupsNaturalOrder);
expect(grid.pinnedColumns.length).toEqual(0);
expect(grid.unpinnedColumns.length).toEqual(18);
}
}
class NestedColGroupsTests {
public static testHeadersRendering(fixture: ComponentFixture<NestedColumnGroupsGridComponent>) {
const ci = fixture.componentInstance;
const grid = ci.grid;
const firstSlaveColGroup = fixture.debugElement.query(By.css('.firstSlaveColGroup'));
const firstSlaveColGroupDepth = 2; // one-level children
const firstSlaveColGroupChildrenCount = 2;
const firstSlaveColGroupWidth = parseInt(ci.columnWidth, 10) + parseInt(ci.phoneColWidth, 10);
testColumnGroupHeaderRendering(firstSlaveColGroup, firstSlaveColGroupWidth,
firstSlaveColGroupDepth * grid.defaultRowHeight,
ci.firstSlaveColGroupTitle, 'firstSlaveChild', firstSlaveColGroupChildrenCount);
const secondSlaveColGroup = fixture.debugElement.query(By.css('.secondSlaveColGroup'));
const secondSlaveColGroupDepth = 2; // one-level children
const secondSlaveColGroupChildrenCount = 2;
const secondSlaveColGroupWidth = parseInt(ci.faxColWidth, 10) + parseInt(ci.cityColWidth, 10);
testColumnGroupHeaderRendering(secondSlaveColGroup, secondSlaveColGroupWidth,
secondSlaveColGroupDepth * grid.defaultRowHeight,
ci.secondSlaveColGroupTitle, 'secondSlaveChild', secondSlaveColGroupChildrenCount);
const masterColGroup = fixture.debugElement.query(By.css('.masterColGroup'));
const masterColGroupWidth = firstSlaveColGroupWidth + secondSlaveColGroupWidth;
const masterSlaveColGroupDepth = 3;
const masterColGroupChildrenCount = 0;
testColumnGroupHeaderRendering(masterColGroup, masterColGroupWidth,
masterSlaveColGroupDepth * grid.defaultRowHeight, ci.masterColGroupTitle,
'slaveColGroup', masterColGroupChildrenCount);
}
}
/* eslint-enable max-len */ | the_stack |
import { basename, isEqual, joinPath } from 'vs/base/common/resources';
import { URI } from 'vs/base/common/uri';
import { coalesce } from 'vs/base/common/arrays';
import { equals, deepClone } from 'vs/base/common/objects';
import { Promises, ResourceQueue } from 'vs/base/common/async';
import { IResolvedWorkingCopyBackup, IWorkingCopyBackupService } from 'vs/workbench/services/workingCopy/common/workingCopyBackup';
import { IFileService, FileOperationError, FileOperationResult } from 'vs/platform/files/common/files';
import { ResourceMap } from 'vs/base/common/map';
import { isReadableStream, peekStream } from 'vs/base/common/stream';
import { bufferToStream, prefixedBufferReadable, prefixedBufferStream, readableToBuffer, streamToBuffer, VSBuffer, VSBufferReadable, VSBufferReadableStream } from 'vs/base/common/buffer';
import { Disposable } from 'vs/base/common/lifecycle';
import { ILogService } from 'vs/platform/log/common/log';
import { CancellationToken } from 'vs/base/common/cancellation';
import { Schemas } from 'vs/base/common/network';
import { hash } from 'vs/base/common/hash';
import { isEmptyObject } from 'vs/base/common/types';
import { IWorkingCopyBackupMeta, IWorkingCopyIdentifier } from 'vs/workbench/services/workingCopy/common/workingCopy';
export class WorkingCopyBackupsModel {
private readonly cache = new ResourceMap<{ versionId?: number, meta?: IWorkingCopyBackupMeta }>();
static async create(backupRoot: URI, fileService: IFileService): Promise<WorkingCopyBackupsModel> {
const model = new WorkingCopyBackupsModel(backupRoot, fileService);
await model.resolve();
return model;
}
private constructor(private backupRoot: URI, private fileService: IFileService) { }
private async resolve(): Promise<void> {
try {
const backupRootStat = await this.fileService.resolve(this.backupRoot);
if (backupRootStat.children) {
await Promises.settled(backupRootStat.children
.filter(child => child.isDirectory)
.map(async backupSchemaFolder => {
// Read backup directory for backups
const backupSchemaFolderStat = await this.fileService.resolve(backupSchemaFolder.resource);
// Remember known backups in our caches
if (backupSchemaFolderStat.children) {
for (const backupForSchema of backupSchemaFolderStat.children) {
if (!backupForSchema.isDirectory) {
this.add(backupForSchema.resource);
}
}
}
}));
}
} catch (error) {
// ignore any errors
}
}
add(resource: URI, versionId = 0, meta?: IWorkingCopyBackupMeta): void {
this.cache.set(resource, { versionId, meta: deepClone(meta) }); // make sure to not store original meta in our cache...
}
count(): number {
return this.cache.size;
}
has(resource: URI, versionId?: number, meta?: IWorkingCopyBackupMeta): boolean {
const entry = this.cache.get(resource);
if (!entry) {
return false; // unknown resource
}
if (typeof versionId === 'number' && versionId !== entry.versionId) {
return false; // different versionId
}
if (meta && !equals(meta, entry.meta)) {
return false; // different metadata
}
return true;
}
get(): URI[] {
return Array.from(this.cache.keys());
}
remove(resource: URI): void {
this.cache.delete(resource);
}
move(source: URI, target: URI): void {
const entry = this.cache.get(source);
if (entry) {
this.cache.delete(source);
this.cache.set(target, entry);
}
}
clear(): void {
this.cache.clear();
}
}
export abstract class WorkingCopyBackupService implements IWorkingCopyBackupService {
declare readonly _serviceBrand: undefined;
private impl: NativeWorkingCopyBackupServiceImpl | InMemoryWorkingCopyBackupService;
constructor(
backupWorkspaceHome: URI | undefined,
@IFileService protected fileService: IFileService,
@ILogService private readonly logService: ILogService
) {
this.impl = this.initialize(backupWorkspaceHome);
}
private initialize(backupWorkspaceHome: URI | undefined): NativeWorkingCopyBackupServiceImpl | InMemoryWorkingCopyBackupService {
if (backupWorkspaceHome) {
return new NativeWorkingCopyBackupServiceImpl(backupWorkspaceHome, this.fileService, this.logService);
}
return new InMemoryWorkingCopyBackupService();
}
reinitialize(backupWorkspaceHome: URI | undefined): void {
// Re-init implementation (unless we are running in-memory)
if (this.impl instanceof NativeWorkingCopyBackupServiceImpl) {
if (backupWorkspaceHome) {
this.impl.initialize(backupWorkspaceHome);
} else {
this.impl = new InMemoryWorkingCopyBackupService();
}
}
}
hasBackups(): Promise<boolean> {
return this.impl.hasBackups();
}
hasBackupSync(identifier: IWorkingCopyIdentifier, versionId?: number): boolean {
return this.impl.hasBackupSync(identifier, versionId);
}
backup(identifier: IWorkingCopyIdentifier, content?: VSBufferReadableStream | VSBufferReadable, versionId?: number, meta?: IWorkingCopyBackupMeta, token?: CancellationToken): Promise<void> {
return this.impl.backup(identifier, content, versionId, meta, token);
}
discardBackup(identifier: IWorkingCopyIdentifier): Promise<void> {
return this.impl.discardBackup(identifier);
}
discardBackups(filter?: { except: IWorkingCopyIdentifier[] }): Promise<void> {
return this.impl.discardBackups(filter);
}
getBackups(): Promise<IWorkingCopyIdentifier[]> {
return this.impl.getBackups();
}
resolve<T extends IWorkingCopyBackupMeta>(identifier: IWorkingCopyIdentifier): Promise<IResolvedWorkingCopyBackup<T> | undefined> {
return this.impl.resolve(identifier);
}
toBackupResource(identifier: IWorkingCopyIdentifier): URI {
return this.impl.toBackupResource(identifier);
}
}
class NativeWorkingCopyBackupServiceImpl extends Disposable implements IWorkingCopyBackupService {
private static readonly PREAMBLE_END_MARKER = '\n';
private static readonly PREAMBLE_END_MARKER_CHARCODE = '\n'.charCodeAt(0);
private static readonly PREAMBLE_META_SEPARATOR = ' '; // using a character that is know to be escaped in a URI as separator
private static readonly PREAMBLE_MAX_LENGTH = 10000;
declare readonly _serviceBrand: undefined;
private readonly ioOperationQueues = this._register(new ResourceQueue()); // queue IO operations to ensure write/delete file order
private ready!: Promise<WorkingCopyBackupsModel>;
private model: WorkingCopyBackupsModel | undefined = undefined;
constructor(
private backupWorkspaceHome: URI,
@IFileService private readonly fileService: IFileService,
@ILogService private readonly logService: ILogService
) {
super();
this.initialize(backupWorkspaceHome);
}
initialize(backupWorkspaceResource: URI): void {
this.backupWorkspaceHome = backupWorkspaceResource;
this.ready = this.doInitialize();
}
private async doInitialize(): Promise<WorkingCopyBackupsModel> {
// Create backup model
this.model = await WorkingCopyBackupsModel.create(this.backupWorkspaceHome, this.fileService);
// Migrate hashes as needed. We used to hash with a MD5
// sum of the path but switched to our own simpler hash
// to avoid a node.js dependency. We still want to
// support the older hash so we:
// - iterate over all backups
// - detect if the file name length is 32 (MD5 length)
// - read the backup's target file path
// - rename the backup to the new hash
// - update the backup in our model
//
// TODO@bpasero remove me eventually
for (const backupResource of this.model.get()) {
if (basename(backupResource).length !== 32) {
continue; // not a MD5 hash, already uses new hash function
}
try {
const identifier = await this.resolveIdentifier(backupResource);
if (!identifier) {
this.logService.warn(`Backup: Unable to read target URI of backup ${backupResource} for migration to new hash.`);
continue;
}
const expectedBackupResource = this.toBackupResource(identifier);
if (!isEqual(expectedBackupResource, backupResource)) {
await this.fileService.move(backupResource, expectedBackupResource, true);
this.model.move(backupResource, expectedBackupResource);
}
} catch (error) {
this.logService.error(`Backup: Unable to migrate backup ${backupResource} to new hash.`);
}
}
return this.model;
}
async hasBackups(): Promise<boolean> {
const model = await this.ready;
return model.count() > 0;
}
hasBackupSync(identifier: IWorkingCopyIdentifier, versionId?: number): boolean {
if (!this.model) {
return false;
}
const backupResource = this.toBackupResource(identifier);
return this.model.has(backupResource, versionId);
}
async backup(identifier: IWorkingCopyIdentifier, content?: VSBufferReadable | VSBufferReadableStream, versionId?: number, meta?: IWorkingCopyBackupMeta, token?: CancellationToken): Promise<void> {
const model = await this.ready;
if (token?.isCancellationRequested) {
return;
}
const backupResource = this.toBackupResource(identifier);
if (model.has(backupResource, versionId, meta)) {
return; // return early if backup version id matches requested one
}
return this.ioOperationQueues.queueFor(backupResource).queue(async () => {
if (token?.isCancellationRequested) {
return;
}
// Encode as: Resource + META-START + Meta + END
// and respect max length restrictions in case
// meta is too large.
let preamble = this.createPreamble(identifier, meta);
if (preamble.length >= NativeWorkingCopyBackupServiceImpl.PREAMBLE_MAX_LENGTH) {
preamble = this.createPreamble(identifier);
}
// Update backup with value
const preambleBuffer = VSBuffer.fromString(preamble);
let backupBuffer: VSBuffer | VSBufferReadableStream | VSBufferReadable;
if (isReadableStream(content)) {
backupBuffer = prefixedBufferStream(preambleBuffer, content);
} else if (content) {
backupBuffer = prefixedBufferReadable(preambleBuffer, content);
} else {
backupBuffer = VSBuffer.concat([preambleBuffer, VSBuffer.fromString('')]);
}
await this.fileService.writeFile(backupResource, backupBuffer);
// Update model
model.add(backupResource, versionId, meta);
});
}
private createPreamble(identifier: IWorkingCopyIdentifier, meta?: IWorkingCopyBackupMeta): string {
return `${identifier.resource.toString()}${NativeWorkingCopyBackupServiceImpl.PREAMBLE_META_SEPARATOR}${JSON.stringify({ ...meta, typeId: identifier.typeId })}${NativeWorkingCopyBackupServiceImpl.PREAMBLE_END_MARKER}`;
}
async discardBackups(filter?: { except: IWorkingCopyIdentifier[] }): Promise<void> {
const model = await this.ready;
// Discard all but some backups
const except = filter?.except;
if (Array.isArray(except) && except.length > 0) {
const exceptMap = new ResourceMap<boolean>();
for (const exceptWorkingCopy of except) {
exceptMap.set(this.toBackupResource(exceptWorkingCopy), true);
}
await Promises.settled(model.get().map(async backupResource => {
if (!exceptMap.has(backupResource)) {
await this.doDiscardBackup(backupResource);
}
}));
}
// Discard all backups
else {
await this.deleteIgnoreFileNotFound(this.backupWorkspaceHome);
model.clear();
}
}
discardBackup(identifier: IWorkingCopyIdentifier): Promise<void> {
const backupResource = this.toBackupResource(identifier);
return this.doDiscardBackup(backupResource);
}
private async doDiscardBackup(backupResource: URI): Promise<void> {
const model = await this.ready;
return this.ioOperationQueues.queueFor(backupResource).queue(async () => {
await this.deleteIgnoreFileNotFound(backupResource);
model.remove(backupResource);
});
}
private async deleteIgnoreFileNotFound(backupResource: URI): Promise<void> {
try {
await this.fileService.del(backupResource, { recursive: true });
} catch (error) {
if ((<FileOperationError>error).fileOperationResult !== FileOperationResult.FILE_NOT_FOUND) {
throw error; // re-throw any other error than file not found which is OK
}
}
}
async getBackups(): Promise<IWorkingCopyIdentifier[]> {
const model = await this.ready;
const backups = await Promise.all(model.get().map(backupResource => this.resolveIdentifier(backupResource)));
return coalesce(backups);
}
private async resolveIdentifier(backupResource: URI): Promise<IWorkingCopyIdentifier | undefined> {
// Read the entire backup preamble by reading up to
// `PREAMBLE_MAX_LENGTH` in the backup file until
// the `PREAMBLE_END_MARKER` is found
const backupPreamble = await this.readToMatchingString(backupResource, NativeWorkingCopyBackupServiceImpl.PREAMBLE_END_MARKER, NativeWorkingCopyBackupServiceImpl.PREAMBLE_MAX_LENGTH);
if (!backupPreamble) {
return undefined;
}
// Figure out the offset in the preamble where meta
// information possibly starts. This can be `-1` for
// older backups without meta.
const metaStartIndex = backupPreamble.indexOf(NativeWorkingCopyBackupServiceImpl.PREAMBLE_META_SEPARATOR);
// Extract the preamble content for resource and meta
let resourcePreamble: string;
let metaPreamble: string | undefined;
if (metaStartIndex > 0) {
resourcePreamble = backupPreamble.substring(0, metaStartIndex);
metaPreamble = backupPreamble.substr(metaStartIndex + 1);
} else {
resourcePreamble = backupPreamble;
metaPreamble = undefined;
}
// Try to find the `typeId` in the meta data if possible
let typeId: string | undefined = undefined;
if (metaPreamble) {
try {
typeId = JSON.parse(metaPreamble).typeId;
} catch (error) {
// ignore JSON parse errors
}
}
return {
typeId: typeId ?? '', // Fallback for previous backups that do not encode the typeId (TODO@bpasero remove me eventually)
resource: URI.parse(resourcePreamble)
};
}
private async readToMatchingString(backupResource: URI, matchingString: string, maximumBytesToRead: number): Promise<string | undefined> {
const contents = (await this.fileService.readFile(backupResource, { length: maximumBytesToRead })).value.toString();
const matchingStringIndex = contents.indexOf(matchingString);
if (matchingStringIndex >= 0) {
return contents.substr(0, matchingStringIndex);
}
// Unable to find matching string in file
return undefined;
}
async resolve<T extends IWorkingCopyBackupMeta>(identifier: IWorkingCopyIdentifier): Promise<IResolvedWorkingCopyBackup<T> | undefined> {
const backupResource = this.toBackupResource(identifier);
const model = await this.ready;
if (!model.has(backupResource)) {
return undefined; // require backup to be present
}
// Load the backup content and peek into the first chunk
// to be able to resolve the meta data
const backupStream = await this.fileService.readFileStream(backupResource);
const peekedBackupStream = await peekStream(backupStream.value, 1);
const firstBackupChunk = VSBuffer.concat(peekedBackupStream.buffer);
// We have seen reports (e.g. https://github.com/microsoft/vscode/issues/78500) where
// if VSCode goes down while writing the backup file, the file can turn empty because
// it always first gets truncated and then written to. In this case, we will not find
// the meta-end marker ('\n') and as such the backup can only be invalid. We bail out
// here if that is the case.
const preambleEndIndex = firstBackupChunk.buffer.indexOf(NativeWorkingCopyBackupServiceImpl.PREAMBLE_END_MARKER_CHARCODE);
if (preambleEndIndex === -1) {
this.logService.trace(`Backup: Could not find meta end marker in ${backupResource}. The file is probably corrupt (filesize: ${backupStream.size}).`);
return undefined;
}
const preambelRaw = firstBackupChunk.slice(0, preambleEndIndex).toString();
// Extract meta data (if any)
let meta: T | undefined;
const metaStartIndex = preambelRaw.indexOf(NativeWorkingCopyBackupServiceImpl.PREAMBLE_META_SEPARATOR);
if (metaStartIndex !== -1) {
try {
meta = JSON.parse(preambelRaw.substr(metaStartIndex + 1));
// `typeId` is a property that we add so we
// remove it when returning to clients.
if (typeof meta?.typeId === 'string') {
delete meta.typeId;
if (isEmptyObject(meta)) {
meta = undefined;
}
}
} catch (error) {
// ignore JSON parse errors
}
}
// Build a new stream without the preamble
const firstBackupChunkWithoutPreamble = firstBackupChunk.slice(preambleEndIndex + 1);
let value: VSBufferReadableStream;
if (peekedBackupStream.ended) {
value = bufferToStream(firstBackupChunkWithoutPreamble);
} else {
value = prefixedBufferStream(firstBackupChunkWithoutPreamble, peekedBackupStream.stream);
}
return { value, meta };
}
toBackupResource(identifier: IWorkingCopyIdentifier): URI {
return joinPath(this.backupWorkspaceHome, identifier.resource.scheme, hashIdentifier(identifier));
}
}
export class InMemoryWorkingCopyBackupService implements IWorkingCopyBackupService {
declare readonly _serviceBrand: undefined;
private backups = new ResourceMap<{ typeId: string, content: VSBuffer, meta?: IWorkingCopyBackupMeta }>();
constructor() { }
async hasBackups(): Promise<boolean> {
return this.backups.size > 0;
}
hasBackupSync(identifier: IWorkingCopyIdentifier, versionId?: number): boolean {
const backupResource = this.toBackupResource(identifier);
return this.backups.has(backupResource);
}
async backup(identifier: IWorkingCopyIdentifier, content?: VSBufferReadable | VSBufferReadableStream, versionId?: number, meta?: IWorkingCopyBackupMeta, token?: CancellationToken): Promise<void> {
const backupResource = this.toBackupResource(identifier);
this.backups.set(backupResource, {
typeId: identifier.typeId,
content: content instanceof VSBuffer ? content : content ? isReadableStream(content) ? await streamToBuffer(content) : readableToBuffer(content) : VSBuffer.fromString(''),
meta
});
}
async resolve<T extends IWorkingCopyBackupMeta>(identifier: IWorkingCopyIdentifier): Promise<IResolvedWorkingCopyBackup<T> | undefined> {
const backupResource = this.toBackupResource(identifier);
const backup = this.backups.get(backupResource);
if (backup) {
return { value: bufferToStream(backup.content), meta: backup.meta as T | undefined };
}
return undefined;
}
async getBackups(): Promise<IWorkingCopyIdentifier[]> {
return Array.from(this.backups.entries()).map(([resource, backup]) => ({ typeId: backup.typeId, resource }));
}
async discardBackup(identifier: IWorkingCopyIdentifier): Promise<void> {
this.backups.delete(this.toBackupResource(identifier));
}
async discardBackups(filter?: { except: IWorkingCopyIdentifier[] }): Promise<void> {
const except = filter?.except;
if (Array.isArray(except) && except.length > 0) {
const exceptMap = new ResourceMap<boolean>();
for (const exceptWorkingCopy of except) {
exceptMap.set(this.toBackupResource(exceptWorkingCopy), true);
}
for (const backup of await this.getBackups()) {
if (!exceptMap.has(this.toBackupResource(backup))) {
await this.discardBackup(backup);
}
}
} else {
this.backups.clear();
}
}
toBackupResource(identifier: IWorkingCopyIdentifier): URI {
return URI.from({ scheme: Schemas.inMemory, path: hashIdentifier(identifier) });
}
}
/*
* Exported only for testing
*/
export function hashIdentifier(identifier: IWorkingCopyIdentifier): string {
// IMPORTANT: for backwards compatibility, ensure that
// we ignore the `typeId` unless a value is provided.
// To preserve previous backups without type id, we
// need to just hash the resource. Otherwise we use
// the type id as a seed to the resource path.
let resource: URI;
if (identifier.typeId.length > 0) {
const typeIdHash = hashString(identifier.typeId);
if (identifier.resource.path) {
resource = joinPath(identifier.resource, typeIdHash);
} else {
resource = identifier.resource.with({ path: typeIdHash });
}
} else {
resource = identifier.resource;
}
return hashPath(resource);
}
function hashPath(resource: URI): string {
const str = resource.scheme === Schemas.file || resource.scheme === Schemas.untitled ? resource.fsPath : resource.toString();
return hashString(str);
}
function hashString(str: string): string {
return hash(str).toString(16);
} | the_stack |
import { Hummer, View, Text, Button, Toast, BasicAnimation, KeyframeAnimation } from '@hummer/hummer-front'
var board = new Array();
var added = new Array();
var score = 0;
var top = 240;
function newgame() {
//初始化棋盘格
init();
//在随机两个各自声称的数字
generateOneNumber();
generateOneNumber();
}
function init() {
score = 0;
for (var i = 0; i < 4; i++) {
for (var j = 0; j < 4; j++) {
var gridCell = $("#grid-cell-" + i + "-" + j);
gridCell.style = {
top: getPosTop(i, j),
left: getPosLeft(i, j),
}
}
}
for (var i = 0; i < 4; i++) {//初始化格子数组
board[i] = new Array();
for (var j = 0; j < 4; j++) {
board[i][j] = 0;
}
}
for (var i = 0; i < 4; i++) {//初始化判定合并的数组
added[i] = new Array();
for (var j = 0; j < 4; j++) {
added[i][j] = 0;
}
}
updateBoardView();//通知前端对board二位数组进行设定。
}
function updateBoardView() {//更新数组的前端样式
for (var key in globalMap) {
if (key.startsWith("#number-cell-")) {
$('#grid-container').removeChild(globalMap[key]);
}
}
for (var i = 0; i < 4; i++) {
for (var j = 0; j < 4; j++) {
var theNumberCell = new Text();
theNumberCell.style = {
position: 'absolute',
textAlign: 'center',
fontSize: 26,
fontWeight: 'bold',
borderRadius: 5,
}
globalMap['#number-cell-' + i + '-' + j] = theNumberCell;
$("#grid-container").appendChild(theNumberCell);
if (board[i][j] == 0) {
theNumberCell.style = {
width: 0,
height: 0,
top: getPosTop(i, j),
left: getPosLeft(i, j),
}
} else {
theNumberCell.style = {
width: CELL_SIZE,
height: CELL_SIZE,
top: getPosTop(i, j),
left: getPosLeft(i, j),
backgroundColor: getNumberBackgroundColor(board[i][j]),
color: getNumberColor(board[i][j]),
}
theNumberCell.text = board[i][j].toString();
}
}
}
}
function generateOneNumber() {//生成随机的格子
if (nospace(board))
return false;
//随机一个位置
var randx = Math.floor(Math.random() * 4);
var randy = Math.floor(Math.random() * 4);
while (true) {
if (board[randx][randy] == 0)
break;
randx = Math.floor(Math.random() * 4);
randy = Math.floor(Math.random() * 4);
}
//随机一个数字
var randNumber = Math.random() < 0.5 ? 2 : 4;
//在随机位置显示随机数字
board[randx][randy] = randNumber;
showNumberWithAnimation(randx, randy, randNumber);
return true;
}
//事件响应循环
var swipeCallback = function (event) {
var keyCode = event.direction;
switch (keyCode) {
// case 37://left
case 2://left
if (moveLeft()) {
getScore();
generateOneNumber();//每次新增一个数字就可能出现游戏结束
setTimeout(() => { isgameover() }, 400);//300毫秒
}
break;
// case 38://up
case 4://up
if (moveUp()) {
getScore();
generateOneNumber();//每次新增一个数字就可能出现游戏结束
setTimeout(() => { isgameover() }, 400);
}
break;
// case 39://right
case 1://right
if (moveRight()) {
getScore();
generateOneNumber();//每次新增一个数字就可能出现游戏结束
setTimeout(() => { isgameover() }, 400);
}
break;
// case 40://down
case 8://down
if (moveDown()) {
getScore();
generateOneNumber();//每次新增一个数字就可能出现游戏结束
setTimeout(() => { isgameover() }, 400);
}
break;
}
}
function isgameover() {
if (nospace(board) && nomove(board)) {
gameover();
}
}
function gameover() {
Toast.show('Game Over!');
}
function isaddedArray() {//将判断能否合并的数组值置为0
for (var i = 0; i < 4; i++) {
for (var j = 0; j < 4; j++) {
added[i][j] = 0;
}
}
}
function moveLeft() {//更多地细节信息
//判断格子是否能够向左移动
if (!canMoveLeft(board))
return false;
isaddedArray();
//真正的moveLeft函数//标准
for (var i = 0; i < 4; i++)
for (var j = 1; j < 4; j++) {//第一列的数字不可能向左移动
if (board[i][j] != 0) {
//(i,j)左侧的元素
for (var k = 0; k < j; k++) {
//落脚位置的数字是否为空 && 中间没有障碍物
if (board[i][k] == 0 && noBlockHorizontal(i, k, j, board)) {
//move
showMoveAnimation(i, j, i, k);
board[i][k] = board[i][j];
board[i][j] = 0;
break;
}
//落脚位置的数字和本来的数字相等 && 中间没有障碍物
else if (board[i][k] == board[i][j] && noBlockHorizontal(i, k, j, board)) {
//move
showMoveAnimation(i, j, i, k);
//add
if (added[i][k] != 0) {//目标落脚点是否完成过合并
board[i][k + 1] = board[i][j];
board[i][j] = 0;
}
else {
board[i][k] += board[i][j];
board[i][j] = 0;
added[i][k] = 1;
score += board[i][k];
}
break;
}
}
}
}
setTimeout(updateBoardView, 200);
return true;
}
function moveRight() {//更多地细节信息
//判断格子是否能够向右移动
if (!canMoveRight(board))
return false;
isaddedArray();
//真正的moveRight函数//标准
for (var i = 0; i < 4; i++)
for (var j = 2; j >= 0; j--) {//最后一列的数字不可能向右移动
if (board[i][j] != 0) {
//(i,j)右侧的元素
for (var k = 3; k > j; k--) {
//落脚位置的数字是否为空 && 中间没有障碍物
if (board[i][k] == 0 && noBlockHorizontal(i, j, k, board)) {
//move
showMoveAnimation(i, j, i, k);
board[i][k] = board[i][j];
board[i][j] = 0;
break;
}
//落脚位置的数字和本来的数字相等 && 中间没有障碍物
else if (board[i][k] == board[i][j] && noBlockHorizontal(i, j, k, board)) {
//move
showMoveAnimation(i, j, i, k);
//add
if (added[i][k] != 0) {
board[i][k - 1] = board[i][j];
board[i][j] = 0;
}
else {
board[i][k] += board[i][j];
board[i][j] = 0;
added[i][k] = 1;
score += board[i][k];
}
break;
}
}
}
}
setTimeout(updateBoardView, 200);
return true;
}
function moveUp() {//更多地细节信息
//判断格子是否能够向上移动
if (!canMoveUp(board))
return false;
isaddedArray();
//真正的moveUp函数//标准
for (var j = 0; j < 4; j++)
for (var i = 1; i < 4; i++) {//第一行的数字不可能向上移动
if (board[i][j] != 0) {
//(i,j)上面的元素
for (var k = 0; k < i; k++) {
//落脚位置的数字是否为空 && 中间没有障碍物
if (board[k][j] == 0 && noBlockVertical(j, k, i, board)) {
//move
showMoveAnimation(i, j, k, j);
board[k][j] = board[i][j];
board[i][j] = 0;
break;
}
//落脚位置的数字和本来的数字相等 && 中间没有障碍物
else if (board[k][j] == board[i][j] && noBlockVertical(j, k, i, board)) {
//move
showMoveAnimation(i, j, k, j);
//add
if (added[k][j] != 0) {
board[k + 1][j] = board[i][j];
board[i][j] = 0;
}
else {
board[k][j] += board[i][j];
board[i][j] = 0;
added[k][j] = 1;
score += board[k][j];
}
break;
}
}
}
}
setTimeout(updateBoardView, 200);
return true;
}
function moveDown() {//更多地细节信息
//判断格子是否能够向下移动
if (!canMoveDown(board))
return false;
isaddedArray();
//真正的moveDown函数//标准
for (var j = 0; j < 4; j++)
for (var i = 2; i >= 0; i--) {//最后一行的数字不可能向下移动
if (board[i][j] != 0) {
//(i,j)上面的元素
for (var k = 3; k > i; k--) {
//落脚位置的数字是否为空 && 中间没有障碍物
if (board[k][j] == 0 && noBlockVertical(j, i, k, board)) {
//move
showMoveAnimation(i, j, k, j);
board[k][j] = board[i][j];
board[i][j] = 0;
break;
}
//落脚位置的数字和本来的数字相等 && 中间没有障碍物
else if (board[k][j] == board[i][j] && noBlockVertical(j, i, k, board)) {
//move
showMoveAnimation(i, j, k, j);
//add
if (added[k][j] != 0) {
board[k - 1][j] = board[i][j];
board[i][j] = 0;
}
else {
board[k][j] += board[i][j];
board[i][j] = 0;
added[k][j] = 1;
score += board[k][j];
}
break;
}
}
}
}
setTimeout(updateBoardView, 200);
return true;
}
/**
* support 2048
*/
function getPosTop(i, j) {
return CELL_SPACE + i * (CELL_SIZE + CELL_SPACE);
}
function getPosLeft(i, j) {
return CELL_SPACE + j * (CELL_SIZE + CELL_SPACE);
}
function getNumberBackgroundColor(number) {
switch (number) {
case 2:
return "#eee4da";
break;
case 4:
return "#eee4da";
break;
case 8:
return "#f26179";
break;
case 16:
return "#f59563";
break;
case 32:
return "#f67c5f";
break;
case 64:
return "#f65e36";
break;
case 128:
return "#edcf72";
break;
case 256:
return "#edcc61";
break;
case 512:
return "#99cc00";
break;
case 1024:
return "#3365a5";
break;
case 2048:
return "#0099cc";
break;
case 4096:
return "#00a6bc";
break;
case 8192:
return "#9933cc";
break;
}
return "#000000";
}
function getNumberColor(number) {
if (number <= 4) {
return "#776e65";
}
return "#FFFFFF";
}
function getScore() {
// document.getElementById("score").innerHTML=score;
$('score').text = score.toString();
}
//在随机生成数字的时候判断16宫格中是否还有空间
function nospace(board) {
for (var i = 0; i < 4; i++)
for (var j = 0; j < 4; j++)
if (board[i][j] == 0)
return false;
return true;
}
//实现功能判断
function canMoveLeft(board) {
for (var i = 0; i < 4; i++)
for (var j = 0; j < 4; j++)
if (board[i][j] != 0 && j != 0)
if (board[i][j - 1] == 0 || board[i][j - 1] == board[i][j])
return true;
return false;
}
function canMoveRight(board) {
for (var i = 0; i < 4; i++)
for (var j = 0; j < 4; j++)
if (board[i][j] != 0 && j != 3)
if (board[i][j + 1] == 0 || board[i][j + 1] == board[i][j])
return true;
return false;
}
function canMoveUp(board) {
for (var i = 0; i < 4; i++)
for (var j = 0; j < 4; j++)
if (board[i][j] != 0 && i != 0)
if (board[i - 1][j] == 0 || board[i - 1][j] == board[i][j])
return true;
return false;
}
function canMoveDown(board) {
for (var i = 0; i < 4; i++)
for (var j = 0; j < 4; j++)
if (board[i][j] != 0 && i != 3)
if (board[i + 1][j] == 0 || board[i + 1][j] == board[i][j])
return true;
return false;
}
//判断水平方向是否有障碍物
function noBlockHorizontal(row, col1, col2, board) {
for (var i = col1 + 1; i < col2; i++)
if (board[row][i] != 0)
return false;
return true;
}
//判断竖直方向是否有障碍物
function noBlockVertical(col, row1, row2, board) {
for (var i = row1 + 1; i < row2; i++)
if (board[i][col] != 0)
return false;
return true;
}
//最后收尾
function nomove(board) {
if (canMoveLeft(board) || canMoveRight(board) || canMoveUp(board) || canMoveDown(board))
return false;
return true;
}
/**
* show Animation 2048
*/
function showNumberWithAnimation(i, j, randNumber) {//实现随机数字的样式变动
var numberCell = $('#number-cell-' + i + '-' + j);
numberCell.style = {
backgroundColor: getNumberBackgroundColor(randNumber),
color: getNumberColor(randNumber),
width: CELL_SIZE,
height: CELL_SIZE,
}
numberCell.text = randNumber.toString();
let anim = new KeyframeAnimation('scale');
anim.keyframes = [{
percent: 0,
value: 0.4,
}, {
percent: 1,
value: 1,
}];
anim.duration = 0.2;
numberCell.addAnimation(anim, "xx");
}
function showMoveAnimation(fromx, fromy, tox, toy) {//实现移动格子的样式变动
var numberCell = $('#number-cell-' + fromx + '-' + fromy);
var anim = new BasicAnimation("position");
anim.value = {
x: getPosLeft(tox, toy) - getPosLeft(fromx, fromy),
y: getPosTop(tox, toy) - getPosTop(fromx, fromy)
};
console.log(anim.value);
anim.duration = 0.2;
numberCell.addAnimation(anim, "xx");
}
/**
* hummer
*/
class RootView extends View {
constructor() {
super();
this.style = {
width: '100%',
height: '100%',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#FFFFFF',
}
this.addEventListener('swipe', swipeCallback);
let title = new Text();
title.text = '2048';
title.style = {
fontSize: 40,
fontWeight: 'bold',
color: '#15D0B4',
}
this.appendChild(title);
let restartBtn = new Button();
restartBtn.text = '重新开始';
restartBtn.style = {
width: 90,
height: 40,
backgroundColor: '#4A90E2',
borderRadius: 4,
margin: 20,
color: '#FFFFFF',
fontSize: 16,
}
restartBtn.addEventListener('tap', () => {
newgame();
})
this.appendChild(restartBtn);
let scoreLayout = new View();
scoreLayout.style = {
flexDirection: 'row',
marginBottom: 14,
}
let scoreLabel = new Text();
scoreLabel.text = '分数:';
scoreLabel.style = {
fontSize: 18,
}
let score = new Text();
score.text = '0';
score.style = {
fontSize: 34,
fontWeight: 'bold',
color: '#15D0B4',
}
scoreLayout.appendChild(scoreLabel);
scoreLayout.appendChild(score);
this.appendChild(scoreLayout);
globalMap['score'] = score;
let boxLayout = new View();
boxLayout.style = {
width: BOX_SIZE,
height: BOX_SIZE,
backgroundColor: '#bbada0',
borderRadius: 8,
}
globalMap['#grid-container'] = boxLayout;
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 4; j++) {
let cell = new View();
cell.style = {
position: 'absolute',
width: CELL_SIZE,
height: CELL_SIZE,
backgroundColor: '#ccc0b3',
borderRadius: 5,
};
globalMap['#grid-cell-' + i + '-' + j] = cell;
boxLayout.appendChild(cell);
}
}
this.appendChild(boxLayout);
}
}
function $(id) {
return globalMap[id];
}
var BOX_SIZE = 300;
var CELL_SIZE = 60;
var CELL_SPACE = (300 - 60 * 4) / 5;
var globalMap = {};
Hummer.render(new RootView());
newgame(); | the_stack |
import { Reader, Writer } from 'protobufjs/minimal';
import { Params, ValidatorOutstandingRewards, ValidatorAccumulatedCommission, ValidatorSlashEvent, DelegationDelegatorReward } from '../../../cosmos/distribution/v1beta1/distribution';
import { PageRequest, PageResponse } from '../../../cosmos/base/query/v1beta1/pagination';
import { DecCoin } from '../../../cosmos/base/v1beta1/coin';
export declare const protobufPackage = "cosmos.distribution.v1beta1";
/** QueryParamsRequest is the request type for the Query/Params RPC method. */
export interface QueryParamsRequest {
}
/** QueryParamsResponse is the response type for the Query/Params RPC method. */
export interface QueryParamsResponse {
/** params defines the parameters of the module. */
params: Params | undefined;
}
/**
* QueryValidatorOutstandingRewardsRequest is the request type for the
* Query/ValidatorOutstandingRewards RPC method.
*/
export interface QueryValidatorOutstandingRewardsRequest {
/** validator_address defines the validator address to query for. */
validatorAddress: string;
}
/**
* QueryValidatorOutstandingRewardsResponse is the response type for the
* Query/ValidatorOutstandingRewards RPC method.
*/
export interface QueryValidatorOutstandingRewardsResponse {
rewards: ValidatorOutstandingRewards | undefined;
}
/**
* QueryValidatorCommissionRequest is the request type for the
* Query/ValidatorCommission RPC method
*/
export interface QueryValidatorCommissionRequest {
/** validator_address defines the validator address to query for. */
validatorAddress: string;
}
/**
* QueryValidatorCommissionResponse is the response type for the
* Query/ValidatorCommission RPC method
*/
export interface QueryValidatorCommissionResponse {
/** commission defines the commision the validator received. */
commission: ValidatorAccumulatedCommission | undefined;
}
/**
* QueryValidatorSlashesRequest is the request type for the
* Query/ValidatorSlashes RPC method
*/
export interface QueryValidatorSlashesRequest {
/** validator_address defines the validator address to query for. */
validatorAddress: string;
/** starting_height defines the optional starting height to query the slashes. */
startingHeight: number;
/** starting_height defines the optional ending height to query the slashes. */
endingHeight: number;
/** pagination defines an optional pagination for the request. */
pagination: PageRequest | undefined;
}
/**
* QueryValidatorSlashesResponse is the response type for the
* Query/ValidatorSlashes RPC method.
*/
export interface QueryValidatorSlashesResponse {
/** slashes defines the slashes the validator received. */
slashes: ValidatorSlashEvent[];
/** pagination defines the pagination in the response. */
pagination: PageResponse | undefined;
}
/**
* QueryDelegationRewardsRequest is the request type for the
* Query/DelegationRewards RPC method.
*/
export interface QueryDelegationRewardsRequest {
/** delegator_address defines the delegator address to query for. */
delegatorAddress: string;
/** validator_address defines the validator address to query for. */
validatorAddress: string;
}
/**
* QueryDelegationRewardsResponse is the response type for the
* Query/DelegationRewards RPC method.
*/
export interface QueryDelegationRewardsResponse {
/** rewards defines the rewards accrued by a delegation. */
rewards: DecCoin[];
}
/**
* QueryDelegationTotalRewardsRequest is the request type for the
* Query/DelegationTotalRewards RPC method.
*/
export interface QueryDelegationTotalRewardsRequest {
/** delegator_address defines the delegator address to query for. */
delegatorAddress: string;
}
/**
* QueryDelegationTotalRewardsResponse is the response type for the
* Query/DelegationTotalRewards RPC method.
*/
export interface QueryDelegationTotalRewardsResponse {
/** rewards defines all the rewards accrued by a delegator. */
rewards: DelegationDelegatorReward[];
/** total defines the sum of all the rewards. */
total: DecCoin[];
}
/**
* QueryDelegatorValidatorsRequest is the request type for the
* Query/DelegatorValidators RPC method.
*/
export interface QueryDelegatorValidatorsRequest {
/** delegator_address defines the delegator address to query for. */
delegatorAddress: string;
}
/**
* QueryDelegatorValidatorsResponse is the response type for the
* Query/DelegatorValidators RPC method.
*/
export interface QueryDelegatorValidatorsResponse {
/** validators defines the validators a delegator is delegating for. */
validators: string[];
}
/**
* QueryDelegatorWithdrawAddressRequest is the request type for the
* Query/DelegatorWithdrawAddress RPC method.
*/
export interface QueryDelegatorWithdrawAddressRequest {
/** delegator_address defines the delegator address to query for. */
delegatorAddress: string;
}
/**
* QueryDelegatorWithdrawAddressResponse is the response type for the
* Query/DelegatorWithdrawAddress RPC method.
*/
export interface QueryDelegatorWithdrawAddressResponse {
/** withdraw_address defines the delegator address to query for. */
withdrawAddress: string;
}
/**
* QueryCommunityPoolRequest is the request type for the Query/CommunityPool RPC
* method.
*/
export interface QueryCommunityPoolRequest {
}
/**
* QueryCommunityPoolResponse is the response type for the Query/CommunityPool
* RPC method.
*/
export interface QueryCommunityPoolResponse {
/** pool defines community pool's coins. */
pool: DecCoin[];
}
export declare const QueryParamsRequest: {
encode(_: QueryParamsRequest, writer?: Writer): Writer;
decode(input: Reader | Uint8Array, length?: number): QueryParamsRequest;
fromJSON(_: any): QueryParamsRequest;
toJSON(_: QueryParamsRequest): unknown;
fromPartial(_: DeepPartial<QueryParamsRequest>): QueryParamsRequest;
};
export declare const QueryParamsResponse: {
encode(message: QueryParamsResponse, writer?: Writer): Writer;
decode(input: Reader | Uint8Array, length?: number): QueryParamsResponse;
fromJSON(object: any): QueryParamsResponse;
toJSON(message: QueryParamsResponse): unknown;
fromPartial(object: DeepPartial<QueryParamsResponse>): QueryParamsResponse;
};
export declare const QueryValidatorOutstandingRewardsRequest: {
encode(message: QueryValidatorOutstandingRewardsRequest, writer?: Writer): Writer;
decode(input: Reader | Uint8Array, length?: number): QueryValidatorOutstandingRewardsRequest;
fromJSON(object: any): QueryValidatorOutstandingRewardsRequest;
toJSON(message: QueryValidatorOutstandingRewardsRequest): unknown;
fromPartial(object: DeepPartial<QueryValidatorOutstandingRewardsRequest>): QueryValidatorOutstandingRewardsRequest;
};
export declare const QueryValidatorOutstandingRewardsResponse: {
encode(message: QueryValidatorOutstandingRewardsResponse, writer?: Writer): Writer;
decode(input: Reader | Uint8Array, length?: number): QueryValidatorOutstandingRewardsResponse;
fromJSON(object: any): QueryValidatorOutstandingRewardsResponse;
toJSON(message: QueryValidatorOutstandingRewardsResponse): unknown;
fromPartial(object: DeepPartial<QueryValidatorOutstandingRewardsResponse>): QueryValidatorOutstandingRewardsResponse;
};
export declare const QueryValidatorCommissionRequest: {
encode(message: QueryValidatorCommissionRequest, writer?: Writer): Writer;
decode(input: Reader | Uint8Array, length?: number): QueryValidatorCommissionRequest;
fromJSON(object: any): QueryValidatorCommissionRequest;
toJSON(message: QueryValidatorCommissionRequest): unknown;
fromPartial(object: DeepPartial<QueryValidatorCommissionRequest>): QueryValidatorCommissionRequest;
};
export declare const QueryValidatorCommissionResponse: {
encode(message: QueryValidatorCommissionResponse, writer?: Writer): Writer;
decode(input: Reader | Uint8Array, length?: number): QueryValidatorCommissionResponse;
fromJSON(object: any): QueryValidatorCommissionResponse;
toJSON(message: QueryValidatorCommissionResponse): unknown;
fromPartial(object: DeepPartial<QueryValidatorCommissionResponse>): QueryValidatorCommissionResponse;
};
export declare const QueryValidatorSlashesRequest: {
encode(message: QueryValidatorSlashesRequest, writer?: Writer): Writer;
decode(input: Reader | Uint8Array, length?: number): QueryValidatorSlashesRequest;
fromJSON(object: any): QueryValidatorSlashesRequest;
toJSON(message: QueryValidatorSlashesRequest): unknown;
fromPartial(object: DeepPartial<QueryValidatorSlashesRequest>): QueryValidatorSlashesRequest;
};
export declare const QueryValidatorSlashesResponse: {
encode(message: QueryValidatorSlashesResponse, writer?: Writer): Writer;
decode(input: Reader | Uint8Array, length?: number): QueryValidatorSlashesResponse;
fromJSON(object: any): QueryValidatorSlashesResponse;
toJSON(message: QueryValidatorSlashesResponse): unknown;
fromPartial(object: DeepPartial<QueryValidatorSlashesResponse>): QueryValidatorSlashesResponse;
};
export declare const QueryDelegationRewardsRequest: {
encode(message: QueryDelegationRewardsRequest, writer?: Writer): Writer;
decode(input: Reader | Uint8Array, length?: number): QueryDelegationRewardsRequest;
fromJSON(object: any): QueryDelegationRewardsRequest;
toJSON(message: QueryDelegationRewardsRequest): unknown;
fromPartial(object: DeepPartial<QueryDelegationRewardsRequest>): QueryDelegationRewardsRequest;
};
export declare const QueryDelegationRewardsResponse: {
encode(message: QueryDelegationRewardsResponse, writer?: Writer): Writer;
decode(input: Reader | Uint8Array, length?: number): QueryDelegationRewardsResponse;
fromJSON(object: any): QueryDelegationRewardsResponse;
toJSON(message: QueryDelegationRewardsResponse): unknown;
fromPartial(object: DeepPartial<QueryDelegationRewardsResponse>): QueryDelegationRewardsResponse;
};
export declare const QueryDelegationTotalRewardsRequest: {
encode(message: QueryDelegationTotalRewardsRequest, writer?: Writer): Writer;
decode(input: Reader | Uint8Array, length?: number): QueryDelegationTotalRewardsRequest;
fromJSON(object: any): QueryDelegationTotalRewardsRequest;
toJSON(message: QueryDelegationTotalRewardsRequest): unknown;
fromPartial(object: DeepPartial<QueryDelegationTotalRewardsRequest>): QueryDelegationTotalRewardsRequest;
};
export declare const QueryDelegationTotalRewardsResponse: {
encode(message: QueryDelegationTotalRewardsResponse, writer?: Writer): Writer;
decode(input: Reader | Uint8Array, length?: number): QueryDelegationTotalRewardsResponse;
fromJSON(object: any): QueryDelegationTotalRewardsResponse;
toJSON(message: QueryDelegationTotalRewardsResponse): unknown;
fromPartial(object: DeepPartial<QueryDelegationTotalRewardsResponse>): QueryDelegationTotalRewardsResponse;
};
export declare const QueryDelegatorValidatorsRequest: {
encode(message: QueryDelegatorValidatorsRequest, writer?: Writer): Writer;
decode(input: Reader | Uint8Array, length?: number): QueryDelegatorValidatorsRequest;
fromJSON(object: any): QueryDelegatorValidatorsRequest;
toJSON(message: QueryDelegatorValidatorsRequest): unknown;
fromPartial(object: DeepPartial<QueryDelegatorValidatorsRequest>): QueryDelegatorValidatorsRequest;
};
export declare const QueryDelegatorValidatorsResponse: {
encode(message: QueryDelegatorValidatorsResponse, writer?: Writer): Writer;
decode(input: Reader | Uint8Array, length?: number): QueryDelegatorValidatorsResponse;
fromJSON(object: any): QueryDelegatorValidatorsResponse;
toJSON(message: QueryDelegatorValidatorsResponse): unknown;
fromPartial(object: DeepPartial<QueryDelegatorValidatorsResponse>): QueryDelegatorValidatorsResponse;
};
export declare const QueryDelegatorWithdrawAddressRequest: {
encode(message: QueryDelegatorWithdrawAddressRequest, writer?: Writer): Writer;
decode(input: Reader | Uint8Array, length?: number): QueryDelegatorWithdrawAddressRequest;
fromJSON(object: any): QueryDelegatorWithdrawAddressRequest;
toJSON(message: QueryDelegatorWithdrawAddressRequest): unknown;
fromPartial(object: DeepPartial<QueryDelegatorWithdrawAddressRequest>): QueryDelegatorWithdrawAddressRequest;
};
export declare const QueryDelegatorWithdrawAddressResponse: {
encode(message: QueryDelegatorWithdrawAddressResponse, writer?: Writer): Writer;
decode(input: Reader | Uint8Array, length?: number): QueryDelegatorWithdrawAddressResponse;
fromJSON(object: any): QueryDelegatorWithdrawAddressResponse;
toJSON(message: QueryDelegatorWithdrawAddressResponse): unknown;
fromPartial(object: DeepPartial<QueryDelegatorWithdrawAddressResponse>): QueryDelegatorWithdrawAddressResponse;
};
export declare const QueryCommunityPoolRequest: {
encode(_: QueryCommunityPoolRequest, writer?: Writer): Writer;
decode(input: Reader | Uint8Array, length?: number): QueryCommunityPoolRequest;
fromJSON(_: any): QueryCommunityPoolRequest;
toJSON(_: QueryCommunityPoolRequest): unknown;
fromPartial(_: DeepPartial<QueryCommunityPoolRequest>): QueryCommunityPoolRequest;
};
export declare const QueryCommunityPoolResponse: {
encode(message: QueryCommunityPoolResponse, writer?: Writer): Writer;
decode(input: Reader | Uint8Array, length?: number): QueryCommunityPoolResponse;
fromJSON(object: any): QueryCommunityPoolResponse;
toJSON(message: QueryCommunityPoolResponse): unknown;
fromPartial(object: DeepPartial<QueryCommunityPoolResponse>): QueryCommunityPoolResponse;
};
/** Query defines the gRPC querier service for distribution module. */
export interface Query {
/** Params queries params of the distribution module. */
Params(request: QueryParamsRequest): Promise<QueryParamsResponse>;
/** ValidatorOutstandingRewards queries rewards of a validator address. */
ValidatorOutstandingRewards(request: QueryValidatorOutstandingRewardsRequest): Promise<QueryValidatorOutstandingRewardsResponse>;
/** ValidatorCommission queries accumulated commission for a validator. */
ValidatorCommission(request: QueryValidatorCommissionRequest): Promise<QueryValidatorCommissionResponse>;
/** ValidatorSlashes queries slash events of a validator. */
ValidatorSlashes(request: QueryValidatorSlashesRequest): Promise<QueryValidatorSlashesResponse>;
/** DelegationRewards queries the total rewards accrued by a delegation. */
DelegationRewards(request: QueryDelegationRewardsRequest): Promise<QueryDelegationRewardsResponse>;
/**
* DelegationTotalRewards queries the total rewards accrued by a each
* validator.
*/
DelegationTotalRewards(request: QueryDelegationTotalRewardsRequest): Promise<QueryDelegationTotalRewardsResponse>;
/** DelegatorValidators queries the validators of a delegator. */
DelegatorValidators(request: QueryDelegatorValidatorsRequest): Promise<QueryDelegatorValidatorsResponse>;
/** DelegatorWithdrawAddress queries withdraw address of a delegator. */
DelegatorWithdrawAddress(request: QueryDelegatorWithdrawAddressRequest): Promise<QueryDelegatorWithdrawAddressResponse>;
/** CommunityPool queries the community pool coins. */
CommunityPool(request: QueryCommunityPoolRequest): Promise<QueryCommunityPoolResponse>;
}
export declare class QueryClientImpl implements Query {
private readonly rpc;
constructor(rpc: Rpc);
Params(request: QueryParamsRequest): Promise<QueryParamsResponse>;
ValidatorOutstandingRewards(request: QueryValidatorOutstandingRewardsRequest): Promise<QueryValidatorOutstandingRewardsResponse>;
ValidatorCommission(request: QueryValidatorCommissionRequest): Promise<QueryValidatorCommissionResponse>;
ValidatorSlashes(request: QueryValidatorSlashesRequest): Promise<QueryValidatorSlashesResponse>;
DelegationRewards(request: QueryDelegationRewardsRequest): Promise<QueryDelegationRewardsResponse>;
DelegationTotalRewards(request: QueryDelegationTotalRewardsRequest): Promise<QueryDelegationTotalRewardsResponse>;
DelegatorValidators(request: QueryDelegatorValidatorsRequest): Promise<QueryDelegatorValidatorsResponse>;
DelegatorWithdrawAddress(request: QueryDelegatorWithdrawAddressRequest): Promise<QueryDelegatorWithdrawAddressResponse>;
CommunityPool(request: QueryCommunityPoolRequest): Promise<QueryCommunityPoolResponse>;
}
interface Rpc {
request(service: string, method: string, data: Uint8Array): Promise<Uint8Array>;
}
declare type Builtin = Date | Function | Uint8Array | string | number | undefined;
export declare type DeepPartial<T> = T extends Builtin ? T : T extends Array<infer U> ? Array<DeepPartial<U>> : T extends ReadonlyArray<infer U> ? ReadonlyArray<DeepPartial<U>> : T extends {} ? {
[K in keyof T]?: DeepPartial<T[K]>;
} : Partial<T>;
export {}; | the_stack |
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js";
import * as msRest from "@azure/ms-rest-js";
export { BaseResource, CloudError };
/**
* The result of the request or operation.
*/
export interface DeleteOperationResult {
/**
* The result of the operation or request.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly operationResult?: boolean;
}
/**
* Subnet first address, scope, and/or last address.
*/
export interface EndpointPropertiesSubnetsItem {
/**
* First address in the subnet.
*/
first?: string;
/**
* Last address in the subnet.
*/
last?: string;
/**
* Block size (number of leading bits in the subnet mask).
*/
scope?: number;
}
/**
* Custom header name and value.
*/
export interface EndpointPropertiesCustomHeadersItem {
/**
* Header name.
*/
name?: string;
/**
* Header value.
*/
value?: string;
}
/**
* Class which is a sparse representation of a Traffic Manager endpoint.
*/
export interface HeatMapEndpoint {
/**
* The ARM Resource ID of this Traffic Manager endpoint.
*/
resourceId?: string;
/**
* A number uniquely identifying this endpoint in query experiences.
*/
endpointId?: number;
}
/**
* Class representing a Traffic Manager HeatMap query experience properties.
*/
export interface QueryExperience {
/**
* The id of the endpoint from the 'endpoints' array which these queries were routed to.
*/
endpointId: number;
/**
* The number of queries originating from this location.
*/
queryCount: number;
/**
* The latency experienced by queries originating from this location.
*/
latency?: number;
}
/**
* Class representing a Traffic Manager HeatMap traffic flow properties.
*/
export interface TrafficFlow {
/**
* The IP address that this query experience originated from.
*/
sourceIp?: string;
/**
* The approximate latitude that these queries originated from.
*/
latitude?: number;
/**
* The approximate longitude that these queries originated from.
*/
longitude?: number;
/**
* The query experiences produced in this HeatMap calculation.
*/
queryExperiences?: QueryExperience[];
}
/**
* The core properties of ARM resources
*/
export interface Resource extends BaseResource {
/**
* Fully qualified resource Id for the resource. Ex -
* /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficManagerProfiles/{resourceName}
*/
id?: string;
/**
* The name of the resource
*/
name?: string;
/**
* The type of the resource. Ex- Microsoft.Network/trafficManagerProfiles.
*/
type?: string;
}
/**
* The resource model definition for a ARM proxy resource. It will have everything other than
* required location and tags
*/
export interface ProxyResource extends Resource {
}
/**
* Class representing a Traffic Manager HeatMap.
*/
export interface HeatMapModel extends ProxyResource {
/**
* The beginning of the time window for this HeatMap, inclusive.
*/
startTime?: Date;
/**
* The ending of the time window for this HeatMap, exclusive.
*/
endTime?: Date;
/**
* The endpoints used in this HeatMap calculation.
*/
endpoints?: HeatMapEndpoint[];
/**
* The traffic flows produced in this HeatMap calculation.
*/
trafficFlows?: TrafficFlow[];
}
/**
* Class representing Traffic Manager User Metrics.
*/
export interface UserMetricsModel extends ProxyResource {
/**
* The key returned by the User Metrics operation.
*/
key?: string;
}
/**
* Class representing a Traffic Manager endpoint.
*/
export interface Endpoint extends ProxyResource {
/**
* The Azure Resource URI of the of the endpoint. Not applicable to endpoints of type
* 'ExternalEndpoints'.
*/
targetResourceId?: string;
/**
* The fully-qualified DNS name or IP address of the endpoint. Traffic Manager returns this value
* in DNS responses to direct traffic to this endpoint.
*/
target?: string;
/**
* The status of the endpoint. If the endpoint is Enabled, it is probed for endpoint health and
* is included in the traffic routing method. Possible values include: 'Enabled', 'Disabled'
*/
endpointStatus?: EndpointStatus;
/**
* The weight of this endpoint when using the 'Weighted' traffic routing method. Possible values
* are from 1 to 1000.
*/
weight?: number;
/**
* The priority of this endpoint when using the 'Priority' traffic routing method. Possible
* values are from 1 to 1000, lower values represent higher priority. This is an optional
* parameter. If specified, it must be specified on all endpoints, and no two endpoints can
* share the same priority value.
*/
priority?: number;
/**
* Specifies the location of the external or nested endpoints when using the 'Performance'
* traffic routing method.
*/
endpointLocation?: string;
/**
* The monitoring status of the endpoint. Possible values include: 'CheckingEndpoint', 'Online',
* 'Degraded', 'Disabled', 'Inactive', 'Stopped'
*/
endpointMonitorStatus?: EndpointMonitorStatus;
/**
* The minimum number of endpoints that must be available in the child profile in order for the
* parent profile to be considered available. Only applicable to endpoint of type
* 'NestedEndpoints'.
*/
minChildEndpoints?: number;
/**
* The minimum number of IPv4 (DNS record type A) endpoints that must be available in the child
* profile in order for the parent profile to be considered available. Only applicable to
* endpoint of type 'NestedEndpoints'.
*/
minChildEndpointsIPv4?: number;
/**
* The minimum number of IPv6 (DNS record type AAAA) endpoints that must be available in the
* child profile in order for the parent profile to be considered available. Only applicable to
* endpoint of type 'NestedEndpoints'.
*/
minChildEndpointsIPv6?: number;
/**
* The list of countries/regions mapped to this endpoint when using the 'Geographic' traffic
* routing method. Please consult Traffic Manager Geographic documentation for a full list of
* accepted values.
*/
geoMapping?: string[];
/**
* The list of subnets, IP addresses, and/or address ranges mapped to this endpoint when using
* the 'Subnet' traffic routing method. An empty list will match all ranges not covered by other
* endpoints.
*/
subnets?: EndpointPropertiesSubnetsItem[];
/**
* List of custom headers.
*/
customHeaders?: EndpointPropertiesCustomHeadersItem[];
}
/**
* Parameters supplied to check Traffic Manager name operation.
*/
export interface CheckTrafficManagerRelativeDnsNameAvailabilityParameters {
/**
* The name of the resource.
*/
name?: string;
/**
* The type of the resource.
*/
type?: string;
}
/**
* Class containing DNS settings in a Traffic Manager profile.
*/
export interface DnsConfig {
/**
* The relative DNS name provided by this Traffic Manager profile. This value is combined with
* the DNS domain name used by Azure Traffic Manager to form the fully-qualified domain name
* (FQDN) of the profile.
*/
relativeName?: string;
/**
* The fully-qualified domain name (FQDN) of the Traffic Manager profile. This is formed from the
* concatenation of the RelativeName with the DNS domain used by Azure Traffic Manager.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly fqdn?: string;
/**
* The DNS Time-To-Live (TTL), in seconds. This informs the local DNS resolvers and DNS clients
* how long to cache DNS responses provided by this Traffic Manager profile.
*/
ttl?: number;
}
/**
* Custom header name and value.
*/
export interface MonitorConfigCustomHeadersItem {
/**
* Header name.
*/
name?: string;
/**
* Header value.
*/
value?: string;
}
/**
* Min and max value of a status code range.
*/
export interface MonitorConfigExpectedStatusCodeRangesItem {
/**
* Min status code.
*/
min?: number;
/**
* Max status code.
*/
max?: number;
}
/**
* Class containing endpoint monitoring settings in a Traffic Manager profile.
*/
export interface MonitorConfig {
/**
* The profile-level monitoring status of the Traffic Manager profile. Possible values include:
* 'CheckingEndpoints', 'Online', 'Degraded', 'Disabled', 'Inactive'
*/
profileMonitorStatus?: ProfileMonitorStatus;
/**
* The protocol (HTTP, HTTPS or TCP) used to probe for endpoint health. Possible values include:
* 'HTTP', 'HTTPS', 'TCP'
*/
protocol?: MonitorProtocol;
/**
* The TCP port used to probe for endpoint health.
*/
port?: number;
/**
* The path relative to the endpoint domain name used to probe for endpoint health.
*/
path?: string;
/**
* The monitor interval for endpoints in this profile. This is the interval at which Traffic
* Manager will check the health of each endpoint in this profile.
*/
intervalInSeconds?: number;
/**
* The monitor timeout for endpoints in this profile. This is the time that Traffic Manager
* allows endpoints in this profile to response to the health check.
*/
timeoutInSeconds?: number;
/**
* The number of consecutive failed health check that Traffic Manager tolerates before declaring
* an endpoint in this profile Degraded after the next failed health check.
*/
toleratedNumberOfFailures?: number;
/**
* List of custom headers.
*/
customHeaders?: MonitorConfigCustomHeadersItem[];
/**
* List of expected status code ranges.
*/
expectedStatusCodeRanges?: MonitorConfigExpectedStatusCodeRangesItem[];
}
/**
* The resource model definition for a ARM tracked top level resource
*/
export interface TrackedResource extends Resource {
/**
* Resource tags.
*/
tags?: { [propertyName: string]: string };
/**
* The Azure Region where the resource lives
*/
location?: string;
}
/**
* Class representing a Traffic Manager profile.
*/
export interface Profile extends TrackedResource {
/**
* The status of the Traffic Manager profile. Possible values include: 'Enabled', 'Disabled'
*/
profileStatus?: ProfileStatus;
/**
* The traffic routing method of the Traffic Manager profile. Possible values include:
* 'Performance', 'Priority', 'Weighted', 'Geographic', 'MultiValue', 'Subnet'
*/
trafficRoutingMethod?: TrafficRoutingMethod;
/**
* The DNS settings of the Traffic Manager profile.
*/
dnsConfig?: DnsConfig;
/**
* The endpoint monitoring settings of the Traffic Manager profile.
*/
monitorConfig?: MonitorConfig;
/**
* The list of endpoints in the Traffic Manager profile.
*/
endpoints?: Endpoint[];
/**
* Indicates whether Traffic View is 'Enabled' or 'Disabled' for the Traffic Manager profile.
* Null, indicates 'Disabled'. Enabling this feature will increase the cost of the Traffic Manage
* profile. Possible values include: 'Enabled', 'Disabled'
*/
trafficViewEnrollmentStatus?: TrafficViewEnrollmentStatus;
/**
* The list of allowed endpoint record types.
*/
allowedEndpointRecordTypes?: AllowedEndpointRecordType[];
/**
* Maximum number of endpoints to be returned for MultiValue routing type.
*/
maxReturn?: number;
}
/**
* Class representing a Traffic Manager Name Availability response.
*/
export interface TrafficManagerNameAvailability {
/**
* The relative name.
*/
name?: string;
/**
* Traffic Manager profile resource type.
*/
type?: string;
/**
* Describes whether the relative name is available or not.
*/
nameAvailable?: boolean;
/**
* The reason why the name is not available, when applicable.
*/
reason?: string;
/**
* Descriptive message that explains why the name is not available, when applicable.
*/
message?: string;
}
/**
* Class representing a region in the Geographic hierarchy used with the Geographic traffic routing
* method.
*/
export interface Region {
/**
* The code of the region
*/
code?: string;
/**
* The name of the region
*/
name?: string;
/**
* The list of Regions grouped under this Region in the Geographic Hierarchy.
*/
regions?: Region[];
}
/**
* Class representing the Geographic hierarchy used with the Geographic traffic routing method.
*/
export interface TrafficManagerGeographicHierarchy extends ProxyResource {
/**
* The region at the root of the hierarchy from all the regions in the hierarchy can be
* retrieved.
*/
geographicHierarchy?: Region;
}
/**
* Optional Parameters.
*/
export interface HeatMapGetOptionalParams extends msRest.RequestOptionsBase {
/**
* The top left latitude,longitude pair of the rectangular viewport to query for.
*/
topLeft?: number[];
/**
* The bottom right latitude,longitude pair of the rectangular viewport to query for.
*/
botRight?: number[];
}
/**
* An interface representing TrafficManagerManagementClientOptions.
*/
export interface TrafficManagerManagementClientOptions extends AzureServiceClientOptions {
baseUri?: string;
}
/**
* @interface
* The list Traffic Manager profiles operation response.
* @extends Array<Profile>
*/
export interface ProfileListResult extends Array<Profile> {
}
/**
* Defines values for EndpointStatus.
* Possible values include: 'Enabled', 'Disabled'
* @readonly
* @enum {string}
*/
export type EndpointStatus = 'Enabled' | 'Disabled';
/**
* Defines values for EndpointMonitorStatus.
* Possible values include: 'CheckingEndpoint', 'Online', 'Degraded', 'Disabled', 'Inactive',
* 'Stopped'
* @readonly
* @enum {string}
*/
export type EndpointMonitorStatus = 'CheckingEndpoint' | 'Online' | 'Degraded' | 'Disabled' | 'Inactive' | 'Stopped';
/**
* Defines values for ProfileMonitorStatus.
* Possible values include: 'CheckingEndpoints', 'Online', 'Degraded', 'Disabled', 'Inactive'
* @readonly
* @enum {string}
*/
export type ProfileMonitorStatus = 'CheckingEndpoints' | 'Online' | 'Degraded' | 'Disabled' | 'Inactive';
/**
* Defines values for MonitorProtocol.
* Possible values include: 'HTTP', 'HTTPS', 'TCP'
* @readonly
* @enum {string}
*/
export type MonitorProtocol = 'HTTP' | 'HTTPS' | 'TCP';
/**
* Defines values for ProfileStatus.
* Possible values include: 'Enabled', 'Disabled'
* @readonly
* @enum {string}
*/
export type ProfileStatus = 'Enabled' | 'Disabled';
/**
* Defines values for TrafficRoutingMethod.
* Possible values include: 'Performance', 'Priority', 'Weighted', 'Geographic', 'MultiValue',
* 'Subnet'
* @readonly
* @enum {string}
*/
export type TrafficRoutingMethod = 'Performance' | 'Priority' | 'Weighted' | 'Geographic' | 'MultiValue' | 'Subnet';
/**
* Defines values for TrafficViewEnrollmentStatus.
* Possible values include: 'Enabled', 'Disabled'
* @readonly
* @enum {string}
*/
export type TrafficViewEnrollmentStatus = 'Enabled' | 'Disabled';
/**
* Defines values for AllowedEndpointRecordType.
* Possible values include: 'DomainName', 'IPv4Address', 'IPv6Address', 'Any'
* @readonly
* @enum {string}
*/
export type AllowedEndpointRecordType = 'DomainName' | 'IPv4Address' | 'IPv6Address' | 'Any';
/**
* Contains response data for the update operation.
*/
export type EndpointsUpdateResponse = Endpoint & {
/**
* 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: Endpoint;
};
};
/**
* Contains response data for the get operation.
*/
export type EndpointsGetResponse = Endpoint & {
/**
* 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: Endpoint;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type EndpointsCreateOrUpdateResponse = Endpoint & {
/**
* 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: Endpoint;
};
};
/**
* Contains response data for the deleteMethod operation.
*/
export type EndpointsDeleteMethodResponse = DeleteOperationResult & {
/**
* 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: DeleteOperationResult;
};
};
/**
* Contains response data for the checkTrafficManagerRelativeDnsNameAvailability operation.
*/
export type ProfilesCheckTrafficManagerRelativeDnsNameAvailabilityResponse = TrafficManagerNameAvailability & {
/**
* 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: TrafficManagerNameAvailability;
};
};
/**
* Contains response data for the listByResourceGroup operation.
*/
export type ProfilesListByResourceGroupResponse = ProfileListResult & {
/**
* 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: ProfileListResult;
};
};
/**
* Contains response data for the listBySubscription operation.
*/
export type ProfilesListBySubscriptionResponse = ProfileListResult & {
/**
* 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: ProfileListResult;
};
};
/**
* Contains response data for the get operation.
*/
export type ProfilesGetResponse = Profile & {
/**
* 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: Profile;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type ProfilesCreateOrUpdateResponse = Profile & {
/**
* 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: Profile;
};
};
/**
* Contains response data for the deleteMethod operation.
*/
export type ProfilesDeleteMethodResponse = DeleteOperationResult & {
/**
* 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: DeleteOperationResult;
};
};
/**
* Contains response data for the update operation.
*/
export type ProfilesUpdateResponse = Profile & {
/**
* 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: Profile;
};
};
/**
* Contains response data for the getDefault operation.
*/
export type GeographicHierarchiesGetDefaultResponse = TrafficManagerGeographicHierarchy & {
/**
* 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: TrafficManagerGeographicHierarchy;
};
};
/**
* Contains response data for the get operation.
*/
export type HeatMapGetResponse = HeatMapModel & {
/**
* 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: HeatMapModel;
};
};
/**
* Contains response data for the get operation.
*/
export type TrafficManagerUserMetricsKeysGetResponse = UserMetricsModel & {
/**
* 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: UserMetricsModel;
};
};
/**
* Contains response data for the createOrUpdate operation.
*/
export type TrafficManagerUserMetricsKeysCreateOrUpdateResponse = UserMetricsModel & {
/**
* 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: UserMetricsModel;
};
};
/**
* Contains response data for the deleteMethod operation.
*/
export type TrafficManagerUserMetricsKeysDeleteMethodResponse = DeleteOperationResult & {
/**
* 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: DeleteOperationResult;
};
}; | the_stack |
import {protoManage} from "../proto/manage";
import i18n from '../base/i18n'
export module convert {
export function getColorByState(state: protoManage.State|undefined|null):string {
switch (state) {
case protoManage.State.StateNot:
return "color-state-main"
case protoManage.State.StateUnknow:
return "color-state-lose"
case protoManage.State.StateNormal:
return "color-state-success"
case protoManage.State.StateWarn:
return "color-state-warning"
case protoManage.State.StateError:
return "color-state-danger"
}
return "color-state-main"
}
export function getColorWithResourceName(state: protoManage.State|undefined|null):string {
switch (state) {
case protoManage.State.StateNormal:
return "success"
}
return "danger"
}
export function getColorWithResourceState(state: protoManage.State|undefined|null):string {
switch (state) {
case protoManage.State.StateNormal:
return "color-state-success"
}
return "color-state-danger"
}
export function getTableRowColorByState(state: protoManage.State|undefined|null):string {
switch (state) {
case protoManage.State.StateUnknow:
return "table-color-state-info"
case protoManage.State.StateNormal:
return "table-color-state-success"
case protoManage.State.StateWarn:
return "table-color-state-warning"
case protoManage.State.StateError:
return "table-color-state-danger"
}
return ""
}
export function getColorByManagerState(state: protoManage.State|undefined|null):string {
switch (state) {
case protoManage.State.StateNormal:
return "color-state-success"
}
return "color-state-lose"
}
export function getColorByLevel(level: protoManage.Level|undefined|null):string {
switch (level) {
case protoManage.Level.LevelPrimary:
return "color-state-main"
case protoManage.Level.LevelIntermediate:
return "color-state-success"
case protoManage.Level.LevelSenior:
return "color-state-warning"
case protoManage.Level.LevelSuper:
return "color-state-danger"
}
return "color-state-lose"
}
export function getNodeStateName(state: protoManage.State):string {
switch (state) {
case protoManage.State.StateNormal:
return i18n.global.t('node.state.normal')
case protoManage.State.StateWarn:
return i18n.global.t('node.state.warn')
case protoManage.State.StateError:
return i18n.global.t('node.state.error')
}
return i18n.global.t('node.state.unknown')
}
export function getStateViewType(level: protoManage.State|undefined|null):string {
switch (level) {
case protoManage.State.StateUnknow:
return "info"
case protoManage.State.StateNormal:
return "success"
case protoManage.State.StateWarn:
return "warning"
case protoManage.State.StateError:
return "danger"
}
return ""
}
export function getManagerLevelName(level: protoManage.Level|undefined|null):string {
switch (level) {
case protoManage.Level.LevelPrimary:
return i18n.global.t('manager.level.primary')
case protoManage.Level.LevelIntermediate:
return i18n.global.t('manager.level.intermediate')
case protoManage.Level.LevelSenior:
return i18n.global.t('manager.level.senior')
case protoManage.Level.LevelSuper:
return i18n.global.t('manager.level.super')
}
return i18n.global.t('manager.level.unknown')
}
export function getLevelViewType(level: protoManage.Level|undefined|null):string {
switch (level) {
case protoManage.Level.LevelPrimary:
return ""
case protoManage.Level.LevelIntermediate:
return "success"
case protoManage.Level.LevelSenior:
return "warning"
case protoManage.Level.LevelSuper:
return "danger"
}
return "info"
}
export function getNodeFuncCallStateName(state: protoManage.State|undefined|null):string {
switch (state) {
case protoManage.State.StateUnknow:
return i18n.global.t('nodeFuncCall.state.timeout')
case protoManage.State.StateNormal:
return i18n.global.t('nodeFuncCall.state.normal')
case protoManage.State.StateWarn:
return i18n.global.t('nodeFuncCall.state.warn')
case protoManage.State.StateError:
return i18n.global.t('nodeFuncCall.state.error')
}
return i18n.global.t('nodeFuncCall.state.unknown')
}
export function getNodeFuncCallStateIcon(state: protoManage.State|undefined|null):string {
switch (state) {
case protoManage.State.StateUnknow:
return "el-icon-remove"
case protoManage.State.StateNormal:
return "el-icon-success"
case protoManage.State.StateWarn:
return "el-icon-warning"
case protoManage.State.StateError:
return "el-icon-error"
}
return "el-icon-question"
}
export function getNodeFuncParameterTypeName():string {
return i18n.global.t('nodeFunc.parameterTypeName.form')
}
export function getNodeFuncReturnTypeName(type: protoManage.NodeFuncReturnType|undefined|null):string {
switch (type) {
case protoManage.NodeFuncReturnType.NotReturn:
return i18n.global.t('nodeFunc.returnTypeName.notReturn')
case protoManage.NodeFuncReturnType.Error:
return i18n.global.t('nodeFunc.returnTypeName.error')
case protoManage.NodeFuncReturnType.Text:
return i18n.global.t('nodeFunc.returnTypeName.text')
case protoManage.NodeFuncReturnType.Json:
return i18n.global.t('nodeFunc.returnTypeName.json')
case protoManage.NodeFuncReturnType.Link:
return i18n.global.t('nodeFunc.returnTypeName.link')
case protoManage.NodeFuncReturnType.Image:
return i18n.global.t('nodeFunc.returnTypeName.image')
case protoManage.NodeFuncReturnType.Media:
return i18n.global.t('nodeFunc.returnTypeName.media')
case protoManage.NodeFuncReturnType.File:
return i18n.global.t('nodeFunc.returnTypeName.file')
case protoManage.NodeFuncReturnType.Table:
return i18n.global.t('nodeFunc.returnTypeName.table')
case protoManage.NodeFuncReturnType.Charts:
return i18n.global.t('nodeFunc.returnTypeName.charts')
}
return i18n.global.t('nodeFunc.returnTypeName.unknown')
}
export function renderSize(fileSize:number):string{
if(null==fileSize){
return "0 Bytes";
}
let unitArr = ["B","KB","MB","GB","TB","PB","EB","ZB","YB"];
let index=0;
let srcSize = parseFloat(String(fileSize));
index=Math.floor(Math.log(srcSize)/Math.log(1024));
let size =srcSize/Math.pow(1024,index);
let v = size.toFixed(2);
return v+unitArr[index];
}
export function getNodeReportIntervalStr(interval: number):string {
if (interval <= 0) {
return i18n.global.t('time.manual')
}
let conf = [{max:1000, name:i18n.global.t('time.ms')}, {max:60, name:i18n.global.t('time.s')},
{max:60, name:i18n.global.t('time.min')}, {max:24, name:i18n.global.t('time.hour')},
{max:30, name:i18n.global.t('time.day')}]
let calc = function (index:number, val:number):string {
if (index >= conf.length){
return ""
}
let f = conf[index]
if (index == conf.length - 1){
return val + f.name
}
if (val >= f.max){
let c = parseInt(String(val / f.max))
let y = val % f.max
let ys = ""
if (y > 0) {
ys = y + f.name
}
return calc(index + 1, c) + ys
}
return val + f.name
}
return calc(0, interval) + "/"+i18n.global.t('time.once')
}
export function isGrayByState(state: protoManage.State):boolean {
return state < protoManage.State.StateNormal || state > protoManage.State.StateError
}
export function isGrayByLevel(state: protoManage.State):boolean {
return state < protoManage.State.StateUnknow || state > protoManage.State.StateError
}
export function uint8ArrayToString(data: Uint8Array):string {
let dataString = "";
for (let i = 0; i < data.length; i++) {
dataString += String.fromCharCode(data[i]);
}
return dataString
}
export function stringToUint8Array(str: string):Uint8Array {
let arr:Array<number> = [];
for (let i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
let tmpUint8Array = new Uint8Array(arr);
return tmpUint8Array
}
export function timeStampToFormatDate (timeStamp:number|undefined|null):string {
if (timeStamp == 0 || timeStamp==undefined){
return "0000-00-00 00:00:00"
}
function two(s:number){
return s<10?"0"+s:s;
}
let date = new Date(timeStamp)
let year = date.getFullYear();
let month = date.getMonth() + 1;
let day = date.getDate();
let hour = date.getHours();
let minute = date.getMinutes();
let second = date.getSeconds();
return year + "-" + two(month) + "-" + two(day) + " " + two(hour) + ":" + two(minute) + ":" + two(second);
}
export function dateStringToTimeStamp(dateStr:string):number {
return new Date(dateStr).getTime()
}
export function timeStampToDateString(timeStamp:number):string {
return new Date(timeStamp).toLocaleString()
}
export function dataToArray(data:any):any[] {
if (data == undefined) {
return data
}
return Array.isArray(data) ? data : [data]
}
export function dataToTimeArray(query:any):any[] {
let senderTimeArray = convert.dataToArray(query)
let protoSenderTime = new Array<protoManage.Time>()
if (senderTimeArray) {
for (let item of senderTimeArray) {
let senderTime = String(item).split("-")
let time = protoManage.Time.create({BeginTime: Number(senderTime[0]), EndTime: Number(senderTime[1])})
protoSenderTime.push(time)
}
}
return protoSenderTime
}
} | the_stack |
import { Dic, _, __, Utils } from "../helpers/utils";
import { strings } from '../model/strings';
import { Sidebar } from '../view/sidebar';
import { Tabs, RemovedTabInfo } from '../view/tabs';
import { WelcomeScene } from '../view/scene-welcome';
import { Doc, DocType } from '../model/doc';
import { Confirm } from '../view/confirm';
import { Connect, ConnectResponse } from '../view/connect';
import { Sheet } from './sheet';
import { PageType } from './page';
import { host, logger, notificationCenter, optionsController, telemetry } from '../main';
import { i18n } from '../model/i18n';
import { PBICloudDatasetOpenWebMessage, PBIDesktopReportOpenWebMessage, UnknownWebMessage, VpaxFileOpenWebMessage, WebMessageType } from '../model/message';
import { Notify } from './notifications';
import { NotificationSidebar } from '../view/notification-sidebar';
import { PBIDesktopReport } from '../model/pbi-report';
import { PBICloudDataset } from '../model/pbi-dataset';
import { ErrorAlert } from '../view/error-alert';
import { AppError } from '../model/exceptions';
import { DiagnosticPane } from '../view/diagnostic-pane';
import Split, { SplitObject } from "split.js";
import { DiagnosticLevelType } from './options';
export interface AppVersionInfo {
version: string
build?: string
downloadUrl?: string
changelogUrl?: string
}
export class AppVersion {
info: AppVersionInfo;
constructor(data: AppVersionInfo) {
this.info = data;
}
toString() {
return `${this.info.version}${this.info.build ? ` (${this.info.build})` : ""}`;
}
}
export class App {
sheets: Dic<Sheet> = {};
welcomeScene: WelcomeScene;
sidebar: Sidebar;
tabs: Tabs;
diagnosticPane: DiagnosticPane;
diagnosticSplit: SplitObject;
notificationSidebar: NotificationSidebar;
defaultConnectSelectedMenu: string;
currentVersion: AppVersion;
newVersion: AppVersion;
constructor(version: AppVersion) {
_(".root").insertAdjacentHTML("beforeend", `
<div id="main-pane"></div>
<div id="bottom-pane"></div>
<iframe name="downloader"></iframe>
`);
this.currentVersion = version;
let mainPane = _("#main-pane");
let sidebarItems: Dic<string> = {};
for(let type in PageType) {
sidebarItems[type] = i18n((<any>strings)[type]);
}
this.sidebar = new Sidebar("sidebar", mainPane, sidebarItems);
this.tabs = new Tabs("tabs", mainPane);
this.notificationSidebar = new NotificationSidebar("notification-sidebar", mainPane);
let bottomPane = _("#bottom-pane");
this.diagnosticPane = new DiagnosticPane("diagnostics", bottomPane, `Bravo for Power BI v${version.toString()}`);
this.updatePanels();
this.listen();
this.showWelcome();
this.checkForUpdates(true);
}
updatePanels() {
if (optionsController.options.diagnosticLevel != DiagnosticLevelType.None) {
if (!this.diagnosticSplit) {
this.diagnosticSplit = Split(["#main-pane", "#bottom-pane"], {
sizes: optionsController.options.customOptions.sizes.main,
minSize: [400, 0],
gutterSize: 6,
direction: "vertical",
cursor: "ns-resize",
onDragEnd: sizes => {
optionsController.update("customOptions.sizes.main", sizes);
}
});
} else {
this.diagnosticSplit.setSizes(optionsController.options.customOptions.sizes.main)
}
this.diagnosticPane.show();
} else {
if (this.diagnosticSplit) {
this.diagnosticSplit.destroy();
this.diagnosticSplit = null;
}
this.diagnosticPane.hide();
}
}
// Event listeners
listen() {
// Catch system keys
window.addEventListener("keydown", e => {
const keys = [
"Ctrl+s", //Save
"Ctrl+p", //Print
"Ctrl+r", "F5", //Reload
"Ctrl+f", "F3", //Find
"Alt+ArrowLeft", //Back
"Alt+ArrowRight", //Forward
];
keys.forEach(keyCombo => {
let combo = keyCombo.toLowerCase().split("+");
let ctrl = (combo.length > 1 && combo[0] == "ctrl");
let alt = (combo.length > 1 && combo[0] == "alt");
let shift = (combo.length > 1 && combo[0] == "shift");
let key = combo[combo.length - 1];
let hotkeyMatched = true;
if ((ctrl && !e.ctrlKey) || (alt && !e.altKey) || (shift && !e.shiftKey)) hotkeyMatched = false;
if (hotkeyMatched && key == e.key.toLowerCase()) {
e.preventDefault();
e.stopPropagation();
}
});
});
// Catch dropping external files
window.addEventListener('dragover', e => {
e.preventDefault();
});
window.addEventListener('drop', e => {
e.preventDefault();
if (e.dataTransfer.files.length) {
this.openFile(e.dataTransfer.files[0]);
}
});
// Catch links & pseudo links
document.addLiveEventListener("click", "span[href], a[href], button[href]", (e, element) => {
e.preventDefault();
const url = element.getAttribute("href");
const target = element.getAttribute("target");
if (target && target == "downloader") {
window.open(url, "downloader");
} else {
host.navigateTo(url);
telemetry.track("Link", { "Url": url});
}
});
// Catch expandable content
document.addLiveEventListener("click", ".expandable .expander", (e, element) => {
e.preventDefault();
let container = element.closest(".expandable");
if (!container.classList.contains("expanded")) {
element.innerText = element.dataset.less;
container.classList.add("expanded");
} else {
element.innerText = element.dataset.more;
container.classList.remove("expanded");
}
});
// Catch host messages
host.on(WebMessageType[WebMessageType.ReportOpen], (data: PBIDesktopReportOpenWebMessage) => {
this.openReport(data.report);
});
host.on(WebMessageType[WebMessageType.DatasetOpen], (data: PBICloudDatasetOpenWebMessage) => {
this.openDataset(data.dataset);
});
host.on(WebMessageType[WebMessageType.VpaxOpen], (data: VpaxFileOpenWebMessage) => {
this.openFile(new File(data.blob, data.name, { lastModified: data.lastModified }));
});
host.on(WebMessageType[WebMessageType.Unknown], (data: UnknownWebMessage) => {
let appError = AppError.InitFromResponseStatus(Utils.ResponseStatusCode.InternalError, `${data.exception ? data.exception : ""} ${data.message ? data.message : "" }` );
let alert = new ErrorAlert(appError, i18n(strings.unknownMessage));
alert.show();
try { logger.logError(appError); } catch(ignore) {}
});
// UI events
this.tabs.on("open", () => {
this.connect(this.defaultConnectSelectedMenu);
});
this.tabs.on("close", (data: RemovedTabInfo) => {
if (data.id in this.sheets) {
if (this.sheets[data.id].doc.isDirty) {
let dialog = new Confirm();
dialog.show(i18n(strings.confirmTabCloseMessage)).then((response: ConnectResponse) => {
if (response.action == "ok")
this.tabs.closeTab(data.element);
});
}else {
this.tabs.closeTab(data.element);
}
}
});
this.tabs.on("remove", (id: string) => {
this.removeSheet(id);
});
this.tabs.on("noTabs", () => {
this.showWelcome();
});
this.tabs.on("change", (id: string) => {
this.showSheet(id, <PageType>this.sidebar.currentItem);
});
this.sidebar.on("change", (id: string) => {
if (this.tabs.currentTab) {
this.showSheet(this.tabs.currentTab, <PageType>id);
}
});
this.diagnosticPane.on("close", ()=> {
this.updatePanels();
});
this.diagnosticPane.on("minimize", ()=> {
this.toggleDiagnostics(false);
});
optionsController.on("diagnosticLevel.change", () => {
this.updatePanels();
});
}
addSheet(id: string, doc: Doc) {
this.hideWelcome();
this.sidebar.disactivateAll();
let container = this.tabs.body;
let sheet = new Sheet(id, container, doc);
this.sheets[id] = sheet;
sheet.on("load", ()=>{
if (this.tabs.currentTab == id)
this.selectFirstSupportedPage(sheet);
});
sheet.on("sync", ()=>{
if (this.tabs.currentTab == id)
this.updateSidebarStatus(sheet);
this.tabs.updateTab(id, doc.name);
});
}
removeSheet(id: string) {
if (id in this.sheets) {
this.sheets[id].destroy();
delete this.sheets[id];
}
}
updateSidebarStatus(sheet: Sheet) {
for (let type in sheet.pages) {
let pageSupported = sheet.doc.featureSupported("Page", <PageType>type);
this.sidebar.toggleInactive(type, !pageSupported[0]);
}
}
selectFirstSupportedPage(sheet: Sheet) {
let page: PageType;
for (let type in sheet.pages) {
let pageSupported = sheet.doc.featureSupported("Page", <PageType>type);
if (pageSupported[0]) {
if (this.sidebar.currentItem == type || !page)
page = <PageType>type;
}
}
this.sidebar.select(page);
}
showSheet(id: string, page?: PageType) {
//Hide all other sheets
for (let _id in this.sheets) {
if (_id != id)
this.sheets[_id].hide();
}
let sheet = this.sheets[id];
this.updateSidebarStatus(sheet);
sheet.show();
sheet.showPage(page);
}
switchToDoc(docId: string) {
for (let id in this.sheets) {
if (this.sheets[id].doc.id == docId) {
this.tabs.changeTab(id);
return true;
}
}
return false;
}
showWelcome() {
if (!this.welcomeScene) {
this.welcomeScene = new WelcomeScene("welcome", this.tabs.body);
this.welcomeScene.on("quickAction", (selectedMenu: string) => {
this.connect(selectedMenu);
});
}
this.welcomeScene.show();
this.sidebar.resetInitialState();
telemetry.trackPage("Welcome");
}
hideWelcome() {
if (this.welcomeScene)
this.welcomeScene.hide();
this.sidebar.enableAll();
}
connect(selectedMenu: string) {
let openedDocs = [];
for (let id in this.sheets)
openedDocs.push(this.sheets[id].doc.id);
telemetry.trackPage("Connect");
let dialog = new Connect(openedDocs);
dialog.show(selectedMenu)
.then((response: ConnectResponse) => {
if (response.data) {
if (response.action == "ok" && response.data.doc) {
this.openDoc(response.data.doc);
} else {
telemetry.trackPreviousPage();
}
if (response.data.lastOpenedMenu)
this.defaultConnectSelectedMenu = response.data.lastOpenedMenu;
}
});
}
openFile(file: File) {
if (file.name.slice(-5) == ".vpax") {
this.openDoc(new Doc(file.name, DocType.vpax, file));
}
}
openReport(report: PBIDesktopReport) {
this.openDoc(new Doc(report.reportName, DocType.pbix, report));
}
openDataset(dataset: PBICloudDataset) {
this.openDoc(new Doc(dataset.name, DocType.dataset, dataset));
}
openDoc(doc: Doc) {
if (!this.switchToDoc(doc.id)) {
let id = Utils.DOM.uniqueId();
this.addSheet(id, doc);
this.tabs.addTab(id, doc);
}
}
toggleDiagnostics(toggle: boolean) {
const sizes = (toggle ? [70, 30] : [100, 0]);
if (toggle && optionsController.options.diagnosticLevel == DiagnosticLevelType.None)
optionsController.options.diagnosticLevel = DiagnosticLevelType.Basic;
optionsController.update("customOptions.sizes.main", sizes);
this.updatePanels();
}
checkForUpdates(automatic = false) {
if (automatic && !optionsController.options.updateCheckEnabled) return;
return host.getCurrentVersion(optionsController.options.updateChannel)
.then(data => {
let newVersion = null;
if (data.updateChannel == optionsController.options.updateChannel && data.isNewerVersion) {
newVersion = new AppVersion({
version: data.currentVersion,
downloadUrl: data.downloadUrl,
changelogUrl: data.changelogUrl
});
}
this.newVersion = newVersion;
if (automatic && newVersion) {
notificationCenter.add(new Notify(i18n(strings.updateMessage, { version: newVersion.info.version }), newVersion.info, `<span class="link" href="${newVersion.info.downloadUrl}" target="downloader">${i18n(strings.appUpdateDownload)}</span> <span class="link" href="${newVersion.info.changelogUrl}">${i18n(strings.appUpdateViewDetails)}</span>`, false, true));
}
return newVersion;
});
/*.catch(ignore => {
return null;
});*/
}
reload() {
document.location.reload();
}
} | the_stack |
* @module Elements
*/
import { Id64String } from "@itwin/core-bentley";
import {
CalloutProps, DefinitionElementProps, ElementProps, GeometricElement2dProps, GeometricElement3dProps, GeometricModel3dProps, IModel,
InformationPartitionElementProps, ModelProps, PhysicalElementProps, PhysicalTypeProps, TypeDefinitionElementProps, ViewAttachmentLabelProps,
} from "@itwin/core-common";
import {
Document, GraphicalElement2d, GraphicalElement3d, GraphicalPartition3d, GraphicalType2d, GroupInformationElement, GroupInformationPartition,
PhysicalElement, PhysicalType, SpatialLocationElement,
} from "../Element";
import { IModelDb } from "../IModelDb";
import { PhysicalMaterial } from "../Material";
import { GraphicalModel3d, GroupInformationModel } from "../Model";
import { SubjectOwnsPartitionElements } from "../NavigationRelationship";
/** A graphical detailing symbol that is placed on a [[Drawing]] or [[Sheet]].
* @public
*/
export abstract class DetailingSymbol extends GraphicalElement2d {
/** @internal */
public static override get className(): string { return "DetailingSymbol"; }
public constructor(props: GeometricElement2dProps, iModel: IModelDb) {
super(props, iModel);
}
}
/** A graphical DetailingSymbol that contains title text.
* @public
*/
export class TitleText extends DetailingSymbol {
/** @internal */
public static override get className(): string { return "TitleText"; }
public constructor(props: GeometricElement2dProps, iModel: IModelDb) {
super(props, iModel);
}
}
/** A graphical DetailingSymbol that contains a view attachment label.
* @public
*/
export class ViewAttachmentLabel extends DetailingSymbol implements ViewAttachmentLabelProps {
/** @internal */
public static override get className(): string { return "ViewAttachmentLabel"; }
public constructor(props: ViewAttachmentLabelProps, iModel: IModelDb) {
super(props, iModel);
}
}
/** A graphical DetailingSymbol that calls out a reference to another drawing.
* @public
*/
export abstract class Callout extends DetailingSymbol implements CalloutProps {
/** @internal */
public static override get className(): string { return "Callout"; }
public constructor(props: CalloutProps, iModel: IModelDb) {
super(props, iModel);
}
}
/** A graphical Callout that references a section drawing.
* @public
*/
export class SectionCallout extends Callout {
/** @internal */
public static override get className(): string { return "SectionCallout"; }
public constructor(props: CalloutProps, iModel: IModelDb) {
super(props, iModel);
}
}
/** A graphical Callout that references an elevation drawing.
* @public
*/
export class ElevationCallout extends Callout {
/** @internal */
public static override get className(): string { return "ElevationCallout"; }
public constructor(props: CalloutProps, iModel: IModelDb) {
super(props, iModel);
}
}
/** A graphical Callout that references a plan drawing.
* @public
*/
export class PlanCallout extends Callout {
/** @internal */
public static override get className(): string { return "PlanCallout"; }
public constructor(props: CalloutProps, iModel: IModelDb) {
super(props, iModel);
}
}
/** A graphical Callout that references a detail drawing.
* @public
*/
export class DetailCallout extends Callout {
/** @internal */
public static override get className(): string { return "DetailCallout"; }
public constructor(props: CalloutProps, iModel: IModelDb) {
super(props, iModel);
}
}
/** A generic container for persisting BisCore:GraphicalElement3d instances.
* @public
*/
export class GenericGraphicalModel3d extends GraphicalModel3d {
/** @internal */
public static override get className(): string { return "GraphicalModel3d"; }
public constructor(props: GeometricModel3dProps, iModel: IModelDb) {
super(props, iModel);
}
/** Insert a BisCore:GraphicalPartition3d and a Generic:GraphicalModel3d that sub-models it.
* @param iModelDb Insert into this iModel
* @param parentSubjectId The GraphicalPartition3d will be inserted as a child of this Subject element.
* @param name The name of the GraphicalPartition3d that the new Generic:GraphicalModel3d will sub-model.
* @param isPlanProjection Optional value (default is false) that indicates if the contents of this model are expected to be in an XY plane.
* @returns The Id of the newly inserted GraphicalPartition3d and GraphicalModel3d (same value).
* @throws [[IModelError]] if there is an insert problem.
*/
public static insert(iModelDb: IModelDb, parentSubjectId: Id64String, name: string, isPlanProjection?: boolean): Id64String {
const partitionProps: InformationPartitionElementProps = {
classFullName: GraphicalPartition3d.classFullName,
model: IModel.repositoryModelId,
parent: new SubjectOwnsPartitionElements(parentSubjectId),
code: GraphicalPartition3d.createCode(iModelDb, parentSubjectId, name),
};
const partitionId = iModelDb.elements.insertElement(partitionProps);
const modelProps: GeometricModel3dProps = {
classFullName: this.classFullName,
modeledElement: { id: partitionId },
isPlanProjection,
};
return iModelDb.models.insertModel(modelProps);
}
}
/** The Generic:Graphic3d class is used when 3D graphics cannot be further classified.
* @note More-specific BisCore:GraphicalElement3d subclasses should be used wherever possible.
* @public
*/
export class Graphic3d extends GraphicalElement3d {
/** @internal */
public static override get className(): string { return "Graphic3d"; }
public constructor(props: GeometricElement3dProps, iModel: IModelDb) {
super(props, iModel);
}
}
/** The Generic:PhysicalObject class is used when physical elements cannot be further classified.
* @note More-specific BisCore:PhysicalElement subclasses should be used wherever possible.
* @public
*/
export class PhysicalObject extends PhysicalElement {
/** @internal */
public static override get className(): string { return "PhysicalObject"; }
public constructor(props: PhysicalElementProps, iModel: IModelDb) {
super(props, iModel);
}
}
/** The Generic:SpatialLocation class is used when spatial locations cannot be further classified.
* @note More-specific BisCore:SpatialLocationElement subclasses should be used wherever possible.
* @public
*/
export class SpatialLocation extends SpatialLocationElement {
/** @internal */
public static override get className(): string { return "SpatialLocation"; }
public constructor(props: GeometricElement3dProps, iModel: IModelDb) {
super(props, iModel);
}
}
/** A generic container for BisCore:GroupInformationElement instances.
* @public
*/
export class GroupModel extends GroupInformationModel {
/** @internal */
public static override get className(): string { return "GroupModel"; }
public constructor(props: ModelProps, iModel: IModelDb) {
super(props, iModel);
}
/** Insert a GroupInformationPartition and a GroupModel that breaks it down.
* @param iModelDb Insert into this iModel
* @param parentSubjectId The GroupInformationPartition will be inserted as a child of this Subject element.
* @param name The name of the GroupInformationPartition that the new GroupModel will break down.
* @returns The Id of the newly inserted GroupModel.
* @throws [[IModelError]] if there is an insert problem.
*/
public static insert(iModelDb: IModelDb, parentSubjectId: Id64String, name: string): Id64String {
const partitionProps: InformationPartitionElementProps = {
classFullName: GroupInformationPartition.classFullName,
model: IModel.repositoryModelId,
parent: new SubjectOwnsPartitionElements(parentSubjectId),
code: GroupInformationPartition.createCode(iModelDb, parentSubjectId, name),
};
const partitionId = iModelDb.elements.insertElement(partitionProps);
return iModelDb.models.insertModel({
classFullName: this.classFullName,
modeledElement: { id: partitionId },
});
}
}
/** The Generic:Group class is used when the group cannot be further classified.
* @public
*/
export class Group extends GroupInformationElement {
/** @internal */
public static override get className(): string { return "Group"; }
public constructor(props: ElementProps, iModel: IModelDb) {
super(props, iModel);
}
}
/** The Generic:Document class is used when a document cannot be further classified.
* @note More-specific BisCore:Document subclasses should be used wherever possible.
* @public
*/
export class GenericDocument extends Document {
/** @internal */
public static override get className(): string { return "Document"; }
public constructor(props: ElementProps, iModel: IModelDb) {
super(props, iModel);
}
}
/** The Generic:PhysicalMaterial class is used when the physical material cannot be further classified.
* @note More-specific BisCore:PhysicalMaterial subclasses should be used wherever possible.
* @public
*/
export class GenericPhysicalMaterial extends PhysicalMaterial {
/** @internal */
public static override get className(): string { return "PhysicalMaterial"; }
public constructor(props: DefinitionElementProps, iModel: IModelDb) {
super(props, iModel);
}
}
/** The Generic:PhysicalType class is used when the physical type cannot be further classified.
* @note More-specific BisCore:PhysicalType subclasses should be used wherever possible.
* @public
*/
export class GenericPhysicalType extends PhysicalType {
/** @internal */
public static override get className(): string { return "PhysicalType"; }
public constructor(props: PhysicalTypeProps, iModel: IModelDb) {
super(props, iModel);
}
}
/** The Generic:GraphicalType2d class is used when graphical types cannot be further classified.
* @note More-specific BisCore:GraphicalType2d subclasses should be used wherever possible.
* @public
*/
export class GenericGraphicalType2d extends GraphicalType2d {
/** @internal */
public static override get className(): string { return "GraphicalType2d"; }
public constructor(props: TypeDefinitionElementProps, iModel: IModelDb) {
super(props, iModel);
}
} | the_stack |
import * as URI from 'uri-js';
import ArrayMethods from './util/ArrayMethods';
import Did from './Did';
import DidState from '../../models/DidState';
import DocumentModel from './models/DocumentModel';
import Encoder from './Encoder';
import ErrorCode from './ErrorCode';
import InputValidator from './InputValidator';
import JsObject from './util/JsObject';
import PatchAction from './PatchAction';
import PublicKeyPurpose from './PublicKeyPurpose';
import SidetreeError from '../../../common/SidetreeError';
/**
* Class that handles the composition of operations into final external-facing document.
*/
export default class DocumentComposer {
private static resolutionObjectContextUrl = 'https://w3id.org/did-resolution/v1';
private static didDocumentContextUrl = 'https://www.w3.org/ns/did/v1';
/**
* Transforms the given DID state into a DID Document.
*/
public static transformToExternalDocument (didState: DidState, did: Did, published: boolean): any {
// If the DID is deactivated.
// Return required metadata and a document with only context and id if so
if (didState.nextRecoveryCommitmentHash === undefined) {
return DocumentComposer.createDeactivatedResolutionResult(did.shortForm, published);
}
const document = didState.document as DocumentModel;
// Put each public key in verificationMethod
// then populate the verification relationships by reference if a key has purposes,
const verificationRelationships: Map<string, string[]> = new Map();
const verificationMethod: any[] = [];
if (Array.isArray(document.publicKeys)) {
for (const publicKey of document.publicKeys) {
const id = '#' + publicKey.id;
const didDocumentPublicKey = {
id: id,
controller: did.isShortForm ? did.shortForm : did.longForm,
type: publicKey.type,
publicKeyJwk: publicKey.publicKeyJwk
};
const purposeSet: Set<string> = new Set(publicKey.purposes);
// add to verificationMethod no matter what,
// then look at purpose to decide what verification relationship to add to
verificationMethod.push(didDocumentPublicKey);
if (purposeSet.size > 0) {
const reference = didDocumentPublicKey.id;
for (const purpose of purposeSet) {
if (!verificationRelationships.has(purpose)) {
verificationRelationships.set(purpose, [reference]);
} else {
verificationRelationships.get(purpose)!.push(reference);
}
}
}
}
}
// Only update `service` if the array is present
let services;
if (Array.isArray(document.services)) {
services = [];
for (const service of document.services) {
const didDocumentService = {
id: '#' + service.id,
type: service.type,
serviceEndpoint: service.serviceEndpoint
};
services.push(didDocumentService);
}
}
const baseId = did.isShortForm ? did.shortForm : did.longForm;
const didDocument: any = {
id: baseId,
'@context': [DocumentComposer.didDocumentContextUrl, { '@base': baseId }],
service: services
};
if (verificationMethod.length !== 0) {
didDocument.verificationMethod = verificationMethod;
}
verificationRelationships.forEach((value, key) => {
didDocument[key] = value;
});
const didResolutionResult: any = {
'@context': DocumentComposer.resolutionObjectContextUrl,
didDocument: didDocument,
didDocumentMetadata: {
method: {
published,
recoveryCommitment: didState.nextRecoveryCommitmentHash,
updateCommitment: didState.nextUpdateCommitmentHash
}
}
};
if (did.isShortForm) {
didResolutionResult.didDocumentMetadata.canonicalId = did.shortForm;
} else {
didResolutionResult.didDocumentMetadata.equivalentId = [did.shortForm];
if (published) {
didResolutionResult.didDocumentMetadata.canonicalId = did.shortForm;
}
}
return didResolutionResult;
}
private static createDeactivatedResolutionResult (did: string, published: boolean) {
const didDocument = {
id: did,
'@context': [DocumentComposer.didDocumentContextUrl, { '@base': did }]
};
const didDocumentMetadata = {
method: {
published
},
canonicalId: did
};
return {
'@context': DocumentComposer.resolutionObjectContextUrl,
didDocument,
didDocumentMetadata
};
}
/**
* Validates the schema of the given full document state.
* @throws SidetreeError if given document patch fails validation.
*/
private static validateDocument (document: any) {
if (document === undefined) {
throw new SidetreeError(ErrorCode.DocumentComposerDocumentMissing);
}
const allowedProperties = new Set(['publicKeys', 'services']);
for (const property in document) {
if (!allowedProperties.has(property)) {
throw new SidetreeError(ErrorCode.DocumentComposerUnknownPropertyInDocument, `Unexpected property ${property} in document.`);
}
}
// Verify 'publicKeys' property if it exists.
if (('publicKeys' in document)) {
DocumentComposer.validatePublicKeys(document.publicKeys);
}
// Verify 'services' property if it exists.
if (('services' in document)) {
// Verify each entry in services array.
DocumentComposer.validateServices(document.services);
}
}
/**
* Validates the schema of the given update document patch.
* @throws SidetreeError if given document patch fails validation.
*/
public static validateDocumentPatches (patches: any) {
if (!Array.isArray(patches)) {
throw new SidetreeError(ErrorCode.DocumentComposerUpdateOperationDocumentPatchesNotArray);
}
for (const patch of patches) {
DocumentComposer.validatePatch(patch);
}
}
private static validatePatch (patch: any) {
const action = patch.action;
switch (action) {
case PatchAction.Replace:
DocumentComposer.validateDocument(patch.document);
break;
case PatchAction.AddPublicKeys:
DocumentComposer.validateAddPublicKeysPatch(patch);
break;
case PatchAction.RemovePublicKeys:
DocumentComposer.validateRemovePublicKeysPatch(patch);
break;
case PatchAction.AddServices:
DocumentComposer.validateAddServicesPatch(patch);
break;
case PatchAction.RemoveServices:
DocumentComposer.validateRemoveServicesPatch(patch);
break;
default:
throw new SidetreeError(ErrorCode.DocumentComposerPatchMissingOrUnknownAction);
}
}
private static validateAddPublicKeysPatch (patch: any) {
const patchProperties = Object.keys(patch);
if (patchProperties.length !== 2) {
throw new SidetreeError(ErrorCode.DocumentComposerPatchMissingOrUnknownProperty);
}
DocumentComposer.validatePublicKeys(patch.publicKeys);
}
private static validatePublicKeys (publicKeys: any) {
if (!Array.isArray(publicKeys)) {
throw new SidetreeError(ErrorCode.DocumentComposerPublicKeysNotArray);
}
const publicKeyIdSet: Set<string> = new Set();
for (const publicKey of publicKeys) {
const allowedProperties = new Set(['id', 'type', 'purposes', 'publicKeyJwk']);
for (const property in publicKey) {
if (!allowedProperties.has(property)) {
throw new SidetreeError(ErrorCode.DocumentComposerPublicKeyUnknownProperty, `Unexpected property, ${property}, in publicKey.`);
}
}
InputValidator.validateNonArrayObject(publicKey.publicKeyJwk, 'publicKeyJwk');
if (typeof publicKey.type !== 'string') {
throw new SidetreeError(ErrorCode.DocumentComposerPublicKeyTypeMissingOrIncorrectType);
}
DocumentComposer.validateId(publicKey.id);
// 'id' must be unique
if (publicKeyIdSet.has(publicKey.id)) {
throw new SidetreeError(ErrorCode.DocumentComposerPublicKeyIdDuplicated);
}
publicKeyIdSet.add(publicKey.id);
if ('purposes' in publicKey) {
if (!Array.isArray(publicKey.purposes)) {
throw new SidetreeError(ErrorCode.DocumentComposerPublicKeyPurposesIncorrectType);
}
if (ArrayMethods.hasDuplicates(publicKey.purposes)) {
throw new SidetreeError(ErrorCode.DocumentComposerPublicKeyPurposesDuplicated);
}
const validPurposes = new Set(Object.values(PublicKeyPurpose));
// Purpose must be one of the valid ones in PublicKeyPurpose
for (const purpose of publicKey.purposes) {
if (!validPurposes.has(purpose)) {
throw new SidetreeError(ErrorCode.DocumentComposerPublicKeyInvalidPurpose);
}
}
}
}
}
private static validateRemovePublicKeysPatch (patch: any) {
const allowedProperties = new Set(['action', 'ids']);
for (const property in patch) {
if (!allowedProperties.has(property)) {
throw new SidetreeError(ErrorCode.DocumentComposerUnknownPropertyInRemovePublicKeysPatch,
`Unexpected property ${property} in remove-public-keys patch.`);
}
}
if (!Array.isArray(patch.ids)) {
throw new SidetreeError(ErrorCode.DocumentComposerPatchPublicKeyIdsNotArray);
}
for (const id of patch.ids) {
DocumentComposer.validateId(id);
}
}
/**
* validate update patch for removing services
*/
private static validateRemoveServicesPatch (patch: any) {
const allowedProperties = new Set(['action', 'ids']);
for (const property in patch) {
if (!allowedProperties.has(property)) {
throw new SidetreeError(ErrorCode.DocumentComposerUnknownPropertyInRemoveServicesPatch, `Unexpected property ${property} in remove-services patch.`);
}
}
if (!Array.isArray(patch.ids)) {
throw new SidetreeError(ErrorCode.DocumentComposerPatchServiceIdsNotArray);
}
for (const id of patch.ids) {
DocumentComposer.validateId(id);
}
}
/**
* Validates update patch for adding services.
*/
private static validateAddServicesPatch (patch: any) {
const patchProperties = Object.keys(patch);
if (patchProperties.length !== 2) {
throw new SidetreeError(ErrorCode.DocumentComposerPatchMissingOrUnknownProperty);
}
if (!Array.isArray(patch.services)) {
throw new SidetreeError(ErrorCode.DocumentComposerPatchServicesNotArray);
}
DocumentComposer.validateServices(patch.services);
}
/**
* Validates and parses services.
* @param services The services to validate and parse.
*/
private static validateServices (services: any) {
if (!Array.isArray(services)) {
throw new SidetreeError(ErrorCode.DocumentComposerPatchServicesNotArray);
}
const serviceIdSet: Set<string> = new Set();
for (const service of services) {
const serviceProperties = Object.keys(service);
if (serviceProperties.length !== 3) { // type, id, and serviceEndpoint
throw new SidetreeError(ErrorCode.DocumentComposerServiceHasMissingOrUnknownProperty);
}
DocumentComposer.validateId(service.id);
if (serviceIdSet.has(service.id)) {
throw new SidetreeError(ErrorCode.DocumentComposerPatchServiceIdNotUnique, 'Service id has to be unique');
}
serviceIdSet.add(service.id);
if (typeof service.type !== 'string') {
throw new SidetreeError(ErrorCode.DocumentComposerPatchServiceTypeNotString);
}
if (service.type.length > 30) {
throw new SidetreeError(ErrorCode.DocumentComposerPatchServiceTypeTooLong);
}
// `serviceEndpoint` validations.
const serviceEndpoint = service.serviceEndpoint;
if (typeof serviceEndpoint === 'string') {
const uri = URI.parse(service.serviceEndpoint);
if (uri.error !== undefined) {
throw new SidetreeError(
ErrorCode.DocumentComposerPatchServiceEndpointStringNotValidUri,
`Service endpoint string '${serviceEndpoint}' is not a valid URI.`
);
}
} else if (typeof serviceEndpoint === 'object') {
// Allow `object` type only if it is not an array.
if (Array.isArray(serviceEndpoint)) {
throw new SidetreeError(ErrorCode.DocumentComposerPatchServiceEndpointCannotBeAnArray);
}
} else {
throw new SidetreeError(ErrorCode.DocumentComposerPatchServiceEndpointMustBeStringOrNonArrayObject);
}
}
}
private static validateId (id: any) {
if (typeof id !== 'string') {
throw new SidetreeError(ErrorCode.DocumentComposerIdNotString, `ID not string: ${JSON.stringify(id)} is of type '${typeof id}'`);
}
if (id.length > 50) {
throw new SidetreeError(ErrorCode.DocumentComposerIdTooLong);
}
if (!Encoder.isBase64UrlString(id)) {
throw new SidetreeError(ErrorCode.DocumentComposerIdNotUsingBase64UrlCharacterSet);
}
}
/**
* Applies the given patches in order to the given document.
* NOTE: Assumes no schema validation is needed, since validation should've already occurred at the time of the operation being parsed.
*/
public static applyPatches (document: any, patches: any[]) {
// Loop through and apply all patches.
for (const patch of patches) {
DocumentComposer.applyPatchToDidDocument(document, patch);
}
}
/**
* Applies the given patch to the given DID Document.
*/
private static applyPatchToDidDocument (document: DocumentModel, patch: any) {
if (patch.action === PatchAction.Replace) {
// In-place replacement of the document.
JsObject.clearObject(document);
Object.assign(document, patch.document);
} else if (patch.action === PatchAction.AddPublicKeys) {
DocumentComposer.addPublicKeys(document, patch);
} else if (patch.action === PatchAction.RemovePublicKeys) {
DocumentComposer.removePublicKeys(document, patch);
} else if (patch.action === PatchAction.AddServices) {
DocumentComposer.addServices(document, patch);
} else if (patch.action === PatchAction.RemoveServices) {
DocumentComposer.removeServices(document, patch);
} else {
throw new SidetreeError(ErrorCode.DocumentComposerApplyPatchUnknownAction, `Cannot apply invalid action: ${patch.action}`);
}
}
/**
* Adds public keys to document.
*/
private static addPublicKeys (document: DocumentModel, patch: any) {
const publicKeyMap = new Map((document.publicKeys || []).map(publicKey => [publicKey.id, publicKey]));
// Loop through all given public keys and add them.
// NOTE: If a key ID already exists, we will just replace the existing key.
// Not throwing error will minimize the need (thus risk) of reusing exposed update reveal value.
for (const publicKey of patch.publicKeys) {
publicKeyMap.set(publicKey.id, publicKey);
}
document.publicKeys = [...publicKeyMap.values()];
}
/**
* Removes public keys from document.
*/
private static removePublicKeys (document: DocumentModel, patch: any) {
if (document.publicKeys === undefined) {
return;
}
const idsOfKeysToRemove = new Set(patch.ids);
// Keep only keys that are not in the removal list.
document.publicKeys = document.publicKeys.filter(publicKey => !idsOfKeysToRemove.has(publicKey.id));
}
private static addServices (document: DocumentModel, patch: any) {
const services = patch.services;
if (document.services === undefined) {
// create a new array if `services` does not exist
document.services = [];
}
const idToIndexMapper = new Map();
// map all id and their index
for (const index in document.services) {
idToIndexMapper.set(document.services[index].id, index);
}
for (const service of services) {
if (idToIndexMapper.has(service.id)) {
const idx = idToIndexMapper.get(service.id);
document.services[idx] = service;
} else {
document.services.push(service);
}
}
}
private static removeServices (document: DocumentModel, patch: any) {
if (document.services === undefined) {
return;
}
const idsToRemove = new Set(patch.ids);
document.services = document.services.filter(service => !idsToRemove.has(service.id));
}
} | the_stack |
import '../../shared/gr-autocomplete/gr-autocomplete';
import {ServerInfo} from '../../../types/common';
import {
AutocompleteQuery,
AutocompleteSuggestion,
GrAutocomplete,
} from '../../shared/gr-autocomplete/gr-autocomplete';
import {getDocsBaseUrl} from '../../../utils/url-util';
import {MergeabilityComputationBehavior} from '../../../constants/constants';
import {getAppContext} from '../../../services/app-context';
import {sharedStyles} from '../../../styles/shared-styles';
import {LitElement, PropertyValues, html, css} from 'lit';
import {
customElement,
property,
state,
query as queryDec,
} from 'lit/decorators';
import {ShortcutController} from '../../lit/shortcut-controller';
import {query as queryUtil} from '../../../utils/common-util';
import {assertIsDefined} from '../../../utils/common-util';
import {Shortcut} from '../../../mixins/keyboard-shortcut-mixin/keyboard-shortcut-mixin';
// Possible static search options for auto complete, without negations.
const SEARCH_OPERATORS: ReadonlyArray<string> = [
'added:',
'after:',
'age:',
'age:1week', // Give an example age
'attention:',
'author:',
'before:',
'branch:',
'bug:',
'cc:',
'cc:self',
'change:',
'cherrypickof:',
'comment:',
'commentby:',
'commit:',
'committer:',
'deleted:',
'delta:',
'dir:',
'directory:',
'ext:',
'extension:',
'file:',
'footer:',
'from:',
'has:',
'has:attention',
'has:draft',
'has:edit',
'has:star',
'has:unresolved',
'hashtag:',
'inhashtag:',
'intopic:',
'is:',
'is:abandoned',
'is:attention',
'is:cherrypick',
'is:closed',
'is:merge',
'is:merged',
'is:open',
'is:owner',
'is:private',
'is:reviewed',
'is:reviewer',
'is:starred',
'is:submittable',
'is:watched',
'is:wip',
'label:',
'mergedafter:',
'mergedbefore:',
'message:',
'onlyexts:',
'onlyextensions:',
'owner:',
'ownerin:',
'parentof:',
'parentproject:',
'project:',
'projects:',
'query:',
'repo:',
'ref:',
'reviewedby:',
'reviewer:',
'reviewer:self',
'reviewerin:',
'rule:',
'size:',
'star:',
'status:',
'status:abandoned',
'status:closed',
'status:merged',
'status:open',
'status:reviewed',
'submissionid:',
'topic:',
'tr:',
];
// All of the ops, with corresponding negations.
const SEARCH_OPERATORS_WITH_NEGATIONS_SET: ReadonlySet<string> = new Set(
SEARCH_OPERATORS.concat(SEARCH_OPERATORS.map(op => `-${op}`))
);
const MAX_AUTOCOMPLETE_RESULTS = 10;
const TOKENIZE_REGEX = /(?:[^\s"]+|"[^"]*")+\s*/g;
export type SuggestionProvider = (
predicate: string,
expression: string
) => Promise<AutocompleteSuggestion[]>;
export interface SearchBarHandleSearchDetail {
inputVal: string;
}
@customElement('gr-search-bar')
export class GrSearchBar extends LitElement {
/**
* Fired when a search is committed
*
* @event handle-search
*/
@queryDec('#searchInput') protected searchInput?: GrAutocomplete;
@property({type: String})
value = '';
@property({type: Object})
projectSuggestions: SuggestionProvider = () => Promise.resolve([]);
@property({type: Object})
groupSuggestions: SuggestionProvider = () => Promise.resolve([]);
@property({type: Object})
accountSuggestions: SuggestionProvider = () => Promise.resolve([]);
@property({type: Object})
serverConfig?: ServerInfo;
@property({type: String})
label = '';
// private but used in test
@state() inputVal = '';
// private but used in test
@state() docBaseUrl: string | null = null;
@state() private query: AutocompleteQuery;
@state() private threshold = 1;
private searchOperators = new Set(SEARCH_OPERATORS_WITH_NEGATIONS_SET);
private readonly restApiService = getAppContext().restApiService;
private readonly shortcuts = new ShortcutController(this);
constructor() {
super();
this.query = (input: string) => this.getSearchSuggestions(input);
this.shortcuts.addAbstract(Shortcut.SEARCH, () => this.handleSearch());
}
static override get styles() {
return [
sharedStyles,
css`
form {
display: flex;
}
gr-autocomplete {
background-color: var(--view-background-color);
border-radius: var(--border-radius);
flex: 1;
outline: none;
}
`,
];
}
override render() {
return html`
<form>
<gr-autocomplete
id="searchInput"
.label=${this.label}
show-search-icon
.text=${this.inputVal}
.query=${this.query}
allow-non-suggested-values
multi
.threshold=${this.threshold}
tab-complete
verticalOffset="30"
@commit=${(e: Event) => {
this.handleInputCommit(e);
}}
@text-changed=${(e: CustomEvent) => {
this.handleSearchTextChanged(e);
}}
>
<a
class="help"
slot="suffix"
href=${this.computeHelpDocLink()}
target="_blank"
tabindex="-1"
>
<iron-icon
icon="gr-icons:help-outline"
title="read documentation"
></iron-icon>
</a>
</gr-autocomplete>
</form>
`;
}
override willUpdate(changedProperties: PropertyValues) {
if (changedProperties.has('serverConfig')) {
this.serverConfigChanged();
}
if (changedProperties.has('value')) {
this.valueChanged();
}
}
private serverConfigChanged() {
const mergeability =
this.serverConfig?.change?.mergeability_computation_behavior;
if (
mergeability ===
MergeabilityComputationBehavior.API_REF_UPDATED_AND_CHANGE_REINDEX ||
mergeability ===
MergeabilityComputationBehavior.REF_UPDATED_AND_CHANGE_REINDEX
) {
// add 'is:mergeable' to searchOperators
this.searchOperators.add('is:mergeable');
this.searchOperators.add('-is:mergeable');
} else {
this.searchOperators.delete('is:mergeable');
this.searchOperators.delete('-is:mergeable');
}
if (this.serverConfig) {
getDocsBaseUrl(this.serverConfig, this.restApiService).then(baseUrl => {
this.docBaseUrl = baseUrl;
});
}
}
private valueChanged() {
this.inputVal = this.value;
}
// private but used in test
computeHelpDocLink() {
// fallback to gerrit's official doc
let baseUrl =
this.docBaseUrl ||
'https://gerrit-review.googlesource.com/documentation/';
if (baseUrl.endsWith('/')) {
baseUrl = baseUrl.substring(0, baseUrl.length - 1);
}
return `${baseUrl}/user-search.html`;
}
private handleInputCommit(e: Event) {
this.preventDefaultAndNavigateToInputVal(e);
}
/**
* This function is called in a few different cases:
* - e.target is the search button
* - e.target is the gr-autocomplete widget (#searchInput)
* - e.target is the input element wrapped within #searchInput
*/
private preventDefaultAndNavigateToInputVal(e: Event) {
e.preventDefault();
const target = e.composedPath()[0] as HTMLElement;
// If the target is the #searchInput or has a sub-input component, that
// is what holds the focus as opposed to the target from the DOM event.
if (queryUtil(target, '#input')) {
queryUtil<HTMLElement>(target, '#input')!.blur();
} else {
target.blur();
}
if (!this.inputVal) return;
const trimmedInput = this.inputVal.trim();
if (trimmedInput) {
const predefinedOpOnlyQuery = [...this.searchOperators].some(
op => op.endsWith(':') && op === trimmedInput
);
if (predefinedOpOnlyQuery) {
return;
}
const detail: SearchBarHandleSearchDetail = {
inputVal: this.inputVal,
};
this.dispatchEvent(
new CustomEvent('handle-search', {
detail,
})
);
}
}
/**
* Determine what array of possible suggestions should be provided
* to getSearchSuggestions.
*
* @param input - The full search term, in lowercase.
* @return This returns a promise that resolves to an array of
* suggestion objects.
*/
private fetchSuggestions(input: string): Promise<AutocompleteSuggestion[]> {
// Split the input on colon to get a two part predicate/expression.
const splitInput = input.split(':');
const predicate = splitInput[0];
const expression = splitInput[1] || '';
// Switch on the predicate to determine what to autocomplete.
switch (predicate) {
case 'ownerin':
case 'reviewerin':
// Fetch groups.
return this.groupSuggestions(predicate, expression);
case 'parentproject':
case 'project':
case 'repo':
// Fetch projects.
return this.projectSuggestions(predicate, expression);
case 'attention':
case 'author':
case 'cc':
case 'commentby':
case 'committer':
case 'from':
case 'owner':
case 'reviewedby':
case 'reviewer':
// Fetch accounts.
return this.accountSuggestions(predicate, expression);
default:
return Promise.resolve(
[...this.searchOperators]
.filter(operator => operator.includes(input))
.map(operator => {
return {text: operator};
})
);
}
}
/**
* Get the sorted, pruned list of suggestions for the current search query.
*
* @param input - The complete search query.
* @return This returns a promise that resolves to an array of
* suggestions.
*
* private but used in test
*/
getSearchSuggestions(input: string): Promise<AutocompleteSuggestion[]> {
// Allow spaces within quoted terms.
const tokens = input.match(TOKENIZE_REGEX);
if (tokens === null) return Promise.resolve([]);
const trimmedInput = tokens[tokens.length - 1].toLowerCase();
return this.fetchSuggestions(trimmedInput).then(suggestions => {
if (!suggestions || !suggestions.length) {
return [];
}
return (
suggestions
// Prioritize results that start with the input.
.sort((a, b) => {
const aContains = a.text?.toLowerCase().indexOf(trimmedInput);
const bContains = b.text?.toLowerCase().indexOf(trimmedInput);
if (aContains === undefined && bContains === undefined) return 0;
if (aContains === undefined && bContains !== undefined) return 1;
if (aContains !== undefined && bContains === undefined) return -1;
if (aContains === bContains) {
return a.text!.localeCompare(b.text!);
}
if (aContains === -1) {
return 1;
}
if (bContains === -1) {
return -1;
}
return aContains! - bContains!;
})
// Return only the first {MAX_AUTOCOMPLETE_RESULTS} results.
.slice(0, MAX_AUTOCOMPLETE_RESULTS - 1)
// Map to an object to play nice with gr-autocomplete.
.map(({text, label}) => {
return {
name: text,
value: text,
label,
};
})
);
});
}
private handleSearch() {
assertIsDefined(this.searchInput, 'searchInput');
this.searchInput.focus();
this.searchInput.selectAll();
}
private handleSearchTextChanged(e: CustomEvent) {
this.inputVal = e.detail.value;
}
}
declare global {
interface HTMLElementTagNameMap {
'gr-search-bar': GrSearchBar;
}
} | the_stack |
import * as i from '@tf2autobot/tradeoffer-manager';
import SKU from '@tf2autobot/tf2-sku';
import Bot from '../../Bot';
import * as t from '../../../lib/tools/export';
import sendTradeDeclined from '../../../lib/DiscordWebhook/sendTradeDeclined';
import { KeyPrices } from '../../../classes/Pricelist';
export default function processDeclined(offer: i.TradeOffer, bot: Bot, isTradingKeys: boolean): void {
const opt = bot.options;
const declined: Declined = {
//nonTf2Items: [],
highNotSellingItems: [],
overstocked: [],
understocked: [],
invalidItems: [],
disabledItems: [],
dupedItems: [],
reasonDescription: '',
highValue: []
};
const offerReceived = offer.data('action') as i.Action;
const meta = offer.data('meta') as i.Meta;
const highValue = offer.data('highValue') as i.HighValueOutput; // can be both offer received and offer sent
const isWebhookEnabled = opt.discordWebhook.declinedTrade.enable && opt.discordWebhook.declinedTrade.url.length > 0;
if (offerReceived) {
switch (offerReceived.reason) {
case 'MANUAL':
declined.reasonDescription = offerReceived.reason + ': Manually declined by the owner.';
break;
case 'ESCROW':
declined.reasonDescription = offerReceived.reason + ': Partner has trade hold.';
break;
case 'BANNED':
declined.reasonDescription = offerReceived.reason + ': Partner is banned in one or more communities.';
break;
case '🟨_CONTAINS_NON_TF2':
declined.reasonDescription = offerReceived.reason + ': Trade includes non-TF2 items.';
//Maybe implement tags for them as well ?
break;
case 'GIFT_NO_NOTE':
declined.reasonDescription = offerReceived.reason + ': We dont accept gift without gift messages.';
break;
case 'CRIME_ATTEMPT':
declined.reasonDescription = offerReceived.reason + ': Tried to take our items for free.';
break;
case 'TAKING_ITEMS_WITH_INTENT_BUY':
declined.reasonDescription = offerReceived.reason + ': Tried to take/buy our item(s) with intent buy.';
break;
case 'GIVING_ITEMS_WITH_INTENT_SELL':
declined.reasonDescription = offerReceived.reason + ': Tried to give their item(s) with intent sell.';
break;
case 'OVERPAY':
declined.reasonDescription = offerReceived.reason + ': We are not accepting overpay.';
break;
case 'DUELING_NOT_5_USES':
declined.reasonDescription = offerReceived.reason + ': We only accept 5 use Dueling Mini-Games.';
break;
case 'NOISE_MAKER_NOT_25_USES':
declined.reasonDescription = offerReceived.reason + ': We only accept 25 use Noise Makers.';
break;
case 'HIGH_VALUE_ITEMS_NOT_SELLING':
declined.reasonDescription =
offerReceived.reason + ': Tried to take our high value items that we are not selling.';
//check our items to add tag
if (meta?.highValueName) declined.highNotSellingItems.push(...meta.highValueName);
break;
case 'ONLY_METAL':
declined.reasonDescription = offerReceived.reason + ': Offer contains only metal.';
break;
case 'NOT_TRADING_KEYS':
declined.reasonDescription = offerReceived.reason + ': We are not trading keys.';
break;
case 'NOT_SELLING_KEYS':
declined.reasonDescription = offerReceived.reason + ': We are not selling keys.';
break;
case 'NOT_BUYING_KEYS':
declined.reasonDescription = offerReceived.reason + ': We are not buying keys.';
break;
case '🟦_OVERSTOCKED':
declined.reasonDescription =
offerReceived.reason + ": Offer contains items that'll make us overstocked.";
break;
case '🟩_UNDERSTOCKED':
declined.reasonDescription =
offerReceived.reason + ": Offer contains items that'll make us understocked.";
break;
case '🟧_DISABLED_ITEMS':
declined.reasonDescription = offerReceived.reason + ': Offer contains disabled items.';
break;
case '🟨_INVALID_ITEMS':
declined.reasonDescription = offerReceived.reason + ': Offer contains invalid items.';
break;
case '🟫_DUPED_ITEMS':
declined.reasonDescription = offerReceived.reason + ': Offer contains duped items.';
break;
case '🟪_DUPE_CHECK_FAILED':
declined.reasonDescription =
offerReceived.reason +
`: Offer contains item(s) that is worth more than ${opt.offerReceived.duped.minKeys} keys, and I was unable ` +
`to determine if this item is duped or not. Please make sure your inventory is public, and your backpack.tf inventory ` +
`is refreshed with no fallback mode and try again later.`;
break;
case '🟥_INVALID_VALUE':
declined.reasonDescription = offerReceived.reason + ': We are paying more than them.';
break;
case 'COUNTER_INVALID_VALUE_FAILED':
declined.reasonDescription =
offerReceived.reason +
': We are paying more than them and we failed to counter the offer, or Steam might be down, or private inventory (failed to load their inventory).';
break;
case 'ONLY_INVALID_VALUE':
case 'ONLY_INVALID_ITEMS':
case 'ONLY_DISABLED_ITEMS':
case 'ONLY_OVERSTOCKED':
case 'ONLY_UNDERSTOCKED':
case 'ONLY_DUPED_ITEM':
case 'ONLY_DUPE_CHECK_FAILED':
//It was probably faster to make them by hand but :/
declined.reasonDescription =
offerReceived.reason +
': We are auto declining ' +
offerReceived.reason
.split('_')
.slice(1)
.join(' ')
.toLowerCase()
.replace(/(\b(?! ).)/g, char => char.toUpperCase());
break;
}
const checkedReasons = {};
meta?.uniqueReasons?.forEach(reason => {
if (checkedReasons[reason]) return;
checkedReasons[reason] = '.';
switch (reason) {
case '🟨_INVALID_ITEMS':
(meta.reasons.filter(el => el.reason === '🟨_INVALID_ITEMS') as i.InvalidItems[]).forEach(el => {
const name = t.testSKU(el.sku) ? bot.schema.getName(SKU.fromString(el.sku), false) : el.sku;
declined.invalidItems.push(`${isWebhookEnabled ? `_${name}_` : name} - ${el.price}`);
});
break;
case '🟧_DISABLED_ITEMS':
(meta.reasons.filter(el => el.reason == '🟧_DISABLED_ITEMS') as i.DisabledItems[]).forEach(el => {
declined.disabledItems.push(
isWebhookEnabled
? `_${bot.schema.getName(SKU.fromString(el.sku), false)}_`
: bot.schema.getName(SKU.fromString(el.sku), false)
);
});
break;
case '🟦_OVERSTOCKED':
(meta.reasons.filter(el => el.reason.includes('🟦_OVERSTOCKED')) as i.Overstocked[]).forEach(el => {
declined.overstocked.push(
`${
isWebhookEnabled
? `_${bot.schema.getName(SKU.fromString(el.sku), false)}_`
: bot.schema.getName(SKU.fromString(el.sku), false)
} (amount can buy was ${el.amountCanTrade}, offered ${el.amountOffered})`
);
});
break;
case '🟩_UNDERSTOCKED':
(meta.reasons.filter(el => el.reason.includes('🟩_UNDERSTOCKED')) as i.Understocked[]).forEach(
el => {
declined.understocked.push(
`${
isWebhookEnabled
? `_${bot.schema.getName(SKU.fromString(el.sku), false)}_`
: bot.schema.getName(SKU.fromString(el.sku), false)
} (amount can sell was ${el.amountCanTrade}, taken ${el.amountTaking})`
);
}
);
break;
case '🟫_DUPED_ITEMS':
(meta.reasons.filter(el => el.reason.includes('🟫_DUPED_ITEMS')) as i.DupedItems[]).forEach(el => {
declined.dupedItems.push(
isWebhookEnabled
? `_${bot.schema.getName(SKU.fromString(el.sku))}_`
: bot.schema.getName(SKU.fromString(el.sku))
);
});
break;
}
});
if (highValue && highValue['has'] === undefined) {
if (Object.keys(highValue.items.their).length > 0) {
// doing this to check if their side have any high value items, if so, push each name into accepted.highValue const.
const itemsName = t.getHighValueItems(highValue.items.their, bot, bot.paints, bot.strangeParts);
for (const name in itemsName) {
if (!Object.prototype.hasOwnProperty.call(itemsName, name)) {
continue;
}
declined.highValue.push(`${isWebhookEnabled ? `_${name}_` : name}` + itemsName[name]);
}
}
if (Object.keys(highValue.items.our).length > 0) {
// doing this to check if our side have any high value items, if so, push each name into accepted.highValue const.
const itemsName = t.getHighValueItems(highValue.items.our, bot, bot.paints, bot.strangeParts);
for (const name in itemsName) {
if (!Object.prototype.hasOwnProperty.call(itemsName, name)) {
continue;
}
declined.highValue.push(`${isWebhookEnabled ? `_${name}_` : name}` + itemsName[name]);
}
}
}
} else if (highValue && highValue['has'] === undefined) {
// This is for offer that bot created from commands
if (highValue.items && Object.keys(highValue.items.their).length > 0) {
const itemsName = t.getHighValueItems(highValue.items.their, bot, bot.paints, bot.strangeParts);
for (const name in itemsName) {
if (!Object.prototype.hasOwnProperty.call(itemsName, name)) {
continue;
}
declined.highValue.push(`${isWebhookEnabled ? `_${name}_` : name}` + itemsName[name]);
}
}
if (highValue.items && Object.keys(highValue.items.our).length > 0) {
const itemsName = t.getHighValueItems(highValue.items.our, bot, bot.paints, bot.strangeParts);
for (const name in itemsName) {
if (!Object.prototype.hasOwnProperty.call(itemsName, name)) {
continue;
}
declined.highValue.push(`${isWebhookEnabled ? `_${name}_` : name}` + itemsName[name]);
}
}
}
const isOfferSent = offer.data('action') === undefined;
const timeTakenToProcessOrConstruct = (offer.data('constructOfferTime') ||
offer.data('processOfferTime')) as number;
if (isWebhookEnabled) {
void sendTradeDeclined(offer, declined, bot, timeTakenToProcessOrConstruct, isTradingKeys, isOfferSent);
} else {
const itemsName = {
invalid: declined.invalidItems, // 🟨_INVALID_ITEMS
disabled: declined.disabledItems, // 🟧_DISABLED_ITEMS
overstock: declined.overstocked, // 🟦_OVERSTOCKED
understock: declined.understocked, // 🟩_UNDERSTOCKED
duped: declined.dupedItems, // '🟫_DUPED_ITEMS'
dupedFailed: [],
highValue: declined.highValue.concat(declined.highNotSellingItems)
};
const keyPrices = bot.pricelist.getKeyPrices;
const value = t.valueDiff(offer, keyPrices, isTradingKeys, opt.miscSettings.showOnlyMetal.enable);
const itemList = t.listItems(offer, bot, itemsName, true);
sendToAdmin(bot, offer, value, itemList, keyPrices, isOfferSent, timeTakenToProcessOrConstruct);
}
//else it's sent by us and they declined it so we don't care ?
}
export function sendToAdmin(
bot: Bot,
offer: i.TradeOffer,
value: t.ValueDiff,
itemList: string,
keyPrices: KeyPrices,
isOfferSent: boolean,
timeTakenToProcessOrConstruct: number
): void {
const slots = bot.tf2.backpackSlots;
const autokeys = bot.handler.autokeys;
const status = autokeys.getOverallStatus;
const offerMessage = offer.message;
const tSum = bot.options.tradeSummary;
const cT = tSum.customText;
const cTKeyRate = cT.keyRate.steamChat ? cT.keyRate.steamChat : '🔑 Key rate:';
const cTPureStock = cT.pureStock.steamChat ? cT.pureStock.steamChat : '💰 Pure stock:';
const cTTotalItems = cT.totalItems.steamChat ? cT.totalItems.steamChat : '🎒 Total items:';
const cTTimeTaken = cT.timeTaken.steamChat ? cT.timeTaken.steamChat : '⏱ Time taken:';
const customInitializer = bot.options.steamChat.customInitializer.declinedTradeSummary;
const isCustomPricer = bot.pricelist.isUseCustomPricer;
bot.messageAdmins(
'trade',
`${customInitializer ? customInitializer : '/me'} Trade #${
offer.id
} with ${offer.partner.getSteamID64()} was declined. ❌` +
t.summarizeToChat(offer, bot, 'declined', false, value, keyPrices, true, isOfferSent) +
(offerMessage.length !== 0 ? `\n\n💬 Offer message: "${offerMessage}"` : '') +
(itemList !== '-' ? `\n\nItem lists:\n${itemList}` : '') +
`\n\n${cTKeyRate} ${keyPrices.buy.toString()}/${keyPrices.sell.toString()}` +
` (${keyPrices.src === 'manual' ? 'manual' : isCustomPricer ? 'custom-pricer' : 'prices.tf'})` +
`${
autokeys.isEnabled
? ' | Autokeys: ' +
(autokeys.getActiveStatus
? '✅' +
(status.isBankingKeys ? ' (banking)' : status.isBuyingKeys ? ' (buying)' : ' (selling)')
: '🛑')
: ''
}` +
`\n${cTPureStock} ${t.pure.stock(bot).join(', ').toString()}` +
`\n${cTTotalItems} ${bot.inventoryManager.getInventory.getTotalItems}${
slots !== undefined ? `/${slots}` : ''
}` +
`\n${cTTimeTaken} ${t.convertTime(
null,
timeTakenToProcessOrConstruct,
undefined,
isOfferSent,
tSum.showDetailedTimeTaken,
tSum.showTimeTakenInMS
)}` +
`\n\nVersion ${process.env.BOT_VERSION}`,
[]
);
}
interface Declined {
//nonTf2Items: string[];
highNotSellingItems: string[];
overstocked: string[];
understocked: string[];
invalidItems: string[];
disabledItems: string[];
dupedItems: string[];
reasonDescription: string;
highValue: string[];
} | the_stack |
'use strict';
import * as assert from 'assert';
import * as sinon from 'sinon';
import { IRunTestContext, TestKind } from '../../src/types';
import { MarkdownString, Range, TestController, TestMessage, TestRunRequest, tests, workspace } from 'vscode';
import { JUnitRunnerResultAnalyzer } from '../../src/runners/junitRunner/JUnitRunnerResultAnalyzer';
import { generateTestItem } from './utils';
// tslint:disable: only-arrow-functions
// tslint:disable: no-object-literal-type-assertion
suite('JUnit Runner Analyzer Tests', () => {
let testController: TestController;
setup(() => {
testController = tests.createTestController('testController', 'Mock Test');
});
teardown(() => {
testController.dispose();
});
test("test JUnit 4 passed result", () => {
const testItem = generateTestItem(testController, 'junit@junit4.TestAnnotation#shouldPass', TestKind.JUnit);
const testRunRequest = new TestRunRequest([testItem], []);
const testRun = testController.createTestRun(testRunRequest);
const startedSpy = sinon.spy(testRun, 'started');
const passedSpy = sinon.spy(testRun, 'passed');
const testRunnerOutput = `%TESTC 1 v2
%TSTTREE1,shouldPass(junit4.TestAnnotation),false,1,false,-1,shouldPass(junit4.TestAnnotation),,
%TESTS 1,shouldPass(junit4.TestAnnotation)
%TESTE 1,shouldPass(junit4.TestAnnotation)
%RUNTIME15`;
const runnerContext: IRunTestContext = {
isDebug: false,
kind: TestKind.JUnit,
projectName: 'junit',
testItems: [testItem],
testRun: testRun,
workspaceFolder: workspace.workspaceFolders?.[0]!,
};
const analyzer = new JUnitRunnerResultAnalyzer(runnerContext);
analyzer.analyzeData(testRunnerOutput);
sinon.assert.calledWith(startedSpy, testItem);
sinon.assert.calledWith(passedSpy, testItem, sinon.match.number);
});
test("test JUnit 4 failed result", () => {
const testItem = generateTestItem(testController, 'junit@junit4.TestAnnotation#shouldFail', TestKind.JUnit);
const testRunRequest = new TestRunRequest([testItem], []);
const testRun = testController.createTestRun(testRunRequest);
const startedSpy = sinon.spy(testRun, 'started');
const failedSpy = sinon.spy(testRun, 'failed');
const testRunnerOutput = `%TESTC 1 v2
%TSTTREE1,shouldFail(junit4.TestAnnotation),false,1,false,-1,shouldFail(junit4.TestAnnotation),,
%TESTS 1,shouldFail(junit4.TestAnnotation)
%FAILED 1,shouldFail(junit4.TestAnnotation)
%TRACES
java.lang.AssertionError
at org.junit.Assert.fail(Assert.java:87)
at org.junit.Assert.assertTrue(Assert.java:42)
at org.junit.Assert.assertTrue(Assert.java:53)
at junit4.TestAnnotation.shouldFail(TestAnnotation.java:15)
%TRACEE
%TESTE 1,shouldFail(junit4.TestAnnotation)
%RUNTIME20;`;
const runnerContext: IRunTestContext = {
isDebug: false,
kind: TestKind.JUnit,
projectName: 'junit',
testItems: [testItem],
testRun: testRun,
workspaceFolder: workspace.workspaceFolders?.[0]!,
};
const analyzer = new JUnitRunnerResultAnalyzer(runnerContext);
analyzer.analyzeData(testRunnerOutput);
sinon.assert.calledWith(startedSpy, testItem);
sinon.assert.calledWith(failedSpy, testItem, sinon.match.any, sinon.match.number);
const testMessage = failedSpy.getCall(0).args[1] as TestMessage;
assert.ok((testMessage.message as MarkdownString).value.includes('junit4.TestAnnotation.shouldFail([TestAnnotation.java:15](command:_java.test.openStackTrace?%5B%22at%20junit4.TestAnnotation.shouldFail(TestAnnotation.java%3A15)%22%2C%22junit%22%5D))'));
});
test("test stacktrace should be simplified", () => {
const testItem = generateTestItem(testController, 'junit@App#name', TestKind.JUnit);
const testRunRequest = new TestRunRequest([testItem], []);
const testRun = testController.createTestRun(testRunRequest);
const failedSpy = sinon.spy(testRun, 'failed');
const testRunnerOutput = `%TESTC 1 v2
%TSTTREE1,name(App),false,1,false,-1,name(App),,
%TESTS 1,name(App)
%FAILED 1,name(App)
%TRACES
java.lang.AssertionError: expected:<1> but was:<2>
at org.junit.Assert.fail(Assert.java:89)
at org.junit.Assert.failNotEquals(Assert.java:835)
at org.junit.Assert.assertEquals(Assert.java:647)
at org.junit.Assert.assertEquals(Assert.java:633)
at App.name(App.java:10)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:40)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:529)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:756)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:452)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
%TRACEE
%TESTE 1,name(App)
%RUNTIME58`;
const runnerContext: IRunTestContext = {
isDebug: false,
kind: TestKind.JUnit,
projectName: 'junit',
testItems: [testItem],
testRun: testRun,
workspaceFolder: workspace.workspaceFolders?.[0]!,
};
const analyzer = new JUnitRunnerResultAnalyzer(runnerContext);
analyzer.analyzeData(testRunnerOutput);
sinon.assert.calledWith(failedSpy, testItem, sinon.match.any, sinon.match.number);
const testMessage = failedSpy.getCall(0).args[1] as TestMessage;
const stringLiteral = (testMessage.message as MarkdownString).value;
assert.ok(stringLiteral.split('<br/>').length === 3);
});
test("test message location should be inside the test case when it's covered", () => {
const testItem = generateTestItem(testController, 'junit@junit4.TestAnnotation#shouldFail', TestKind.JUnit, new Range(10, 0, 16, 0));
const testRunRequest = new TestRunRequest([testItem], []);
const testRun = testController.createTestRun(testRunRequest);
const startedSpy = sinon.spy(testRun, 'started');
const erroredSpy = sinon.spy(testRun, 'errored');
const testRunnerOutput = `%TESTC 1 v2
%TSTTREE1,shouldFail(junit4.TestAnnotation),false,1,false,-1,shouldFail(junit4.TestAnnotation),,
%TESTS 1,shouldFail(junit4.TestAnnotation)
%ERROR 1,shouldFail(junit4.TestAnnotation)
%TRACES
java.lang.RuntimeException
at junit4.TestAnnotation.fail2(TestAnnotation.java:23)
at junit4.TestAnnotation.fail(TestAnnotation.java:19)
at junit4.TestAnnotation.shouldFail(TestAnnotation.java:15)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
%TRACEE
%TESTE 1,shouldFail(junit4.TestAnnotation)
%RUNTIME16`;
const runnerContext: IRunTestContext = {
isDebug: false,
kind: TestKind.JUnit,
projectName: 'junit',
testItems: [testItem],
testRun: testRun,
workspaceFolder: workspace.workspaceFolders?.[0]!,
};
const analyzer = new JUnitRunnerResultAnalyzer(runnerContext);
analyzer.analyzeData(testRunnerOutput);
sinon.assert.calledWith(startedSpy, testItem);
sinon.assert.calledWith(erroredSpy, testItem, sinon.match.any);
const testMessage = erroredSpy.getCall(0).args[1] as TestMessage;
assert.strictEqual(testMessage.location?.range.start.line, 14);
});
test("test message location should at the test header when it's out of the test", () => {
const testItem = generateTestItem(testController, 'junit@junit4.TestAnnotation#shouldFail', TestKind.JUnit, new Range(8, 0, 10, 0));
const testRunRequest = new TestRunRequest([testItem], []);
const testRun = testController.createTestRun(testRunRequest);
const startedSpy = sinon.spy(testRun, 'started');
const erroredSpy = sinon.spy(testRun, 'errored');
const testRunnerOutput = `%TESTC 1 v2
%TSTTREE1,shouldFail(junit4.TestAnnotation),false,1,false,-1,shouldFail(junit4.TestAnnotation),,
%TESTS 1,shouldFail(junit4.TestAnnotation)
%ERROR 1,shouldFail(junit4.TestAnnotation)
%TRACES
java.lang.RuntimeException
at junit4.TestAnnotation.fail2(TestAnnotation.java:23)
at junit4.TestAnnotation.fail(TestAnnotation.java:19)
at junit4.TestAnnotation.shouldFail(TestAnnotation.java:15)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
%TRACEE
%TESTE 1,shouldFail(junit4.TestAnnotation)
%RUNTIME16`;
const runnerContext: IRunTestContext = {
isDebug: false,
kind: TestKind.JUnit,
projectName: 'junit',
testItems: [testItem],
testRun: testRun,
workspaceFolder: workspace.workspaceFolders?.[0]!,
};
const analyzer = new JUnitRunnerResultAnalyzer(runnerContext);
analyzer.analyzeData(testRunnerOutput);
sinon.assert.calledWith(startedSpy, testItem);
sinon.assert.calledWith(erroredSpy, testItem, sinon.match.any);
const testMessage = erroredSpy.getCall(0).args[1] as TestMessage;
assert.strictEqual(testMessage.location?.range.start.line, 8);
});
}); | the_stack |
* @module Settings
*/
import { AccessToken, BentleyError, BentleyStatus } from "@itwin/core-bentley";
import { Client, request, RequestOptions, Response } from "@bentley/itwin-client";
import { SettingsAdmin, SettingsMapResult, SettingsResult, SettingsStatus } from "./SettingsAdmin";
/** Client API for the iTwin Product Settings Service
*
* This class is not accessed directly from applications, they should use IModelApp.settingsAdmin.
*
* Requires the OIDC Scope `product-setting-service`
*
* @internal
*/
export class ConnectSettingsClient extends Client implements SettingsAdmin {
public static readonly apiVersion: string = "v1.0";
/** Creates an instance of ConnectSettingsClient.
*/
public constructor(public applicationId: string) {
super();
this.baseUrl = "https://api.bentley.com/productsettings";
}
protected override async setupOptionDefaults(options: RequestOptions): Promise<void> {
await super.setupOptionDefaults(options);
}
/** Gets the URL of the service.
* Attempts to discover and cache the URL from the URL Discovery Service. If not
* found uses the default URL provided by client implementations. Note that for consistency
* sake, the URL is stripped of any trailing "/"
* @param excludeApiVersion Pass true to optionally exclude the API version from the URL.
* @returns URL for the service
*/
public override async getUrl(excludeApiVersion?: boolean): Promise<string> {
if (this._url)
return this._url;
const url = await super.getUrl();
this._url = url;
if (!excludeApiVersion)
this._url = `${this._url}/${ConnectSettingsClient.apiVersion}`;
return this._url;
}
// gets the portion of the Url that encapsulates the type of setting requested.
private getUrlOptions(forRead: boolean, settingNamespace: string | undefined, settingName: string | undefined, userSpecific: boolean, applicationSpecific: boolean, shared: boolean, iTwinId?: string, iModelId?: string) {
// /Context/{ContextId}/Settings
// /Context/{ContextId}/SharedSettings
// /Context/{ContextId}/User/Settings
// /Context/{ContextId}/iModel/{iModelId}/Settings
// /Context/{ContextId}/iModel/{iModelId}/SharedSettings
// /Context/{ContextId}/iModel/{iModelId}/User/Settings
// /Application/{AppId}/Org/Settings
// /Application/{AppId}/User/Settings
// /Application/{AppId}/Context/{ContextId}/Settings
// /Application/{AppId}/Context/{ContextId}/SharedSettings
// /Application/{AppId}/Context/{ContextId}/User/Settings
// /Application/{AppId}/Context/{ContextId}/iModel/{iModelId}/Settings
// /Application/{AppId}/Context/{ContextId}/iModel/{iModelId}/SharedSettings
// /Application/{AppId}/Context/{ContextId}/iModel/{iModelId}/User/Settings
// The types of settings are:
// Application, iTwin, iModel, and User specific.
// Application, iTwin, and User Specific
// Application and User Specific
// iTwin, iModel, and User specific
// iTwin and User Specific
// Application Specific
let urlTerminator: string;
if (userSpecific)
urlTerminator = "/User/Setting";
else if (shared)
urlTerminator = "/SharedSetting";
else
urlTerminator = "/Setting";
// CHANGE:
// - If you supply a context, do not require a user
// - If no context, default to user
// Set up the settingsNamespace and settingName if appropriate.
// Note: In the read case, we use a query rather than the URL including the namespace and setting because the Settings service returns an empty array rather than a 404 status in that case.
// We are avoiding the 404 status because it gets logged in various places.
if (settingNamespace && settingName)
urlTerminator = forRead ? urlTerminator.concat(`?$filter=namespace+eq+'${settingNamespace}'+and+name+eq+'${settingName}'`) : urlTerminator.concat(`/${settingNamespace}/${settingName}`);
else if (settingNamespace)
urlTerminator = forRead ? urlTerminator.concat(`?$filter=namespace+eq+'${settingNamespace}'`) : urlTerminator.concat(`/${settingNamespace}`);
let urlOptions: string;
if (applicationSpecific) {
if (iTwinId) {
if (iModelId) {
urlOptions = `/Application/${this.applicationId}/Context/${iTwinId}/iModel/${iModelId}${urlTerminator}`;
} else {
urlOptions = `/Application/${this.applicationId}/Context/${iTwinId}${urlTerminator}`;
}
} else {
if (userSpecific)
urlOptions = `/Application/${this.applicationId}${urlTerminator}`;
else
urlOptions = `/Application/${this.applicationId}/Org/${urlTerminator}`;
}
} else {
if (iTwinId) {
if (iModelId) {
urlOptions = `/Context/${iTwinId}/iModel/${iModelId}${urlTerminator}`;
} else {
urlOptions = `/Context/${iTwinId}${urlTerminator}`;
}
} else {
// settings must depend on at least one of Application and iTwin
throw new BentleyError(BentleyStatus.ERROR, "Improperly specified setting");
}
}
return urlOptions;
}
/** Forms the response when there is an error.
* @internal
*/
public formErrorResponse(response: Response): SettingsResult {
if (400 === response.status) {
return new SettingsResult(SettingsStatus.ITwinInvalid, `Malformed URL or invalid iTwin ${JSON.stringify(response)}`);
} else if (401 === response.status) {
return new SettingsResult(SettingsStatus.AuthorizationError, `Authorization failure ${JSON.stringify(response)}`);
} else if (404 === response.status) {
return new SettingsResult(SettingsStatus.SettingNotFound);
} else {
return new SettingsResult(SettingsStatus.ServerError, `Status indicates server error ${JSON.stringify(response)}`);
}
}
// Private function that can retrieve either user specific settings or non-user-specific settings
private async saveAnySetting(accessToken: AccessToken, userSpecific: boolean, settings: any, settingNamespace: string, settingName: string, applicationSpecific: boolean, shared: boolean, iTwinId?: string, iModelId?: string): Promise<SettingsResult> {
const baseUrl: string = await this.getUrl();
const options: RequestOptions = {
method: "PUT",
headers: { authorization: accessToken },
body: {
properties: settings,
},
};
await this.setupOptionDefaults(options);
const urlOptions: string = this.getUrlOptions(false, settingNamespace, settingName, userSpecific, applicationSpecific, shared, iTwinId, iModelId);
const url: string = baseUrl.concat(urlOptions);
try {
await request(url, options);
return new SettingsResult(SettingsStatus.Success);
} catch (response: any) {
if ((response.status < 200) || (response.status > 299))
return this.formErrorResponse(response);
return new SettingsResult(SettingsStatus.UnknownError, `Unexpected Status ${JSON.stringify(response)}`);
}
}
// Retrieves previously saved user settings
private async getAnySetting(accessToken: AccessToken, userSpecific: boolean, settingNamespace: string, settingName: string, applicationSpecific: boolean, shared: boolean, iTwinId?: string, iModelId?: string): Promise<SettingsResult> {
const baseUrl: string = await this.getUrl();
const options: RequestOptions = {
method: "GET",
headers: { authorization: accessToken },
};
await this.setupOptionDefaults(options);
const urlOptions: string = this.getUrlOptions(true, settingNamespace, settingName, userSpecific, applicationSpecific, shared, iTwinId, iModelId);
const url: string = baseUrl.concat(urlOptions);
try {
const response = await request(url, options);
// should get back an array. It should have either one item or be empty.
if (Array.isArray(response.body) && (response.body.length > 0))
return new SettingsResult(SettingsStatus.Success, undefined, response.body[0].properties);
return new SettingsResult(SettingsStatus.SettingNotFound);
} catch (response: any) {
if ((response.status < 200) || (response.status > 299))
return this.formErrorResponse(response);
return new SettingsResult(SettingsStatus.UnknownError, `Unexpected Status ${JSON.stringify(response)}`);
}
}
// Retrieves all saved settings with the same namespace.
private async getAnySettingsByNamespace(accessToken: AccessToken, userSpecific: boolean, settingNamespace: string, applicationSpecific: boolean, shared: boolean, iTwinId?: string, iModelId?: string): Promise<SettingsMapResult> {
const baseUrl: string = await this.getUrl();
const options: RequestOptions = {
method: "GET",
headers: { authorization: accessToken },
};
await this.setupOptionDefaults(options);
const urlOptions: string = this.getUrlOptions(true, undefined, undefined, userSpecific, applicationSpecific, shared, iTwinId, iModelId);
let url: string = baseUrl.concat(urlOptions);
// now we want to append the query for the namespace.
const queryString = `?$filter=namespace+eq+'${settingNamespace}'`;
url = url.concat(queryString);
const settingsMap: Map<string, any> = new Map<string, any>();
while (true) {
try {
// attempt to get the settings
const response: Response = await request(url, options);
// body contains an array of settings.
for (const settingBody of response.body) {
settingsMap.set(settingBody.name, settingBody.properties);
}
// The absence of a continuation token indicates that there are no more settings to gather
// However, adding check anyway
if (undefined === response.header.continuationtoken || 0 === response.body.length)
break;
// Update the continuation token for the next iteration
options.headers.continuationtoken = response.header.continuationtoken;
} catch (errResponse: any) {
if ((errResponse.status < 200) || (errResponse.status > 299))
return this.formErrorResponse(errResponse);
else
return new SettingsResult(SettingsStatus.UnknownError, `Unexpected Status ${JSON.stringify(errResponse)}`);
}
}
return new SettingsMapResult(SettingsStatus.Success, undefined, settingsMap);
}
private async deleteAnySetting(accessToken: AccessToken, userSpecific: boolean, settingNamespace: string, settingName: string, applicationSpecific: boolean, shared: boolean, iTwinId?: string, iModelId?: string): Promise<SettingsResult> {
const baseUrl: string = await this.getUrl();
const options: RequestOptions = {
method: "DELETE",
headers: { authorization: accessToken },
};
await this.setupOptionDefaults(options);
const urlOptions: string = this.getUrlOptions(false, settingNamespace, settingName, userSpecific, applicationSpecific, shared, iTwinId, iModelId);
const url: string = baseUrl.concat(urlOptions);
try {
await request(url, options);
return new SettingsResult(SettingsStatus.Success);
} catch (response: any) {
if ((response.status < 200) || (response.status > 299))
return this.formErrorResponse(response);
else
return new SettingsResult(SettingsStatus.UnknownError, `Unexpected Status ${JSON.stringify(response)}`);
}
}
// app specific, no context, no shared, no user
public async saveUserSetting(accessToken: AccessToken, settings: any, settingNamespace: string, settingName: string, applicationSpecific: boolean, iTwinId?: string, iModelId?: string): Promise<SettingsResult> {
return this.saveAnySetting(accessToken, true, settings, settingNamespace, settingName, applicationSpecific, false, iTwinId, iModelId);
}
public async getUserSetting(accessToken: AccessToken, settingNamespace: string, settingName: string, applicationSpecific: boolean, iTwinId?: string, iModelId?: string): Promise<SettingsResult> {
return this.getAnySetting(accessToken, true, settingNamespace, settingName, applicationSpecific, false, iTwinId, iModelId);
}
public async deleteUserSetting(accessToken: AccessToken, settingNamespace: string, settingName: string, applicationSpecific: boolean, iTwinId?: string, iModelId?: string): Promise<SettingsResult> {
return this.deleteAnySetting(accessToken, true, settingNamespace, settingName, applicationSpecific, false, iTwinId, iModelId);
}
public async getUserSettingsByNamespace(accessToken: AccessToken, namespace: string, applicationSpecific: boolean, iTwinId?: string, iModelId?: string): Promise<SettingsMapResult> {
return this.getAnySettingsByNamespace(accessToken, true, namespace, applicationSpecific, false, iTwinId, iModelId);
}
public async saveSharedSetting(accessToken: AccessToken, settings: any, settingNamespace: string, settingName: string, applicationSpecific: boolean, iTwinId: string, iModelId?: string): Promise<SettingsResult> {
return this.saveAnySetting(accessToken, false, settings, settingNamespace, settingName, applicationSpecific, true, iTwinId, iModelId);
}
public async getSharedSetting(accessToken: AccessToken, settingNamespace: string, settingName: string, applicationSpecific: boolean, iTwinId: string, iModelId?: string): Promise<SettingsResult> {
return this.getAnySetting(accessToken, false, settingNamespace, settingName, applicationSpecific, true, iTwinId, iModelId);
}
public async deleteSharedSetting(accessToken: AccessToken, settingNamespace: string, settingName: string, applicationSpecific: boolean, iTwinId: string, iModelId?: string): Promise<SettingsResult> {
return this.deleteAnySetting(accessToken, false, settingNamespace, settingName, applicationSpecific, true, iTwinId, iModelId);
}
public async getSharedSettingsByNamespace(accessToken: AccessToken, namespace: string, applicationSpecific: boolean, iTwinId: string, iModelId?: string): Promise<SettingsMapResult> {
return this.getAnySettingsByNamespace(accessToken, false, namespace, applicationSpecific, true, iTwinId, iModelId);
}
public async saveSetting(accessToken: AccessToken, settings: any, settingNamespace: string, settingName: string, applicationSpecific: boolean, iTwinId?: string, iModelId?: string): Promise<SettingsResult> {
return this.saveAnySetting(accessToken, false, settings, settingNamespace, settingName, applicationSpecific, false, iTwinId, iModelId);
}
public async getSetting(accessToken: AccessToken, settingNamespace: string, settingName: string, applicationSpecific: boolean, iTwinId?: string, iModelId?: string): Promise<SettingsResult> {
return this.getAnySetting(accessToken, false, settingNamespace, settingName, applicationSpecific, false, iTwinId, iModelId);
}
public async deleteSetting(accessToken: AccessToken, settingNamespace: string, settingName: string, applicationSpecific: boolean, iTwinId?: string, iModelId?: string): Promise<SettingsResult> {
return this.deleteAnySetting(accessToken, false, settingNamespace, settingName, applicationSpecific, false, iTwinId, iModelId);
}
public async getSettingsByNamespace(accessToken: AccessToken, namespace: string, applicationSpecific: boolean, iTwinId?: string, iModelId?: string): Promise<SettingsMapResult> {
return this.getAnySettingsByNamespace(accessToken, false, namespace, applicationSpecific, false, iTwinId, iModelId);
}
} | the_stack |
import { createLogger } from '../../logger'
import { selectors as robotSelectors } from '../robot'
import { getConnectedRobot } from '../discovery'
import * as CustomLabware from '../custom-labware'
import * as SystemInfo from '../system-info'
import * as brActions from '../buildroot/constants'
import * as Sessions from '../sessions'
import * as Alerts from '../alerts'
import * as Constants from './constants'
import { sharedCalCommands } from '../sessions/common-calibration/constants'
import * as RobotAdmin from '../robot-admin'
import {
getProtocolAnalyticsData,
getRobotAnalyticsData,
getBuildrootAnalyticsData,
getAnalyticsPipetteCalibrationData,
getAnalyticsTipLengthCalibrationData,
getAnalyticsHealthCheckData,
getAnalyticsDeckCalibrationData,
getAnalyticsSessionExitDetails,
getSessionInstrumentAnalyticsData,
} from './selectors'
import type { State, Action } from '../types'
import type { AnalyticsEvent } from './types'
import type { Mount } from '../pipettes/types'
const log = createLogger(__filename)
const EVENT_APP_UPDATE_DISMISSED = 'appUpdateDismissed'
export function makeEvent(
action: Action,
state: State
): Promise<AnalyticsEvent | null> {
switch (action.type) {
case 'robot:CONNECT_RESPONSE': {
const robot = getConnectedRobot(state)
if (!robot) {
log.warn('No robot found for connect response')
return Promise.resolve(null)
}
const data = getRobotAnalyticsData(state)
return Promise.resolve({
name: 'robotConnect',
properties: {
...data,
success: !action.payload.error,
method: robot.local ? 'usb' : 'wifi',
error: (action.payload.error && action.payload.error.message) || '',
},
})
}
// TODO (ka, 2018-6-6): add file open type 'button' | 'drag-n-drop' (work required in action meta)
case 'protocol:UPLOAD': {
return getProtocolAnalyticsData(state).then(data => ({
name: 'protocolUploadRequest',
properties: {
...getRobotAnalyticsData(state),
...data,
},
}))
}
case 'robot:SESSION_RESPONSE':
case 'robot:SESSION_ERROR': {
// only fire event if we had a protocol upload in flight; we don't want
// to fire if user connects to robot with protocol already loaded
const { type: actionType, payload: actionPayload, meta } = action
if (!meta.freshUpload) return Promise.resolve(null)
return getProtocolAnalyticsData(state).then(data => ({
name: 'protocolUploadResponse',
properties: {
...getRobotAnalyticsData(state),
...data,
success: actionType === 'robot:SESSION_RESPONSE',
// @ts-expect-error even if we used the in operator, TS cant narrow error to anything more specific than 'unknown' https://github.com/microsoft/TypeScript/issues/25720
error: (actionPayload.error && actionPayload.error.message) || '',
},
}))
}
case 'robot:RUN': {
return getProtocolAnalyticsData(state).then(data => ({
name: 'runStart',
properties: {
...getRobotAnalyticsData(state),
...data,
},
}))
}
// TODO(mc, 2019-01-22): we only get this event if the user keeps their app
// open for the entire run. Fixing this is blocked until we can fix
// session.stop from triggering a run error
case 'robot:RUN_RESPONSE': {
const runTime = robotSelectors.getRunSeconds(state)
const success = !action.error
const error = action.error ? action.payload?.message || '' : ''
return getProtocolAnalyticsData(state).then(data => ({
name: 'runFinish',
properties: {
...getRobotAnalyticsData(state),
...data,
runTime,
success,
error,
},
}))
}
case 'robot:PAUSE': {
const runTime = robotSelectors.getRunSeconds(state)
return getProtocolAnalyticsData(state).then(data => ({
name: 'runPause',
properties: { ...data, runTime },
}))
}
case 'robot:RESUME': {
const runTime = robotSelectors.getRunSeconds(state)
return getProtocolAnalyticsData(state).then(data => ({
name: 'runResume',
properties: { ...data, runTime },
}))
}
case 'robot:CANCEL':
const runTime = robotSelectors.getRunSeconds(state)
return getProtocolAnalyticsData(state).then(data => ({
name: 'runCancel',
properties: { ...data, runTime },
}))
// buildroot update events
case brActions.BR_SET_UPDATE_SEEN: {
const data = getBuildrootAnalyticsData(state, action.meta.robotName)
return Promise.resolve({
name: 'robotUpdateView',
properties: { ...data },
})
}
case brActions.BR_CHANGELOG_SEEN: {
const data = getBuildrootAnalyticsData(state, action.meta.robotName)
return Promise.resolve({
name: 'robotUpdateChangeLogView',
properties: { ...data },
})
}
case brActions.BR_UPDATE_IGNORED: {
const data = getBuildrootAnalyticsData(state, action.meta.robotName)
return Promise.resolve({
name: 'robotUpdateIgnore',
properties: { ...data },
})
}
case brActions.BR_START_UPDATE: {
const data = getBuildrootAnalyticsData(state)
return Promise.resolve({
name: 'robotUpdateInitiate',
properties: { ...data },
})
}
case brActions.BR_UNEXPECTED_ERROR: {
const data = getBuildrootAnalyticsData(state)
return Promise.resolve({
name: 'robotUpdateError',
properties: { ...data },
})
}
case brActions.BR_SET_SESSION_STEP: {
if (action.payload !== 'finished') return Promise.resolve(null)
const data = getBuildrootAnalyticsData(state)
return Promise.resolve({
name: 'robotUpdateComplete',
properties: { ...data },
})
}
case CustomLabware.CUSTOM_LABWARE_LIST: {
const { payload: labware, meta } = action
const { source } = meta
const customLabwareCount = labware.filter(
lw => lw.type === CustomLabware.VALID_LABWARE_FILE
).length
const superProperties = { customLabwareCount }
if (
source === CustomLabware.ADD_LABWARE ||
source === CustomLabware.OVERWRITE_LABWARE
) {
return Promise.resolve({
name: 'addCustomLabware',
properties: {
success: true,
overwrite: source === CustomLabware.OVERWRITE_LABWARE,
error: '',
},
superProperties,
})
}
if (source === CustomLabware.CHANGE_DIRECTORY) {
return Promise.resolve({
name: 'changeLabwareSourceDirectory',
properties: { success: true, error: '' },
superProperties,
})
}
return Promise.resolve({ superProperties })
}
case CustomLabware.CUSTOM_LABWARE_LIST_FAILURE: {
const { message: error } = action.payload
const { source } = action.meta
if (source === CustomLabware.CHANGE_DIRECTORY) {
return Promise.resolve({
name: 'changeLabwareSourceDirectory',
properties: { success: false, error },
})
}
if (source === CustomLabware.INITIAL) {
return Promise.resolve({
name: 'customLabwareListError',
properties: { error },
})
}
break
}
case CustomLabware.ADD_CUSTOM_LABWARE_FAILURE: {
const { labware, message } = action.payload
let error = ''
if (labware !== null) {
error = labware.type
} else if (message !== null) {
error = message
}
return Promise.resolve({
name: 'addCustomLabware',
properties: { success: false, overwrite: false, error },
})
}
case SystemInfo.INITIALIZED:
case SystemInfo.USB_DEVICE_ADDED:
case SystemInfo.NETWORK_INTERFACES_CHANGED: {
const systemInfoProps = SystemInfo.getU2EDeviceAnalyticsProps(state)
return Promise.resolve(
systemInfoProps
? {
superProperties: {
...systemInfoProps,
// anonymize IP address so analytics profile can't be mapped to more
// specific Intercom support profile
'U2E IPv4 Address': Boolean(
systemInfoProps['U2E IPv4 Address']
),
},
}
: null
)
}
case Sessions.ENSURE_SESSION: {
switch (action.payload.sessionType) {
case Sessions.SESSION_TYPE_DECK_CALIBRATION:
const dcAnalyticsProps = getAnalyticsDeckCalibrationData(state)
return Promise.resolve(
dcAnalyticsProps
? {
name: 'deckCalibrationStarted',
properties: dcAnalyticsProps,
}
: null
)
case Sessions.SESSION_TYPE_CALIBRATION_HEALTH_CHECK:
const hcAnalyticsProps = getAnalyticsHealthCheckData(state)
return Promise.resolve(
hcAnalyticsProps
? {
name: 'calibrationHealthCheckStarted',
properties: hcAnalyticsProps,
}
: null
)
default:
return Promise.resolve(null)
}
}
case Sessions.CREATE_SESSION_COMMAND: {
switch (action.payload.command.command) {
case sharedCalCommands.EXIT:
const sessionDetails = getAnalyticsSessionExitDetails(
state,
action.payload.robotName,
action.payload.sessionId
)
return Promise.resolve(
sessionDetails
? {
name: `${sessionDetails.sessionType}Exit`,
properties: {
step: sessionDetails.step,
},
}
: null
)
case sharedCalCommands.LOAD_LABWARE:
const commandData = action.payload.command.data
if (commandData) {
const instrData = getSessionInstrumentAnalyticsData(
state,
action.payload.robotName,
action.payload.sessionId
)
return Promise.resolve(
instrData
? {
name: `${instrData.sessionType}TipRackSelect`,
properties: {
pipetteModel: instrData.pipetteModel,
// @ts-expect-error TODO: use in operator and add test case for no tiprackDefiniton on CommandData
tipRackDisplayName: commandData.tiprackDefinition
? // @ts-expect-error TODO: use in operator and add test case for no tiprackDefiniton on CommandData
commandData.tiprackDefinition.metadata.displayName
: null,
},
}
: null
)
} else {
return Promise.resolve(null)
}
default:
return Promise.resolve(null)
}
}
case Alerts.ALERT_DISMISSED: {
const { alertId, remember } = action.payload
if (alertId === Alerts.ALERT_APP_UPDATE_AVAILABLE) {
return Promise.resolve({
name: EVENT_APP_UPDATE_DISMISSED,
properties: { updatesIgnored: remember },
})
}
return Promise.resolve(null)
}
case Constants.ANALYTICS_PIPETTE_OFFSET_STARTED: {
return Promise.resolve({
name: 'pipetteOffsetCalibrationStarted',
properties: {
...action.payload,
...getAnalyticsPipetteCalibrationData(
state,
action.payload.mount as Mount
),
},
})
}
case Constants.ANALYTICS_TIP_LENGTH_STARTED: {
return Promise.resolve({
name: 'tipLengthCalibrationStarted',
properties: {
...action.payload,
...getAnalyticsTipLengthCalibrationData(
state,
action.payload.mount as Mount
),
},
})
}
case RobotAdmin.RESET_CONFIG: {
const { resets } = action.payload
return Promise.resolve({
name: 'resetRobotConfig',
properties: { ...resets },
})
}
}
return Promise.resolve(null)
} | the_stack |
namespace vfs {
/**
* Posix-style path to the TypeScript compiler build outputs (including tsc.js, lib.d.ts, etc.)
*/
export const builtFolder = "/.ts";
/**
* Posix-style path to additional mountable folders (./tests/projects in this repo)
*/
export const projectsFolder = "/.projects";
/**
* Posix-style path to additional test libraries
*/
export const testLibFolder = "/.lib";
/**
* Posix-style path to sources under test
*/
export const srcFolder = "/.src";
// file type
const S_IFMT = 0o170000; // file type
const S_IFSOCK = 0o140000; // socket
const S_IFLNK = 0o120000; // symbolic link
const S_IFREG = 0o100000; // regular file
const S_IFBLK = 0o060000; // block device
const S_IFDIR = 0o040000; // directory
const S_IFCHR = 0o020000; // character device
const S_IFIFO = 0o010000; // FIFO
let devCount = 0; // A monotonically increasing count of device ids
let inoCount = 0; // A monotonically increasing count of inodes
export interface DiffOptions {
includeChangedFileWithSameContent?: boolean;
baseIsNotShadowRoot?: boolean;
}
/**
* Represents a virtual POSIX-like file system.
*/
export class FileSystem {
/** Indicates whether the file system is case-sensitive (`false`) or case-insensitive (`true`). */
public readonly ignoreCase: boolean;
/** Gets the comparison function used to compare two paths. */
public readonly stringComparer: (a: string, b: string) => number;
// lazy-initialized state that should be mutable even if the FileSystem is frozen.
private _lazy: {
links?: collections.SortedMap<string, Inode>;
shadows?: Map<number, Inode>;
meta?: collections.Metadata;
} = {};
private _cwd: string; // current working directory
private _time: number | Date | (() => number | Date);
private _shadowRoot: FileSystem | undefined;
private _dirStack: string[] | undefined;
constructor(ignoreCase: boolean, options: FileSystemOptions = {}) {
const { time = -1, files, meta } = options;
this.ignoreCase = ignoreCase;
this.stringComparer = this.ignoreCase ? vpath.compareCaseInsensitive : vpath.compareCaseSensitive;
this._time = time;
if (meta) {
for (const key of Object.keys(meta)) {
this.meta.set(key, meta[key]);
}
}
if (files) {
this._applyFiles(files, /*dirname*/ "");
}
let cwd = options.cwd;
if ((!cwd || !vpath.isRoot(cwd)) && this._lazy.links) {
const iterator = collections.getIterator(this._lazy.links.keys());
try {
for (let i = collections.nextResult(iterator); i; i = collections.nextResult(iterator)) {
const name = i.value;
cwd = cwd ? vpath.resolve(name, cwd) : name;
break;
}
}
finally {
collections.closeIterator(iterator);
}
}
if (cwd) {
vpath.validate(cwd, vpath.ValidationFlags.Absolute);
this.mkdirpSync(cwd);
}
this._cwd = cwd || "";
}
/**
* Gets metadata for this `FileSystem`.
*/
public get meta(): collections.Metadata {
if (!this._lazy.meta) {
this._lazy.meta = new collections.Metadata(this._shadowRoot ? this._shadowRoot.meta : undefined);
}
return this._lazy.meta;
}
/**
* Gets a value indicating whether the file system is read-only.
*/
public get isReadonly() {
return Object.isFrozen(this);
}
/**
* Makes the file system read-only.
*/
public makeReadonly() {
Object.freeze(this);
return this;
}
/**
* Gets the file system shadowed by this file system.
*/
public get shadowRoot() {
return this._shadowRoot;
}
/**
* Snapshots the current file system, effectively shadowing itself. This is useful for
* generating file system patches using `.diff()` from one snapshot to the next. Performs
* no action if this file system is read-only.
*/
public snapshot() {
if (this.isReadonly) return;
const fs = new FileSystem(this.ignoreCase, { time: this._time });
fs._lazy = this._lazy;
fs._cwd = this._cwd;
fs._time = this._time;
fs._shadowRoot = this._shadowRoot;
fs._dirStack = this._dirStack;
fs.makeReadonly();
this._lazy = {};
this._shadowRoot = fs;
}
/**
* Gets a shadow copy of this file system. Changes to the shadow copy do not affect the
* original, allowing multiple copies of the same core file system without multiple copies
* of the same data.
*/
public shadow(ignoreCase = this.ignoreCase) {
if (!this.isReadonly) throw new Error("Cannot shadow a mutable file system.");
if (ignoreCase && !this.ignoreCase) throw new Error("Cannot create a case-insensitive file system from a case-sensitive one.");
const fs = new FileSystem(ignoreCase, { time: this._time });
fs._shadowRoot = this;
fs._cwd = this._cwd;
return fs;
}
/**
* Gets or sets the timestamp (in milliseconds) used for file status, returning the previous timestamp.
*
* @link http://pubs.opengroup.org/onlinepubs/9699919799/functions/time.html
*/
public time(value?: number | Date | (() => number | Date)): number {
if (value !== undefined && this.isReadonly) throw createIOError("EPERM");
let result = this._time;
if (typeof result === "function") result = result();
if (typeof result === "object") result = result.getTime();
if (result === -1) result = Date.now();
if (value !== undefined) {
this._time = value;
}
return result;
}
/**
* Gets the metadata object for a path.
* @param path
*/
public filemeta(path: string): collections.Metadata {
const { node } = this._walk(this._resolve(path));
if (!node) throw createIOError("ENOENT");
return this._filemeta(node);
}
private _filemeta(node: Inode): collections.Metadata {
if (!node.meta) {
const parentMeta = node.shadowRoot && this._shadowRoot && this._shadowRoot._filemeta(node.shadowRoot);
node.meta = new collections.Metadata(parentMeta);
}
return node.meta;
}
/**
* Get the pathname of the current working directory.
*
* @link - http://pubs.opengroup.org/onlinepubs/9699919799/functions/getcwd.html
*/
public cwd() {
if (!this._cwd) throw new Error("The current working directory has not been set.");
const { node } = this._walk(this._cwd);
if (!node) throw createIOError("ENOENT");
if (!isDirectory(node)) throw createIOError("ENOTDIR");
return this._cwd;
}
/**
* Changes the current working directory.
*
* @link http://pubs.opengroup.org/onlinepubs/9699919799/functions/chdir.html
*/
public chdir(path: string) {
if (this.isReadonly) throw createIOError("EPERM");
path = this._resolve(path);
const { node } = this._walk(path);
if (!node) throw createIOError("ENOENT");
if (!isDirectory(node)) throw createIOError("ENOTDIR");
this._cwd = path;
}
/**
* Pushes the current directory onto the directory stack and changes the current working directory to the supplied path.
*/
public pushd(path?: string) {
if (this.isReadonly) throw createIOError("EPERM");
if (path) path = this._resolve(path);
if (this._cwd) {
if (!this._dirStack) this._dirStack = [];
this._dirStack.push(this._cwd);
}
if (path && path !== this._cwd) {
this.chdir(path);
}
}
/**
* Pops the previous directory from the location stack and changes the current directory to that directory.
*/
public popd() {
if (this.isReadonly) throw createIOError("EPERM");
const path = this._dirStack && this._dirStack.pop();
if (path) {
this.chdir(path);
}
}
/**
* Update the file system with a set of files.
*/
public apply(files: FileSet) {
this._applyFiles(files, this._cwd);
}
/**
* Scan file system entries along a path. If `path` is a symbolic link, it is dereferenced.
* @param path The path at which to start the scan.
* @param axis The axis along which to traverse.
* @param traversal The traversal scheme to use.
*/
public scanSync(path: string, axis: Axis, traversal: Traversal) {
path = this._resolve(path);
const results: string[] = [];
this._scan(path, this._stat(this._walk(path)), axis, traversal, /*noFollow*/ false, results);
return results;
}
/**
* Scan file system entries along a path.
* @param path The path at which to start the scan.
* @param axis The axis along which to traverse.
* @param traversal The traversal scheme to use.
*/
public lscanSync(path: string, axis: Axis, traversal: Traversal) {
path = this._resolve(path);
const results: string[] = [];
this._scan(path, this._stat(this._walk(path, /*noFollow*/ true)), axis, traversal, /*noFollow*/ true, results);
return results;
}
private _scan(path: string, stats: Stats, axis: Axis, traversal: Traversal, noFollow: boolean, results: string[]) {
if (axis === "ancestors-or-self" || axis === "self" || axis === "descendants-or-self") {
if (!traversal.accept || traversal.accept(path, stats)) {
results.push(path);
}
}
if (axis === "ancestors-or-self" || axis === "ancestors") {
const dirname = vpath.dirname(path);
if (dirname !== path) {
try {
const stats = this._stat(this._walk(dirname, noFollow));
if (!traversal.traverse || traversal.traverse(dirname, stats)) {
this._scan(dirname, stats, "ancestors-or-self", traversal, noFollow, results);
}
}
catch { /*ignored*/ }
}
}
if (axis === "descendants-or-self" || axis === "descendants") {
if (stats.isDirectory() && (!traversal.traverse || traversal.traverse(path, stats))) {
for (const file of this.readdirSync(path)) {
try {
const childpath = vpath.combine(path, file);
const stats = this._stat(this._walk(childpath, noFollow));
this._scan(childpath, stats, "descendants-or-self", traversal, noFollow, results);
}
catch { /*ignored*/ }
}
}
}
}
/**
* Mounts a physical or virtual file system at a location in this virtual file system.
*
* @param source The path in the physical (or other virtual) file system.
* @param target The path in this virtual file system.
* @param resolver An object used to resolve files in `source`.
*/
public mountSync(source: string, target: string, resolver: FileSystemResolver) {
if (this.isReadonly) throw createIOError("EROFS");
source = vpath.validate(source, vpath.ValidationFlags.Absolute);
const { parent, links, node: existingNode, basename } = this._walk(this._resolve(target), /*noFollow*/ true);
if (existingNode) throw createIOError("EEXIST");
const time = this.time();
const node = this._mknod(parent ? parent.dev : ++devCount, S_IFDIR, /*mode*/ 0o777, time);
node.source = source;
node.resolver = resolver;
this._addLink(parent, links, basename, node, time);
}
/**
* Recursively remove all files and directories underneath the provided path.
*/
public rimrafSync(path: string) {
try {
const stats = this.lstatSync(path);
if (stats.isFile() || stats.isSymbolicLink()) {
this.unlinkSync(path);
}
else if (stats.isDirectory()) {
for (const file of this.readdirSync(path)) {
this.rimrafSync(vpath.combine(path, file));
}
this.rmdirSync(path);
}
}
catch (e) {
if (e.code === "ENOENT") return;
throw e;
}
}
/**
* Make a directory and all of its parent paths (if they don't exist).
*/
public mkdirpSync(path: string) {
path = this._resolve(path);
const result = this._walk(path, /*noFollow*/ true, (error, result) => {
if (error.code === "ENOENT") {
this._mkdir(result);
return "retry";
}
return "throw";
});
if (!result.node) this._mkdir(result);
}
public getFileListing(): string {
let result = "";
const printLinks = (dirname: string | undefined, links: collections.SortedMap<string, Inode>) => {
const iterator = collections.getIterator(links);
try {
for (let i = collections.nextResult(iterator); i; i = collections.nextResult(iterator)) {
const [name, node] = i.value;
const path = dirname ? vpath.combine(dirname, name) : name;
const marker = vpath.compare(this._cwd, path, this.ignoreCase) === 0 ? "*" : " ";
if (result) result += "\n";
result += marker;
if (isDirectory(node)) {
result += vpath.addTrailingSeparator(path);
printLinks(path, this._getLinks(node));
}
else if (isFile(node)) {
result += path;
}
else if (isSymlink(node)) {
result += path + " -> " + node.symlink;
}
}
}
finally {
collections.closeIterator(iterator);
}
};
printLinks(/*dirname*/ undefined, this._getRootLinks());
return result;
}
/**
* Print diagnostic information about the structure of the file system to the console.
*/
public debugPrint(): void {
console.log(this.getFileListing());
}
// POSIX API (aligns with NodeJS "fs" module API)
/**
* Determines whether a path exists.
*/
public existsSync(path: string) {
const result = this._walk(this._resolve(path), /*noFollow*/ true, () => "stop");
return result !== undefined && result.node !== undefined;
}
/**
* Get file status. If `path` is a symbolic link, it is dereferenced.
*
* @link http://pubs.opengroup.org/onlinepubs/9699919799/functions/stat.html
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public statSync(path: string) {
return this._stat(this._walk(this._resolve(path)));
}
/**
* Change file access times
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public utimesSync(path: string, atime: Date, mtime: Date) {
if (this.isReadonly) throw createIOError("EROFS");
if (!isFinite(+atime) || !isFinite(+mtime)) throw createIOError("EINVAL");
const entry = this._walk(this._resolve(path));
if (!entry || !entry.node) {
throw createIOError("ENOENT");
}
entry.node.atimeMs = +atime;
entry.node.mtimeMs = +mtime;
entry.node.ctimeMs = this.time();
}
/**
* Get file status. If `path` is a symbolic link, it is dereferenced.
*
* @link http://pubs.opengroup.org/onlinepubs/9699919799/functions/lstat.html
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public lstatSync(path: string) {
return this._stat(this._walk(this._resolve(path), /*noFollow*/ true));
}
private _stat(entry: WalkResult) {
const node = entry.node;
if (!node) throw createIOError(`ENOENT`, entry.realpath);
return new Stats(
node.dev,
node.ino,
node.mode,
node.nlink,
/*rdev*/ 0,
/*size*/ isFile(node) ? this._getSize(node) : isSymlink(node) ? node.symlink.length : 0,
/*blksize*/ 4096,
/*blocks*/ 0,
node.atimeMs,
node.mtimeMs,
node.ctimeMs,
node.birthtimeMs,
);
}
/**
* Read a directory. If `path` is a symbolic link, it is dereferenced.
*
* @link http://pubs.opengroup.org/onlinepubs/9699919799/functions/readdir.html
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public readdirSync(path: string) {
const { node } = this._walk(this._resolve(path));
if (!node) throw createIOError("ENOENT");
if (!isDirectory(node)) throw createIOError("ENOTDIR");
return Array.from(this._getLinks(node).keys());
}
/**
* Make a directory.
*
* @link http://pubs.opengroup.org/onlinepubs/9699919799/functions/mkdir.html
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public mkdirSync(path: string) {
if (this.isReadonly) throw createIOError("EROFS");
this._mkdir(this._walk(this._resolve(path), /*noFollow*/ true));
}
private _mkdir({ parent, links, node: existingNode, basename }: WalkResult) {
if (existingNode) throw createIOError("EEXIST");
const time = this.time();
const node = this._mknod(parent ? parent.dev : ++devCount, S_IFDIR, /*mode*/ 0o777, time);
this._addLink(parent, links, basename, node, time);
}
/**
* Remove a directory.
*
* @link http://pubs.opengroup.org/onlinepubs/9699919799/functions/rmdir.html
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public rmdirSync(path: string) {
if (this.isReadonly) throw createIOError("EROFS");
path = this._resolve(path);
const { parent, links, node, basename } = this._walk(path, /*noFollow*/ true);
if (!parent) throw createIOError("EPERM");
if (!isDirectory(node)) throw createIOError("ENOTDIR");
if (this._getLinks(node).size !== 0) throw createIOError("ENOTEMPTY");
this._removeLink(parent, links, basename, node);
}
/**
* Link one file to another file (also known as a "hard link").
*
* @link http://pubs.opengroup.org/onlinepubs/9699919799/functions/link.html
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public linkSync(oldpath: string, newpath: string) {
if (this.isReadonly) throw createIOError("EROFS");
const { node } = this._walk(this._resolve(oldpath));
if (!node) throw createIOError("ENOENT");
if (isDirectory(node)) throw createIOError("EPERM");
const { parent, links, basename, node: existingNode } = this._walk(this._resolve(newpath), /*noFollow*/ true);
if (!parent) throw createIOError("EPERM");
if (existingNode) throw createIOError("EEXIST");
this._addLink(parent, links, basename, node);
}
/**
* Remove a directory entry.
*
* @link http://pubs.opengroup.org/onlinepubs/9699919799/functions/unlink.html
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public unlinkSync(path: string) {
if (this.isReadonly) throw createIOError("EROFS");
const { parent, links, node, basename } = this._walk(this._resolve(path), /*noFollow*/ true);
if (!parent) throw createIOError("EPERM");
if (!node) throw createIOError("ENOENT");
if (isDirectory(node)) throw createIOError("EISDIR");
this._removeLink(parent, links, basename, node);
}
/**
* Rename a file.
*
* @link http://pubs.opengroup.org/onlinepubs/9699919799/functions/rename.html
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public renameSync(oldpath: string, newpath: string) {
if (this.isReadonly) throw createIOError("EROFS");
const { parent: oldParent, links: oldParentLinks, node, basename: oldBasename } = this._walk(this._resolve(oldpath), /*noFollow*/ true);
if (!oldParent) throw createIOError("EPERM");
if (!node) throw createIOError("ENOENT");
const { parent: newParent, links: newParentLinks, node: existingNode, basename: newBasename } = this._walk(this._resolve(newpath), /*noFollow*/ true);
if (!newParent) throw createIOError("EPERM");
const time = this.time();
if (existingNode) {
if (isDirectory(node)) {
if (!isDirectory(existingNode)) throw createIOError("ENOTDIR");
// if both old and new arguments point to the same directory, just pass. So we could rename /src/a/1 to /src/A/1 in Win.
// if not and the directory pointed by the new path is not empty, throw an error.
if (this.stringComparer(oldpath, newpath) !== 0 && this._getLinks(existingNode).size > 0) throw createIOError("ENOTEMPTY");
}
else {
if (isDirectory(existingNode)) throw createIOError("EISDIR");
}
this._removeLink(newParent, newParentLinks, newBasename, existingNode, time);
}
this._replaceLink(oldParent, oldParentLinks, oldBasename, newParent, newParentLinks, newBasename, node, time);
}
/**
* Make a symbolic link.
*
* @link http://pubs.opengroup.org/onlinepubs/9699919799/functions/symlink.html
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public symlinkSync(target: string, linkpath: string) {
if (this.isReadonly) throw createIOError("EROFS");
const { parent, links, node: existingNode, basename } = this._walk(this._resolve(linkpath), /*noFollow*/ true);
if (!parent) throw createIOError("EPERM");
if (existingNode) throw createIOError("EEXIST");
const time = this.time();
const node = this._mknod(parent.dev, S_IFLNK, /*mode*/ 0o666, time);
node.symlink = vpath.validate(target, vpath.ValidationFlags.RelativeOrAbsolute);
this._addLink(parent, links, basename, node, time);
}
/**
* Resolve a pathname.
*
* @link http://pubs.opengroup.org/onlinepubs/9699919799/functions/realpath.html
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public realpathSync(path: string) {
const { realpath } = this._walk(this._resolve(path));
return realpath;
}
/**
* Read from a file.
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public readFileSync(path: string, encoding?: null): Buffer;
/**
* Read from a file.
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public readFileSync(path: string, encoding: BufferEncoding): string;
/**
* Read from a file.
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
public readFileSync(path: string, encoding?: BufferEncoding | null): string | Buffer;
public readFileSync(path: string, encoding: BufferEncoding | null = null) { // eslint-disable-line no-null/no-null
const { node } = this._walk(this._resolve(path));
if (!node) throw createIOError("ENOENT");
if (isDirectory(node)) throw createIOError("EISDIR");
if (!isFile(node)) throw createIOError("EBADF");
const buffer = this._getBuffer(node).slice();
return encoding ? buffer.toString(encoding) : buffer;
}
/**
* Write to a file.
*
* NOTE: do not rename this method as it is intended to align with the same named export of the "fs" module.
*/
// eslint-disable-next-line no-null/no-null
public writeFileSync(path: string, data: string | Buffer, encoding: string | null = null) {
if (this.isReadonly) throw createIOError("EROFS");
const { parent, links, node: existingNode, basename } = this._walk(this._resolve(path), /*noFollow*/ false);
if (!parent) throw createIOError("EPERM");
const time = this.time();
let node = existingNode;
if (!node) {
node = this._mknod(parent.dev, S_IFREG, 0o666, time);
this._addLink(parent, links, basename, node, time);
}
if (isDirectory(node)) throw createIOError("EISDIR");
if (!isFile(node)) throw createIOError("EBADF");
node.buffer = Buffer.isBuffer(data) ? data.slice() : ts.sys.bufferFrom!("" + data, encoding || "utf8") as Buffer;
node.size = node.buffer.byteLength;
node.mtimeMs = time;
node.ctimeMs = time;
}
/**
* Generates a `FileSet` patch containing all the entries in this `FileSystem` that are not in `base`.
* @param base The base file system. If not provided, this file system's `shadowRoot` is used (if present).
*/
public diff(base?: FileSystem | undefined, options: DiffOptions = {}) {
if (!base && !options.baseIsNotShadowRoot) base = this.shadowRoot;
const differences: FileSet = {};
const hasDifferences = base ?
FileSystem.rootDiff(differences, this, base, options) :
FileSystem.trackCreatedInodes(differences, this, this._getRootLinks());
return hasDifferences ? differences : undefined;
}
/**
* Generates a `FileSet` patch containing all the entries in `changed` that are not in `base`.
*/
public static diff(changed: FileSystem, base: FileSystem, options: DiffOptions = {}) {
const differences: FileSet = {};
return FileSystem.rootDiff(differences, changed, base, options) ?
differences :
undefined;
}
private static diffWorker(container: FileSet, changed: FileSystem, changedLinks: ReadonlyMap<string, Inode> | undefined, base: FileSystem, baseLinks: ReadonlyMap<string, Inode> | undefined, options: DiffOptions) {
if (changedLinks && !baseLinks) return FileSystem.trackCreatedInodes(container, changed, changedLinks);
if (baseLinks && !changedLinks) return FileSystem.trackDeletedInodes(container, baseLinks);
if (changedLinks && baseLinks) {
let hasChanges = false;
// track base items missing in changed
baseLinks.forEach((node, basename) => {
if (!changedLinks.has(basename)) {
container[basename] = isDirectory(node) ? new Rmdir() : new Unlink();
hasChanges = true;
}
});
// track changed items missing or differing in base
changedLinks.forEach((changedNode, basename) => {
const baseNode = baseLinks.get(basename);
if (baseNode) {
if (isDirectory(changedNode) && isDirectory(baseNode)) {
return hasChanges = FileSystem.directoryDiff(container, basename, changed, changedNode, base, baseNode, options) || hasChanges;
}
if (isFile(changedNode) && isFile(baseNode)) {
return hasChanges = FileSystem.fileDiff(container, basename, changed, changedNode, base, baseNode, options) || hasChanges;
}
if (isSymlink(changedNode) && isSymlink(baseNode)) {
return hasChanges = FileSystem.symlinkDiff(container, basename, changedNode, baseNode) || hasChanges;
}
}
return hasChanges = FileSystem.trackCreatedInode(container, basename, changed, changedNode) || hasChanges;
});
return hasChanges;
}
return false;
}
private static rootDiff(container: FileSet, changed: FileSystem, base: FileSystem, options: DiffOptions) {
while (!changed._lazy.links && changed._shadowRoot) changed = changed._shadowRoot;
while (!base._lazy.links && base._shadowRoot) base = base._shadowRoot;
// no difference if the file systems are the same reference
if (changed === base) return false;
// no difference if the root links are empty and unshadowed
if (!changed._lazy.links && !changed._shadowRoot && !base._lazy.links && !base._shadowRoot) return false;
return FileSystem.diffWorker(container, changed, changed._getRootLinks(), base, base._getRootLinks(), options);
}
private static directoryDiff(container: FileSet, basename: string, changed: FileSystem, changedNode: DirectoryInode, base: FileSystem, baseNode: DirectoryInode, options: DiffOptions) {
while (!changedNode.links && changedNode.shadowRoot) changedNode = changedNode.shadowRoot;
while (!baseNode.links && baseNode.shadowRoot) baseNode = baseNode.shadowRoot;
// no difference if the nodes are the same reference
if (changedNode === baseNode) return false;
// no difference if both nodes are non shadowed and have no entries
if (isEmptyNonShadowedDirectory(changedNode) && isEmptyNonShadowedDirectory(baseNode)) return false;
// no difference if both nodes are unpopulated and point to the same mounted file system
if (!changedNode.links && !baseNode.links &&
changedNode.resolver && changedNode.source !== undefined &&
baseNode.resolver === changedNode.resolver && baseNode.source === changedNode.source) return false;
// no difference if both nodes have identical children
const children: FileSet = {};
if (!FileSystem.diffWorker(children, changed, changed._getLinks(changedNode), base, base._getLinks(baseNode), options)) {
return false;
}
container[basename] = new Directory(children);
return true;
}
private static fileDiff(container: FileSet, basename: string, changed: FileSystem, changedNode: FileInode, base: FileSystem, baseNode: FileInode, options: DiffOptions) {
while (!changedNode.buffer && changedNode.shadowRoot) changedNode = changedNode.shadowRoot;
while (!baseNode.buffer && baseNode.shadowRoot) baseNode = baseNode.shadowRoot;
// no difference if the nodes are the same reference
if (changedNode === baseNode) return false;
// no difference if both nodes are non shadowed and have no entries
if (isEmptyNonShadowedFile(changedNode) && isEmptyNonShadowedFile(baseNode)) return false;
// no difference if both nodes are unpopulated and point to the same mounted file system
if (!changedNode.buffer && !baseNode.buffer &&
changedNode.resolver && changedNode.source !== undefined &&
baseNode.resolver === changedNode.resolver && baseNode.source === changedNode.source) return false;
const changedBuffer = changed._getBuffer(changedNode);
const baseBuffer = base._getBuffer(baseNode);
// no difference if both buffers are the same reference
if (changedBuffer === baseBuffer) return false;
// no difference if both buffers are identical
if (Buffer.compare(changedBuffer, baseBuffer) === 0) {
if (!options.includeChangedFileWithSameContent) return false;
container[basename] = new SameFileContentFile(changedBuffer);
return true;
}
container[basename] = new File(changedBuffer);
return true;
}
private static symlinkDiff(container: FileSet, basename: string, changedNode: SymlinkInode, baseNode: SymlinkInode) {
// no difference if the nodes are the same reference
if (changedNode.symlink === baseNode.symlink) return false;
container[basename] = new Symlink(changedNode.symlink);
return true;
}
private static trackCreatedInode(container: FileSet, basename: string, changed: FileSystem, node: Inode) {
if (isDirectory(node)) {
const children: FileSet = {};
FileSystem.trackCreatedInodes(children, changed, changed._getLinks(node));
container[basename] = new Directory(children);
}
else if (isSymlink(node)) {
container[basename] = new Symlink(node.symlink);
}
else {
container[basename] = new File(node.buffer || "");
}
return true;
}
private static trackCreatedInodes(container: FileSet, changed: FileSystem, changedLinks: ReadonlyMap<string, Inode>) {
// no difference if links are empty
if (!changedLinks.size) return false;
changedLinks.forEach((node, basename) => {
FileSystem.trackCreatedInode(container, basename, changed, node);
});
return true;
}
private static trackDeletedInodes(container: FileSet, baseLinks: ReadonlyMap<string, Inode>) {
// no difference if links are empty
if (!baseLinks.size) return false;
baseLinks.forEach((node, basename) => {
container[basename] = isDirectory(node) ? new Rmdir() : new Unlink();
});
return true;
}
private _mknod(dev: number, type: typeof S_IFREG, mode: number, time?: number): FileInode;
private _mknod(dev: number, type: typeof S_IFDIR, mode: number, time?: number): DirectoryInode;
private _mknod(dev: number, type: typeof S_IFLNK, mode: number, time?: number): SymlinkInode;
private _mknod(dev: number, type: number, mode: number, time = this.time()) {
return {
dev,
ino: ++inoCount,
mode: (mode & ~S_IFMT & ~0o022 & 0o7777) | (type & S_IFMT),
atimeMs: time,
mtimeMs: time,
ctimeMs: time,
birthtimeMs: time,
nlink: 0
} as Inode;
}
private _addLink(parent: DirectoryInode | undefined, links: collections.SortedMap<string, Inode>, name: string, node: Inode, time = this.time()) {
links.set(name, node);
node.nlink++;
node.ctimeMs = time;
if (parent) parent.mtimeMs = time;
if (!parent && !this._cwd) this._cwd = name;
}
private _removeLink(parent: DirectoryInode | undefined, links: collections.SortedMap<string, Inode>, name: string, node: Inode, time = this.time()) {
links.delete(name);
node.nlink--;
node.ctimeMs = time;
if (parent) parent.mtimeMs = time;
}
private _replaceLink(oldParent: DirectoryInode, oldLinks: collections.SortedMap<string, Inode>, oldName: string, newParent: DirectoryInode, newLinks: collections.SortedMap<string, Inode>, newName: string, node: Inode, time: number) {
if (oldParent !== newParent) {
this._removeLink(oldParent, oldLinks, oldName, node, time);
this._addLink(newParent, newLinks, newName, node, time);
}
else {
oldLinks.delete(oldName);
oldLinks.set(newName, node);
oldParent.mtimeMs = time;
newParent.mtimeMs = time;
}
}
private _getRootLinks() {
if (!this._lazy.links) {
this._lazy.links = new collections.SortedMap<string, Inode>(this.stringComparer);
if (this._shadowRoot) {
this._copyShadowLinks(this._shadowRoot._getRootLinks(), this._lazy.links);
}
this._lazy.links = this._lazy.links;
}
return this._lazy.links;
}
private _getLinks(node: DirectoryInode) {
if (!node.links) {
const links = new collections.SortedMap<string, Inode>(this.stringComparer);
const { source, resolver } = node;
if (source && resolver) {
node.source = undefined;
node.resolver = undefined;
for (const name of resolver.readdirSync(source)) {
const path = vpath.combine(source, name);
const stats = resolver.statSync(path);
switch (stats.mode & S_IFMT) {
case S_IFDIR:
const dir = this._mknod(node.dev, S_IFDIR, 0o777);
dir.source = vpath.combine(source, name);
dir.resolver = resolver;
this._addLink(node, links, name, dir);
break;
case S_IFREG:
const file = this._mknod(node.dev, S_IFREG, 0o666);
file.source = vpath.combine(source, name);
file.resolver = resolver;
file.size = stats.size;
this._addLink(node, links, name, file);
break;
}
}
}
else if (this._shadowRoot && node.shadowRoot) {
this._copyShadowLinks(this._shadowRoot._getLinks(node.shadowRoot), links);
}
node.links = links;
}
return node.links;
}
private _getShadow(root: DirectoryInode): DirectoryInode;
private _getShadow(root: Inode): Inode;
private _getShadow(root: Inode) {
const shadows = this._lazy.shadows || (this._lazy.shadows = new Map<number, Inode>());
let shadow = shadows.get(root.ino);
if (!shadow) {
shadow = {
dev: root.dev,
ino: root.ino,
mode: root.mode,
atimeMs: root.atimeMs,
mtimeMs: root.mtimeMs,
ctimeMs: root.ctimeMs,
birthtimeMs: root.birthtimeMs,
nlink: root.nlink,
shadowRoot: root
} as Inode;
if (isSymlink(root)) (shadow as SymlinkInode).symlink = root.symlink;
shadows.set(shadow.ino, shadow);
}
return shadow;
}
private _copyShadowLinks(source: ReadonlyMap<string, Inode>, target: collections.SortedMap<string, Inode>) {
const iterator = collections.getIterator(source);
try {
for (let i = collections.nextResult(iterator); i; i = collections.nextResult(iterator)) {
const [name, root] = i.value;
target.set(name, this._getShadow(root));
}
}
finally {
collections.closeIterator(iterator);
}
}
private _getSize(node: FileInode): number {
if (node.buffer) return node.buffer.byteLength;
if (node.size !== undefined) return node.size;
if (node.source && node.resolver) return node.size = node.resolver.statSync(node.source).size;
if (this._shadowRoot && node.shadowRoot) return node.size = this._shadowRoot._getSize(node.shadowRoot);
return 0;
}
private _getBuffer(node: FileInode): Buffer {
if (!node.buffer) {
const { source, resolver } = node;
if (source && resolver) {
node.source = undefined;
node.resolver = undefined;
node.size = undefined;
node.buffer = resolver.readFileSync(source);
}
else if (this._shadowRoot && node.shadowRoot) {
node.buffer = this._shadowRoot._getBuffer(node.shadowRoot);
}
else {
node.buffer = Buffer.allocUnsafe(0);
}
}
return node.buffer;
}
/**
* Walk a path to its end.
*
* @param path The path to follow.
* @param noFollow A value indicating whether to *not* dereference a symbolic link at the
* end of a path.
*
* @link http://man7.org/linux/man-pages/man7/path_resolution.7.html
*/
private _walk(path: string, noFollow?: boolean, onError?: (error: NodeJS.ErrnoException, fragment: WalkResult) => "retry" | "throw"): WalkResult;
private _walk(path: string, noFollow?: boolean, onError?: (error: NodeJS.ErrnoException, fragment: WalkResult) => "stop" | "retry" | "throw"): WalkResult | undefined;
private _walk(path: string, noFollow?: boolean, onError?: (error: NodeJS.ErrnoException, fragment: WalkResult) => "stop" | "retry" | "throw"): WalkResult | undefined {
let links = this._getRootLinks();
let parent: DirectoryInode | undefined;
let components = vpath.parse(path);
let step = 0;
let depth = 0;
let retry = false;
while (true) {
if (depth >= 40) throw createIOError("ELOOP");
const lastStep = step === components.length - 1;
let basename = components[step];
const linkEntry = links.getEntry(basename);
if (linkEntry) {
components[step] = basename = linkEntry[0];
}
const node = linkEntry?.[1];
if (lastStep && (noFollow || !isSymlink(node))) {
return { realpath: vpath.format(components), basename, parent, links, node };
}
if (node === undefined) {
if (trapError(createIOError("ENOENT"), node)) continue;
return undefined;
}
if (isSymlink(node)) {
const dirname = vpath.format(components.slice(0, step));
const symlink = vpath.resolve(dirname, node.symlink);
links = this._getRootLinks();
parent = undefined;
components = vpath.parse(symlink).concat(components.slice(step + 1));
step = 0;
depth++;
retry = false;
continue;
}
if (isDirectory(node)) {
links = this._getLinks(node);
parent = node;
step++;
retry = false;
continue;
}
if (trapError(createIOError("ENOTDIR"), node)) continue;
return undefined;
}
function trapError(error: NodeJS.ErrnoException, node?: Inode) {
const realpath = vpath.format(components.slice(0, step + 1));
const basename = components[step];
const result = !retry && onError ? onError(error, { realpath, basename, parent, links, node }) : "throw";
if (result === "stop") return false;
if (result === "retry") {
retry = true;
return true;
}
throw error;
}
}
/**
* Resolve a path relative to the current working directory.
*/
private _resolve(path: string) {
return this._cwd
? vpath.resolve(this._cwd, vpath.validate(path, vpath.ValidationFlags.RelativeOrAbsolute | vpath.ValidationFlags.AllowWildcard))
: vpath.validate(path, vpath.ValidationFlags.Absolute | vpath.ValidationFlags.AllowWildcard);
}
private _applyFiles(files: FileSet, dirname: string) {
const deferred: [Symlink | Link | Mount, string][] = [];
this._applyFilesWorker(files, dirname, deferred);
for (const [entry, path] of deferred) {
this.mkdirpSync(vpath.dirname(path));
this.pushd(vpath.dirname(path));
if (entry instanceof Symlink) {
if (this.stringComparer(vpath.dirname(path), path) === 0) {
throw new TypeError("Roots cannot be symbolic links.");
}
this.symlinkSync(vpath.resolve(dirname, entry.symlink), path);
this._applyFileExtendedOptions(path, entry);
}
else if (entry instanceof Link) {
if (this.stringComparer(vpath.dirname(path), path) === 0) {
throw new TypeError("Roots cannot be hard links.");
}
this.linkSync(entry.path, path);
}
else {
this.mountSync(entry.source, path, entry.resolver);
this._applyFileExtendedOptions(path, entry);
}
this.popd();
}
}
private _applyFileExtendedOptions(path: string, entry: Directory | File | Symlink | Mount) {
const { meta } = entry;
if (meta !== undefined) {
const filemeta = this.filemeta(path);
for (const key of Object.keys(meta)) {
filemeta.set(key, meta[key]);
}
}
}
private _applyFilesWorker(files: FileSet, dirname: string, deferred: [Symlink | Link | Mount, string][]) {
for (const key of Object.keys(files)) {
const value = normalizeFileSetEntry(files[key]);
const path = dirname ? vpath.resolve(dirname, key) : key;
vpath.validate(path, vpath.ValidationFlags.Absolute);
// eslint-disable-next-line no-null/no-null
if (value === null || value === undefined || value instanceof Rmdir || value instanceof Unlink) {
if (this.stringComparer(vpath.dirname(path), path) === 0) {
throw new TypeError("Roots cannot be deleted.");
}
this.rimrafSync(path);
}
else if (value instanceof File) {
if (this.stringComparer(vpath.dirname(path), path) === 0) {
throw new TypeError("Roots cannot be files.");
}
this.mkdirpSync(vpath.dirname(path));
this.writeFileSync(path, value.data, value.encoding);
this._applyFileExtendedOptions(path, value);
}
else if (value instanceof Directory) {
this.mkdirpSync(path);
this._applyFileExtendedOptions(path, value);
this._applyFilesWorker(value.files, path, deferred);
}
else {
deferred.push([value, path]);
}
}
}
}
export interface FileSystemOptions {
// Sets the initial timestamp for new files and directories, or the function used
// to calculate timestamps.
time?: number | Date | (() => number | Date);
// A set of file system entries to initially add to the file system.
files?: FileSet;
// Sets the initial working directory for the file system.
cwd?: string;
// Sets initial metadata attached to the file system.
meta?: Record<string, any>;
}
export interface FileSystemCreateOptions extends FileSystemOptions {
// Sets the documents to add to the file system.
documents?: readonly documents.TextDocument[];
}
export type Axis = "ancestors" | "ancestors-or-self" | "self" | "descendants-or-self" | "descendants";
export interface Traversal {
/** A function called to choose whether to continue to traverse to either ancestors or descendants. */
traverse?(path: string, stats: Stats): boolean;
/** A function called to choose whether to accept a path as part of the result. */
accept?(path: string, stats: Stats): boolean;
}
export interface FileSystemResolver {
statSync(path: string): { mode: number; size: number; };
readdirSync(path: string): string[];
readFileSync(path: string): Buffer;
}
export interface FileSystemResolverHost {
useCaseSensitiveFileNames(): boolean;
getAccessibleFileSystemEntries(path: string): ts.FileSystemEntries;
directoryExists(path: string): boolean;
fileExists(path: string): boolean;
getFileSize(path: string): number;
readFile(path: string): string | undefined;
getWorkspaceRoot(): string;
}
export function createResolver(host: FileSystemResolverHost): FileSystemResolver {
return {
readdirSync(path: string): string[] {
const { files, directories } = host.getAccessibleFileSystemEntries(path);
return directories.concat(files);
},
statSync(path: string): { mode: number; size: number; } {
if (host.directoryExists(path)) {
return { mode: S_IFDIR | 0o777, size: 0 };
}
else if (host.fileExists(path)) {
return { mode: S_IFREG | 0o666, size: host.getFileSize(path) };
}
else {
throw new Error("ENOENT: path does not exist");
}
},
readFileSync(path: string): Buffer {
return ts.sys.bufferFrom!(host.readFile(path)!, "utf8") as Buffer; // TODO: GH#18217
}
};
}
/**
* Create a virtual file system from a physical file system using the following path mappings:
*
* - `/.ts` is a directory mapped to `${workspaceRoot}/built/local`
* - `/.lib` is a directory mapped to `${workspaceRoot}/tests/lib`
* - `/.src` is a virtual directory to be used for tests.
*
* Unless overridden, `/.src` will be the current working directory for the virtual file system.
*/
export function createFromFileSystem(host: FileSystemResolverHost, ignoreCase: boolean, { documents, files, cwd, time, meta }: FileSystemCreateOptions = {}) {
const fs = getBuiltLocal(host, ignoreCase).shadow();
if (meta) {
for (const key of Object.keys(meta)) {
fs.meta.set(key, meta[key]);
}
}
if (time) {
fs.time(time);
}
if (cwd) {
fs.mkdirpSync(cwd);
fs.chdir(cwd);
}
if (documents) {
for (const document of documents) {
fs.mkdirpSync(vpath.dirname(document.file));
fs.writeFileSync(document.file, document.text, "utf8");
fs.filemeta(document.file).set("document", document);
// Add symlinks
const symlink = document.meta.get("symlink");
if (symlink) {
for (const link of symlink.split(",").map(link => link.trim())) {
fs.mkdirpSync(vpath.dirname(link));
fs.symlinkSync(vpath.resolve(fs.cwd(), document.file), link);
}
}
}
}
if (files) {
fs.apply(files);
}
return fs;
}
export class Stats {
public dev: number;
public ino: number;
public mode: number;
public nlink: number;
public uid: number;
public gid: number;
public rdev: number;
public size: number;
public blksize: number;
public blocks: number;
public atimeMs: number;
public mtimeMs: number;
public ctimeMs: number;
public birthtimeMs: number;
public atime: Date;
public mtime: Date;
public ctime: Date;
public birthtime: Date;
constructor();
constructor(dev: number, ino: number, mode: number, nlink: number, rdev: number, size: number, blksize: number, blocks: number, atimeMs: number, mtimeMs: number, ctimeMs: number, birthtimeMs: number);
constructor(dev = 0, ino = 0, mode = 0, nlink = 0, rdev = 0, size = 0, blksize = 0, blocks = 0, atimeMs = 0, mtimeMs = 0, ctimeMs = 0, birthtimeMs = 0) {
this.dev = dev;
this.ino = ino;
this.mode = mode;
this.nlink = nlink;
this.uid = 0;
this.gid = 0;
this.rdev = rdev;
this.size = size;
this.blksize = blksize;
this.blocks = blocks;
this.atimeMs = atimeMs;
this.mtimeMs = mtimeMs;
this.ctimeMs = ctimeMs;
this.birthtimeMs = birthtimeMs;
this.atime = new Date(this.atimeMs);
this.mtime = new Date(this.mtimeMs);
this.ctime = new Date(this.ctimeMs);
this.birthtime = new Date(this.birthtimeMs);
}
public isFile() { return (this.mode & S_IFMT) === S_IFREG; }
public isDirectory() { return (this.mode & S_IFMT) === S_IFDIR; }
public isSymbolicLink() { return (this.mode & S_IFMT) === S_IFLNK; }
public isBlockDevice() { return (this.mode & S_IFMT) === S_IFBLK; }
public isCharacterDevice() { return (this.mode & S_IFMT) === S_IFCHR; }
public isFIFO() { return (this.mode & S_IFMT) === S_IFIFO; }
public isSocket() { return (this.mode & S_IFMT) === S_IFSOCK; }
}
export const IOErrorMessages = Object.freeze({
EACCES: "access denied",
EIO: "an I/O error occurred",
ENOENT: "no such file or directory",
EEXIST: "file already exists",
ELOOP: "too many symbolic links encountered",
ENOTDIR: "no such directory",
EISDIR: "path is a directory",
EBADF: "invalid file descriptor",
EINVAL: "invalid value",
ENOTEMPTY: "directory not empty",
EPERM: "operation not permitted",
EROFS: "file system is read-only"
});
export function createIOError(code: keyof typeof IOErrorMessages, details = "") {
const err: NodeJS.ErrnoException = new Error(`${code}: ${IOErrorMessages[code]} ${details}`);
err.code = code;
if (Error.captureStackTrace) Error.captureStackTrace(err, createIOError);
return err;
}
/**
* A template used to populate files, directories, links, etc. in a virtual file system.
*/
export interface FileSet {
[name: string]: DirectoryLike | FileLike | Link | Symlink | Mount | Rmdir | Unlink | null | undefined;
}
export type DirectoryLike = FileSet | Directory;
export type FileLike = File | Buffer | string;
/** Extended options for a directory in a `FileSet` */
export class Directory {
public readonly files: FileSet;
public readonly meta: Record<string, any> | undefined;
constructor(files: FileSet, { meta }: { meta?: Record<string, any> } = {}) {
this.files = files;
this.meta = meta;
}
}
/** Extended options for a file in a `FileSet` */
export class File {
public readonly data: Buffer | string;
public readonly encoding: string | undefined;
public readonly meta: Record<string, any> | undefined;
constructor(data: Buffer | string, { meta, encoding }: { encoding?: string, meta?: Record<string, any> } = {}) {
this.data = data;
this.encoding = encoding;
this.meta = meta;
}
}
export class SameFileContentFile extends File {
constructor(data: Buffer | string, metaAndEncoding?: { encoding?: string, meta?: Record<string, any> }) {
super(data, metaAndEncoding);
}
}
/** Extended options for a hard link in a `FileSet` */
export class Link {
public readonly path: string;
constructor(path: string) {
this.path = path;
}
}
/** Removes a directory in a `FileSet` */
export class Rmdir {
public _rmdirBrand?: never; // brand necessary for proper type guards
}
/** Unlinks a file in a `FileSet` */
export class Unlink {
public _unlinkBrand?: never; // brand necessary for proper type guards
}
/** Extended options for a symbolic link in a `FileSet` */
export class Symlink {
public readonly symlink: string;
public readonly meta: Record<string, any> | undefined;
constructor(symlink: string, { meta }: { meta?: Record<string, any> } = {}) {
this.symlink = symlink;
this.meta = meta;
}
}
/** Extended options for mounting a virtual copy of an external file system via a `FileSet` */
export class Mount {
public readonly source: string;
public readonly resolver: FileSystemResolver;
public readonly meta: Record<string, any> | undefined;
constructor(source: string, resolver: FileSystemResolver, { meta }: { meta?: Record<string, any> } = {}) {
this.source = source;
this.resolver = resolver;
this.meta = meta;
}
}
// a generic POSIX inode
type Inode = FileInode | DirectoryInode | SymlinkInode;
interface FileInode {
dev: number; // device id
ino: number; // inode id
mode: number; // file mode
atimeMs: number; // access time
mtimeMs: number; // modified time
ctimeMs: number; // status change time
birthtimeMs: number; // creation time
nlink: number; // number of hard links
size?: number;
buffer?: Buffer;
source?: string;
resolver?: FileSystemResolver;
shadowRoot?: FileInode;
meta?: collections.Metadata;
}
interface DirectoryInode {
dev: number; // device id
ino: number; // inode id
mode: number; // file mode
atimeMs: number; // access time
mtimeMs: number; // modified time
ctimeMs: number; // status change time
birthtimeMs: number; // creation time
nlink: number; // number of hard links
links?: collections.SortedMap<string, Inode>;
source?: string;
resolver?: FileSystemResolver;
shadowRoot?: DirectoryInode;
meta?: collections.Metadata;
}
interface SymlinkInode {
dev: number; // device id
ino: number; // inode id
mode: number; // file mode
atimeMs: number; // access time
mtimeMs: number; // modified time
ctimeMs: number; // status change time
birthtimeMs: number; // creation time
nlink: number; // number of hard links
symlink: string;
shadowRoot?: SymlinkInode;
meta?: collections.Metadata;
}
function isEmptyNonShadowedDirectory(node: DirectoryInode) {
return !node.links && !node.shadowRoot && !node.resolver && !node.source;
}
function isEmptyNonShadowedFile(node: FileInode) {
return !node.buffer && !node.shadowRoot && !node.resolver && !node.source;
}
function isFile(node: Inode | undefined): node is FileInode {
return node !== undefined && (node.mode & S_IFMT) === S_IFREG;
}
function isDirectory(node: Inode | undefined): node is DirectoryInode {
return node !== undefined && (node.mode & S_IFMT) === S_IFDIR;
}
function isSymlink(node: Inode | undefined): node is SymlinkInode {
return node !== undefined && (node.mode & S_IFMT) === S_IFLNK;
}
interface WalkResult {
realpath: string;
basename: string;
parent: DirectoryInode | undefined;
links: collections.SortedMap<string, Inode>;
node: Inode | undefined;
}
let builtLocalHost: FileSystemResolverHost | undefined;
let builtLocalCI: FileSystem | undefined;
let builtLocalCS: FileSystem | undefined;
function getBuiltLocal(host: FileSystemResolverHost, ignoreCase: boolean): FileSystem {
if (builtLocalHost !== host) {
builtLocalCI = undefined;
builtLocalCS = undefined;
builtLocalHost = host;
}
if (!builtLocalCI) {
const resolver = createResolver(host);
builtLocalCI = new FileSystem(/*ignoreCase*/ true, {
files: {
[builtFolder]: new Mount(vpath.resolve(host.getWorkspaceRoot(), "built/local"), resolver),
[testLibFolder]: new Mount(vpath.resolve(host.getWorkspaceRoot(), "tests/lib"), resolver),
[projectsFolder]: new Mount(vpath.resolve(host.getWorkspaceRoot(), "tests/projects"), resolver),
[srcFolder]: {}
},
cwd: srcFolder,
meta: { defaultLibLocation: builtFolder }
});
builtLocalCI.makeReadonly();
}
if (ignoreCase) return builtLocalCI;
if (!builtLocalCS) {
builtLocalCS = builtLocalCI.shadow(/*ignoreCase*/ false);
builtLocalCS.makeReadonly();
}
return builtLocalCS;
}
/* eslint-disable no-null/no-null */
function normalizeFileSetEntry(value: FileSet[string]) {
if (value === undefined ||
value === null ||
value instanceof Directory ||
value instanceof File ||
value instanceof Link ||
value instanceof Symlink ||
value instanceof Mount ||
value instanceof Rmdir ||
value instanceof Unlink) {
return value;
}
return typeof value === "string" || Buffer.isBuffer(value) ? new File(value) : new Directory(value);
}
export function formatPatch(patch: FileSet): string;
export function formatPatch(patch: FileSet | undefined): string | null;
export function formatPatch(patch: FileSet | undefined) {
return patch ? formatPatchWorker("", patch) : null;
}
/* eslint-enable no-null/no-null */
function formatPatchWorker(dirname: string, container: FileSet): string {
let text = "";
for (const name of Object.keys(container)) {
const entry = normalizeFileSetEntry(container[name]);
const file = dirname ? vpath.combine(dirname, name) : name;
// eslint-disable-next-line no-null/no-null
if (entry === null || entry === undefined || entry instanceof Unlink || entry instanceof Rmdir) {
text += `//// [${file}] unlink\r\n`;
}
else if (entry instanceof Rmdir) {
text += `//// [${vpath.addTrailingSeparator(file)}] rmdir\r\n`;
}
else if (entry instanceof Directory) {
text += formatPatchWorker(file, entry.files);
}
else if (entry instanceof SameFileContentFile) {
text += `//// [${file}] file written with same contents\r\n`;
}
else if (entry instanceof File) {
const content = typeof entry.data === "string" ? entry.data : entry.data.toString("utf8");
text += `//// [${file}]\r\n${content}\r\n\r\n`;
}
else if (entry instanceof Link) {
text += `//// [${file}] link(${entry.path})\r\n`;
}
else if (entry instanceof Symlink) {
text += `//// [${file}] symlink(${entry.symlink})\r\n`;
}
else if (entry instanceof Mount) {
text += `//// [${file}] mount(${entry.source})\r\n`;
}
}
return text;
}
export function iteratePatch(patch: FileSet | undefined): IterableIterator<[string, string]> | null {
// eslint-disable-next-line no-null/no-null
return patch ? Harness.Compiler.iterateOutputs(iteratePatchWorker("", patch)) : null;
}
function* iteratePatchWorker(dirname: string, container: FileSet): IterableIterator<documents.TextDocument> {
for (const name of Object.keys(container)) {
const entry = normalizeFileSetEntry(container[name]);
const file = dirname ? vpath.combine(dirname, name) : name;
if (entry instanceof Directory) {
yield* ts.arrayFrom(iteratePatchWorker(file, entry.files));
}
else if (entry instanceof File) {
const content = typeof entry.data === "string" ? entry.data : entry.data.toString("utf8");
yield new documents.TextDocument(file, content);
}
}
}
} | the_stack |
'use strict';
import { statSync } from 'fs';
import * as path from 'path';
import * as crypto from 'crypto';
import * as utils from './utils';
import { EOL } from "os";
import * as log from 'fancy-log';
import * as colors from 'ansi-colors';
import * as ts from 'typescript';
import Vinyl = require('vinyl');
export interface IConfiguration {
json: boolean;
noFilesystemLookup: boolean;
verbose: boolean;
base: string;
_emitWithoutBasePath?: boolean;
}
export interface CancellationToken {
isCancellationRequested(): boolean;
}
export namespace CancellationToken {
export const NoneTsToken: ts.CancellationToken = {
isCancellationRequested() { return false },
throwIfCancellationRequested: () => { }
};
export function createTsCancellationToken(token: CancellationToken): ts.CancellationToken {
return {
isCancellationRequested: () => token.isCancellationRequested(),
throwIfCancellationRequested: () => {
if (token.isCancellationRequested()) {
throw new ts.OperationCanceledException();
}
}
};
}
}
export interface ITypeScriptBuilder {
build(out: (file: Vinyl) => void, onError: (err: any) => void, token?: CancellationToken): Promise<any>;
file(file: Vinyl): void;
getProgram(): ts.Program;
}
function normalize(path: string): string {
return path.replace(/\\/g, '/');
}
function fixCompilerOptions(config: IConfiguration, compilerOptions: ts.CompilerOptions) {
// clean up compiler options that conflict with gulp
if (compilerOptions.inlineSourceMap) compilerOptions.sourceMap = true;
delete compilerOptions.inlineSourceMap; // handled by gulp-sourcemaps
delete compilerOptions.inlineSources; // handled by gulp-sourcemaps
delete compilerOptions.sourceRoot; // incompatible with gulp-sourcemaps
delete compilerOptions.mapRoot; // incompatible with gulp-sourcemaps
delete compilerOptions.outDir; // always emit relative to source file
return compilerOptions;
}
enum Topics {
Cancel = "[CANCEL]",
EmitCode = "[emit code]",
CheckSyntax = "[check syntax]",
CheckSemantics = "[check semantics]",
CheckSemanticsInfo = "[check semantics*]"
}
function _log(config: IConfiguration, topic: Topics, message: string): void {
if (config.verbose) {
log(colors.cyan(topic), message);
}
}
function logCancel(config: IConfiguration) {
_log(config, Topics.Cancel, ">>This compile run was cancelled<<");
}
function printDiagnostics(config: IConfiguration, diagnostics: ReadonlyArray<ts.Diagnostic>, onError: (err: any) => void) {
if (diagnostics.length > 0) {
diagnostics.forEach(diag => {
let message: string;
if (diag.file) {
let lineAndCh = diag.file.getLineAndCharacterOfPosition(diag.start);
if (!config.json) {
message = utils.strings.format('{0}({1},{2}): {3}',
diag.file.fileName,
lineAndCh.line + 1,
lineAndCh.character + 1,
ts.flattenDiagnosticMessageText(diag.messageText, '\n'));
} else {
message = JSON.stringify({
filename: diag.file.fileName,
offset: diag.start,
length: diag.length,
message: ts.flattenDiagnosticMessageText(diag.messageText, '\n')
});
}
}
else {
message = ts.flattenDiagnosticMessageText(diag.messageText, '\n');
if (config.json) {
message = JSON.stringify({
message
});
}
}
onError(message);
});
}
}
function getNewLine(compilerOptions: ts.CompilerOptions) {
switch (compilerOptions.newLine) {
case ts.NewLineKind.CarriageReturnLineFeed: return "\r\n";
case ts.NewLineKind.LineFeed: return "\n";
default: return EOL;
}
}
function getDefaultLibFileName(options: ts.CompilerOptions): string {
return normalize(path.join(getDefaultLibLocation(), ts.getDefaultLibFileName(options)));
}
function getDefaultLibLocation() {
let typescriptInstall = require.resolve('typescript');
return normalize(path.dirname(typescriptInstall));
}
function printStats(config: IConfiguration, existingHeapUsed: number, startTime: number) {
// print stats
if (config.verbose) {
const headNow = process.memoryUsage().heapUsed,
MB = 1024 * 1024;
log('[tsb]',
'time:', colors.yellow((Date.now() - startTime) + 'ms'),
'mem:', colors.cyan(Math.ceil(headNow / MB) + 'MB'), colors.bgcyan('Δ' + Math.ceil((headNow - existingHeapUsed) / MB)));
return headNow;
}
}
function outFiles(config: IConfiguration, files: Vinyl[], out: (file: Vinyl) => void) {
for (let file of files) {
_log(config, Topics.EmitCode, file.path);
out(file);
}
}
interface EmitResult {
signature: string;
files: Vinyl[];
}
interface EmitVinyls {
javaScriptFile?: Vinyl;
sourceMapFile?: Vinyl;
declarationFile?: Vinyl;
}
function updateEmitVinyl(config: IConfiguration, emitVinyls: EmitVinyls, base: string | undefined, fileName: string, text: string, ) {
// When gulp-sourcemaps writes out a sourceMap, it uses the path
// information of the associated file. Specifically, it uses the base
// directory and relative path of the file to make decisions on how to
// write the "sources" and "sourceRoot" properties.
//
// To emit the correct paths, we need to have the output files emulate
// a path local to the source location, not the expected output location.
//
// Since gulp.dest sets our output location for us, then all that matters
// to gulp.dest is the relative path for each file. This means that we
// should be able to safely treat output files as local to sources to
// better support gulp-sourcemaps.
const relative = base && path.relative(base, fileName);
const name = relative ? path.resolve(base, relative) : fileName;
const contents = new Buffer(text);
const vinyl = new Vinyl({ path: name, base, contents });
if (/\.js$/.test(vinyl.path)) {
emitVinyls.javaScriptFile = vinyl;
}
else if (/\.js\.map$/.test(vinyl.path)) {
emitVinyls.sourceMapFile = vinyl;
}
else if (/\.d\.ts$/.test(vinyl.path)) {
emitVinyls.declarationFile = vinyl;
}
}
function getEmitResult(
config: IConfiguration,
emitSourceMapsInStream: boolean,
originalCompilerOptions: Readonly<ts.CompilerOptions>,
compilerOptions: ts.CompilerOptions,
getSourceContent: (fileName: string) => string,
getSourceVinyl: (fileName: string) => Vinyl | undefined,
{ javaScriptFile, declarationFile, sourceMapFile }: EmitVinyls,
ignoreSignatureAndUseDeclarationFile?: boolean
): EmitResult {
const files: Vinyl[] = [];
let signature: string | undefined;
if (javaScriptFile) {
// gulp-sourcemaps will add an appropriate sourceMappingURL comment, so we need to remove the
// one that TypeScript generates.
const sourceMappingURLPattern = /(\r\n?|\n)?\/\/# sourceMappingURL=[^\r\n]+(?=[\r\n\s]*$)/;
const contents = javaScriptFile.contents.toString();
javaScriptFile.contents = new Buffer(contents.replace(sourceMappingURLPattern, ""));
files.push(javaScriptFile);
}
if (declarationFile) {
if (ignoreSignatureAndUseDeclarationFile) {
files.push(declarationFile);
}
else {
signature = crypto.createHash('md5')
.update(declarationFile.contents as Buffer)
.digest('base64');
if (originalCompilerOptions.declaration) {
// don't leak .d.ts files if users don't want them
files.push(declarationFile);
}
}
}
if (sourceMapFile) {
// adjust the source map to be relative to the source directory.
const sourceMap = JSON.parse(sourceMapFile.contents.toString());
let sourceRoot = sourceMap.sourceRoot;
const sources = sourceMap.sources.map(source => path.resolve(sourceMapFile.base, source));
const destPath = path.resolve(config.base, originalCompilerOptions.outDir || ".");
// update sourceRoot to be relative from the expected destination path
sourceRoot = emitSourceMapsInStream ? originalCompilerOptions.sourceRoot : sourceRoot;
sourceMap.sourceRoot = sourceRoot ? normalize(path.relative(destPath, sourceRoot)) : undefined;
if (emitSourceMapsInStream) {
// update sourcesContent
if (originalCompilerOptions.inlineSources) {
sourceMap.sourcesContent = sources.map(getSourceContent);
}
// make all sources relative to the sourceRoot or destPath
sourceMap.sources = sources.map(source => {
source = path.resolve(sourceMapFile.base, source);
source = path.relative(sourceRoot || destPath, source);
source = normalize(source);
return source;
});
// update the contents for the sourcemap file
sourceMapFile.contents = new Buffer(JSON.stringify(sourceMap));
const newLine = getNewLine(compilerOptions);
let contents = javaScriptFile.contents.toString();
if (originalCompilerOptions.inlineSourceMap) {
// restore the sourcemap as an inline source map in the javaScript file.
contents += newLine + "//# sourceMappingURL=data:application/json;charset=utf8;base64," + sourceMapFile.contents.toString("base64") + newLine;
}
else {
contents += newLine + "//# sourceMappingURL=" + normalize(path.relative(path.dirname(javaScriptFile.path), sourceMapFile.path)) + newLine;
files.push(sourceMapFile);
}
javaScriptFile.contents = new Buffer(contents);
}
else {
// sourcesContent is handled by gulp-sourcemaps
sourceMap.sourcesContent = undefined;
// make all of the sources in the source map relative paths
sourceMap.sources = sources.map(source => {
const vinyl = getSourceVinyl(source);
return vinyl ? normalize(vinyl.relative) : source;
});
(<any>javaScriptFile).sourceMap = sourceMap;
}
}
return {
files,
signature
};
}
interface Work<T = {}, U = {}> {
arg: T;
action: (arg: T, tsToken?: ts.CancellationToken) => U;
onfulfilled: (result: U) => void;
}
function scheduleWork(
config: IConfiguration,
finalResolve: () => void,
getNextWork: () => Work,
tsToken?: ts.CancellationToken) {
scheduleNextWork();
function scheduleNextWork() {
const work = getNextWork();
if (work) {
const { action, arg, onfulfilled } = work;
return new Promise(resolve => {
process.nextTick(function () {
resolve(action(arg, tsToken));
});
}).then(onfulfilled, err => {
if (err instanceof ts.OperationCanceledException) {
logCancel(config);
}
console.error(err);
}).then(() => {
// After completion, schedule next work
process.nextTick(scheduleNextWork);
}).catch(err => {
console.error(err);
});
}
else {
finalResolve();
}
}
}
export function createTypeScriptBuilder(config: IConfiguration, compilerOptions: ts.CompilerOptions): ITypeScriptBuilder {
// fix compiler options
const originalCompilerOptions = utils.collections.structuredClone(compilerOptions)
compilerOptions = fixCompilerOptions(config, utils.collections.structuredClone(compilerOptions));
return WatchApi.createTypeScriptBuilder(config, originalCompilerOptions, compilerOptions);
}
namespace WatchApi {
interface EmitResult {
affected: ts.SourceFile | ts.Program,
files: Vinyl[];
diagnostics: ReadonlyArray<ts.Diagnostic>;
}
export function createTypeScriptBuilder(config: IConfiguration, originalCompilerOptions: Readonly<ts.CompilerOptions>, compilerOptions: ts.CompilerOptions): ITypeScriptBuilder {
const host = createHost(compilerOptions, config.noFilesystemLookup || false);
let emitSourceMapsInStream = true;
// Creates/ synchronizes the program
let watch: ts.WatchOfFilesAndCompilerOptions<ts.EmitAndSemanticDiagnosticsBuilderProgram>;
let fileListChanged = false;
// Program and builder to emit/check files
let heapUsed = process.memoryUsage().heapUsed;
return {
file,
build,
getProgram: () => getBuilderProgram().getProgram()
};
function file(file: Vinyl) {
// support gulp-sourcemaps
if ((<any>file).sourceMap) {
emitSourceMapsInStream = false;
}
fileListChanged = (!file.contents ? host.removeFile(file.path) : host.addFile(file)) || fileListChanged;
}
function getBuilderProgram() {
// Create/update the program
if (!watch) {
host.rootFiles = host.getFileNames();
host.options = compilerOptions;
watch = ts.createWatchProgram(host);
}
else if (fileListChanged) {
fileListChanged = false;
watch.updateRootFileNames(host.getFileNames());
}
return watch.getProgram();
}
function build(out: (file: Vinyl) => void, onError: (err: any) => void, token?: CancellationToken): Promise<any> {
const startTime = Date.now();
let toCheckSyntaxOf: ts.SourceFile | undefined;
let toCheckSemanticOf: ts.SourceFile | undefined;
let sourceFilesToCheck: ts.SourceFile[] | undefined;
let unrecoverableError = false;
let rootFileNames: string[];
let requireAffectedFileToBeRoot = watch === undefined;
// Check only root file names - as thats what earlier happened
let requireRootForOtherFiles = true;
let hasPendingEmit = true;
const tsToken = token ? CancellationToken.createTsCancellationToken(token) : CancellationToken.NoneTsToken;
let builderProgram: ts.EmitAndSemanticDiagnosticsBuilderProgram;
return new Promise(resolve => {
rootFileNames = host.getFileNames();
// Create/update the program
builderProgram = getBuilderProgram();
host.updateWithProgram(builderProgram);
// Schedule next work
sourceFilesToCheck = builderProgram.getSourceFiles().slice();
scheduleWork(config, resolve, getNextWork, tsToken);
}).then(() => {
// print stats
heapUsed = printStats(config, heapUsed, startTime);
});
function getSyntacticDiagnostics(file: ts.SourceFile, token: ts.CancellationToken) {
return builderProgram.getSyntacticDiagnostics(file, token);
}
function getSemanticDiagnostics(file: ts.SourceFile, token: ts.CancellationToken) {
return builderProgram.getSemanticDiagnostics(file, token);
}
function emitNextAffectedFile(_arg: undefined, token: ts.CancellationToken): EmitResult {
const emitVinyls: EmitVinyls = {};
const result = builderProgram.emitNextAffectedFile(writeFile, token);
if (!result) {
return undefined;
}
const { result: { diagnostics }, affected } = result;
const { files } = getEmitResult(
config,
emitSourceMapsInStream,
originalCompilerOptions,
compilerOptions,
source => {
const vinyl = host.getFile(source);
return vinyl ? (<Buffer>vinyl.contents).toString("utf8") : ts.sys.readFile(source);
},
source => host.getFile(source),
emitVinyls,
/*ignoreSignatureAndUseDeclarationFile*/ true
);
return { affected, files, diagnostics };
function writeFile(fileName: string, text: string, _writeByteOrderMark: boolean, _onError: (message: string) => void, sourceFiles: ts.SourceFile[]) {
updateEmitVinyl(config, emitVinyls, sourceFiles.length === 1 && !config._emitWithoutBasePath ? host.getFile(sourceFiles[0].fileName).base : undefined, fileName, text);
}
}
function setFileToCheck(file: ts.SourceFile, requiresToBeRoot: boolean) {
if (!requiresToBeRoot || rootFileNames.findIndex(fileName => fileName === file.fileName) !== -1) {
utils.maps.unorderedRemoveItem(rootFileNames, file.fileName);
toCheckSyntaxOf = toCheckSemanticOf = file;
return true;
}
return false;
}
function getNextWork(): Work | undefined {
// If unrecoverable error, stop
if (unrecoverableError) {
logCancel(config);
return undefined;
}
// someone told us to stop this
if (tsToken.isCancellationRequested()) {
logCancel(config);
return undefined;
}
// SyntaxCheck
if (toCheckSyntaxOf) {
const work: Work<ts.SourceFile, ReadonlyArray<ts.Diagnostic>> = {
arg: toCheckSyntaxOf,
action: getSyntacticDiagnostics,
onfulfilled: diagnostics => {
printDiagnostics(config, diagnostics, onError);
unrecoverableError = diagnostics.length > 0;
}
};
toCheckSyntaxOf = undefined;
_log(config, Topics.CheckSyntax, work.arg.fileName);
return work;
}
// check semantics
if (toCheckSemanticOf) {
const work: Work<ts.SourceFile, ReadonlyArray<ts.Diagnostic>> = {
arg: toCheckSemanticOf,
action: getSemanticDiagnostics,
onfulfilled: diagnostics => printDiagnostics(config, diagnostics, onError)
};
toCheckSemanticOf = undefined;
_log(config, Topics.CheckSemantics, work.arg.fileName);
return work;
}
// If there are pending files to emit, emit next file
if (hasPendingEmit) {
const work: Work<undefined, EmitResult> = {
arg: undefined,
action: emitNextAffectedFile,
onfulfilled: emitResult => {
if (!emitResult) {
// All emits complete, remove the toEmitFromBuilderState and
// set it as useOld
hasPendingEmit = false;
return;
}
const { affected, diagnostics, files } = emitResult;
if (isAffectedProgram(affected)) {
// Whole program is changed, syntax check for all the files with requireAffectedFileToBeRoot setting
requireRootForOtherFiles = requireAffectedFileToBeRoot;
}
else if (utils.maps.unorderedRemoveItem(sourceFilesToCheck, affected as ts.SourceFile)) {
// Set affected file to be checked for syntax and semantics
setFileToCheck(affected as ts.SourceFile, /*requiresToBeRoot*/ requireAffectedFileToBeRoot);
}
printDiagnostics(config, diagnostics, onError);
outFiles(config, files, out);
}
};
return work;
}
// Check remaining (non-affected files)
while (sourceFilesToCheck.length) {
const file = sourceFilesToCheck.pop();
// Check only root file names - as thats what earlier happened
if (setFileToCheck(file, requireRootForOtherFiles)) {
return getNextWork();
}
}
// Report global diagnostics
printDiagnostics(config, builderProgram.getOptionsDiagnostics(), onError);
printDiagnostics(config, builderProgram.getGlobalDiagnostics(), onError);
// Done
return undefined;
}
}
}
function isAffectedProgram(affected: ts.SourceFile | ts.Program): affected is ts.Program {
return (affected as ts.SourceFile).kind !== ts.SyntaxKind.SourceFile
}
interface VinylFile {
file: Vinyl;
text: string;
mtime: Date;
name: string;
}
function getTextOfVinyl(file: Vinyl) {
return (<Buffer>file.contents).toString("utf8");
}
function createVinylFile(file: Vinyl): VinylFile {
return {
file,
name: normalize(file.path),
text: getTextOfVinyl(file),
mtime: file.stat.mtime,
};
}
interface Host extends ts.WatchCompilerHostOfFilesAndCompilerOptions<ts.EmitAndSemanticDiagnosticsBuilderProgram> {
addFile(file: Vinyl): boolean;
removeFile(filename: string): boolean;
getFile(filename: string): Vinyl;
getFileNames(): string[];
updateWithProgram(program: ts.EmitAndSemanticDiagnosticsBuilderProgram): void;
}
function createHost(options: ts.CompilerOptions, noFileSystemLookup: boolean): Host {
const watchedFiles = utils.maps.createMultiMap<ts.FileWatcherCallback>();
const watchedDirectories = utils.maps.createMultiMap<ts.DirectoryWatcherCallback>();
const watchedDirectoriesRecursive = utils.maps.createMultiMap<ts.DirectoryWatcherCallback>();
const files = utils.maps.createMap<VinylFile>();
const useCaseSensitiveFileNames = ts.sys.useCaseSensitiveFileNames;
const getCanonicalFileName: (s: string) => string = useCaseSensitiveFileNames ?
((fileName) => fileName) :
((fileName) => fileName.toLowerCase());
const otherFiles = utils.maps.createMap<Vinyl>();
return {
addFile,
removeFile,
getFile,
getFileNames,
updateWithProgram,
createHash: data => ts.sys.createHash(data),
useCaseSensitiveFileNames: () => useCaseSensitiveFileNames,
getNewLine: () => ts.sys.newLine,
getCurrentDirectory,
getDefaultLibFileName,
getDefaultLibLocation,
fileExists,
readFile,
directoryExists,
getDirectories,
readDirectory,
realpath: resolvePath,
watchFile,
watchDirectory,
createProgram: ts.createEmitAndSemanticDiagnosticsBuilderProgram,
// To be filled in later
rootFiles: [],
options: undefined,
};
function toPath(filename: string) {
return resolvePath(getCanonicalFileName(normalize(filename)));
}
function addFile(file: Vinyl) {
const filename = toPath(file.path);
const existingFile = files.get(filename);
if (existingFile) {
const mtime = file.stat.mtime;
if (existingFile.mtime !== mtime) {
existingFile.mtime = mtime;
const text = getTextOfVinyl(file);
if (file.text !== text) {
existingFile.text = text;
invokeFileWatcher(filename, ts.FileWatcherEventKind.Changed);
}
}
}
else {
otherFiles.delete(filename);
files.set(filename, createVinylFile(file));
invokeFileWatcher(filename, ts.FileWatcherEventKind.Created);
invokeDirectoryWatcher(path.dirname(filename), filename);
return true;
}
}
function removeFile(filename: string) {
filename = toPath(filename);
if (files.has(filename)) {
files.delete(filename);
invokeFileWatcher(filename, ts.FileWatcherEventKind.Deleted);
invokeDirectoryWatcher(path.dirname(filename), filename);
return true;
}
}
function getFile(filename: string) {
filename = toPath(filename);
const file = files.get(filename);
return file && file.file || otherFiles.get(filename);
}
function getFileNames() {
const result: string[] = [];
files.forEach(file => {
result.push(file.name);
});
return result;
}
function updateWithProgram(program: ts.EmitAndSemanticDiagnosticsBuilderProgram) {
otherFiles.forEach((file, filename) => {
if (!program.getSourceFile(file.path)) {
otherFiles.delete(filename);
}
});
}
function invokeWatcherCallbacks<T extends (fileName: string, anotherArg?: ts.FileWatcherEventKind) => void>(callbacks: T[], fileName: string, eventKind?: ts.FileWatcherEventKind) {
if (callbacks) {
// The array copy is made to ensure that even if one of the callback removes the callbacks,
// we dont miss any callbacks following it
const cbs = callbacks.slice();
for (const cb of cbs) {
cb(fileName, eventKind);
}
}
}
function invokeFileWatcher(fileName: string, eventKind: ts.FileWatcherEventKind) {
invokeWatcherCallbacks(watchedFiles.get(fileName), fileName, eventKind);
}
function invokeDirectoryWatcher(directory: string, fileAddedOrRemoved: string) {
invokeWatcherCallbacks(watchedDirectories.get(directory), fileAddedOrRemoved);
invokeRecursiveDirectoryWatcher(directory, fileAddedOrRemoved);
}
function invokeRecursiveDirectoryWatcher(directory: string, fileAddedOrRemoved: string) {
invokeWatcherCallbacks(watchedDirectoriesRecursive.get(directory), fileAddedOrRemoved);
const basePath = path.dirname(directory);
if (directory !== basePath) {
invokeRecursiveDirectoryWatcher(basePath, fileAddedOrRemoved);
}
}
function readFile(path: string, encoding?: string) {
const canonicalName = toPath(path);
const file = files.get(canonicalName);
if (file) {
return file.text;
}
if (noFileSystemLookup) {
return undefined;
}
const text = ts.sys.readFile(path, encoding);
if (text !== undefined) {
otherFiles.set(canonicalName, new Vinyl({
path,
contents: new Buffer(text),
base: options.outDir,
stat: statSync(path)
}));
}
return text;
}
function fileExists(path: string) {
return !!files.get(toPath(path)) || !noFileSystemLookup && ts.sys.fileExists(path);
}
function directoryExists(dir: string) {
if (!noFileSystemLookup) {
return ts.sys.directoryExists(dir);
}
dir = toPath(dir)
return utils.maps.forEachEntry(files, (_file, filename) => dir === path.dirname(filename));
}
function getCurrentDirectory() {
return process.cwd();
}
function getDirectories(path: string): string[] {
return !noFileSystemLookup && ts.sys.getDirectories(path);
}
function readDirectory(path: string, extensions?: ReadonlyArray<string>, exclude?: ReadonlyArray<string>, include?: ReadonlyArray<string>, depth?: number): string[] {
return !noFileSystemLookup && ts.sys.readDirectory(path, extensions, exclude, include, depth);
}
// NO fs watch
function createWatcher<T>(path: string, map: utils.maps.MultiMap<T>, callback: T): ts.FileWatcher {
path = toPath(path);
map.add(path, callback);
return {
close: () => {
map.remove(path, callback);
}
};
}
function watchFile(path: string, callback: ts.FileWatcherCallback, pollingInterval?: number) {
return createWatcher(path, watchedFiles, callback);
}
function watchDirectory(path: string, callback: ts.DirectoryWatcherCallback, recursive?: boolean) {
return createWatcher(path, recursive ? watchedDirectoriesRecursive : watchedDirectories, callback);
}
function resolvePath(path: string) {
return !noFileSystemLookup ? ts.sys.resolvePath(path) : path;
}
}
} | the_stack |
import { isMobile } from "../../clientUtils/Util"
import * as React from "react"
import { observable, computed, action } from "mobx"
import { observer } from "mobx-react"
import { Bounds, DEFAULT_BOUNDS } from "../../clientUtils/Bounds"
import { LoadingIndicator } from "../loadingIndicator/LoadingIndicator"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { faDownload } from "@fortawesome/free-solid-svg-icons/faDownload"
import classNames from "classnames"
import { BlankOwidTable, OwidTable } from "../../coreTable/OwidTable"
export interface DownloadTabManager {
idealBounds?: Bounds
staticSVG: string
displaySlug: string
baseUrl?: string
queryStr?: string
table?: OwidTable
externalCsvLink?: string // Todo: we can ditch this once rootTable === externalCsv (currently not quite the case for Covid Explorer)
}
interface DownloadTabProps {
bounds?: Bounds
manager: DownloadTabManager
}
declare let Blob: any
const polyfillToBlob = (): void => {
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob#Polyfill
Object.defineProperty(HTMLCanvasElement.prototype, "toBlob", {
value: function (
callback: (blob: Blob) => void,
type: string,
quality: any
) {
const binStr = atob(
(this as HTMLCanvasElement)
.toDataURL(type, quality)
.split(",")[1]
)
const len = binStr.length
const arr = new Uint8Array(len)
for (let i = 0; i < len; i++) {
arr[i] = binStr.charCodeAt(i)
}
callback(new Blob([arr], { type: type || "image/png" }))
},
})
}
// Wrapped because JSDOM does not support this method yet:
// https://stackoverflow.com/questions/52968969/jest-url-createobjecturl-is-not-a-function/56643520#56643520
const createObjectURL = (obj: any): string =>
URL.createObjectURL ? URL.createObjectURL(obj) : ""
@observer
export class DownloadTab extends React.Component<DownloadTabProps> {
@computed private get idealBounds(): Bounds {
return this.manager.idealBounds ?? DEFAULT_BOUNDS
}
@computed private get bounds(): Bounds {
return this.props.bounds ?? DEFAULT_BOUNDS
}
@computed private get targetWidth(): number {
return this.idealBounds.width
}
@computed private get targetHeight(): number {
return this.idealBounds.height
}
@computed private get manager(): DownloadTabManager {
return this.props.manager
}
@observable private svgBlob?: Blob
@observable private svgDownloadUrl?: string
@observable private svgPreviewUrl?: string
@observable private pngBlob?: Blob
@observable private pngDownloadUrl?: string
@observable private pngPreviewUrl?: string
@observable private isReady: boolean = false
@action.bound private export(): void {
if (!HTMLCanvasElement.prototype.toBlob) polyfillToBlob()
this.createSvg()
const reader = new FileReader()
reader.onload = (ev: any): void => {
this.svgPreviewUrl = ev.target.result as string
this.tryCreatePng(this.svgPreviewUrl)
}
reader.readAsDataURL(this.svgBlob as Blob)
}
@action.bound private createSvg(): void {
const staticSVG = this.manager.staticSVG
this.svgBlob = new Blob([staticSVG], {
type: "image/svg+xml;charset=utf-8",
})
this.svgDownloadUrl = createObjectURL(this.svgBlob)
}
@action.bound private tryCreatePng(svgPreviewUrl: string): void {
const { targetWidth, targetHeight } = this
// Client-side SVG => PNG export. Somewhat experimental, so there's a lot of cross-browser fiddling and fallbacks here.
const img = new Image()
img.onload = (): void => {
try {
const canvas = document.createElement("canvas")
// We draw the chart at 4x res then scale it down again -- much better text quality
canvas.width = targetWidth * 4
canvas.height = targetHeight * 4
const ctx = canvas.getContext("2d", {
alpha: false,
}) as CanvasRenderingContext2D
ctx.imageSmoothingEnabled = false
ctx.setTransform(4, 0, 0, 4, 0, 0)
ctx.drawImage(img, 0, 0)
this.pngPreviewUrl = canvas.toDataURL("image/png")
canvas.toBlob((blob) => {
this.pngBlob = blob as Blob
this.pngDownloadUrl = createObjectURL(blob)
this.markAsReady()
})
} catch (e) {
console.error(e)
this.markAsReady()
}
}
img.onerror = (err): void => {
console.error(JSON.stringify(err))
this.markAsReady()
}
img.src = svgPreviewUrl
}
@action.bound private markAsReady(): void {
this.isReady = true
}
@computed private get fallbackPngUrl(): string {
return `${this.manager.baseUrl || ""}.png${this.manager.queryStr || ""}`
}
@computed private get baseFilename(): string {
return this.manager.displaySlug
}
@computed private get inputTable(): OwidTable {
return this.manager.table ?? BlankOwidTable()
}
private onCsvDownload(ev: React.MouseEvent<HTMLAnchorElement>): void {
const { manager, inputTable } = this
const csvFilename = manager.displaySlug + ".csv"
const csv = inputTable.toPrettyCsv() || ""
// IE11 compatibility
const downloadLink = document.createElement("a")
downloadLink.setAttribute(
"href",
`data:text/csv,` + encodeURIComponent(csv)
)
downloadLink.setAttribute("download", csvFilename)
downloadLink.click()
}
@computed private get csvButton(): JSX.Element {
const { manager } = this
const externalCsvLink = manager.externalCsvLink
const csvFilename = manager.displaySlug + ".csv"
const props = externalCsvLink
? {
href: externalCsvLink,
download: csvFilename,
}
: {
onClick: (ev: React.MouseEvent<HTMLAnchorElement>): void =>
this.onCsvDownload(ev),
}
return (
<div className="download-csv" style={{ maxWidth: "100%" }}>
<p>
Download a CSV file containing all data used in this
visualization:
</p>
<a
className="btn btn-primary"
data-track-note="chart-download-csv"
{...props}
>
<FontAwesomeIcon icon={faDownload} /> {csvFilename}
</a>
</div>
)
}
private renderReady(): JSX.Element {
const {
targetWidth,
targetHeight,
svgPreviewUrl,
svgDownloadUrl,
baseFilename,
bounds,
} = this
const pngPreviewUrl = this.pngPreviewUrl || this.fallbackPngUrl
const pngDownloadUrl = this.pngDownloadUrl || pngPreviewUrl
let previewWidth: number
let previewHeight: number
const boundScalar = 0.4
if (bounds.width / bounds.height > targetWidth / targetHeight) {
previewHeight = bounds.height * boundScalar
previewWidth = (targetWidth / targetHeight) * previewHeight
} else {
previewWidth = bounds.width * boundScalar
previewHeight = (targetHeight / targetWidth) * previewWidth
}
const imgStyle = {
minWidth: previewWidth,
minHeight: previewHeight,
maxWidth: previewWidth,
maxHeight: previewHeight,
border: "1px solid #ccc",
}
const asideStyle = {
maxWidth: previewWidth,
}
return (
<React.Fragment>
<div className="img-downloads">
<a
key="png"
href={pngDownloadUrl}
download={baseFilename + ".png"}
data-track-note="chart-download-png"
>
<div>
<img src={pngPreviewUrl} style={imgStyle} />
<aside style={asideStyle}>
<h2>Save as .png</h2>
<p>
A standard image of the visualization that
can be used in presentations or other
documents.
</p>
</aside>
</div>
</a>
<a
key="svg"
href={svgDownloadUrl}
download={baseFilename + ".svg"}
data-track-note="chart-download-svg"
>
<div>
<img src={svgPreviewUrl} style={imgStyle} />
<aside style={asideStyle}>
<h2>Save as .svg</h2>
<p>
A vector format image useful for further
redesigning the visualization with vector
graphic software.
</p>
</aside>
</div>
</a>
</div>
{this.csvButton}
</React.Fragment>
)
}
componentDidMount(): void {
this.export()
}
componentWillUnmount(): void {
if (this.pngDownloadUrl !== undefined)
URL.revokeObjectURL(this.pngDownloadUrl)
if (this.svgDownloadUrl !== undefined)
URL.revokeObjectURL(this.svgDownloadUrl)
}
render(): JSX.Element {
return (
<div
className={classNames("DownloadTab", {
mobile: isMobile(),
})}
style={{ ...this.bounds.toCSS(), position: "absolute" }}
>
{this.isReady ? (
this.renderReady()
) : (
<LoadingIndicator color="#000" />
)}
</div>
)
}
} | the_stack |
declare const describe: any;
declare const it: any;
declare const expect: any;
declare const beforeEach: any;
import * as Immutable from "immutable";
import * as moment from "moment";
import Moment = moment.Moment;
import { collection } from "../src/collection";
import { duration } from "../src/duration";
import { event } from "../src/event";
import { avg, sum } from "../src/functions";
import { AggregationSpec } from "../src/groupedcollection";
import { index, Index } from "../src/index";
import { sorted } from "../src/sortedcollection";
import { time, Time } from "../src/time";
import { TimeRange } from "../src/timerange";
import { TimeAlignment } from "../src/types";
describe("Collection", () => {
describe("Creation", () => {
it("can remap keys", () => {
const c1 = collection(
Immutable.List([
event(time("2015-04-22T03:30:00Z"), Immutable.Map({ a: 5, b: 6 })),
event(time("2015-04-22T02:30:00Z"), Immutable.Map({ a: 4, b: 2 }))
])
);
const c2 = c1.mapKeys<TimeRange>(t =>
t.toTimeRange(duration("1h"), TimeAlignment.Middle)
);
expect(
c2
.at(0)
.getKey()
.toUTCString()
).toBe("[Wed, 22 Apr 2015 03:00:00 GMT, Wed, 22 Apr 2015 04:00:00 GMT]");
});
it("can make an empty collection and add events to it", () => {
const c = collection(
Immutable.List([
event(time("2015-04-22T03:30:00Z"), Immutable.Map({ a: 5, b: 6 })),
event(time("2015-04-22T02:30:00Z"), Immutable.Map({ a: 4, b: 2 }))
])
);
expect(c.size()).toEqual(2);
expect(c.at(0).get("a")).toEqual(5);
expect(c.at(1).get("a")).toEqual(4);
});
it("can make a collection from another collection", () => {
const timestamp1 = new Time("2015-04-22T03:30:00Z");
const timestamp2 = new Time("2015-04-22T02:30:00Z");
const e1 = event(timestamp1, Immutable.Map({ a: 5, b: 6 }));
const e2 = event(timestamp2, Immutable.Map({ a: 4, b: 2 }));
const c1 = collection()
.addEvent(e1)
.addEvent(e2);
const c2 = collection(c1);
expect(c2.size()).toEqual(2);
expect(c2.at(0).get("a")).toEqual(5);
expect(c2.at(1).get("a")).toEqual(4);
});
it("make a collection from List", () => {
const e1 = event(time("2015-04-22T03:30:00Z"), Immutable.Map({ a: 5, b: 6 }));
const e2 = event(time("2015-04-22T02:30:00Z"), Immutable.Map({ a: 4, b: 2 }));
const eventList = Immutable.List([e1, e2]);
const c = collection(eventList);
expect(c.size()).toEqual(2);
expect(c.at(0).get("a")).toEqual(5);
expect(c.at(1).get("a")).toEqual(4);
});
});
describe("Conversion", () => {
it("can convert the collection to a string", () => {
const e1 = event(time("2015-04-22T03:30:00Z"), Immutable.Map({ a: 5, b: 6 }));
const e2 = event(time("2015-04-22T02:30:00Z"), Immutable.Map({ a: 4, b: 2 }));
const c = collection(Immutable.List([e1, e2]));
const expected =
// tslint:disable-next-line:max-line-length
'[{"time":1429673400000,"data":{"a":5,"b":6}},{"time":1429669800000,"data":{"a":4,"b":2}}]';
expect(c.toString()).toEqual(expected);
});
});
describe("Persistent changes", () => {
it("can add an event and de-dup with default latest wins", () => {
const timestamp1 = time("2015-04-22T03:30:00Z");
const timestamp2 = time("2015-04-22T02:30:00Z");
const e1 = event(timestamp1, Immutable.Map({ a: 5, b: 6 }));
const e2 = event(timestamp2, Immutable.Map({ a: 4, b: 2 }));
const e3 = event(timestamp2, Immutable.Map({ a: 6, b: 3 }));
const c = collection<Time>()
.addEvent(e1)
.addEvent(e2)
.addEvent(e3, true);
expect(c.size()).toEqual(2);
expect(c.at(1).get("a")).toEqual(6);
});
it("can add an event and de-dup with custom function", () => {
const timestamp1 = time("2015-04-22T03:30:00Z");
const timestamp2 = time("2015-04-22T02:30:00Z");
const e1 = event(timestamp1, Immutable.Map({ a: 5, b: 6 }));
const e2 = event(timestamp2, Immutable.Map({ a: 4, b: 2 }));
const e3 = event(timestamp2, Immutable.Map({ a: 6, b: 3 }));
const c = collection<Time>()
.addEvent(e1)
.addEvent(e2)
.addEvent(e3, events => {
const a = events.reduce((total, e) => total + e.get("a"), 0);
return event(timestamp2, Immutable.Map({ a }));
});
expect(c.size()).toEqual(2);
expect(c.at(1).get("a")).toEqual(10);
});
it("can add an event and de-dup multiple existing duplicates", () => {
const timestamp1 = time("2015-04-22T03:30:00Z");
const timestamp2 = time("2015-04-22T02:30:00Z");
const e1 = event(timestamp1, Immutable.Map({ a: 5, b: 6 }));
const e2 = event(timestamp2, Immutable.Map({ a: 4, b: 2 }));
const e3 = event(timestamp2, Immutable.Map({ a: 6, b: 3 }));
const e4 = event(timestamp2, Immutable.Map({ a: 7, b: 1 }));
const c = collection<Time>()
.addEvent(e1)
.addEvent(e2)
.addEvent(e3);
const c2 = c.addEvent(e4, events => {
const a = events.reduce((total, e) => total + e.get("a"), 0);
return event(timestamp2, Immutable.Map({ a }));
});
expect(c.size()).toEqual(3);
expect(c.at(0).get("a")).toEqual(5);
expect(c.at(1).get("a")).toEqual(4);
expect(c.at(2).get("a")).toEqual(6);
expect(c2.size()).toEqual(2);
expect(c2.at(0).get("a")).toEqual(5);
expect(c2.at(1).get("a")).toEqual(17);
});
it("can use setEvents to replace all events in the collection", () => {
const timestamp1 = time("2015-04-22T03:30:00Z");
const timestamp2 = time("2015-04-22T02:30:00Z");
const e0 = event(timestamp1, Immutable.Map({ a: 1, b: 2 }));
const c = collection<Time>().addEvent(e0);
expect(c.size()).toEqual(1);
// events
const e1 = event(timestamp1, Immutable.Map({ a: 5, b: 6 }));
const e2 = event(timestamp2, Immutable.Map({ a: 4, b: 2 }));
const e3 = event(timestamp2, Immutable.Map({ a: 3, b: 2 }));
const c2 = c.setEvents(Immutable.List([e1, e2, e3]));
expect(c2.size()).toEqual(3);
expect(c2.at(0).get("a")).toEqual(5);
expect(c2.at(1).get("a")).toEqual(4);
expect(c2.at(2).get("a")).toEqual(3);
});
});
describe("Query", () => {
it("can return the number of valid events", () => {
const timestamp1 = new Time("2015-04-22T01:30:00Z");
const timestamp2 = new Time("2015-04-22T02:30:00Z");
const timestamp3 = new Time("2015-04-22T03:30:00Z");
const e1 = event(timestamp1, Immutable.Map({ a: 5, b: 6 }));
const e2 = event(timestamp2, Immutable.Map({ a: null, b: 2 }));
const e3 = event(timestamp3, Immutable.Map({ a: 4, b: 2 }));
const c = collection<Time>(Immutable.List([e1, e2, e3]));
expect(c.size()).toEqual(3);
expect(c.sizeValid("a")).toEqual(2);
});
it("can return the timerange covered by the collection", () => {
const t1 = time("2015-04-22T02:30:00Z");
const t2 = time("2015-04-22T01:30:00Z");
const t3 = time("2015-04-22T03:30:00Z");
const e1 = event(t1, Immutable.Map({ a: 8 }));
const e2 = event(t2, Immutable.Map({ a: 3 }));
const e3 = event(t3, Immutable.Map({ a: 5 }));
const timerange = collection(Immutable.List([e1, e2, e3])).timerange();
expect(timerange.duration()).toEqual(7200000);
expect(timerange.begin()).toEqual(t2.timestamp());
expect(timerange.end()).toEqual(t3.timestamp());
});
it("can access events using at() and atKey()", () => {
const timestamp1 = time("2015-04-22T01:30:00Z");
const timestamp2 = time("2015-04-22T02:30:00Z");
const timestamp3 = time("2015-04-22T03:30:00Z");
const e1 = event(timestamp1, Immutable.Map({ a: 1 }));
const e2 = event(timestamp2, Immutable.Map({ a: 2 }));
const e3 = event(timestamp3, Immutable.Map({ a: 3 }));
const c = collection(Immutable.List([e1, e2, e2]));
expect(c.at(1).get("a")).toEqual(2);
expect(
c
.atKey(timestamp2)
.get(0)
.get("a")
).toEqual(2);
});
it("can return the first and last events", () => {
const t1 = new Time("2015-04-22T02:30:00Z");
const t2 = new Time("2015-04-22T01:30:00Z");
const t3 = new Time("2015-04-22T03:30:00Z");
const e1 = event(t1, Immutable.Map({ a: 8 }));
const e2 = event(t2, Immutable.Map({ a: 3 }));
const e3 = event(t3, Immutable.Map({ a: 5 }));
const c = collection(Immutable.List([e1, e2, e3]));
expect(c.firstEvent().get("a")).toEqual(8);
expect(c.lastEvent().get("a")).toEqual(5);
});
it("can determine if a collection is chronological", () => {
const unorderedEvents = Immutable.List([
event(time("2015-04-22T03:31:00Z"), Immutable.Map({ in: 3, out: 4 })),
event(time("2015-04-22T03:30:00Z"), Immutable.Map({ in: 1, out: 2 })),
event(time("2015-04-22T03:32:00Z"), Immutable.Map({ in: 5, out: 6 }))
]);
const unsortedCollection = collection(unorderedEvents);
expect(unsortedCollection.isChronological()).toBeFalsy();
const sortedCollection = unsortedCollection.sortByKey();
expect(sortedCollection.isChronological()).toBeTruthy();
});
});
describe("Filtering", () => {
it("can filter a list of events", () => {
const timestamp1 = new Time("2015-04-22T01:30:00Z");
const timestamp2 = new Time("2015-04-22T02:30:00Z");
const timestamp3 = new Time("2015-04-22T03:30:00Z");
const e1 = event(timestamp1, Immutable.Map({ a: 1 }));
const e2 = event(timestamp2, Immutable.Map({ a: 2 }));
const e3 = event(timestamp3, Immutable.Map({ a: 3 }));
const c = collection(Immutable.List([e1, e2, e3]));
const filtered = c.filter(e => e.get("a") <= 2);
expect(filtered.size()).toEqual(2);
});
});
describe("Side effects", () => {
it("can iterate over the events", () => {
const timestamp1 = new Time("2015-04-22T01:30:00Z");
const timestamp2 = new Time("2015-04-22T02:30:00Z");
const timestamp3 = new Time("2015-04-22T03:30:00Z");
const e1 = event(timestamp1, Immutable.Map({ a: 1 }));
const e2 = event(timestamp2, Immutable.Map({ a: 2 }));
const e3 = event(timestamp3, Immutable.Map({ a: 3 }));
const c = collection(Immutable.List([e1, e2, e3]));
let total = 0;
c.forEach(e => {
total = total + e.get("a");
});
expect(total).toEqual(6);
});
});
describe("Sequence", () => {
it("can map over the events", () => {
const timestamp1 = new Time("2015-04-22T01:30:00Z");
const timestamp2 = new Time("2015-04-22T02:30:00Z");
const timestamp3 = new Time("2015-04-22T03:30:00Z");
const e1 = event(timestamp1, Immutable.Map({ a: 1 }));
const e2 = event(timestamp2, Immutable.Map({ a: 2 }));
const e3 = event(timestamp3, Immutable.Map({ a: 3 }));
const c = collection(Immutable.List([e1, e2, e3]));
let i = 1;
const remapped = c.map(e => {
return event(e.getKey(), Immutable.Map({ a: 3 * i++ }));
});
expect(remapped.at(0).get("a")).toEqual(3);
expect(remapped.at(1).get("a")).toEqual(6);
expect(remapped.at(2).get("a")).toEqual(9);
});
/*
it("can filter the collection", () => {
const t1 = new Time("2015-04-22T02:30:00Z");
const t2 = new Time("2015-04-22T01:30:00Z");
const t3 = new Time("2015-04-22T03:30:00Z");
const e1 = event(t1, { a: 8 });
const e2 = event(t2, { a: 3 });
const e3 = event(t3, { a: 5 });
const filtered = collection<Time>()
.addEvent(e1)
.addEvent(e2)
.addEvent(e3)
.filter((e) => e.get("a") < 8);
expect(filtered.size()).toEqual(2);
});
*/
it("can sort by time", () => {
const timestamp1 = new Time("2015-04-22T02:30:00Z");
const timestamp2 = new Time("2015-04-22T01:30:00Z");
const timestamp3 = new Time("2015-04-22T03:30:00Z");
const e1 = event(timestamp1, Immutable.Map({ a: 1 }));
const e2 = event(timestamp2, Immutable.Map({ a: 2 }));
const e3 = event(timestamp3, Immutable.Map({ a: 3 }));
const sortedCollection = collection<Time>()
.addEvent(e1)
.addEvent(e2)
.addEvent(e3)
.sortByKey();
expect(sortedCollection.at(0).get("a")).toEqual(2);
expect(sortedCollection.at(1).get("a")).toEqual(1);
expect(sortedCollection.at(2).get("a")).toEqual(3);
});
it("can sort by field", () => {
const timestamp1 = time("2015-04-22T02:30:00Z");
const timestamp2 = time("2015-04-22T01:30:00Z");
const timestamp3 = time("2015-04-22T03:30:00Z");
const e1 = event(timestamp1, Immutable.Map({ a: 8 }));
const e2 = event(timestamp2, Immutable.Map({ a: 3 }));
const e3 = event(timestamp3, Immutable.Map({ a: 5 }));
const sortedCollection = collection<Time>()
.addEvent(e1)
.addEvent(e2)
.addEvent(e3)
.sort("a");
expect(sortedCollection.at(0).get("a")).toEqual(3);
expect(sortedCollection.at(1).get("a")).toEqual(5);
expect(sortedCollection.at(2).get("a")).toEqual(8);
});
});
describe("Aggregation", () => {
const e1 = event(time("2015-04-22T02:30:00Z"), Immutable.Map({ a: 8, b: 2 }));
const e2 = event(time("2015-04-22T01:30:00Z"), Immutable.Map({ a: 3, b: 1 }));
const e3 = event(time("2015-04-22T03:30:00Z"), Immutable.Map({ a: 5, b: 5 }));
const test = collection<Time>()
.addEvent(e1)
.addEvent(e2)
.addEvent(e3);
it("can find the first event", () => {
expect(test.first("a")).toEqual(8);
expect(test.first(["a", "b"])).toEqual({ a: 8, b: 2 });
});
it("can find the last event", () => {
expect(test.last("a")).toEqual(5);
expect(test.last(["a", "b"])).toEqual({ a: 5, b: 5 });
});
it("can sum events", () => {
expect(test.sum("a")).toEqual(16);
expect(test.sum(["a"])).toEqual({ a: 16 });
expect(test.sum(["a", "b"])).toEqual({ a: 16, b: 8 });
});
it("can average events", () => {
expect(test.avg("a")).toEqual(5.333333333333333);
expect(test.avg(["a"])).toEqual({ a: 5.333333333333333 });
expect(test.avg(["a", "b"])).toEqual({ a: 5.333333333333333, b: 2.6666666666666665 });
});
it("can find max events", () => {
expect(test.max("a")).toEqual(8);
expect(test.max(["a"])).toEqual({ a: 8 });
expect(test.max(["a", "b"])).toEqual({ a: 8, b: 5 });
});
it("can find min events", () => {
expect(test.min("a")).toEqual(3);
expect(test.min(["a"])).toEqual({ a: 3 });
expect(test.min(["a", "b"])).toEqual({ a: 3, b: 1 });
});
});
describe("Processing", () => {
it("can collapse events in a Collection", () => {
const timestamp1 = time("2015-04-22T02:30:00Z");
const timestamp2 = time("2015-04-22T03:30:00Z");
const timestamp3 = time("2015-04-22T04:30:00Z");
const e1 = event(timestamp1, Immutable.Map({ a: 5, b: 6 }));
const e2 = event(timestamp2, Immutable.Map({ a: 4, b: 2 }));
const e3 = event(timestamp2, Immutable.Map({ a: 6, b: 3 }));
const c = collection<Time>()
.addEvent(e1)
.addEvent(e2)
.addEvent(e3);
const c1 = c.collapse({
fieldSpecList: ["a", "b"],
fieldName: "ab",
reducer: sum(),
append: false
});
const c2 = c.collapse({
fieldSpecList: ["a", "b"],
fieldName: "ab",
reducer: avg(),
append: true
});
expect(c1.size()).toEqual(3);
expect(c1.at(0).get("ab")).toEqual(11);
expect(c1.at(1).get("ab")).toEqual(6);
expect(c1.at(2).get("ab")).toEqual(9);
expect(c1.at(0).get("a")).toBeUndefined();
expect(c2.size()).toEqual(3);
expect(c2.at(0).get("ab")).toEqual(5.5);
expect(c2.at(0).get("a")).toEqual(5);
});
it("can select fields from events in a Collection", () => {
const timestamp1 = time("2015-04-22T02:30:00Z");
const timestamp2 = time("2015-04-22T03:30:00Z");
const timestamp3 = time("2015-04-22T04:30:00Z");
const e1 = event(timestamp1, Immutable.Map({ a: 5, b: 6, c: 7 }));
const e2 = event(timestamp2, Immutable.Map({ a: 4, b: 5, c: 6 }));
const e3 = event(timestamp2, Immutable.Map({ a: 6, b: 3, c: 2 }));
const c = collection<Time>()
.addEvent(e1)
.addEvent(e2)
.addEvent(e3);
const c1 = c.select({
fields: ["b", "c"]
});
expect(c1.size()).toEqual(3);
expect(c1.at(0).get("a")).toBeUndefined();
expect(c1.at(0).get("b")).toBe(6);
expect(c1.at(0).get("c")).toBe(7);
expect(c1.at(2).get("a")).toBeUndefined();
expect(c1.at(2).get("b")).toBe(3);
expect(c1.at(2).get("c")).toBe(2);
});
it("can use groupBy with a fieldSpec on a Collection", () => {
const t1 = time("2015-04-22T02:30:00Z");
const t2 = time("2015-04-22T03:30:00Z");
const t3 = time("2015-04-22T04:30:00Z");
const e1 = event(t1, Immutable.Map({ team: "raptors", a: 3, b: 1 }));
const e2 = event(t2, Immutable.Map({ team: "raptors", a: 4, b: 2 }));
const e3 = event(t1, Immutable.Map({ team: "dragons", a: 6, b: 3 }));
const e4 = event(t2, Immutable.Map({ team: "dragons", a: 7, b: 4 }));
const e5 = event(t3, Immutable.Map({ team: "dragons", a: 8, b: 5 }));
const events = Immutable.List([e1, e2, e3, e4, e5]);
const grouped = sorted(collection(events)).groupBy("team");
expect(grouped.get("raptors").avg("b")).toBe(1.5);
expect(grouped.get("dragons").avg("a")).toBe(7);
const agg = grouped.aggregate({
a_avg: ["a", avg()],
b_avg: ["b", avg()]
});
expect(agg.get("raptors").get("a_avg")).toBe(3.5); // 3, 4
expect(agg.get("dragons").get("b_avg")).toBe(4); // 3, 4, 5
});
it("can use groupBy with a fieldSpec on a Collection", () => {
const t1 = time("2015-04-22T02:30:00Z");
const t2 = time("2015-04-22T03:30:00Z");
const t3 = time("2015-04-22T04:30:00Z");
const e1 = event(t1, Immutable.Map({ team: "raptors", a: 3, b: 1 }));
const e2 = event(t2, Immutable.Map({ team: "raptors", a: 4, b: 2 }));
const e3 = event(t1, Immutable.Map({ team: "dragons", a: 6, b: 3 }));
const e4 = event(t2, Immutable.Map({ team: "dragons", a: 7, b: 4 }));
const e5 = event(t3, Immutable.Map({ team: "dragons", a: 8, b: 5 }));
const events = Immutable.List([e1, e2, e3, e4, e5]);
const grouped = sorted(collection(events)).groupBy("team");
expect(grouped.get("raptors").avg("b")).toBe(1.5);
expect(grouped.get("dragons").avg("a")).toBe(7);
const agg = grouped.aggregate({
a_avg: ["a", avg()],
b_avg: ["b", avg()]
});
expect(agg.get("raptors").get("a_avg")).toBe(3.5); // 3, 4
expect(agg.get("dragons").get("b_avg")).toBe(4); // 3, 4, 5
/*
const windowed = collection(events)
.window(period("1h"));
const agg2 = windowed
.aggregatePerWindow({
a: [ "a", avg() ],
b: [ "b", avg() ],
})
.mapKeys((key) => time(key.asTimerange().mid()));
console.log(">>", agg2.toJSON());
const agg3 = collection(events)
.groupBy("team")
.window(period("1h"))
.aggregatePerWindow({
a: [ "a", avg() ],
b: [ "b", avg() ],
})
.mapKeys((key) => time(key.asTimerange().mid()));
console.log("AGG3", agg3.toJSON())
const grpwin = grouped
.window(period("3h"));
const ungrouped = grouped.removeGrouping();
console.log("Ungrouped", ungrouped);
*/
});
});
}); | the_stack |
import utils from './util';
import { List, KeyboardKeyName, ClickType } from './event';
import ftr, {
ViewController, Div, Indep, View,
Limit, Button, Text, TextNode, Clip, _CVD,
} from './index';
import * as value from './value';
import {prop} from './ctr';
import {event, EventNoticer, Event, ListItem} from './event';
const TRANSITION_TIME = 400;
const g_navigationStack = new List<Navigation>();
var g_navigationInit_ok = false;
function get_valid_focus(nav: Navigation, focus_move: View | null) {
if (!nav) return null;
var view = nav.__meta__;
return focus_move && view.hasChild(focus_move) ? view.firstButton() : focus_move;
}
export enum Status {
INIT = -1,
FOREGROUND = 0,
BACKGROUND = 1,
}
/**
* @class Status
*/
class NavigationStatus extends ViewController {
private m_status: Status = Status.INIT; // 1=background,0=foreground,-1=init or exit
get status() { return this.m_status }
intoBackground(animate: number) { this.m_status = 1 }
intoForeground(animate: number) { this.m_status = 0 }
intoLeave(animate: number) { this.m_status = -1 }
}
/**
* @class Navigation
*/
export class Navigation extends NavigationStatus {
private m_stack = g_navigationStack;
private m_iterator: ListItem<Navigation> | null = null;
private m_focus_resume: View | null = null;
@event readonly onBackground: EventNoticer<Event<void, Navigation>>;
@event readonly onForeground: EventNoticer<Event<void, Navigation>>;
private static _navigationInit(nav: Navigation) {
if ( (nav as any).m_stack !== g_navigationStack || g_navigationInit_ok || !ftr.root) {
return;
}
// initialize
g_navigationInit_ok = true;
var root = ftr.root;
root.onBack.on(function(ev) {
var last = g_navigationStack.last;
while(last) {
if ( last.value.navigationBack() ) {
ev.cancelDefault(); // 取消默认动作
break;
}
last = last.prev;
}
});
root.onClick.on(function(ev) {
// console.log('onClick--', ev.keyboard );
if ( ev.type == ClickType.KEYBOARD ) { // 需要键盘产生的事件
var last = g_navigationStack.last;
if ( last ) {
last.value.navigationEnter(ev.sender);
}
}
});
root.onKeyDown.on(function(ev) {
var last = g_navigationStack.last;
if ( last ) {
var focus_move = ev.focusMove;
var nav = last.value;
switch(ev.keycode) {
case KeyboardKeyName.LEFT: // left
focus_move = nav.navigationLeft(focus_move);
break;
case KeyboardKeyName.UP: // up
focus_move = nav.navigationTop(focus_move);
break;
case KeyboardKeyName.RIGHT: // right
focus_move = nav.navigationRight(focus_move);
break;
case KeyboardKeyName.DOWN: // down
focus_move = nav.navigationDown(focus_move);
break;
case KeyboardKeyName.MENU: // menu
nav.navigationMenu();
default: return;
}
ev.focusMove = focus_move;
}
});
}
protected triggerBackground() {
this.trigger('Background');
}
protected triggerForeground() {
this.trigger('Foreground');
}
intoBackground(animate: number) {
super.intoBackground(animate);
this.triggerBackground();
}
intoForeground(animate: number) {
super.intoForeground(animate);
this.triggerForeground();
}
/**
* @func defaultFocus() 导航初始化时,返回一个焦点视图,重写这个函数
*/
defaultFocus(): View | null {
return null;
}
protected triggerRemove() {
if ( this.m_iterator ) { // force delete global nav stack
this.m_stack.del(this.m_iterator);
this.m_iterator = null;
}
return super.triggerRemove();
}
/**
* @func registerNavigation()
*/
registerNavigation(animate: number = 0) {
if ( !this.m_iterator ) { // No need to repeat it
Navigation._navigationInit(this);
this.m_iterator = this.m_stack.push(this);
// console.log('push_navigation()-----', this.m_stack.length);
ftr.lock(()=>{
var prev = (this.m_iterator as ListItem<Navigation>).prev;
if ( prev ) {
var focus = ftr.app.focusView;
prev.value.m_focus_resume = focus && prev.value.__meta__.hasChild(focus) ? focus : null;
prev.value.intoBackground(animate);
}
var view = this.defaultFocus();
if ( view ) {
view.focus();
}
this.intoForeground(animate);
});
}
}
/**
* @func unregisterNavigation(time, data)
*/
unregisterNavigation(animate: number = 0) {
if ( this.m_iterator ) {
// utils.assert(this.m_iterator, 'Bad iterator!');
var last = this.m_stack.last;
this.m_stack.del(this.m_iterator);
this.m_iterator = null;
if (!last || last.value !== this) return;
ftr.lock(()=>{
this.intoLeave(animate);
var last = this.m_stack.last;
if ( last ) {
if (last.value.m_focus_resume) {
last.value.m_focus_resume.focus();
}
last.value.intoForeground(animate);
}
});
}
}
/* 导航事件产生时系统会首先将事件发送给焦点视图,事件如果能成功传递到root,
* 那么事件最终将发送到达当前导航列表栈最顶端
*/
navigationBack() {
/* 这里如果返回false会继续往导航列表栈底端传递,直到返回true或到达栈底退出应用程序 */
return true;
}
navigationEnter(focus: View) {
// Rewrite this function to implement your logic
}
/**
* navigationTop()
* navigationDown()
* navigationLeft()
* navigationRight()
* 返回null时焦点不会发生任何改变
*/
navigationTop(focus_move: View | null) {
return get_valid_focus(this, focus_move);
}
navigationDown(focus_move: View | null) {
return get_valid_focus(this, focus_move);
}
navigationLeft(focus_move: View | null) {
return get_valid_focus(this, focus_move);
}
navigationRight(focus_move: View | null) {
return get_valid_focus(this, focus_move);
}
/* 按下menu按键时会调用 */
navigationMenu() {
// Rewrite this function to implement your logic
}
}
/**
* @func refresh_bar_style
*/
function refresh_bar_style(self: NavPageCollection, time: number) {
if ( self.IDs.navbar && self.length ) {
time = self.enableAnimate ? time : 0;
var navbar = self.navbar || {
height: 0, border: 0, backgroundColor: '#0000', borderColor: '#0000'
};
var toolbar = self.toolbar || {
height: 0, border: 0, backgroundColor: '#0000', borderColor: '#0000'
};
var navbarHidden = (self as any).$navbarHidden || (self as any).navbar.$hidden; // private props visit
var toolbarHidden = (self as any).$toolbarHidden || (self as any).toolbar.$hidden; // private props visit
var navbar_height = navbarHidden ? 0 : navbar.height + (self as any).m_padding as number + navbar.border; // private props visit
var toolbar_height = toolbarHidden ? 0 : toolbar.height + toolbar.border;
if ( time ) {
if ( !navbarHidden ) self.find('navbar').show();
if ( !toolbarHidden ) self.find('toolbar').show();
ftr.lock(()=>{
self.find('navbar').transition({
height: Math.max(0, navbar_height - navbar.border),
borderBottom: `${navbar.border} ${navbar.borderColor}`,
backgroundColor: navbar.backgroundColor,
time: time,
});
//console.log(navbar.backgroundColor, 'OKOK1', time);
self.find('toolbar').transition({
height: Math.max(0, toolbar_height - toolbar.border),
borderTop: `${toolbar.border} ${toolbar.borderColor}`,
backgroundColor: toolbar.backgroundColor,
time: time,
});
self.find('page').transition({ height: navbar_height + toolbar_height + '!', time: time }, ()=>{
if ( navbarHidden ) self.find('navbar').hide();
if ( toolbarHidden ) self.find('toolbar').hide();
});
});
} else {
var style = {
height: Math.max(0, navbar_height - navbar.border),
borderBottom: `${navbar.border} ${navbar.borderColor}`,
backgroundColor: navbar.backgroundColor,
visible: !navbarHidden,
};
self.IDs.navbar.style = style;
//console.log(navbar.backgroundColor, 'OKOK2', time);
self.IDs.toolbar.style = {
height: Math.max(0, toolbar_height - toolbar.border),
borderTop: `${toolbar.border} ${toolbar.borderColor}`,
backgroundColor: toolbar.backgroundColor,
visible: !toolbarHidden,
};
self.IDs.page.style = { height: navbar_height + toolbar_height + '!' };
}
}
}
/**
* @class NavPageCollection
*/
export class NavPageCollection extends Navigation {
private m_padding = ftr.statusBarHeight; // ios/android, 20
private m_pages: NavPage[] = [];
private m_substack = new List<Navigation>();
private m_default_toolbar: Toolbar | null = null;
private m_animating = false;
private m_default_page: any;
protected $navbarHidden = false;
protected $toolbarHidden = false;
/**
* @field enableAnimate
*/
enableAnimate = true;
@event readonly onPush: EventNoticer<Event<NavPage, NavPageCollection>>;
@event readonly onPop: EventNoticer<Event<NavPage, NavPageCollection>>;
get padding() { return this.m_padding }
get navbarHidden() { return this.$navbarHidden }
get toolbarHidden() { return this.$toolbarHidden }
set navbarHidden(value) { this.setNavbarHidden(value, false) }
set toolbarHidden(value) { this.setToolbarHidden(value, false) }
get length() { return this.m_pages.length }
get pages() { return this.m_pages.slice() }
get current() {
utils.assert(this.length, 'current empty');
return this.m_pages.indexReverse(0);
}
get navbar() { return (this.current as NavPage).navbar }
get toolbar() { return (this.current as NavPage).toolbar }
get defaultToolbar(): Toolbar | null { return this.m_default_toolbar }
isCurrent(page: NavPage) {
return page && this.m_pages.indexReverse(0) === page;
}
set padding(value) {
utils.assert(typeof value == 'number');
this.m_padding = Math.max(value, 0);
refresh_bar_style(this, 0);
}
protected triggerPush(page: NavPage) {
this.trigger('Push', page);
}
protected triggerPop(page: NavPage) {
this.trigger('Pop', page);
}
/**
* @func setNavbarHidden
*/
setNavbarHidden(value: boolean, animate?: boolean) {
this.$navbarHidden = !!value;
refresh_bar_style(this, animate ? TRANSITION_TIME : 0);
}
/**
* @func setToolbarHidden
*/
setToolbarHidden(value: boolean, animate?: boolean) {
this.$toolbarHidden = !!value;
refresh_bar_style(this, animate ? TRANSITION_TIME : 0);
}
/**
* @set defaultToolbar {Toolbar} # Set default toolbar
*/
set defaultToolbar(value: Toolbar | null) {
if (value) {
var bar = ftr.render(value) as Toolbar;
utils.assert(bar instanceof Toolbar, 'Type not correct');
utils.assert(!bar.collection || bar.collection !== this);
if ( bar !== this.m_default_toolbar ) {
if ( this.m_default_toolbar ) {
this.m_default_toolbar.remove();
}
this.m_default_toolbar = bar;
(this.m_default_toolbar as any).m_collection = this; // private props visit
}
} else { // cancel
if ( this.m_default_toolbar ) {
this.m_default_toolbar.remove();
this.m_default_toolbar = null;
}
}
}
protected render(...vdoms: any[]) {
this.m_default_page = vdoms.find(e=>e);
return (
<Clip width="100%" height="100%">
<Div id="navbar" width="100%" />
<Div id="page" width="100%" />
<Div id="toolbar" width="100%" />
</Clip>
);
}
protected triggerMounted() {
if (this.m_default_page) {
/* delay 因为是第一次加载,布局系统还未初始化
* 无法正确的获取数值来进行title bar的排版计算
* 所以这里延时一帧画面
*/
ftr.nextFrame(()=>this.push(this.m_default_page));
}
ftr.nextFrame(()=>this.registerNavigation(0));
return super.triggerMounted();
}
protected triggerRemove() {
this.m_pages.forEach(e=>e.remove());
this.m_pages = [];
return super.triggerRemove();
}
push(arg: any, animate?: boolean) {
if ( this.m_animating ) {
return;
}
var time = this.enableAnimate && animate && this.length ? TRANSITION_TIME : 0;
var prev = this.m_pages.indexReverse(0);
var page: NavPage = arg;
// console.log('push---', time, animate, this.length, this.enableAnimate);
if ( arg ) {
if ( arg instanceof NavPage ) { // dom
utils.assert(!arg.collection, 'NavPage can only be a new entity');
page = ftr.render(arg, this.IDs.page as View) as NavPage;
} else {
if (ViewController.typeOf(arg, NavPage)) {
page = ftr.render(arg, this.IDs.page as View) as NavPage;
} else {
page = ftr.render(<NavPage>{arg}</NavPage>, this.IDs.page as View) as NavPage;
}
}
}
utils.assert(page instanceof NavPage, 'The argument navpage is not of the correct type, '+
'Only for NavPage entities or NavPage VX data.');
// set page
(page as any).m_stack = this.m_substack; // private props visit
(page as any).m_collection = this; // private props visit
(page as any).m_prevPage = prev; // private props visit
if (prev) { // set next page
(prev as any).m_nextPage = page; // private props visit
}
if (!(page as any).m_navbar) { // Create default navbar
page.navbar = <Navbar />;
}
if (!(page as any).m_toolbar) { // use default toolbar
if (this.defaultToolbar) {
page.toolbar = this.defaultToolbar;
} else {
page.toolbar = <Toolbar />;
}
}
this.m_pages.push(page);
(page.navbar as any).m_collection = this; // private props visit
(page.toolbar as any).m_collection = this; // private props visit
page.navbar.appendTo(this.IDs.navbar as View);
page.toolbar.appendTo(this.IDs.toolbar as View);
this.m_animating = time ? true: false;
if ( time ) {
setTimeout(()=>{ this.m_animating = false }, time);
}
page.navbar.setBackText(prev ? prev.title : '');
refresh_bar_style(this, time);
// switch and animate
this.triggerPush(page);
page.registerNavigation(time);
}
pop(animate?: boolean) {
this.pops(1, animate);
}
pops(count: number, animate?: boolean) {
count = Number(count) || 0;
count = Math.min(this.length - 1, count);
if ( count < 1 ) {
return;
}
if ( this.m_animating ) {
return;
}
var time = this.enableAnimate && animate ? TRANSITION_TIME : 0;
// var page = this.m_pages[this.length - 1 - count];
var arr = this.m_pages.splice(this.length - count);
var next = arr.pop();
if (next) {
arr.forEach(page=>page.intoLeave(0)); // private props visit
this.m_animating = time ? true: false;
if ( time ) {
setTimeout(()=>{ this.m_animating = false }, time);
}
refresh_bar_style(this, time);
// switch and animate
this.triggerPop(next);
next.unregisterNavigation(time);
}
}
// @overwrite
navigationBack(): boolean {
if (this.m_pages.length)
return this.m_pages.indexReverse(0).navigationBack(); // private props visit
return false;
}
// @overwrite
navigationEnter(focus: View) {
if (this.m_pages.length)
this.m_pages.indexReverse(0).navigationEnter(focus); // private props visit
}
// @overwrite
navigationTop(focus_move: View | null) {
return get_valid_focus(this.m_pages.indexReverse(0), focus_move);
}
// @overwrite
navigationDown(focus_move: View | null) {
return get_valid_focus(this.m_pages.indexReverse(0), focus_move);
}
// @overwrite
navigationLeft(focus_move: View | null) {
return get_valid_focus(this.m_pages.indexReverse(0), focus_move);
}
// @overwrite
navigationRight(focus_move: View | null) {
return get_valid_focus(this.m_pages.indexReverse(0), focus_move);
}
// @overwrite
navigationMenu() {
if (this.m_pages.length)
this.m_pages.indexReverse(0).navigationMenu(); // private props visit
}
}
/**
* @class Bar
*/
class Bar extends NavigationStatus {
protected $height = 44;
protected $hidden = false;
protected $border = ftr.atomPixel;
protected $borderColor = '#b3b3b3';
protected $backgroundColor = '#f9f9f9';
protected m_page: NavPage;
protected m_collection: NavPageCollection;
get height() { return this.$height }
get hidden() { return this.$hidden }
get border() { return this.$border }
get borderColor() { return this.$borderColor }
get backgroundColor() { return this.$backgroundColor }
get collection() { return this.m_collection }
get page() { return this.m_page }
get isCurrent() { return this.m_page && this.m_page.isCurrent }
set height(value) {
utils.assert(typeof value == 'number');
this.$height = value;
this.refreshStyle(0);
}
set hidden(value) {
this.$hidden = !!value;
this.refreshStyle(0);
}
set border(value: number) {
utils.assert(typeof value == 'number');
this.$border = value;
this.refreshStyle(0);
}
set borderColor(value: string) {
this.$borderColor = value;
this.refreshStyle(0);
}
set backgroundColor(value) {
this.$backgroundColor = value;
this.refreshStyle(0);
}
setHidden(value: boolean, animate?: boolean) {
this.$hidden = !!value;
this.refreshStyle(animate ? TRANSITION_TIME : 0);
}
/**
* @fun refreshStyle
*/
refreshStyle(time: number) {
if (this.isCurrent) {
refresh_bar_style(this.m_page.collection, time);
}
}
get visible() {
return this.domAs().visible;
}
set visible(value) {
if ( value ) {
if (this.isCurrent) {
this.domAs().visible = true;
}
} else {
if (!this.isCurrent) {
this.domAs().visible = false;
}
}
}
}
/**
* @class Navbar
*/
export class Navbar extends Bar {
private m_back_panel_width = 0;
private m_title_panel_width = 0;
protected $defaultStyle = true;
protected $backIconVisible = true;
protected $titleMenuWidth = 40; // display right menu button width
protected $backgroundColor = '#2c86e5'; // 3c89fb
@prop backTextColor = '#fff';
@prop titleTextColor = '#fff';
/**
* @func _navbar_compute_title_layout
*/
private _navbar_compute_title_layout() {
var self: Navbar = this;
if ( self.$defaultStyle ) {
var back_text = (self.IDs.back_text1 as TextNode).value;
var title_text = (self.IDs.title_text_panel as Text).value;
var backIconVisible = self.$backIconVisible;
if ( self.page && self.page.prevPage ) {
(self.IDs.back_text_btn as View).visible = true;
} else {
(self.IDs.back_text_btn as View).visible = false;
back_text = '';
backIconVisible = false;
}
var nav_width = self.collection ? self.collection.domAs<Div>().finalWidth : 0;
// console.log('----------------------nav_width', nav_width);
var back_width = (self.IDs.back_text1 as TextNode).simpleLayoutWidth(back_text) + 3; // 3间隔
var title_width = (self.IDs.title_text_panel as TextNode).simpleLayoutWidth(title_text);
// console.log('back_width', 'title_width', back_width, title_width);
var marginRight = Math.min(nav_width / 3, Math.max(self.$titleMenuWidth, 0));
var marginLeft = 0;
var min_back_width = 6;
if ( backIconVisible ) {
min_back_width += (self.IDs.back_text0 as TextNode).simpleLayoutWidth('\uedc5');
back_width += min_back_width;
}
(self.IDs.title_panel as Indep).marginLeft = new value.Value(value.ValueType.PIXEL, marginLeft);
(self.IDs.title_panel as Indep).marginRight = new value.Value(value.ValueType.PIXEL, marginRight);
(self.IDs.title_panel as Indep).show();
(self.IDs.back_text0 as TextNode).visible = backIconVisible;
if ( nav_width ) {
var title_x = nav_width / 2 - title_width / 2 - marginLeft;
if ( back_width <= title_x ) {
back_width = title_x;
} else { // back 的宽度超过title-x位置
//console.log(back_width, (nav_width - marginLeft - marginRight) - title_width);
back_width = Math.min(back_width, (nav_width - marginLeft - marginRight) - title_width);
back_width = Math.max(min_back_width, back_width);
}
title_width = nav_width - back_width - marginLeft - marginRight;
self.m_back_panel_width = back_width;// - min_back_width;
self.m_title_panel_width = title_width;
} else {
self.m_back_panel_width = 0;
self.m_title_panel_width = 0;
back_width = 30;
title_width = 70;
}
var back_text_num = back_width / (back_width + title_width);
var titl_text_num = title_width / (back_width + title_width);
// 为保证浮点数在转换后之和不超过100,向下保留三位小数
(self.IDs.back_text_panel as Div).width = value.parseValue(Math.floor(back_text_num * 100000) / 1000 + '%');
(self.IDs.title_text_panel as Div).width = value.parseValue(Math.floor(titl_text_num * 100000) / 1000 + '%');
} else {
(self.IDs.title_panel as View).hide(); // hide title text and back text
}
}
get backIconVisible() { return this.$backIconVisible }
get defaultStyle() { return this.$defaultStyle }
get titleMenuWidth() { return this.$titleMenuWidth }
set backIconVisible(value) {
this.$backIconVisible = !!value;
this._navbar_compute_title_layout();
}
set defaultStyle(value) {
this.$defaultStyle = !!value;
this._navbar_compute_title_layout();
}
set titleMenuWidth(value) {
utils.assert(typeof value == 'number');
this.$titleMenuWidth = value;
this._navbar_compute_title_layout();
}
refreshStyle(time: number) {
if (this.isCurrent) {
(this.domAs() as Indep).alignY = value.parseAlign('bottom');
(this.domAs() as Indep).height = new value.Value(value.ValueType.PIXEL, this.height);
(this.IDs.title_text_panel as Text).textLineHeight = value.parseTextLineHeight(this.height);
(this.IDs.back_text_btn as Button).textLineHeight = value.parseTextLineHeight(this.height);
super.refreshStyle(time);
}
}
/**
* @overwrite
*/
protected render(...vdoms: any[]) {
var height = this.height;
var textSize = 16;
return (
<Indep width="100%" height={height} visible={0} alignY="bottom">
{vdoms}
<Indep id="title_panel" width="full" height="100%" visible={0}>
<Div id="back_text_panel" height="full">
<Limit maxWidth="100%">
{/* textColor="#0079ff"*/}
<Button id="back_text_btn"
onClick={()=>this.collection.pop(true)}
textColor={this.backTextColor}
width="full"
textLineHeight={height}
textSize={textSize}
textWhiteSpace="no_wrap" textOverflow="ellipsis">
<Div width={6} />
<TextNode id="back_text0"
textLineHeight="auto"
textSize={20}
height={26} y={2}
textColor="inherit"
textFamily="icon" value={'\uedc5'} />
<TextNode id="back_text1" />
</Button>
</Limit>
</Div>
<Text id="title_text_panel"
height="full"
textColor={this.titleTextColor}
textLineHeight={height}
textSize={textSize}
textWhiteSpace="no_wrap"
textStyle="bold" textOverflow="ellipsis" />
</Indep>
</Indep>
);
}
/**
* @fun setBackText # set navbar back text
*/
setBackText(value: string) {
(this.IDs.back_text1 as TextNode).value = value;
this._navbar_compute_title_layout();
}
/**
* @fun $setTitleText # set navbar title text
*/
setTitleText(value: string) {
(this.IDs.title_text_panel as Text).value = value;
this._navbar_compute_title_layout();
}
intoBackground(time: number) {
if ( time ) {
if ( this.$defaultStyle ) {
var back_icon_width = (this.IDs.back_text0 as View).visible ? (this.IDs.back_text0 as TextNode).clientWidth : 0;
(this.IDs.back_text1 as View).transition({
x: -(this.IDs.back_text1 as TextNode).clientWidth, time: time,
});
(this.IDs.title_text_panel as View).transition({
x: -this.m_back_panel_width + back_icon_width, time: time,
});
}
this.domAs().transition({ opacity: 0, time: time }, ()=>{ this.domAs().hide() });
} else {
this.domAs().opacity = 0;
this.domAs().hide();
}
super.intoBackground(time);
}
intoForeground(time: number) {
this.domAs().show(); // show
if ( time ) {
if ( this.$defaultStyle ) {
var back_icon_width = 0; // this.IDs.back_text0.visible ? 20 : 0;
if ( this.status == -1 ) {
(this.IDs.back_text1 as View).x = this.m_back_panel_width - back_icon_width;
(this.IDs.title_text_panel as View).x = this.m_title_panel_width + this.$titleMenuWidth;
}
(this.IDs.back_text1 as View).transition({ x: 0, time: time });
(this.IDs.title_text_panel as View).transition({ x: 0, time: time });
} else {
(this.IDs.back_text1 as View).x = 0;
(this.IDs.title_text_panel as View).x = 0;
}
this.domAs().opacity = 0;
this.domAs().transition({ opacity: 1, time: time });
} else {
this.domAs().opacity = 1;
(this.IDs.back_text1 as View).x = 0;
(this.IDs.title_text_panel as View).x = 0;
}
super.intoForeground(time);
}
intoLeave(time: number) {
if ( this.status == 0 && time ) {
if ( this.$defaultStyle ) {
var back_icon_width = (this.IDs.back_text0 as View).visible ? (this.IDs.back_text0 as TextNode).clientWidth : 0;
(this.IDs.back_text1 as View).transition({ x: this.m_back_panel_width - back_icon_width, time: time });
(this.IDs.title_text_panel as View).transition({
x: this.m_title_panel_width + this.$titleMenuWidth, time: time,
});
}
this.domAs().transition({ opacity: 0, time: time }, ()=>{ this.remove() });
} else {
this.remove();
}
super.intoLeave(time);
}
}
/**
* @class Toolbar
*/
export class Toolbar extends Bar {
protected $height = 49;
/**
* @overwrite
*/
protected render(...vdoms: any[]) {
return (
<Indep width="100%" height="full" visible={0}>{vdoms}</Indep>
);
}
intoForeground(time: number) {
if ( this.isDefault ) {
this.m_page = this.collection.current as NavPage;
}
if ( time ) {
var page = (this.page.nextPage || this.page.prevPage);
if (!page || page.toolbar !== this) {
this.domAs().show();
this.domAs().opacity = 0;
this.domAs().transition({ opacity: 1, time: time });
}
} else {
this.domAs().show();
this.domAs().opacity = 1;
}
super.intoForeground(time);
}
intoBackground(time: number) {
if ( this.collection.current.toolbar !== this ) {
if ( time ) {
this.domAs().transition({ opacity: 0, time: time }, ()=>{ this.domAs().hide() });
} else {
this.domAs().opacity = 0;
this.domAs().hide();
}
}
super.intoBackground(time);
}
intoLeave(time: number) {
if ( this.collection.current.toolbar !== this ) {
if ( this.status == 0 && time ) {
this.domAs().transition({ opacity: 0, time: time }, ()=>{
if ( this.collection.defaultToolbar !== this ) {
this.remove();
} else {
this.domAs().hide();
}
});
} else {
if ( this.collection.defaultToolbar !== this ) {
this.remove();
} else {
this.domAs().hide();
}
}
}
super.intoLeave(time);
}
get isDefault() {
return this.collection && this.collection.defaultToolbar === this;
}
}
/**
* @func backgroundColorReverse
*/
function backgroundColorReverse(self: NavPage) {
var color = self.domAs<Indep>().backgroundColor.reverse();
color.a = 255 * 0.6;
return color;
}
/**
* @class NavPage
*/
export class NavPage extends Navigation {
private m_title = '';
private m_navbar: Navbar;
private m_toolbar: Toolbar;
private m_collection: NavPageCollection;
private m_prevPage: NavPage | null = null;
private m_nextPage: NavPage | null = null;
@prop backgroundColor = '#fff';
// @public
get title() { return this.m_title }
get collection() { return this.m_collection }
get navbar(): Navbar {
if ( this.m_navbar ) {
return this.m_navbar;
} else {
this.navbar = <Navbar />;
return this.m_navbar;
}
}
get toolbar(): Toolbar {
if ( this.m_toolbar ) {
return this.m_toolbar;
} else {
this.toolbar = <Toolbar />;
return this.m_toolbar;
}
}
get prevPage() { return this.m_prevPage }
get nextPage() { return this.m_nextPage }
get isCurrent() { return this.m_collection && this.m_collection.isCurrent(this) }
set title(value) {
this.m_title = String(value);
if (this.m_navbar) {
this.m_navbar.setTitleText(this.m_title);
}
if (this.m_nextPage && this.m_nextPage.navbar) {
this.m_nextPage.navbar.setBackText(value);
}
}
set navbar(value: Navbar) {
if (value) {
value = ftr.render(value) as Navbar;
utils.assert(value instanceof Navbar, 'Type not correct');
if (value !== this.m_navbar) {
utils.assert(!value.page);
if (this.m_navbar) {
this.m_navbar.remove();
}
this.m_navbar = value;
(this as any).m_navbar.m_page = this; // private props visit
this.m_navbar.setTitleText(this.m_title);
this.m_navbar.setBackText(this.prevPage ? this.prevPage.title : '');
this.m_navbar.refreshStyle(0);
}
}
}
set toolbar(value: Toolbar) {
if (value) {
value = ftr.render(value) as Toolbar;
utils.assert(value instanceof Toolbar, 'Type not correct');
if (value !== this.m_toolbar) {
utils.assert(!value.page || value.isDefault);
if (this.m_toolbar) {
if ( !this.m_toolbar.isDefault ) {
this.m_toolbar.remove();
}
}
this.m_toolbar = value;
(this as any).m_toolbar.m_page = this;
this.m_toolbar.refreshStyle(0);
} else {
(this as any).m_toolbar.m_page = this;
}
}
}
// @overwrite
protected render(...vdoms: any[]) {
return (
<Indep width="100%" height="full" backgroundColor={this.backgroundColor} visible={0}>{vdoms}</Indep>
);
}
// @overwrite
intoBackground(time: number) {
// console.log('intoBackground', time);
//console.log( this.nextPage == null ? 'null' : 'no null' )
if ( this.nextPage == null ) return;
//console.log( 'natpage intoBackground' )
this.navbar.intoBackground(time);
this.toolbar.intoBackground(time);
if ( this.status != 1 ) {
if ( time && (this.domAs().parent as Div).finalVisible ) {
this.domAs().transition({ x: (this.domAs().parent as Div).finalWidth / -3, visible: false, time: time });
} else {
this.domAs().style = { x: ((this.domAs().parent as Div).finalWidth || 100) / -3, visible: false };
}
}
super.intoBackground(time);
}
// @overwrite
intoForeground(time: number) {
// console.log('intoForeground', time);
if ( this.status == 0 ) return;
this.navbar.intoForeground(time);
this.toolbar.intoForeground(time);
this.m_nextPage = null;
if ( this.status == -1 ) {
if ( time && (this.domAs().parent as Div).finalVisible ) {
this.domAs().style = {
borderLeftColor: backgroundColorReverse(this),
borderLeftWidth: ftr.atomPixel,
x: (this.domAs().parent as Div).finalWidth,
visible: true,
};
this.domAs().transition({ x: 0, time: time }, ()=>{
(this.domAs() as Indep).borderLeftWidth = 0;
});
} else {
this.domAs().style = { x: 0, borderLeftWidth: 0, visible: true };
}
(this.m_toolbar as any).m_page = this;
}
else if ( this.status == 1 ) {
if ( time && (this.domAs().parent as Div).finalVisible ) {
this.domAs().visible = true;
this.domAs().transition({ x: 0, time: time });
} else {
this.domAs().style = { x: 0, visible: true };
}
(this.m_toolbar as any).m_page = this;
}
super.intoForeground(time);
}
// @overwrite
intoLeave(time: number) {
// console.log('intoLeave', time);
this.navbar.intoLeave(time);
this.toolbar.intoLeave(time);
if ( this.status == 0 ) {
if ( time && (this.domAs().parent as Div).finalVisible ) {
this.domAs().style = {
borderLeftColor: backgroundColorReverse(this),
borderLeftWidth: ftr.atomPixel,
};
this.domAs().transition({ x: (this.domAs().parent as Div).finalWidth, visible: false, time: time }, ()=>{
this.remove();
});
super.intoLeave(time);
return;
}
}
super.intoLeave(time);
this.remove();
}
// @overwrite
protected triggerRemove() {
if (this.m_navbar) {
this.m_navbar.remove();
}
if (this.m_toolbar && !this.m_toolbar.isDefault) {
this.m_toolbar.remove();
}
return super.triggerRemove();
}
// @overwrite
navigationBack() {
if ( this.m_prevPage ) {
this.m_collection.pop(true);
return true;
} else {
return false;
}
}
} | the_stack |
import * as zrUtil from 'zrender/src/core/util';
import BoundingRect from 'zrender/src/core/BoundingRect';
import * as visualSolution from '../../visual/visualSolution';
import { BrushSelectableArea, makeBrushCommonSelectorForSeries } from './selector';
import * as throttleUtil from '../../util/throttle';
import BrushTargetManager from '../helper/BrushTargetManager';
import GlobalModel from '../../model/Global';
import ExtensionAPI from '../../core/ExtensionAPI';
import { Payload } from '../../util/types';
import BrushModel, { BrushAreaParamInternal } from './BrushModel';
import SeriesModel from '../../model/Series';
import ParallelSeriesModel from '../../chart/parallel/ParallelSeries';
import { ZRenderType } from 'zrender/src/zrender';
import { BrushType, BrushDimensionMinMax } from '../helper/BrushController';
type BrushVisualState = 'inBrush' | 'outOfBrush';
const STATE_LIST = ['inBrush', 'outOfBrush'] as const;
const DISPATCH_METHOD = '__ecBrushSelect' as const;
const DISPATCH_FLAG = '__ecInBrushSelectEvent' as const;
interface BrushGlobalDispatcher extends ZRenderType {
[DISPATCH_FLAG]: boolean;
[DISPATCH_METHOD]: typeof doDispatch;
}
interface BrushSelectedItem {
brushId: string;
brushIndex: number;
brushName: string;
areas: BrushAreaParamInternal[];
selected: {
seriesId: string;
seriesIndex: number;
seriesName: string;
dataIndex: number[];
}[]
};
export function layoutCovers(ecModel: GlobalModel): void {
ecModel.eachComponent({mainType: 'brush'}, function (brushModel: BrushModel) {
const brushTargetManager = brushModel.brushTargetManager = new BrushTargetManager(brushModel.option, ecModel);
brushTargetManager.setInputRanges(brushModel.areas, ecModel);
});
}
/**
* Register the visual encoding if this modules required.
*/
export default function brushVisual(ecModel: GlobalModel, api: ExtensionAPI, payload: Payload) {
const brushSelected: BrushSelectedItem[] = [];
let throttleType;
let throttleDelay;
ecModel.eachComponent({mainType: 'brush'}, function (brushModel: BrushModel) {
payload && payload.type === 'takeGlobalCursor' && brushModel.setBrushOption(
payload.key === 'brush' ? payload.brushOption : {brushType: false}
);
});
layoutCovers(ecModel);
ecModel.eachComponent({mainType: 'brush'}, function (brushModel: BrushModel, brushIndex) {
const thisBrushSelected: BrushSelectedItem = {
brushId: brushModel.id,
brushIndex: brushIndex,
brushName: brushModel.name,
areas: zrUtil.clone(brushModel.areas),
selected: []
};
// Every brush component exists in event params, convenient
// for user to find by index.
brushSelected.push(thisBrushSelected);
const brushOption = brushModel.option;
const brushLink = brushOption.brushLink;
const linkedSeriesMap: {[seriesIndex: number]: 0 | 1} = [];
const selectedDataIndexForLink: {[dataIndex: number]: 0 | 1} = [];
const rangeInfoBySeries: {[seriesIndex: number]: BrushSelectableArea[]} = [];
let hasBrushExists = false;
if (!brushIndex) { // Only the first throttle setting works.
throttleType = brushOption.throttleType;
throttleDelay = brushOption.throttleDelay;
}
// Add boundingRect and selectors to range.
const areas: BrushSelectableArea[] = zrUtil.map(brushModel.areas, function (area) {
const builder = boundingRectBuilders[area.brushType];
const selectableArea = zrUtil.defaults(
{boundingRect: builder ? builder(area) : void 0},
area
) as BrushSelectableArea;
selectableArea.selectors = makeBrushCommonSelectorForSeries(selectableArea);
return selectableArea;
});
const visualMappings = visualSolution.createVisualMappings(
brushModel.option, STATE_LIST, function (mappingOption) {
mappingOption.mappingMethod = 'fixed';
}
);
zrUtil.isArray(brushLink) && zrUtil.each(brushLink, function (seriesIndex) {
linkedSeriesMap[seriesIndex] = 1;
});
function linkOthers(seriesIndex: number): boolean {
return brushLink === 'all' || !!linkedSeriesMap[seriesIndex];
}
// If no supported brush or no brush on the series,
// all visuals should be in original state.
function brushed(rangeInfoList: BrushSelectableArea[]): boolean {
return !!rangeInfoList.length;
}
/**
* Logic for each series: (If the logic has to be modified one day, do it carefully!)
*
* ( brushed ┬ && ┬hasBrushExist ┬ && linkOthers ) => StepA: ┬record, ┬ StepB: ┬visualByRecord.
* !brushed┘ ├hasBrushExist ┤ └nothing,┘ ├visualByRecord.
* └!hasBrushExist┘ └nothing.
* ( !brushed && ┬hasBrushExist ┬ && linkOthers ) => StepA: nothing, StepB: ┬visualByRecord.
* └!hasBrushExist┘ └nothing.
* ( brushed ┬ && !linkOthers ) => StepA: nothing, StepB: ┬visualByCheck.
* !brushed┘ └nothing.
* ( !brushed && !linkOthers ) => StepA: nothing, StepB: nothing.
*/
// Step A
ecModel.eachSeries(function (seriesModel, seriesIndex) {
const rangeInfoList: BrushSelectableArea[] = rangeInfoBySeries[seriesIndex] = [];
seriesModel.subType === 'parallel'
? stepAParallel(seriesModel as ParallelSeriesModel, seriesIndex)
: stepAOthers(seriesModel, seriesIndex, rangeInfoList);
});
function stepAParallel(seriesModel: ParallelSeriesModel, seriesIndex: number): void {
const coordSys = seriesModel.coordinateSystem;
hasBrushExists = hasBrushExists || coordSys.hasAxisBrushed();
linkOthers(seriesIndex) && coordSys.eachActiveState(
seriesModel.getData(),
function (activeState, dataIndex) {
activeState === 'active' && (selectedDataIndexForLink[dataIndex] = 1);
}
);
}
function stepAOthers(
seriesModel: SeriesModel, seriesIndex: number, rangeInfoList: BrushSelectableArea[]
): void {
if (!seriesModel.brushSelector || brushModelNotControll(brushModel, seriesIndex)) {
return;
}
zrUtil.each(areas, function (area) {
if (brushModel.brushTargetManager.controlSeries(area, seriesModel, ecModel)) {
rangeInfoList.push(area);
}
hasBrushExists = hasBrushExists || brushed(rangeInfoList);
});
if (linkOthers(seriesIndex) && brushed(rangeInfoList)) {
const data = seriesModel.getData();
data.each(function (dataIndex) {
if (checkInRange(seriesModel, rangeInfoList, data, dataIndex)) {
selectedDataIndexForLink[dataIndex] = 1;
}
});
}
}
// Step B
ecModel.eachSeries(function (seriesModel, seriesIndex) {
const seriesBrushSelected: BrushSelectedItem['selected'][0] = {
seriesId: seriesModel.id,
seriesIndex: seriesIndex,
seriesName: seriesModel.name,
dataIndex: []
};
// Every series exists in event params, convenient
// for user to find series by seriesIndex.
thisBrushSelected.selected.push(seriesBrushSelected);
const rangeInfoList = rangeInfoBySeries[seriesIndex];
const data = seriesModel.getData();
const getValueState = linkOthers(seriesIndex)
? function (dataIndex: number): BrushVisualState {
return selectedDataIndexForLink[dataIndex]
? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush')
: 'outOfBrush';
}
: function (dataIndex: number): BrushVisualState {
return checkInRange(seriesModel, rangeInfoList, data, dataIndex)
? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush')
: 'outOfBrush';
};
// If no supported brush or no brush, all visuals are in original state.
(linkOthers(seriesIndex) ? hasBrushExists : brushed(rangeInfoList))
&& visualSolution.applyVisual(
STATE_LIST, visualMappings, data, getValueState
);
});
});
dispatchAction(api, throttleType, throttleDelay, brushSelected, payload);
};
function dispatchAction(
api: ExtensionAPI,
throttleType: throttleUtil.ThrottleType,
throttleDelay: number,
brushSelected: BrushSelectedItem[],
payload: Payload
): void {
// This event will not be triggered when `setOpion`, otherwise dead lock may
// triggered when do `setOption` in event listener, which we do not find
// satisfactory way to solve yet. Some considered resolutions:
// (a) Diff with prevoius selected data ant only trigger event when changed.
// But store previous data and diff precisely (i.e., not only by dataIndex, but
// also detect value changes in selected data) might bring complexity or fragility.
// (b) Use spectial param like `silent` to suppress event triggering.
// But such kind of volatile param may be weird in `setOption`.
if (!payload) {
return;
}
const zr = api.getZr() as BrushGlobalDispatcher;
if (zr[DISPATCH_FLAG]) {
return;
}
if (!zr[DISPATCH_METHOD]) {
zr[DISPATCH_METHOD] = doDispatch;
}
const fn = throttleUtil.createOrUpdate(zr, DISPATCH_METHOD, throttleDelay, throttleType);
fn(api, brushSelected);
}
function doDispatch(api: ExtensionAPI, brushSelected: BrushSelectedItem[]): void {
if (!api.isDisposed()) {
const zr = api.getZr() as BrushGlobalDispatcher;
zr[DISPATCH_FLAG] = true;
api.dispatchAction({
type: 'brushSelect',
batch: brushSelected
});
zr[DISPATCH_FLAG] = false;
}
}
function checkInRange(
seriesModel: SeriesModel,
rangeInfoList: BrushSelectableArea[],
data: ReturnType<SeriesModel['getData']>,
dataIndex: number
) {
for (let i = 0, len = rangeInfoList.length; i < len; i++) {
const area = rangeInfoList[i];
if (seriesModel.brushSelector(
dataIndex, data, area.selectors, area
)) {
return true;
}
}
}
function brushModelNotControll(brushModel: BrushModel, seriesIndex: number): boolean {
const seriesIndices = brushModel.option.seriesIndex;
return seriesIndices != null
&& seriesIndices !== 'all'
&& (
zrUtil.isArray(seriesIndices)
? zrUtil.indexOf(seriesIndices, seriesIndex) < 0
: seriesIndex !== seriesIndices
);
}
type AreaBoundingRectBuilder = (area: BrushAreaParamInternal) => BoundingRect;
const boundingRectBuilders: Partial<Record<BrushType, AreaBoundingRectBuilder>> = {
rect: function (area) {
return getBoundingRectFromMinMax(area.range as BrushDimensionMinMax[]);
},
polygon: function (area) {
let minMax;
const range = area.range as BrushDimensionMinMax[];
for (let i = 0, len = range.length; i < len; i++) {
minMax = minMax || [[Infinity, -Infinity], [Infinity, -Infinity]];
const rg = range[i];
rg[0] < minMax[0][0] && (minMax[0][0] = rg[0]);
rg[0] > minMax[0][1] && (minMax[0][1] = rg[0]);
rg[1] < minMax[1][0] && (minMax[1][0] = rg[1]);
rg[1] > minMax[1][1] && (minMax[1][1] = rg[1]);
}
return minMax && getBoundingRectFromMinMax(minMax);
}
};
function getBoundingRectFromMinMax(minMax: BrushDimensionMinMax[]): BoundingRect {
return new BoundingRect(
minMax[0][0],
minMax[1][0],
minMax[0][1] - minMax[0][0],
minMax[1][1] - minMax[1][0]
);
} | the_stack |
import { ComponentFactory, ComponentFactoryResolver } from '@angular/core';
import { Location } from '@angular/common';
import { App } from '../components/app/app';
import { DIRECTION_BACK, NavLink, NavSegment, TransitionDoneFn, convertToViews, isNav, isTab, isTabs } from './nav-util';
import { ModuleLoader } from '../util/module-loader';
import { isArray, isPresent } from '../util/util';
import { Tab, Tabs } from './nav-interfaces';
import { NavigationContainer } from './navigation-container';
import { NavController } from './nav-controller';
import { UrlSerializer, formatUrlPart } from './url-serializer';
import { ViewController } from './view-controller';
/**
* @hidden
*/
export class DeepLinker {
/** @internal */
_history: string[] = [];
/** @internal */
_indexAliasUrl: string;
constructor(
public _app: App,
public _serializer: UrlSerializer,
public _location: Location,
public _moduleLoader: ModuleLoader,
public _baseCfr: ComponentFactoryResolver
) {}
/**
* @internal
*/
init() {
// scenario 1: Initial load of all navs from the initial browser URL
const browserUrl = normalizeUrl(this._location.path());
console.debug(`DeepLinker, init load: ${browserUrl}`);
// remember this URL in our internal history stack
this._historyPush(browserUrl);
// listen for browser URL changes
this._location.subscribe((locationChg: { url: string }) => {
this._urlChange(normalizeUrl(locationChg.url));
});
}
/**
* The browser's location has been updated somehow.
* @internal
*/
_urlChange(browserUrl: string) {
// do nothing if this url is the same as the current one
if (!this._isCurrentUrl(browserUrl)) {
let isGoingBack = true;
if (this._isBackUrl(browserUrl)) {
// scenario 2: user clicked the browser back button
// scenario 4: user changed the browser URL to what was the back url was
// scenario 5: user clicked a link href that was the back url
console.debug(`DeepLinker, browser urlChange, back to: ${browserUrl}`);
this._historyPop();
} else {
// scenario 3: user click forward button
// scenario 4: user changed browser URL that wasn't the back url
// scenario 5: user clicked a link href that wasn't the back url
isGoingBack = false;
console.debug(`DeepLinker, browser urlChange, forward to: ${browserUrl}`);
this._historyPush(browserUrl);
}
// get the app's root nav container
const activeNavContainers = this._app.getActiveNavContainers();
if (activeNavContainers && activeNavContainers.length) {
if (browserUrl === '/') {
// a url change to the index url
if (isPresent(this._indexAliasUrl)) {
// we already know the indexAliasUrl
// update the url to use the know alias
browserUrl = this._indexAliasUrl;
} else {
// the url change is to the root but we don't
// already know the url used. So let's just
// reset the root nav to its root page
activeNavContainers.forEach((navContainer: NavController) => {
navContainer.goToRoot({
updateUrl: false,
isNavRoot: true
});
});
return;
}
}
// normal url
const segments = this.getCurrentSegments(browserUrl);
segments
.map(segment => {
// find the matching nav container
for (const navContainer of activeNavContainers) {
const nav = getNavFromTree(navContainer, segment.navId);
if (nav) {
return {
segment: segment,
navContainer: nav
};
}
}
})
.filter(pair => !!pair)
.forEach(pair => {
this._loadViewForSegment(pair.navContainer, pair.segment, () => {});
});
}
}
}
getCurrentSegments(browserUrl?: string) {
if (!browserUrl) {
browserUrl = normalizeUrl(this._location.path());
}
return this._serializer.parse(browserUrl);
}
/**
* Update the deep linker using the NavController's current active view.
* @internal
*/
navChange(direction: string) {
if (direction) {
const activeNavContainers = this._app.getActiveNavContainers();
// the only time you'll ever get a TABS here is when loading directly from a URL
// this method will be called again when the TAB is loaded
// so just don't worry about the TABS for now
// if you encounter a TABS, just return
for (const activeNavContainer of activeNavContainers) {
if (isTabs(activeNavContainer) || (activeNavContainer as NavController).isTransitioning()) {
return;
}
}
// okay, get the root navs and build the segments up
let segments: NavSegment[] = [];
const navContainers: NavigationContainer[] = this._app.getRootNavs();
for (const navContainer of navContainers) {
const segmentsForNav = this.getSegmentsFromNav(navContainer);
segments = segments.concat(segmentsForNav);
}
segments = segments.filter(segment => !!segment);
if (segments.length) {
const browserUrl = this._serializer.serialize(segments);
this._updateLocation(browserUrl, direction);
}
}
}
getSegmentsFromNav(nav: NavigationContainer): NavSegment[] {
let segments: NavSegment[] = [];
if (isNav(nav)) {
segments.push(this.getSegmentFromNav(nav as NavController));
} else if (isTab(nav)) {
segments.push(this.getSegmentFromTab(nav));
}
nav.getActiveChildNavs().forEach(child => {
segments = segments.concat(this.getSegmentsFromNav(child));
});
return segments;
}
getSegmentFromNav(nav: NavController, component?: any, data?: any): NavSegment {
if (!component) {
const viewController = nav.getActive(true);
if (viewController) {
component = viewController.component;
data = viewController.data;
}
}
return this._serializer.serializeComponent(nav, component, data);
}
getSegmentFromTab(navContainer: NavigationContainer, component?: any, data?: any): NavSegment {
if (navContainer && navContainer.parent) {
const tabsNavContainer = navContainer.parent as NavigationContainer;
const activeChildNavs = tabsNavContainer.getActiveChildNavs();
if (activeChildNavs && activeChildNavs.length) {
const activeChildNav = activeChildNavs[0];
const viewController = (activeChildNav as NavController).getActive(true);
if (viewController) {
component = viewController.component;
data = viewController.data;
}
return this._serializer.serializeComponent(tabsNavContainer, component, data);
}
}
}
/**
* @internal
*/
_updateLocation(browserUrl: string, direction: string) {
if (this._indexAliasUrl === browserUrl) {
browserUrl = '/';
}
if (direction === DIRECTION_BACK && this._isBackUrl(browserUrl)) {
// this URL is exactly the same as the back URL
// it's safe to use the browser's location.back()
console.debug(`DeepLinker, location.back(), url: '${browserUrl}'`);
this._historyPop();
this._location.back();
} else if (!this._isCurrentUrl(browserUrl)) {
// probably navigating forward
console.debug(`DeepLinker, location.go('${browserUrl}')`);
this._historyPush(browserUrl);
this._location.go(browserUrl);
}
}
getComponentFromName(componentName: string): Promise<any> {
const link = this._serializer.getLinkFromName(componentName);
if (link) {
// cool, we found the right link for this component name
return this.getNavLinkComponent(link);
}
// umm, idk
return Promise.reject(`invalid link: ${componentName}`);
}
getNavLinkComponent(link: NavLink) {
if (link.component) {
// sweet, we're already got a component loaded for this link
return Promise.resolve(link.component);
}
if (link.loadChildren) {
// awesome, looks like we'll lazy load this component
// using loadChildren as the URL to request
return this._moduleLoader.load(link.loadChildren).then((response) => {
link.component = response.component;
return response.component;
});
}
return Promise.reject(`invalid link component: ${link.name}`);
}
/**
* @internal
*/
resolveComponent(component: any): ComponentFactory<any> {
let cfr = this._moduleLoader.getComponentFactoryResolver(component);
if (!cfr) {
cfr = this._baseCfr;
}
return cfr.resolveComponentFactory(component);
}
/**
* @internal
*/
createUrl(navContainer: NavigationContainer, nameOrComponent: any, _data: any, prepareExternalUrl: boolean = true): string {
// create a segment out of just the passed in name
const segment = this._serializer.createSegmentFromName(navContainer, nameOrComponent);
const allSegments = this.getCurrentSegments();
if (segment) {
for (let i = 0; i < allSegments.length; i++) {
if (allSegments[i].navId === navContainer.name || allSegments[i].navId === navContainer.id) {
allSegments[i] = segment;
const url = this._serializer.serialize(allSegments);
return prepareExternalUrl ? this._location.prepareExternalUrl(url) : url;
}
}
}
return '';
}
/**
* Each NavController will call this method when it initializes for
* the first time. This allows each NavController to figure out
* where it lives in the path and load up the correct component.
* @internal
*/
getSegmentByNavIdOrName(navId: string, name: string): NavSegment {
const browserUrl = normalizeUrl(this._location.path());
const segments = this._serializer.parse(browserUrl);
for (const segment of segments) {
if (segment.navId === navId || segment.navId === name) {
return segment;
}
}
return null;
}
/**
* @internal
*/
initViews(segment: NavSegment) {
const link = this._serializer.getLinkFromName(segment.name);
return this.getNavLinkComponent(link).then((component: any) => {
segment.component = component;
const view = new ViewController(component, segment.data);
view.id = segment.id;
if (isArray(segment.defaultHistory)) {
return convertToViews(this, segment.defaultHistory).then(views => {
views.push(view);
return views;
});
}
return [view];
});
}
/**
* @internal
*/
_isBackUrl(browserUrl: string) {
return (browserUrl === this._history[this._history.length - 2]);
}
/**
* @internal
*/
_isCurrentUrl(browserUrl: string) {
return (browserUrl === this._history[this._history.length - 1]);
}
/**
* @internal
*/
_historyPush(browserUrl: string) {
if (!this._isCurrentUrl(browserUrl)) {
this._history.push(browserUrl);
if (this._history.length > 30) {
this._history.shift();
}
}
}
/**
* @internal
*/
_historyPop() {
this._history.pop();
if (!this._history.length) {
this._historyPush(this._location.path());
}
}
/**
* @internal
*/
_getTabSelector(tab: Tab): string {
if (isPresent(tab.tabUrlPath)) {
return tab.tabUrlPath;
}
if (isPresent(tab.tabTitle)) {
return formatUrlPart(tab.tabTitle);
}
return `tab-${tab.index}`;
}
/**
* Using the known Path of Segments, walk down all descendents
* from the root NavController and load each NavController according
* to each Segment. This is usually called after a browser URL and
* Path changes and needs to update all NavControllers to match
* the new browser URL. Because the URL is already known, it will
* not update the browser's URL when transitions have completed.
*
* @internal
*/
_loadViewForSegment(navContainer: NavigationContainer, segment: NavSegment, done: TransitionDoneFn) {
if (!segment) {
return done(false, false);
}
if (isTabs(navContainer) || (isTab(navContainer) && navContainer.parent)) {
const tabs = <Tabs> <any> (isTabs(navContainer) ? navContainer : navContainer.parent);
const selectedIndex = tabs._getSelectedTabIndex(segment.secondaryId);
const tab = tabs.getByIndex(selectedIndex);
tab._segment = segment;
tabs.select(tab, {
updateUrl: false,
animate: false
}, true);
return done(false, false);
}
const navController = <NavController> <any> navContainer;
const numViews = navController.length() - 1;
// walk backwards to see if the exact view we want to show here
// is already in the stack that we can just pop back to
for (let i = numViews; i >= 0; i--) {
const viewController = navController.getByIndex(i);
if (viewController && (viewController.id === segment.id || viewController.id === segment.name)) {
// hooray! we've already got a view loaded in the stack
// matching the view they wanted to show
if (i === numViews) {
// this is the last view in the stack and it's the same
// as the segment so there's no change needed
return done(false, false);
} else {
// it's not the exact view as the end
// let's have this nav go back to this exact view
return navController.popTo(viewController, {
animate: false,
updateUrl: false,
}, done);
}
}
}
// ok, so we don't know about a view that they're navigating to
// so we might as well just call setRoot and make tthe view the first view
// this seems like the least bad option
return navController.setRoot(segment.component || segment.name, segment.data, {
id: segment.id, animate: false, updateUrl: false
}, done);
}
}
export function setupDeepLinker(app: App, serializer: UrlSerializer, location: Location, moduleLoader: ModuleLoader, cfr: ComponentFactoryResolver) {
const deepLinker = new DeepLinker(app, serializer, location, moduleLoader, cfr);
deepLinker.init();
return deepLinker;
}
export function normalizeUrl(browserUrl: string): string {
browserUrl = browserUrl.trim();
if (browserUrl.charAt(0) !== '/') {
// ensure first char is a /
browserUrl = '/' + browserUrl;
}
if (browserUrl.length > 1 && browserUrl.charAt(browserUrl.length - 1) === '/') {
// ensure last char is not a /
browserUrl = browserUrl.substr(0, browserUrl.length - 1);
}
return browserUrl;
}
export function getNavFromTree(nav: NavigationContainer, id: string) {
while (nav) {
if (nav.id === id || nav.name === id) {
return nav;
}
nav = nav.parent;
}
return null;
} | the_stack |
import Convert from '../convert';
import * as Utils from '../utils';
import { CancellationTokenSource } from 'vscode-jsonrpc';
import { ActiveServer } from '../server-manager';
import { filter } from 'fuzzaldrin-plus';
import {
CompletionContext,
CompletionItem,
CompletionItemKind,
CompletionList,
CompletionParams,
CompletionTriggerKind,
InsertTextFormat,
LanguageClientConnection,
ServerCapabilities,
TextEdit,
} from '../languageclient';
import {
Point,
TextEditor,
} from 'atom';
import * as ac from 'atom/autocomplete-plus';
import { Suggestion, TextSuggestion, SnippetSuggestion } from 'atom-ide';
/**
* Holds a list of suggestions generated from the CompletionItem[]
* list sent by the server, as well as metadata about the context
* it was collected in
*/
interface SuggestionCacheEntry {
/** If `true`, the server will send a list of suggestions to replace this one */
isIncomplete: boolean;
/** The point left of the first character in the original prefix sent to the server */
triggerPoint: Point;
/** The point right of the last character in the original prefix sent to the server */
originalBufferPoint: Point;
/** The trigger string that caused the autocomplete (if any) */
triggerChar: string;
suggestionMap: Map<Suggestion, PossiblyResolvedCompletionItem>;
}
type CompletionItemAdjuster =
(item: CompletionItem, suggestion: ac.AnySuggestion, request: ac.SuggestionsRequestedEvent) => void;
class PossiblyResolvedCompletionItem {
constructor(
public completionItem: CompletionItem,
public isResolved: boolean,
) {
}
}
/**
* Public: Adapts the language server protocol "textDocument/completion" to the Atom
* AutoComplete+ package.
*/
export default class AutocompleteAdapter {
public static canAdapt(serverCapabilities: ServerCapabilities): boolean {
return serverCapabilities.completionProvider != null;
}
public static canResolve(serverCapabilities: ServerCapabilities): boolean {
return serverCapabilities.completionProvider != null &&
serverCapabilities.completionProvider.resolveProvider === true;
}
private _suggestionCache: WeakMap<ActiveServer, SuggestionCacheEntry> = new WeakMap();
private _cancellationTokens: WeakMap<LanguageClientConnection, CancellationTokenSource> = new WeakMap();
/**
* Public: Obtain suggestion list for AutoComplete+ by querying the language server using
* the `textDocument/completion` request.
*
* @param server An {ActiveServer} pointing to the language server to query.
* @param request The {atom$AutocompleteRequest} to satisfy.
* @param onDidConvertCompletionItem An optional function that takes a {CompletionItem},
* an {atom$AutocompleteSuggestion} and a {atom$AutocompleteRequest}
* allowing you to adjust converted items.
* @returns A {Promise} of an {Array} of {atom$AutocompleteSuggestion}s containing the
* AutoComplete+ suggestions to display.
*/
public async getSuggestions(
server: ActiveServer,
request: ac.SuggestionsRequestedEvent,
onDidConvertCompletionItem?: CompletionItemAdjuster,
minimumWordLength?: number,
): Promise<ac.AnySuggestion[]> {
const triggerChars = server.capabilities.completionProvider != null
? server.capabilities.completionProvider.triggerCharacters || []
: [];
// triggerOnly is true if we have just typed in a trigger character, and is false if we
// have typed additional characters following a trigger character.
const [triggerChar, triggerOnly] = AutocompleteAdapter.getTriggerCharacter(request, triggerChars);
if (!this.shouldTrigger(request, triggerChar, minimumWordLength || 0)) {
return [];
}
// Get the suggestions either from the cache or by calling the language server
const suggestions = await
this.getOrBuildSuggestions(server, request, triggerChar, triggerOnly, onDidConvertCompletionItem);
// We must update the replacement prefix as characters are added and removed
const cache = this._suggestionCache.get(server)!;
const replacementPrefix = request.editor.getTextInBufferRange([cache.triggerPoint, request.bufferPosition]);
for (const suggestion of suggestions) {
if (suggestion.customReplacmentPrefix) { // having this property means a custom range was provided
const len = replacementPrefix.length;
const preReplacementPrefix = suggestion.customReplacmentPrefix
+ replacementPrefix.substring(len + cache.originalBufferPoint.column - request.bufferPosition.column, len);
// we cannot replace text after the cursor with the current autocomplete-plus API
// so we will simply ignore it for now
suggestion.replacementPrefix = preReplacementPrefix;
} else {
suggestion.replacementPrefix = replacementPrefix;
}
}
const filtered = !(request.prefix === "" || (triggerChar !== '' && triggerOnly));
return filtered ? filter(suggestions, request.prefix, { key: 'filterText' }) : suggestions;
}
private shouldTrigger(
request: ac.SuggestionsRequestedEvent,
triggerChar: string,
minWordLength: number,
): boolean {
return request.activatedManually
|| triggerChar !== ''
|| minWordLength <= 0
|| request.prefix.length >= minWordLength;
}
private async getOrBuildSuggestions(
server: ActiveServer,
request: ac.SuggestionsRequestedEvent,
triggerChar: string,
triggerOnly: boolean,
onDidConvertCompletionItem?: CompletionItemAdjuster,
): Promise<Suggestion[]> {
const cache = this._suggestionCache.get(server);
const triggerColumn = (triggerChar !== '' && triggerOnly)
? request.bufferPosition.column - triggerChar.length
: request.bufferPosition.column - request.prefix.length - triggerChar.length;
const triggerPoint = new Point(request.bufferPosition.row, triggerColumn);
// Do we have complete cached suggestions that are still valid for this request?
if (cache && !cache.isIncomplete && cache.triggerChar === triggerChar
&& cache.triggerPoint.isEqual(triggerPoint)
&& cache.originalBufferPoint.isLessThanOrEqual(request.bufferPosition)) {
return Array.from(cache.suggestionMap.keys());
}
// Our cached suggestions can't be used so obtain new ones from the language server
const completions = await Utils.doWithCancellationToken(server.connection, this._cancellationTokens,
(cancellationToken) => server.connection.completion(
AutocompleteAdapter.createCompletionParams(request, triggerChar, triggerOnly), cancellationToken),
);
// spec guarantees all edits are on the same line, so we only need to check the columns
const triggerColumns: [number, number] = [triggerPoint.column, request.bufferPosition.column];
// Setup the cache for subsequent filtered results
const isComplete = completions === null || Array.isArray(completions) || completions.isIncomplete === false;
const suggestionMap =
this.completionItemsToSuggestions(completions, request, triggerColumns, onDidConvertCompletionItem);
this._suggestionCache.set(server, {
isIncomplete: !isComplete,
triggerChar,
triggerPoint,
originalBufferPoint: request.bufferPosition,
suggestionMap,
});
return Array.from(suggestionMap.keys());
}
/**
* Public: Obtain a complete version of a suggestion with additional information
* the language server can provide by way of the `completionItem/resolve` request.
*
* @param server An {ActiveServer} pointing to the language server to query.
* @param suggestion An {atom$AutocompleteSuggestion} suggestion that should be resolved.
* @param request An {Object} with the AutoComplete+ request to satisfy.
* @param onDidConvertCompletionItem An optional function that takes a {CompletionItem}, an
* {atom$AutocompleteSuggestion} and a {atom$AutocompleteRequest} allowing you to adjust converted items.
* @returns A {Promise} of an {atom$AutocompleteSuggestion} with the resolved AutoComplete+ suggestion.
*/
public async completeSuggestion(
server: ActiveServer,
suggestion: ac.AnySuggestion,
request: ac.SuggestionsRequestedEvent,
onDidConvertCompletionItem?: CompletionItemAdjuster,
): Promise<ac.AnySuggestion> {
const cache = this._suggestionCache.get(server);
if (cache) {
const possiblyResolvedCompletionItem = cache.suggestionMap.get(suggestion);
if (possiblyResolvedCompletionItem != null && possiblyResolvedCompletionItem.isResolved === false) {
const resolvedCompletionItem = await
server.connection.completionItemResolve(possiblyResolvedCompletionItem.completionItem);
if (resolvedCompletionItem != null) {
AutocompleteAdapter.resolveSuggestion(
resolvedCompletionItem, suggestion, request, onDidConvertCompletionItem);
possiblyResolvedCompletionItem.isResolved = true;
}
}
}
return suggestion;
}
public static resolveSuggestion(
resolvedCompletionItem: CompletionItem,
suggestion: ac.AnySuggestion,
request: ac.SuggestionsRequestedEvent,
onDidConvertCompletionItem?: CompletionItemAdjuster,
) {
// only the `documentation` and `detail` properties may change when resolving
AutocompleteAdapter.applyDetailsToSuggestion(resolvedCompletionItem, suggestion);
if (onDidConvertCompletionItem != null) {
onDidConvertCompletionItem(resolvedCompletionItem, suggestion as ac.AnySuggestion, request);
}
}
/**
* Public: Get the trigger character that caused the autocomplete (if any). This is required because
* AutoComplete-plus does not have trigger characters. Although the terminology is 'character' we treat
* them as variable length strings as this will almost certainly change in the future to support '->' etc.
*
* @param request An {Array} of {atom$AutocompleteSuggestion}s to locate the prefix, editor, bufferPosition etc.
* @param triggerChars The {Array} of {string}s that can be trigger characters.
* @returns A [{string}, boolean] where the string is the matching trigger character or an empty string
* if one was not matched, and the boolean is true if the trigger character is in request.prefix, and false
* if it is in the word before request.prefix. The boolean return value has no meaning if the string return
* value is an empty string.
*/
public static getTriggerCharacter(
request: ac.SuggestionsRequestedEvent,
triggerChars: string[],
): [string, boolean] {
// AutoComplete-Plus considers text after a symbol to be a new trigger. So we should look backward
// from the current cursor position to see if one is there and thus simulate it.
const buffer = request.editor.getBuffer();
const cursor = request.bufferPosition;
const prefixStartColumn = cursor.column - request.prefix.length;
for (const triggerChar of triggerChars) {
if (request.prefix.endsWith(triggerChar)) {
return [triggerChar, true];
}
if (prefixStartColumn >= triggerChar.length) { // Far enough along a line to fit the trigger char
const start = new Point(cursor.row, prefixStartColumn - triggerChar.length);
const possibleTrigger = buffer.getTextInRange([start, [cursor.row, prefixStartColumn]]);
if (possibleTrigger === triggerChar) { // The text before our trigger is a trigger char!
return [triggerChar, false];
}
}
}
// There was no explicit trigger char
return ['', false];
}
/**
* Public: Create TextDocumentPositionParams to be sent to the language server
* based on the editor and position from the AutoCompleteRequest.
*
* @param request The {atom$AutocompleteRequest} to obtain the editor from.
* @param triggerPoint The {atom$Point} where the trigger started.
* @returns A {string} containing the prefix including the trigger character.
*/
public static getPrefixWithTrigger(
request: ac.SuggestionsRequestedEvent,
triggerPoint: Point,
): string {
return request.editor
.getBuffer()
.getTextInRange([[triggerPoint.row, triggerPoint.column], request.bufferPosition]);
}
/**
* Public: Create {CompletionParams} to be sent to the language server
* based on the editor and position from the Autocomplete request etc.
*
* @param request The {atom$AutocompleteRequest} containing the request details.
* @param triggerCharacter The {string} containing the trigger character (empty if none).
* @param triggerOnly A {boolean} representing whether this completion is triggered right after a trigger character.
* @returns A {CompletionParams} with the keys:
* * `textDocument` the language server protocol textDocument identification.
* * `position` the position within the text document to display completion request for.
* * `context` containing the trigger character and kind.
*/
public static createCompletionParams(
request: ac.SuggestionsRequestedEvent,
triggerCharacter: string,
triggerOnly: boolean,
): CompletionParams {
return {
textDocument: Convert.editorToTextDocumentIdentifier(request.editor),
position: Convert.pointToPosition(request.bufferPosition),
context: AutocompleteAdapter.createCompletionContext(triggerCharacter, triggerOnly),
};
}
/**
* Public: Create {CompletionContext} to be sent to the language server
* based on the trigger character.
*
* @param triggerCharacter The {string} containing the trigger character or '' if none.
* @param triggerOnly A {boolean} representing whether this completion is triggered right after a trigger character.
* @returns An {CompletionContext} that specifies the triggerKind and the triggerCharacter
* if there is one.
*/
public static createCompletionContext(triggerCharacter: string, triggerOnly: boolean): CompletionContext {
if (triggerCharacter === '') {
return { triggerKind: CompletionTriggerKind.Invoked };
} else {
return triggerOnly
? { triggerKind: CompletionTriggerKind.TriggerCharacter, triggerCharacter }
: { triggerKind: CompletionTriggerKind.TriggerForIncompleteCompletions, triggerCharacter };
}
}
/**
* Public: Convert a language server protocol CompletionItem array or CompletionList to
* an array of ordered AutoComplete+ suggestions.
*
* @param completionItems An {Array} of {CompletionItem} objects or a {CompletionList} containing completion
* items to be converted.
* @param request The {atom$AutocompleteRequest} to satisfy.
* @param onDidConvertCompletionItem A function that takes a {CompletionItem}, an {atom$AutocompleteSuggestion}
* and a {atom$AutocompleteRequest} allowing you to adjust converted items.
* @returns A {Map} of AutoComplete+ suggestions ordered by the CompletionItems sortText.
*/
public completionItemsToSuggestions(
completionItems: CompletionItem[] | CompletionList | null,
request: ac.SuggestionsRequestedEvent,
triggerColumns: [number, number],
onDidConvertCompletionItem?: CompletionItemAdjuster,
): Map<Suggestion, PossiblyResolvedCompletionItem> {
const completionsArray = Array.isArray(completionItems)
? completionItems
: (completionItems && completionItems.items) || [];
return new Map(completionsArray
.sort((a, b) => (a.sortText || a.label).localeCompare(b.sortText || b.label))
.map<[Suggestion, PossiblyResolvedCompletionItem]>(
(s) => [
AutocompleteAdapter.completionItemToSuggestion(
s, {} as Suggestion, request, triggerColumns, onDidConvertCompletionItem),
new PossiblyResolvedCompletionItem(s, false),
],
),
);
}
/**
* Public: Convert a language server protocol CompletionItem to an AutoComplete+ suggestion.
*
* @param item An {CompletionItem} containing a completion item to be converted.
* @param suggestion A {atom$AutocompleteSuggestion} to have the conversion applied to.
* @param request The {atom$AutocompleteRequest} to satisfy.
* @param onDidConvertCompletionItem A function that takes a {CompletionItem}, an {atom$AutocompleteSuggestion}
* and a {atom$AutocompleteRequest} allowing you to adjust converted items.
* @returns The {atom$AutocompleteSuggestion} passed in as suggestion with the conversion applied.
*/
public static completionItemToSuggestion(
item: CompletionItem,
suggestion: Suggestion,
request: ac.SuggestionsRequestedEvent,
triggerColumns: [number, number],
onDidConvertCompletionItem?: CompletionItemAdjuster,
): Suggestion {
AutocompleteAdapter.applyCompletionItemToSuggestion(item, suggestion as TextSuggestion);
AutocompleteAdapter.applyTextEditToSuggestion(
item.textEdit, request.editor, triggerColumns, request.bufferPosition, suggestion as TextSuggestion,
);
AutocompleteAdapter.applySnippetToSuggestion(item, suggestion as SnippetSuggestion);
if (onDidConvertCompletionItem != null) {
onDidConvertCompletionItem(item, suggestion as ac.AnySuggestion, request);
}
return suggestion;
}
/**
* Public: Convert the primary parts of a language server protocol CompletionItem to an AutoComplete+ suggestion.
*
* @param item An {CompletionItem} containing the completion items to be merged into.
* @param suggestion The {Suggestion} to merge the conversion into.
* @returns The {Suggestion} with details added from the {CompletionItem}.
*/
public static applyCompletionItemToSuggestion(
item: CompletionItem,
suggestion: TextSuggestion,
) {
suggestion.text = item.insertText || item.label;
suggestion.filterText = item.filterText || item.label;
suggestion.displayText = item.label;
suggestion.type = AutocompleteAdapter.completionKindToSuggestionType(item.kind);
AutocompleteAdapter.applyDetailsToSuggestion(item, suggestion);
}
public static applyDetailsToSuggestion(
item: CompletionItem,
suggestion: Suggestion,
) {
suggestion.rightLabel = item.detail;
// Older format, can't know what it is so assign to both and hope for best
if (typeof (item.documentation) === 'string') {
suggestion.descriptionMarkdown = item.documentation;
suggestion.description = item.documentation;
}
if (item.documentation != null && typeof (item.documentation) === 'object') {
// Newer format specifies the kind of documentation, assign appropriately
if (item.documentation.kind === 'markdown') {
suggestion.descriptionMarkdown = item.documentation.value;
} else {
suggestion.description = item.documentation.value;
}
}
}
/**
* Public: Applies the textEdit part of a language server protocol CompletionItem to an
* AutoComplete+ Suggestion via the replacementPrefix and text properties.
*
* @param textEdit A {TextEdit} from a CompletionItem to apply.
* @param editor An Atom {TextEditor} used to obtain the necessary text replacement.
* @param suggestion An {atom$AutocompleteSuggestion} to set the replacementPrefix and text properties of.
*/
public static applyTextEditToSuggestion(
textEdit: TextEdit | undefined,
editor: TextEditor,
triggerColumns: [number, number],
originalBufferPosition: Point,
suggestion: TextSuggestion,
): void {
if (!textEdit) { return; }
if (textEdit.range.start.character !== triggerColumns[0]) {
const range = Convert.lsRangeToAtomRange(textEdit.range);
suggestion.customReplacmentPrefix = editor.getTextInBufferRange([range.start, originalBufferPosition]);
}
suggestion.text = textEdit.newText;
}
/**
* Public: Adds a snippet to the suggestion if the CompletionItem contains
* snippet-formatted text
*
* @param item An {CompletionItem} containing the completion items to be merged into.
* @param suggestion The {atom$AutocompleteSuggestion} to merge the conversion into.
*/
public static applySnippetToSuggestion(item: CompletionItem, suggestion: SnippetSuggestion): void {
if (item.insertTextFormat === InsertTextFormat.Snippet) {
suggestion.snippet = item.textEdit != null ? item.textEdit.newText : (item.insertText || '');
}
}
/**
* Public: Obtain the textual suggestion type required by AutoComplete+ that
* most closely maps to the numeric completion kind supplies by the language server.
*
* @param kind A {Number} that represents the suggestion kind to be converted.
* @returns A {String} containing the AutoComplete+ suggestion type equivalent
* to the given completion kind.
*/
public static completionKindToSuggestionType(kind: number | undefined): string {
switch (kind) {
case CompletionItemKind.Constant:
return 'constant';
case CompletionItemKind.Method:
return 'method';
case CompletionItemKind.Function:
case CompletionItemKind.Constructor:
return 'function';
case CompletionItemKind.Field:
case CompletionItemKind.Property:
return 'property';
case CompletionItemKind.Variable:
return 'variable';
case CompletionItemKind.Class:
return 'class';
case CompletionItemKind.Struct:
case CompletionItemKind.TypeParameter:
return 'type';
case CompletionItemKind.Operator:
return 'selector';
case CompletionItemKind.Interface:
return 'mixin';
case CompletionItemKind.Module:
return 'module';
case CompletionItemKind.Unit:
return 'builtin';
case CompletionItemKind.Enum:
case CompletionItemKind.EnumMember:
return 'enum';
case CompletionItemKind.Keyword:
return 'keyword';
case CompletionItemKind.Snippet:
return 'snippet';
case CompletionItemKind.File:
case CompletionItemKind.Folder:
return 'import';
case CompletionItemKind.Reference:
return 'require';
default:
return 'value';
}
}
} | the_stack |
import * as seedrandom from "seedrandom";
import { ENV } from "../../environment";
import * as util from "../../util";
import { TypedArray } from "../../util";
import * as broadcast_util from "../broadcast_util";
import * as concat_util from "../concat_util";
import { Conv2DInfo } from "../conv_util";
import { Array1D, Array2D, Array3D, Array4D, DataId, DataType, DataTypeMap,
IntDType, NDArray, Rank, Scalar } from "../ndarray";
import * as types from "../types";
import { MatrixOrientation, SumTypes, SumTypesMap } from "../types";
import * as axis_util from "./../axis_util";
import { MathBackend } from "./backend";
export class MathBackendCPU implements MathBackend {
private data = new WeakMap<DataId, DataTypeMap[DataType]>();
private canvas: HTMLCanvasElement;
constructor() {
if (typeof document !== "undefined") {
this.canvas = document.createElement("canvas");
}
}
register(dataId: DataId, shape: number[], dtype: DataType): void {
this.data.set(dataId, null);
}
write<D extends DataType>(dataId: DataId, values: DataTypeMap[D]): void {
if (values == null) {
throw new Error("MathBackendCPU.write(): values can not be null");
}
this.throwIfNoData(dataId);
this.data.set(dataId, values);
}
writePixels(
dataId: DataId,
pixels: ImageData | HTMLImageElement | HTMLCanvasElement |
HTMLVideoElement,
numChannels: number): void {
if (pixels == null) {
throw new Error("MathBackendCPU.writePixels(): pixels can not be null");
}
this.throwIfNoData(dataId);
let vals: Uint8ClampedArray;
if (pixels instanceof ImageData) {
vals = pixels.data;
} else if (pixels instanceof HTMLCanvasElement) {
vals = pixels.getContext("2d")
.getImageData(0, 0, pixels.width, pixels.height)
.data;
} else if (
pixels instanceof HTMLImageElement ||
pixels instanceof HTMLVideoElement) {
if (this.canvas == null) {
throw new Error(
"Can't read pixels from HTMLImageElement outside " +
"the browser.");
}
this.canvas.width = pixels.width;
this.canvas.height = pixels.height;
this.canvas.getContext("2d").drawImage(
pixels, 0, 0, pixels.width, pixels.height);
vals = this.canvas.getContext("2d")
.getImageData(0, 0, pixels.width, pixels.height)
.data;
} else {
throw new Error(
`pixels is of unknown type: ${(pixels as {}).constructor.name}`);
}
let values: Int32Array;
if (numChannels === 4) {
values = new Int32Array(vals);
} else {
const numPixels = pixels.width * pixels.height;
values = new Int32Array(numPixels * numChannels);
for (let i = 0; i < numPixels; i++) {
for (let channel = 0; channel < numChannels; ++channel) {
values[i * numChannels + channel] = vals[i * 4 + channel];
}
}
}
this.data.set(dataId, values);
}
async read<D extends DataType>(dataId: DataId): Promise<DataTypeMap[D]> {
this.throwIfNoData(dataId);
return this.data.get(dataId);
}
readSync<D extends DataType>(dataId: DataId): DataTypeMap[D] {
this.throwIfNoData(dataId);
return this.data.get(dataId);
}
disposeData(dataId: DataId): void {
this.data.delete(dataId);
}
async time(query: () => NDArray): Promise<number> {
const start = performance.now();
query();
return performance.now() - start;
}
private throwIfNoData(dataId: DataId) {
if (!this.data.has(dataId)) {
throw new Error(
`No data found for NDArray with data id ${dataId}. ` +
`Use dl.ENV.math instead of constructing your own NDArrayMath. ` +
`If you need to construct your own math, make sure this array is ` +
`allocated after the math construction`);
}
}
clone<T extends NDArray>(x: T): T {
const values = x.dataSync().slice();
return NDArray.make(x.shape, {values}, x.dtype) as T;
}
// Optimized version of gather for the case where axis = 0.
// writes into outData.
private gather0(indices: Int32Array, strideSize: number, inData: TypedArray,
outData: TypedArray): void {
const s = strideSize;
for (let outIndex = 0; outIndex < indices.length; ++outIndex) {
const inIndex = indices[outIndex];
const inSlice = inData.subarray(s * inIndex, s * (1 + inIndex));
const outSlice = outData.subarray(s * outIndex, s * (1 + outIndex));
outSlice.set(inSlice);
}
}
gather(x: NDArray, indices: Array1D<"int32">, axis: number): NDArray {
const outShape = x.shape.slice();
outShape[axis] = indices.shape[0];
const indicesA = indices.dataSync();
const inData = x.dataSync();
const result = NDArray.zeros(outShape, x.dtype);
const outData = result.dataSync();
const s = x.strides.length > axis ? x.strides[axis] : 1;
if (axis === 0) {
this.gather0(indicesA, s, inData, outData);
} else if (axis === 1) {
for (let i = 0; i < x.shape[0]; i++) {
const outSlice = outData.subarray(i * result.strides[0],
(i + 1) * result.strides[0]);
const inSlice = inData.subarray(i * x.strides[0],
(i + 1) * x.strides[0]);
this.gather0(indicesA, s, inSlice, outSlice);
}
} else {
throw Error("Not implemented dl/cpu/gather axis > 1");
}
return result;
}
pad(x: NDArray, paddings: Array<[number, number]>,
padValue: number): NDArray {
const xData = x.dataSync();
const shape = x.shape.slice();
const off = [];
for (let i = 0; i < paddings.length; ++i) {
const before = paddings[i][0];
const after = paddings[i][1];
shape[i] += before + after;
off.push(before);
}
const size = shape.reduce((a, b) => a * b);
const values = new Float32Array(size);
values.fill(padValue);
const result = NDArray.make(shape, {values});
switch (x.rank) {
case 1: {
values.subarray(off[0]).set(xData);
break;
}
case 2: {
for (let i = 0; i < x.shape[0]; ++i) {
const xRow = xData.subarray(x.strides[0] * i, x.strides[0] * (i + 1));
const valuesBegin = result.strides[0] * (i + off[0]) + off[1];
const valuesEnd = valuesBegin + x.strides[0];
const valuesRow = values.subarray(valuesBegin, valuesEnd);
valuesRow.set(xRow);
}
break;
}
case 3: {
for (let i = 0; i < x.shape[0]; ++i) {
for (let j = 0; j < x.shape[1]; ++j) {
const xRow = xData.subarray(
x.strides[0] * i + x.strides[1] * j,
x.strides[0] * i + x.strides[1] * (j + 1));
const valuesBegin =
result.strides[0] * (i + off[0]) +
result.strides[1] * (j + off[1]) +
off[2];
const valuesEnd = valuesBegin + x.strides[1];
const valuesRow = values.subarray(valuesBegin, valuesEnd);
valuesRow.set(xRow);
}
}
break;
}
default: {
throw Error("pad for rank > 2 not yet implemented.");
}
}
return result;
}
slice1D(x: Array1D, begin: number, size: number): Array1D {
const newVals = x.dataSync().slice(begin, begin + size);
return Array1D.new(newVals, x.dtype);
}
slice2D(x: Array2D, begin: [number, number], size: [number, number]):
Array2D {
const result = Array2D.zeros(size, x.dtype);
const [startI, startJ] = begin;
for (let i = 0; i < size[0]; ++i) {
for (let j = 0; j < size[1]; ++j) {
const val = x.get(i + startI, j + startJ);
result.set(val, i, j);
}
}
return result;
}
slice3D(x: Array3D, begin: [number, number, number], size: [
number, number, number
]): Array3D {
const result = Array3D.zeros(size, x.dtype);
const [startI, startJ, startK] = begin;
for (let i = 0; i < size[0]; ++i) {
for (let j = 0; j < size[1]; ++j) {
for (let k = 0; k < size[2]; ++k) {
const val = x.get(i + startI, j + startJ, k + startK);
result.set(val, i, j, k);
}
}
}
return result;
}
slice4D(x: Array4D, begin: [number, number, number, number], size: [
number, number, number, number
]): Array4D {
const result = Array4D.zeros(size, x.dtype);
const [startI, startJ, startK, startL] = begin;
for (let i = 0; i < size[0]; ++i) {
for (let j = 0; j < size[1]; ++j) {
for (let k = 0; k < size[2]; ++k) {
for (let l = 0; l < size[3]; ++l) {
const val = x.get(i + startI, j + startJ, k + startK, l + startL);
result.set(val, i, j, k, l);
}
}
}
}
return result;
}
concat1D(a: Array1D, b: Array1D): Array1D {
const outShape = concat_util.computeOutShape(a.shape, b.shape, 0);
const result = Array1D.zeros(outShape as [number]);
// Use built-in TypedArray.set() method for speed.
const aVals = a.dataSync();
const bVals = b.dataSync();
const vals = result.dataSync();
vals.set(aVals, 0);
vals.set(bVals, a.size);
return result;
}
concat2D(a: Array2D, b: Array2D, axis: number): Array2D {
const outShape = concat_util.computeOutShape(a.shape, b.shape, axis);
const result = Array2D.zeros(outShape as [number, number]);
if (axis === 0) {
// Use built-in TypedArray.set() method for speed.
const aVals = a.dataSync();
const bVals = b.dataSync();
const vals = result.dataSync();
vals.set(aVals, 0);
vals.set(bVals, a.size);
return result;
}
for (let i = 0; i < outShape[0]; ++i) {
for (let j = 0; j < outShape[1]; ++j) {
const index: [number, number] = [i, j];
let value: number;
if (index[axis] < a.shape[axis]) {
value = a.get(i, j);
} else {
index[axis] -= a.shape[axis];
const [i2, j2] = index;
value = b.get(i2, j2);
}
result.set(value, i, j);
}
}
return result;
}
concat3D(a: Array3D, b: Array3D, axis: number): Array3D {
const outShape = concat_util.computeOutShape(a.shape, b.shape, axis);
const result = Array3D.zeros(outShape as [number, number, number]);
if (axis === 0) {
// Use built-in TypedArray.set() method for speed.
const aVals = a.dataSync();
const bVals = b.dataSync();
const vals = result.dataSync();
vals.set(aVals, 0);
vals.set(bVals, a.size);
return result;
}
for (let i = 0; i < outShape[0]; ++i) {
for (let j = 0; j < outShape[1]; ++j) {
for (let k = 0; k < outShape[2]; ++k) {
// Shader begins.
const index: [number, number, number] = [i, j, k];
let value: number;
if (index[axis] < a.shape[axis]) {
value = a.get(i, j, k);
} else {
index[axis] -= a.shape[axis];
const [i2, j2, k2] = index;
value = b.get(i2, j2, k2);
}
result.set(value, i, j, k);
}
}
}
return result;
}
concat4D(a: Array4D, b: Array4D, axis: number): Array4D {
const outShape = concat_util.computeOutShape(a.shape, b.shape, axis);
const result = Array4D.zeros(outShape as [number, number, number, number]);
if (axis === 0) {
// Use built-in TypedArray.set() method for speed.
const aVals = a.dataSync();
const bVals = b.dataSync();
const vals = result.dataSync();
vals.set(aVals, 0);
vals.set(bVals, a.size);
return result;
}
for (let i = 0; i < outShape[0]; ++i) {
for (let j = 0; j < outShape[1]; ++j) {
for (let k = 0; k < outShape[2]; ++k) {
for (let l = 0; l < outShape[3]; ++l) {
// Shader begins.
const index: [number, number, number, number] = [i, j, k, l];
let value: number;
if (index[axis] < a.shape[axis]) {
value = a.get(i, j, k, l);
} else {
index[axis] -= a.shape[axis];
const [i2, j2, k2, l2] = index;
value = b.get(i2, j2, k2, l2);
}
result.set(value, i, j, k, l);
}
}
}
}
return result;
}
neg<T extends NDArray>(x: T): T {
return this.multiply(Scalar.new(-1), x) as T;
}
add<D extends DataType>(a: NDArray<D>, b: NDArray<D>): NDArray<D> {
return this.broadcastedBinaryOp(
a, b, types.upcastType(a.dtype, b.dtype),
(aValue, bValue) => aValue + bValue) as NDArray<D>;
}
subtract<D extends DataType>(a: NDArray<D>, b: NDArray<D>): NDArray<D> {
return this.broadcastedBinaryOp(
a, b, types.upcastType(a.dtype, b.dtype),
(aValue, bValue) => aValue - bValue) as NDArray<D>;
}
pow<T extends NDArray>(a: T, b: NDArray): T {
return this.broadcastedBinaryOp(
a, b, a.dtype, (aValue, bValue) => Math.pow(aValue, bValue)) as
T;
}
matMul(
a: Array2D, b: Array2D, aOrientation = MatrixOrientation.REGULAR,
bOrientation = MatrixOrientation.REGULAR): Array2D {
const sharedDim =
(aOrientation === MatrixOrientation.REGULAR) ? a.shape[1] : a.shape[0];
const leftDim =
(aOrientation === MatrixOrientation.REGULAR) ? a.shape[0] : a.shape[1];
const rightDim =
(bOrientation === MatrixOrientation.REGULAR) ? b.shape[1] : b.shape[0];
const aValues = a.dataSync();
const bValues = b.dataSync();
const [aOuterStep, aInnerStep] =
(aOrientation === MatrixOrientation.REGULAR)
? [a.strides[0], 1]
: [1, a.strides[0]];
const [bInnerStep, bOuterStep] =
(bOrientation === MatrixOrientation.REGULAR)
? [b.strides[0], 1]
: [1, b.strides[0]];
const aOuterEnd = leftDim * aOuterStep;
const bOuterEnd = rightDim * bOuterStep;
const result = util.getTypedArrayFromDType(a.dtype, leftDim * rightDim);
let resultIndex = 0;
for (let aOuter = 0; aOuter < aOuterEnd; aOuter += aOuterStep) {
for (let bOuter = 0; bOuter < bOuterEnd; bOuter += bOuterStep) {
let aInner = aOuter;
let bInner = bOuter;
let sum = 0;
for (let k = 0; k < sharedDim; ++k) {
sum += aValues[aInner] * bValues[bInner];
aInner += aInnerStep;
bInner += bInnerStep;
}
result[resultIndex++] = sum;
}
}
return Array2D.new([leftDim, rightDim], result, a.dtype);
}
multiply<D extends DataType>(a: NDArray<D>, b: NDArray<D>): NDArray<D> {
return this.broadcastedBinaryOp(
a, b, types.upcastType(a.dtype, b.dtype),
(aValue, bValue) => aValue * bValue) as NDArray<D>;
}
divide(a: NDArray, b: NDArray): NDArray<"float32"> {
return this.broadcastedBinaryOp(
a, b, "float32", (aValue, bValue) => aValue / bValue) as
NDArray<"float32">;
}
sum<D extends DataType>(x: NDArray<D>, axes: number[]): NDArray<SumTypes[D]> {
axis_util.assertAxesAreInnerMostDims("sum", axes, x.rank);
const [outShape, reduceShape] =
axis_util.computeOutAndReduceShapes(x.shape, axes);
const resultDtype = SumTypesMap[x.dtype] as keyof SumTypes;
const result = NDArray.zeros(outShape, resultDtype);
const reduceSize = util.sizeFromShape(reduceShape);
const vals = result.dataSync();
const aVals = x.dataSync();
for (let i = 0; i < vals.length; ++i) {
const offset = i * reduceSize;
let sum = 0;
for (let j = 0; j < reduceSize; ++j) {
sum += aVals[offset + j];
}
vals[i] = sum;
}
return result as NDArray<SumTypes[D]>;
}
argMin(x: NDArray, axes: number[]): NDArray<"int32"> {
axis_util.assertAxesAreInnerMostDims("argMin", axes, x.rank);
const [outShape, reduceShape] =
axis_util.computeOutAndReduceShapes(x.shape, axes);
const result = NDArray.zeros(outShape, "int32");
const reduceSize = util.sizeFromShape(reduceShape);
const vals = result.dataSync();
const aVals = x.dataSync();
for (let i = 0; i < vals.length; ++i) {
const offset = i * reduceSize;
let min = aVals[offset];
let minIndex = 0;
for (let j = 0; j < reduceSize; ++j) {
const value = aVals[offset + j];
if (isNaN(value)) {
minIndex = util.NAN_INT32;
break;
}
if (value < min) {
min = value;
minIndex = j;
}
}
vals[i] = minIndex;
}
return result;
}
argMax(x: NDArray, axes: number[]): NDArray<"int32"> {
axis_util.assertAxesAreInnerMostDims("argMax", axes, x.rank);
const [outShape, reduceShape] =
axis_util.computeOutAndReduceShapes(x.shape, axes);
const result = NDArray.zeros(outShape, "int32");
const reduceSize = util.sizeFromShape(reduceShape);
const vals = result.dataSync();
const aVals = x.dataSync();
for (let i = 0; i < vals.length; ++i) {
const offset = i * reduceSize;
let max = aVals[offset];
let maxIndex = 0;
for (let j = 0; j < reduceSize; ++j) {
const value = aVals[offset + j];
if (isNaN(value)) {
maxIndex = util.NAN_INT32;
break;
}
if (value > max) {
max = value;
maxIndex = j;
}
}
vals[i] = maxIndex;
}
return result;
}
equal(a: NDArray, b: NDArray): NDArray<"bool"> {
return this.broadcastedBinaryOp(a, b, "bool", (aVal, bVal) => {
if (util.isValNaN(aVal, a.dtype) || util.isValNaN(bVal, b.dtype)) {
return util.getNaN("bool");
} else {
return (aVal === bVal) ? 1 : 0;
}
});
}
notEqual(a: NDArray, b: NDArray): NDArray<"bool"> {
return this.broadcastedBinaryOp(a, b, "bool", (aVal, bVal) => {
if (util.isValNaN(aVal, a.dtype) || util.isValNaN(bVal, b.dtype)) {
return util.getNaN("bool");
} else {
return (aVal !== bVal) ? 1 : 0;
}
});
}
greater(a: NDArray, b: NDArray): NDArray<"bool"> {
return this.broadcastedBinaryOp(a, b, "bool", (aVal, bVal) => {
if (util.isValNaN(aVal, a.dtype) || util.isValNaN(bVal, b.dtype)) {
return util.getNaN("bool");
} else {
return (aVal > bVal) ? 1 : 0;
}
});
}
greaterEqual(a: NDArray, b: NDArray): NDArray<"bool"> {
return this.broadcastedBinaryOp(a, b, "bool", (aVal, bVal) => {
if (util.isValNaN(aVal, a.dtype) || util.isValNaN(bVal, b.dtype)) {
return util.getNaN("bool");
} else {
return (aVal >= bVal) ? 1 : 0;
}
});
}
less(a: NDArray, b: NDArray): NDArray<"bool"> {
return this.broadcastedBinaryOp(a, b, "bool", (aVal, bVal) => {
if (util.isValNaN(aVal, a.dtype) || util.isValNaN(bVal, b.dtype)) {
return util.getNaN("bool");
} else {
return (aVal < bVal) ? 1 : 0;
}
});
}
lessEqual(a: NDArray, b: NDArray): NDArray<"bool"> {
return this.broadcastedBinaryOp(a, b, "bool", (aVal, bVal) => {
if (util.isValNaN(aVal, a.dtype) || util.isValNaN(bVal, b.dtype)) {
return util.getNaN("bool");
} else {
return (aVal <= bVal) ? 1 : 0;
}
});
}
select(cond: NDArray<"bool">, a: NDArray, b: NDArray): NDArray {
return this.ternaryOp(cond, a, b, a.dtype, (condVal, aVal, bVal) => {
return condVal ? aVal : bVal;
});
}
topKValues<D extends DataType, T extends NDArray<D>>(x: T, k: number):
Array1D<D> {
return this.topK(x, k).values as Array1D<D>;
}
topKIndices(x: NDArray, k: number): Array1D<"int32"> {
return this.topK(x, k).indices;
}
private topK<D extends DataType, T extends NDArray<D>>(x: T, k: number):
{values: Array1D<D>, indices: Array1D<"int32">} {
const values = x.dataSync();
const valuesAndIndices: Array<{value: number, index: number}> = [];
for (let i = 0; i < values.length; i++) {
valuesAndIndices.push({value: values[i], index: i});
}
valuesAndIndices.sort((a, b) => {
return b.value - a.value;
});
const topkValues = util.getTypedArrayFromDType(x.dtype, k);
const topkIndices = new Int32Array(k);
for (let i = 0; i < k; i++) {
topkValues[i] = valuesAndIndices[i].value;
topkIndices[i] = valuesAndIndices[i].index;
}
return {
values: Array1D.new<D>(topkValues),
indices: Array1D.new<"int32">(topkIndices)
};
}
min<D extends DataType>(x: NDArray<D>, axes: number[]): NDArray<D> {
axis_util.assertAxesAreInnerMostDims("min", axes, x.rank);
const [outShape, reduceShape] =
axis_util.computeOutAndReduceShapes(x.shape, axes);
const result = NDArray.zeros(outShape, x.dtype);
const reduceSize = util.sizeFromShape(reduceShape);
const vals = result.dataSync();
const aVals = x.dataSync();
for (let i = 0; i < vals.length; ++i) {
const offset = i * reduceSize;
let min = aVals[0];
for (let j = 0; j < reduceSize; ++j) {
const value = aVals[offset + j];
if (isNaN(value)) {
min = Number.NaN;
break;
}
if (value < min) {
min = value;
}
}
vals[i] = min;
}
return result;
}
minimum<D extends DataType>(a: NDArray<D>, b: NDArray<D>): NDArray<D> {
return this.broadcastedBinaryOp(
a, b, a.dtype, (aVal, bVal) => Math.min(aVal, bVal));
}
max<D extends DataType>(x: NDArray<D>, axes: number[]): NDArray<D> {
axis_util.assertAxesAreInnerMostDims("max", axes, x.rank);
const [outShape, reduceShape] =
axis_util.computeOutAndReduceShapes(x.shape, axes);
const result = NDArray.zeros(outShape, x.dtype);
const reduceSize = util.sizeFromShape(reduceShape);
const vals = result.dataSync();
const aVals = x.dataSync();
for (let i = 0; i < vals.length; ++i) {
const offset = i * reduceSize;
let max = aVals[offset];
for (let j = 0; j < reduceSize; ++j) {
const value = aVals[offset + j];
if (isNaN(value)) {
max = Number.NaN;
break;
}
if (value > max) {
max = value;
}
}
vals[i] = max;
}
return result;
}
maximum<D extends DataType>(a: NDArray<D>, b: NDArray<D>): NDArray<D> {
return this.broadcastedBinaryOp(
a, b, a.dtype, (aVal, bVal) => Math.max(aVal, bVal));
}
ceil<T extends NDArray>(x: T): T {
const values = x.dataSync();
const newValues = new Float32Array(values.length);
for (let i = 0; i < values.length; ++i) {
newValues[i] = Math.ceil(values[i]);
}
return NDArray.make(x.shape, {values: newValues}) as T;
}
floor<T extends NDArray>(x: T): T {
const values = x.dataSync();
const newValues = new Float32Array(values.length);
for (let i = 0; i < values.length; ++i) {
newValues[i] = Math.floor(values[i]);
}
return NDArray.make(x.shape, {values: newValues}) as T;
}
exp<T extends NDArray>(x: T): T {
const values = x.dataSync();
const newValues = new Float32Array(values.length);
for (let i = 0; i < values.length; ++i) {
newValues[i] = Math.exp(values[i]);
}
return NDArray.make(x.shape, {values: newValues}) as T;
}
log<T extends NDArray>(x: T): T {
const values = x.dataSync();
const newValues = new Float32Array(values.length);
for (let i = 0; i < values.length; ++i) {
const value = values[i];
newValues[i] = Math.log(value);
}
return NDArray.make(x.shape, {values: newValues}) as T;
}
sqrt<T extends NDArray>(x: T): T {
const values = x.dataSync();
const newValues = new Float32Array(values.length);
for (let i = 0; i < values.length; ++i) {
const value = values[i];
newValues[i] = Math.sqrt(value);
}
return NDArray.make(x.shape, {values: newValues}) as T;
}
square<T extends NDArray>(x: T): T {
const values = x.dataSync();
const newValues = new Float32Array(values.length);
for (let i = 0; i < values.length; ++i) {
const value = values[i];
newValues[i] = value * value;
}
return NDArray.make(x.shape, {values: newValues}) as T;
}
relu<T extends NDArray>(x: T): T {
const res = NDArray.zeros(x.shape, x.dtype);
const resVals = res.dataSync();
const inVals = x.dataSync();
for (let i = 0; i < inVals.length; ++i) {
const val = inVals[i];
if (util.isValNaN(val, x.dtype)) {
resVals[i] = util.getNaN(res.dtype);
} else {
resVals[i] = Math.max(0, inVals[i]);
}
}
return res as T;
}
elu<T extends NDArray>(x: T): T {
const resultValues = new Float32Array(x.size);
const values = x.dataSync();
for (let i = 0; i < values.length; ++i) {
const v = values[i];
if (v >= 0) {
resultValues[i] = v;
} else {
resultValues[i] = (Math.exp(v) - 1);
}
}
return NDArray.make(x.shape, {values: resultValues}) as T;
}
eluDer<T extends NDArray>(x: T): T {
const resultValues = new Float32Array(x.size);
const values = x.dataSync();
for (let i = 0; i < values.length; ++i) {
const v = values[i];
if (v >= 0) {
resultValues[i] = 1;
} else {
resultValues[i] = Math.exp(v);
}
}
return NDArray.make(x.shape, {values: resultValues}) as T;
}
selu<T extends NDArray>(x: T): T {
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
const scaleAlpha = 1.7580993408473768599402175208123;
const scale = 1.0507009873554804934193349852946;
const resultValues = new Float32Array(x.size);
const values = x.dataSync();
for (let i = 0; i < values.length; ++i) {
const v = values[i];
if (v >= 0) {
resultValues[i] = scale * v;
} else {
resultValues[i] = scaleAlpha * (Math.exp(v) - 1);
}
}
return NDArray.make(x.shape, {values: resultValues}) as T;
}
leakyRelu<T extends NDArray>(x: T, alpha: number) {
const resultValues = new Float32Array(x.size);
const values = x.dataSync();
for (let i = 0; i < values.length; i++) {
const v = values[i];
if (v >= 0) {
resultValues[i] = v;
} else {
resultValues[i] = alpha * v;
}
}
return NDArray.make(x.shape, {values: resultValues}) as T;
}
prelu<T extends NDArray>(x: T, alpha: T) {
const resultValues = new Float32Array(x.size);
const values = x.dataSync();
const alphas = alpha.dataSync();
for (let i = 0; i < values.length; i++) {
const v = values[i];
if (v >= 0) {
resultValues[i] = v;
} else {
resultValues[i] = alphas[i] * v;
}
}
return NDArray.make(x.shape, {values: resultValues}) as T;
}
preluDer<T extends NDArray>(x: T, alpha: T) {
const resultValues = new Float32Array(x.size);
const values = x.dataSync();
const alphas = alpha.dataSync();
for (let i = 0; i < values.length; i++) {
const v = values[i];
if (v > 0) {
resultValues[i] = 1;
} else if (v < 0) {
resultValues[i] = alphas[i];
} else {
resultValues[i] = v;
}
}
return NDArray.make(x.shape, {values: resultValues}) as T;
}
clip<T extends NDArray>(x: T, min: number, max: number): T {
const resultValues = new Float32Array(x.size);
const values = x.dataSync();
for (let i = 0; i < values.length; ++i) {
resultValues[i] = Math.min(max, Math.max(min, values[i]));
}
return NDArray.make(x.shape, {values: resultValues}) as T;
}
abs<T extends NDArray>(x: T): T {
const resultValues = util.getTypedArrayFromDType(x.dtype, x.size);
const values = x.dataSync();
for (let i = 0; i < values.length; ++i) {
resultValues[i] = Math.abs(values[i]);
}
return NDArray.make(x.shape, {values: resultValues}, x.dtype) as T;
}
int<D extends IntDType, R extends Rank>(
x: NDArray<DataType, R>, dtype: D): NDArray<D, R> {
const resultValues = util.getTypedArrayFromDType(dtype, x.size);
const values = x.dataSync();
for (let i = 0; i < values.length; ++i) {
resultValues[i] = values[i];
}
return NDArray.make(x.shape, {values: resultValues}, dtype) as
NDArray<D, R>;
}
sigmoid<T extends NDArray>(x: T): T {
const resultValues = new Float32Array(x.size);
const values = x.dataSync();
for (let i = 0; i < values.length; ++i) {
resultValues[i] = 1 / (1 + Math.exp(-values[i]));
}
return NDArray.make(x.shape, {values: resultValues}) as T;
}
sin<T extends NDArray>(x: T): T {
const resultValues = new Float32Array(x.size);
const values = x.dataSync();
for (let i = 0; i < values.length; ++i) {
resultValues[i] = Math.sin(values[i]);
}
return NDArray.make(x.shape, {values: resultValues}) as T;
}
cos<T extends NDArray>(x: T): T {
const resultValues = new Float32Array(x.size);
const values = x.dataSync();
for (let i = 0; i < values.length; ++i) {
resultValues[i] = Math.cos(values[i]);
}
return NDArray.make(x.shape, {values: resultValues}) as T;
}
tan<T extends NDArray>(x: T): T {
const resultValues = new Float32Array(x.size);
const values = x.dataSync();
for (let i = 0; i < values.length; ++i) {
resultValues[i] = Math.tan(values[i]);
}
return NDArray.make(x.shape, {values: resultValues}) as T;
}
asin<T extends NDArray>(x: T): T {
const resultValues = new Float32Array(x.size);
const values = x.dataSync();
for (let i = 0; i < values.length; ++i) {
resultValues[i] = Math.asin(values[i]);
}
return NDArray.make(x.shape, {values: resultValues}) as T;
}
acos<T extends NDArray>(x: T): T {
const resultValues = new Float32Array(x.size);
const values = x.dataSync();
for (let i = 0; i < values.length; ++i) {
resultValues[i] = Math.acos(values[i]);
}
return NDArray.make(x.shape, {values: resultValues}) as T;
}
atan<T extends NDArray>(x: T): T {
const resultValues = new Float32Array(x.size);
const values = x.dataSync();
for (let i = 0; i < values.length; ++i) {
resultValues[i] = Math.atan(values[i]);
}
return NDArray.make(x.shape, {values: resultValues}) as T;
}
sinh<T extends NDArray>(x: T): T {
const resultValues = new Float32Array(x.size);
const values = x.dataSync();
for (let i = 0; i < values.length; ++i) {
resultValues[i] = Math.sinh(values[i]);
}
return NDArray.make(x.shape, {values: resultValues}) as T;
}
cosh<T extends NDArray>(x: T): T {
const resultValues = new Float32Array(x.size);
const values = x.dataSync();
for (let i = 0; i < values.length; ++i) {
resultValues[i] = Math.cosh(values[i]);
}
return NDArray.make(x.shape, {values: resultValues}) as T;
}
tanh<T extends NDArray>(x: T): T {
const resultValues = new Float32Array(x.size);
const values = x.dataSync();
for (let i = 0; i < values.length; ++i) {
resultValues[i] = util.tanh(values[i]);
}
return NDArray.make(x.shape, {values: resultValues}) as T;
}
step<T extends NDArray>(x: T, alpha = 0): T {
const resultValues = new Float32Array(x.size);
const values = x.dataSync();
for (let i = 0; i < values.length; ++i) {
const value = values[i];
if (util.isValNaN(value, x.dtype)) {
resultValues[i] = util.getNaN(x.dtype);
} else {
resultValues[i] = value > 0 ? 1 : alpha;
}
}
return NDArray.make(x.shape, {values: resultValues}) as T;
}
conv2d(x: Array4D, filter: Array4D, bias: Array1D | null,
convInfo: Conv2DInfo): Array4D {
const filterHeight = convInfo.filterHeight;
const filterWidth = convInfo.filterWidth;
const padLeft = convInfo.padInfo.left;
const padTop = convInfo.padInfo.top;
const y = Array4D.zeros(convInfo.outShape);
for (let b = 0; b < convInfo.batchSize; ++b) {
for (let d2 = 0; d2 < convInfo.outChannels; ++d2) {
for (let yR = 0; yR < convInfo.outHeight; ++yR) {
const xRCorner = yR * convInfo.strideHeight - padLeft;
const xRMin = Math.max(0, xRCorner);
const xRMax = Math.min(convInfo.inHeight, filterHeight + xRCorner);
for (let yC = 0; yC < convInfo.outWidth; ++yC) {
const xCCorner = yC * convInfo.strideWidth - padTop;
const xCMin = Math.max(0, xCCorner);
const xCMax = Math.min(convInfo.inWidth, filterWidth + xCCorner);
let dotProd = 0;
for (let xR = xRMin; xR < xRMax; ++xR) {
const wR = xR - xRCorner;
for (let xC = xCMin; xC < xCMax; ++xC) {
const wC = xC - xCCorner;
for (let d1 = 0; d1 < convInfo.inChannels; ++d1) {
const pixel = x.get(b, xR, xC, d1);
const weight = filter.get(wR, wC, d1, d2);
dotProd += pixel * weight;
}
}
}
const biasVal = (bias != null) ? bias.get(d2) : 0;
y.set(dotProd + biasVal, b, yR, yC, d2);
}
}
}
}
return y;
}
conv2dDerInput(dy: Array4D, filter: Array4D, convInfo: Conv2DInfo): Array4D {
const filterHeight = convInfo.filterHeight;
const filterWidth = convInfo.filterWidth;
const topPad = filterHeight - 1 - convInfo.padInfo.top;
const leftPad = filterWidth - 1 - convInfo.padInfo.left;
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const dx = Array4D.zeros(convInfo.inShape);
for (let b = 0; b < convInfo.batchSize; ++b) {
for (let d1 = 0; d1 < convInfo.inChannels; ++d1) {
for (let xR = 0; xR < convInfo.inHeight; ++xR) {
const xRCorner = xR - leftPad;
const xRMin = Math.max(0, Math.ceil(xRCorner / strideHeight));
const yRMax = Math.min(
convInfo.outHeight, (filterHeight + xRCorner) / strideHeight);
for (let xC = 0; xC < convInfo.inWidth; ++xC) {
const xCCorner = xC - topPad;
const xCMin = Math.max(0, Math.ceil(xCCorner / strideWidth));
const yCMax = Math.min(
convInfo.outWidth, (filterWidth + xCCorner) / strideWidth);
let dotProd = 0;
for (let yR = xRMin; yR < yRMax; ++yR) {
const wR = yR * strideHeight - xRCorner;
for (let yC = xCMin; yC < yCMax; ++yC) {
const wC = yC * strideWidth - xCCorner;
for (let d2 = 0; d2 < convInfo.outChannels; ++d2) {
const pixel = dy.get(b, yR, yC, d2);
const weight = filter.get(
filterHeight - 1 - wR, filterWidth - 1 - wC, d1, d2);
dotProd += pixel * weight;
}
}
}
dx.set(dotProd, b, xR, xC, d1);
}
}
}
}
return dx;
}
conv2dDerFilter(x: Array4D, dy: Array4D, convInfo: Conv2DInfo): Array4D {
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const filterHeight = convInfo.filterHeight;
const filterWidth = convInfo.filterWidth;
const dW = Array4D.zeros(convInfo.filterShape);
const leftPad = convInfo.padInfo.left;
const topPad = convInfo.padInfo.top;
for (let wR = 0; wR < filterHeight; ++wR) {
const yRMin = Math.max(0, Math.ceil((topPad - wR) / strideHeight));
const yRMax = Math.min(
convInfo.outHeight, (convInfo.inHeight + topPad - wR) / strideHeight);
for (let wC = 0; wC < filterWidth; ++wC) {
const yCMin = Math.max(0, Math.ceil((leftPad - wC) / strideWidth));
const yCMax = Math.min(
convInfo.outWidth, (convInfo.inWidth + leftPad - wC) / strideWidth);
for (let d1 = 0; d1 < convInfo.inChannels; ++d1) {
for (let d2 = 0; d2 < convInfo.outChannels; ++d2) {
// Need to convolve.
let dotProd = 0;
for (let b = 0; b < convInfo.batchSize; ++b) {
for (let yR = yRMin; yR < yRMax; ++yR) {
const xR = wR + yR * strideHeight - topPad;
for (let yC = yCMin; yC < yCMax; ++yC) {
const xC = wC + yC * strideWidth - leftPad;
dotProd += x.get(b, xR, xC, d1) * dy.get(b, yR, yC, d2);
}
}
}
dW.set(dotProd, wR, wC, d1, d2);
}
}
}
}
return dW;
}
conv2dDerBias(dy: Array4D): Array1D {
const [batchSize, numRows, numCols, outDepth] = dy.shape;
const values = new Float32Array(outDepth);
for (let d2 = 0; d2 < outDepth; ++d2) {
let sum = 0;
for (let b = 0; b < batchSize; ++b) {
for (let r = 0; r < numRows; ++r) {
for (let c = 0; c < numCols; ++c) {
sum += dy.get(b, r, c, d2);
}
}
}
values[d2] = sum;
}
return Array1D.new(values);
}
depthwiseConv2D(x: Array4D, filter: Array4D, convInfo: Conv2DInfo): Array4D {
const filterHeight = convInfo.filterHeight;
const filterWidth = convInfo.filterWidth;
const padLeft = convInfo.padInfo.left;
const padTop = convInfo.padInfo.top;
const chMul = convInfo.outChannels / convInfo.inChannels;
const y = Array4D.zeros(convInfo.outShape);
for (let b = 0; b < convInfo.batchSize; ++b) {
for (let d1 = 0; d1 < convInfo.inChannels; ++d1) {
for (let yR = 0; yR < convInfo.outHeight; ++yR) {
const xRCorner = yR * convInfo.strideHeight - padLeft;
const xRMin = Math.max(0, xRCorner);
const xRMax = Math.min(convInfo.inHeight, filterHeight + xRCorner);
for (let yC = 0; yC < convInfo.outWidth; ++yC) {
const xCCorner = yC * convInfo.strideWidth - padTop;
const xCMin = Math.max(0, xCCorner);
const xCMax = Math.min(convInfo.inWidth, filterWidth + xCCorner);
for (let q = 0; q < chMul; ++q) {
let dotProd = 0;
for (let xR = xRMin; xR < xRMax; ++xR) {
const wR = xR - xRCorner;
for (let xC = xCMin; xC < xCMax; ++xC) {
const wC = xC - xCCorner;
const pixel = x.get(b, xR, xC, d1);
const weight = filter.get(wR, wC, d1, q);
dotProd += pixel * weight;
}
}
y.set(dotProd, b, yR, yC, d1 * chMul + q);
}
}
}
}
}
return y;
}
tile<D extends DataType, T extends NDArray<D>>(x: T, reps: number[]): T {
const newShape: number[] = new Array(x.rank);
for (let i = 0; i < newShape.length; i++) {
newShape[i] = x.shape[i] * reps[i];
}
const size = util.sizeFromShape(newShape);
const resultValues = util.getTypedArrayFromDType(x.dtype, size);
const result = NDArray.make(newShape, {values: resultValues}, x.dtype) as T;
const values = x.dataSync();
for (let i = 0; i < result.size; ++i) {
const newLoc = result.indexToLoc(i);
const originalLoc: number[] = new Array(x.rank);
for (let i = 0; i < originalLoc.length; i++) {
originalLoc[i] = newLoc[i] % x.shape[i];
}
const originalIndex = x.locToIndex(originalLoc);
resultValues[i] = values[originalIndex];
}
return result;
}
transpose<D extends DataType, T extends NDArray<D>>(x: T, perm: number[]): T {
const newShape: number[] = new Array(x.rank);
for (let i = 0; i < newShape.length; i++) {
newShape[i] = x.shape[perm[i]];
}
const resultValues = util.getTypedArrayFromDType(x.dtype, x.size);
const values = x.dataSync();
const result = NDArray.make(newShape, {values: resultValues}, x.dtype) as T;
for (let i = 0; i < x.size; ++i) {
const loc = x.indexToLoc(i);
// Permute location.
const newLoc: number[] = new Array(loc.length);
for (let i = 0; i < newLoc.length; i++) {
newLoc[i] = loc[perm[i]];
}
const newIndex = result.locToIndex(newLoc);
resultValues[newIndex] = values[i];
}
return result;
}
private pool(x: Array4D, convInfo: Conv2DInfo,
poolType: "max" | "min" | "avg") {
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const filterHeight = convInfo.filterHeight;
const filterWidth = convInfo.filterWidth;
const y = Array4D.zeros(convInfo.outShape);
const padTop = convInfo.padInfo.top;
const padLeft = convInfo.padInfo.left;
for (let b = 0; b < convInfo.batchSize; ++b) {
for (let d = 0; d < convInfo.inChannels; ++d) {
for (let yR = 0; yR < convInfo.outHeight; ++yR) {
const xRCorner = yR * strideHeight - padTop;
const xRMin = Math.max(0, xRCorner);
const xRMax = Math.min(convInfo.inHeight, filterHeight + xRCorner);
for (let yC = 0; yC < convInfo.outWidth; ++yC) {
const xCCorner = yC * strideWidth - padLeft;
const xCMin = Math.max(0, xCCorner);
const xCMax = Math.min(convInfo.inWidth, filterWidth + xCCorner);
let minMaxValue =
(poolType === "max" ? Number.NEGATIVE_INFINITY :
Number.POSITIVE_INFINITY);
let avgValue = 0;
for (let xR = xRMin; xR < xRMax; ++xR) {
for (let xC = xCMin; xC < xCMax; ++xC) {
const pixel = x.get(b, xR, xC, d);
if (isNaN(pixel)) {
minMaxValue = NaN;
avgValue = NaN;
break;
}
if ((poolType === "max" && pixel > minMaxValue) ||
(poolType === "min" && pixel < minMaxValue)) {
minMaxValue = pixel;
} else if (poolType === "avg") {
avgValue += pixel / (filterHeight * filterWidth);
}
}
if (isNaN(minMaxValue)) {
break;
}
}
y.set(poolType === "avg" ? avgValue : minMaxValue, b, yR, yC, d);
}
}
}
}
return y;
}
maxPool(x: Array4D, convInfo: Conv2DInfo): Array4D {
return this.pool(x, convInfo, "max");
}
maxPoolPositions(x: Array4D, convInfo: Conv2DInfo) {
const maxPositions = Array4D.zeros(convInfo.outShape);
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const filterHeight = convInfo.filterHeight;
const filterWidth = convInfo.filterWidth;
const padTop = convInfo.padInfo.top;
const padLeft = convInfo.padInfo.left;
for (let b = 0; b < convInfo.batchSize; ++b) {
for (let d = 0; d < convInfo.inChannels; ++d) {
for (let yR = 0; yR < convInfo.outHeight; ++yR) {
const xRCorner = yR * strideHeight - padTop;
const xRMin = Math.max(0, xRCorner);
const xRMax = Math.min(convInfo.inHeight, filterHeight + xRCorner);
for (let yC = 0; yC < convInfo.outWidth; ++yC) {
const xCCorner = yC * strideWidth - padLeft;
const xCMin = Math.max(0, xCCorner);
const xCMax = Math.min(convInfo.inWidth, filterWidth + xCCorner);
let maxValue = Number.NEGATIVE_INFINITY;
let maxPosition = -1;
for (let xR = xRMin; xR < xRMax; ++xR) {
const wR = xR - xRCorner;
for (let xC = xCMin; xC < xCMax; ++xC) {
const wC = xC - xCCorner;
const pixel = x.get(b, xR, xC, d);
if (pixel > maxValue) {
maxValue = pixel;
maxPosition = wR * filterWidth + wC;
}
}
}
maxPositions.set(maxPosition, b, yR, yC, d);
}
}
}
}
return maxPositions;
}
maxPoolBackprop(dy: Array4D, x: Array4D, convInfo: Conv2DInfo): Array4D {
const maxPositions = this.maxPoolPositions(x, convInfo);
const strideHeight = convInfo.strideHeight;
const strideWidth = convInfo.strideWidth;
const filterHeight = convInfo.filterHeight;
const filterWidth = convInfo.filterWidth;
const padLeft = filterWidth - 1 - convInfo.padInfo.left;
const padTop = filterHeight - 1 - convInfo.padInfo.top;
const dx = Array4D.zeros(x.shape);
for (let b = 0; b < convInfo.batchSize; ++b) {
for (let d = 0; d < convInfo.inChannels; ++d) {
for (let dxR = 0; dxR < convInfo.inHeight; ++dxR) {
for (let dxC = 0; dxC < convInfo.inWidth; ++dxC) {
// Shader code begins.
const dyRCorner = dxR - padTop;
const dyCCorner = dxC - padLeft;
let dotProd = 0;
for (let wR = 0; wR < filterHeight; ++wR) {
const dyR = (dyRCorner + wR) / strideHeight;
if (dyR < 0 || dyR >= convInfo.outHeight ||
Math.floor(dyR) !== dyR) {
continue;
}
for (let wC = 0; wC < filterWidth; ++wC) {
const dyC = (dyCCorner + wC) / strideWidth;
if (dyC < 0 || dyC >= convInfo.outWidth ||
Math.floor(dyC) !== dyC) {
continue;
}
const maxPos = filterHeight * filterWidth - 1 -
maxPositions.get(b, dyR, dyC, d);
const curPos = wR * filterWidth + wC;
const mask = maxPos === curPos ? 1 : 0;
if (mask === 0) {
continue;
}
const pixel = dy.get(b, dyR, dyC, d);
dotProd += pixel * mask;
}
}
dx.set(dotProd, b, dxR, dxC, d);
}
}
}
}
return dx;
}
minPool(x: Array4D, convInfo: Conv2DInfo): Array4D {
return this.pool(x, convInfo, "min");
}
avgPool(x: Array4D, convInfo: Conv2DInfo): Array4D {
return this.pool(x, convInfo, "avg");
}
resizeBilinear3D(
x: Array3D, newShape2D: [number, number],
alignCorners: boolean): Array3D {
const output = Array3D.zeros([newShape2D[0], newShape2D[1], x.shape[2]]);
const effectiveInputSize =
alignCorners ? [x.shape[0] - 1, x.shape[1] - 1, x.shape[2]] : x.shape;
const effectiveOutputSize = alignCorners ?
[output.shape[0] - 1, output.shape[1] - 1, output.shape[2]] :
output.shape;
for (let r = 0; r < output.shape[0]; r++) {
for (let c = 0; c < output.shape[1]; c++) {
for (let d = 0; d < output.shape[2]; d++) {
// Begin shader.
// Compute the fractional index of the source.
const sourceFracRow =
(effectiveInputSize[0]) * r / (effectiveOutputSize[0]);
const sourceFracCol =
(effectiveInputSize[1]) * c / (effectiveOutputSize[1]);
const sourceRowFloor = Math.floor(sourceFracRow);
const sourceRowCeil =
Math.min(x.shape[0] - 1, Math.ceil(sourceFracRow));
const sourceColFloor = Math.floor(sourceFracCol);
const sourceColCeil =
Math.min(x.shape[1] - 1, Math.ceil(sourceFracCol));
const topLeft = x.get(sourceRowFloor, sourceColFloor, d);
const bottomLeft = x.get(sourceRowCeil, sourceColFloor, d);
const topRight = x.get(sourceRowFloor, sourceColCeil, d);
const bottomRight = x.get(sourceRowCeil, sourceColCeil, d);
const rowFrac = sourceFracRow - sourceRowFloor;
const colFrac = sourceFracCol - sourceColFloor;
const top = topLeft + (topRight - topLeft) * colFrac;
const bottom = bottomLeft + (bottomRight - bottomLeft) * colFrac;
const newValue = top + (bottom - top) * rowFrac;
output.set(newValue, r, c, d);
}
}
}
return output;
}
multinomial(probabilities: Array2D, numSamples: number, seed: number):
Array2D<"int32"> {
const batchSize = probabilities.shape[0];
const numEvents = probabilities.shape[1];
const res = Array2D.zeros([batchSize, numSamples], "int32");
const resVals = res.dataSync();
const probVals = probabilities.dataSync();
for (let b = 0; b < batchSize; ++b) {
const offset = b * numEvents;
// The cdf won't include the last event. It will be implicit if no other
// event happened.
const cdf = new Float32Array(numEvents - 1);
cdf[0] = probVals[offset];
for (let event = 1; event < cdf.length; ++event) {
cdf[event] = cdf[event - 1] + probVals[offset + event];
}
const random = seedrandom.alea(seed.toString());
const outOffset = b * numSamples;
for (let sampleId = 0; sampleId < numSamples; ++sampleId) {
const r = random();
// Assume last event happened by default.
resVals[outOffset + sampleId] = cdf.length;
for (let event = 0; event < cdf.length; event++) {
if (r < cdf[event]) {
resVals[outOffset + sampleId] = event;
break;
}
}
}
}
return res;
}
oneHot(indices: Array1D, depth: number, onValue: number, offValue: number):
Array2D {
const res = new Float32Array(indices.size * depth);
res.fill(offValue);
for (let event = 0; event < indices.size; ++event) {
res[event * depth + indices.get(event)] = onValue;
}
return Array2D.new([indices.size, depth], res);
}
setDiag(input: Array2D, diag: Array1D): Array2D {
const out = this.clone(input);
const diagVals = diag.dataSync();
// const newValues = new Float32Array(values.length);
for (let i = 0; i < diagVals.length; ++i) {
const val = diagVals[i];
out.set(val, i, i);
}
return out;
}
private broadcastedBinaryOp<D extends DataType>(
a: NDArray, b: NDArray, dtype: D,
op: (a: number, b: number) => number): NDArray<D> {
const newShape =
broadcast_util.assertAndGetBroadcastShape(a.shape, b.shape);
const result = NDArray.zeros(newShape, dtype);
const newValues = result.dataSync();
const aValues = a.dataSync();
const bValues = b.dataSync();
const aBroadcastDims = broadcast_util.getBroadcastDims(a.shape, newShape);
const bBroadcastDims = broadcast_util.getBroadcastDims(b.shape, newShape);
for (let i = 0; i < newValues.length; ++i) {
const loc = result.indexToLoc(i);
const aLoc = loc.slice(-a.rank);
aBroadcastDims.forEach(d => aLoc[d] = 0);
const aIndex = a.locToIndex(aLoc);
const bLoc = loc.slice(-b.rank);
bBroadcastDims.forEach(d => bLoc[d] = 0);
const bIndex = b.locToIndex(bLoc);
newValues[i] = op(aValues[aIndex], bValues[bIndex]);
}
return result;
}
private ternaryOp<D extends DataType>(
a: NDArray, b: NDArray, c: NDArray, dtype: D,
op: (a: number, b: number, c: number) => number): NDArray<D> {
util.assertShapesMatch(a.shape, b.shape);
util.assertShapesMatch(b.shape, c.shape);
const newShape = a.shape;
const result = NDArray.zeros(newShape, dtype);
const newValues = result.dataSync();
const aValues = a.dataSync();
const bValues = b.dataSync();
const cValues = c.dataSync();
for (let i = 0; i < newValues.length; ++i) {
// This is probably overkill. We can probably just use i.
const loc = result.indexToLoc(i);
const aIndex = a.locToIndex(loc);
const bIndex = b.locToIndex(loc);
const cIndex = c.locToIndex(loc);
newValues[i] = op(aValues[aIndex], bValues[bIndex], cValues[cIndex]);
}
return result;
}
dispose() {}
}
ENV.registerBackend("cpu", () => new MathBackendCPU()); | the_stack |
import type { GraphQLModel } from '@glazed/graphql-types'
import { pascalCase } from 'change-case'
import {
GraphQLBoolean,
GraphQLFloat,
GraphQLID,
GraphQLInputObjectType,
GraphQLInt,
GraphQLList,
GraphQLNonNull,
GraphQLObjectType,
GraphQLSchema,
GraphQLString,
} from 'graphql'
import type {
GraphQLFieldConfig,
GraphQLFieldConfigMap,
GraphQLInputFieldConfigMap,
GraphQLInterfaceType,
} from 'graphql'
import {
connectionArgs,
connectionDefinitions,
fromGlobalId,
mutationWithClientMutationId,
nodeDefinitions,
toGlobalId,
} from 'graphql-relay'
import type { Connection } from 'graphql-relay'
import type { Context } from './context'
import type { Doc } from './types'
import { createGlobalId, toDoc } from './utils'
const SCALARS = {
boolean: GraphQLBoolean,
float: GraphQLFloat,
integer: GraphQLInt,
string: GraphQLString,
}
const SCALAR_FIELDS = Object.keys(SCALARS)
function sortedObject<T = Record<string, any>>(input: T): T {
const keys = Object.keys(input)
keys.sort()
return keys.reduce((acc, key) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
acc[key] = input[key]
return acc
}, {}) as T
}
export function createGraphQLSchema(model: GraphQLModel): GraphQLSchema {
const inputObjects: Record<string, GraphQLInputObjectType> = {}
const mutations: Record<string, GraphQLFieldConfig<any, any>> = {}
const types: Record<string, GraphQLObjectType> = {}
const resolveType = (doc: Doc): GraphQLObjectType<any, Context> | null => {
if (doc.schema == null) {
return null
}
const { name } = model.referenced[doc.schema]
if (name == null) {
return null
}
return types[name] ?? null
}
const { nodeInterface, nodeField } = nodeDefinitions(async (globalId: string, ctx: Context) => {
const { id } = fromGlobalId(globalId)
return await ctx.loadDoc(id)
}, resolveType)
const nodes = Object.entries(model.referenced).reduce((acc, [schema, { name, type }]) => {
if (type === 'object') {
acc[name] = { interfaces: [nodeInterface], schema }
}
return acc
}, {} as Record<string, { interfaces: Array<GraphQLInterfaceType>; schema: string }>)
for (const [name, { fields }] of Object.entries(sortedObject(model.objects))) {
const node = nodes[name]
inputObjects[name] = new GraphQLInputObjectType({
name: `${name}Input`,
fields: (): GraphQLInputFieldConfigMap => {
return Object.entries(fields).reduce((acc, [key, field]) => {
let type
if (field.type === 'reference') {
const ref = model.referenced[field.schemas[0]]
if (ref.type === 'object') {
type = GraphQLID
}
} else if (field.type === 'object') {
type = inputObjects[field.name]
} else if (field.type === 'list') {
const listItem = model.lists[field.name]
if (listItem.type === 'object') {
type = new GraphQLList(inputObjects[listItem.name])
} else if (listItem.type === 'reference') {
type = new GraphQLList(GraphQLID)
} else if (SCALAR_FIELDS.includes(listItem.type)) {
type = new GraphQLList(SCALARS[listItem.type])
}
} else if (SCALAR_FIELDS.includes(field.type)) {
type = SCALARS[field.type]
} else {
throw new Error(`Unsupported field type ${field.type}`)
}
if (type != null) {
acc[key] = { type: field.required ? new GraphQLNonNull(type) : type }
}
return acc
}, {} as GraphQLInputFieldConfigMap)
},
})
types[name] = new GraphQLObjectType<Doc>({
name,
interfaces: node?.interfaces,
fields: (): GraphQLFieldConfigMap<Doc, Context> => {
return Object.entries(fields).reduce(
(acc, [key, field]) => {
if (field.type === 'reference') {
const ref = model.referenced[field.schemas[0]]
if (ref.type === 'collection') {
const { item } = model.collections[ref.name]
let nodeType
if (item.type === 'object') {
nodeType = types[item.name]
} else if (item.type === 'reference') {
const nodeRef = model.referenced[item.schemas[0]]
nodeType = types[nodeRef.name]
} else if (SCALAR_FIELDS.includes(item.type)) {
nodeType = SCALARS[item.type]
}
if (nodeType == null) {
throw new Error(`Missing node type for collection: ${name}`)
}
const connectionType = types[`${nodeType.name}Connection`]
if (connectionType == null) {
throw new Error(`No connection defined for node: ${nodeType.name}`)
}
acc[key] = {
type: field.required ? new GraphQLNonNull(connectionType) : connectionType,
args: connectionArgs,
resolve: async (doc, args, ctx): Promise<Connection<any> | null> => {
const id = doc.content[key] as string | undefined
if (id == null) {
return null
}
const handler =
item.type === 'reference'
? await ctx.getReferenceConnection(id, item.schemas[0])
: await ctx.getItemConnection(id)
return await handler.load(args)
},
}
} else if (ref.type === 'object') {
// TODO: support union type when multiple schemas
const typeName = ref.name
const type = types[typeName]
acc[key] = {
type: field.required ? new GraphQLNonNull(type) : type,
resolve: async (doc, _args, ctx): Promise<Doc | null> => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
const id = doc.content[key].id as string | undefined
return id ? await ctx.loadDoc(id) : null
},
}
acc[`${key}ID`] = {
type: field.required ? new GraphQLNonNull(GraphQLID) : GraphQLID,
resolve: (doc): string | null => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
const id = doc.content[key].id as string | undefined
return id ? toGlobalId(typeName, id) : null
},
}
} else {
throw new Error(`Unsupported reference type: ${ref.type as string}`)
}
} else {
let type
if (field.type === 'object') {
type = types[field.name]
} else if (field.type === 'list') {
const listItem = model.lists[field.name]
if (listItem.type === 'object') {
type = new GraphQLList(types[listItem.name])
} else if (listItem.type === 'reference') {
type = new GraphQLList(GraphQLID)
} else if (SCALAR_FIELDS.includes(listItem.type)) {
type = new GraphQLList(SCALARS[listItem.type])
} else {
throw new Error(`Unsupported list item type ${listItem.type}`)
}
} else if (SCALAR_FIELDS.includes(field.type)) {
type = SCALARS[field.type]
} else {
throw new Error(`Unsupported field type ${field.type}`)
}
if (type != null) {
acc[key] = {
type: field.required ? new GraphQLNonNull(type) : type,
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
resolve: (doc: Doc): any => doc.content[key],
}
}
}
return acc
},
node ? createGlobalId(name) : {}
)
},
})
if (node != null) {
mutations[`create${name}`] = mutationWithClientMutationId({
name: `Create${name}`,
inputFields: () => ({
content: { type: new GraphQLNonNull(inputObjects[name]) },
}),
outputFields: () => ({
node: { type: new GraphQLNonNull(types[name]) },
}),
mutateAndGetPayload: async (input: { content: Record<string, any> }, ctx: Context) => {
if (ctx.ceramic.did == null || !ctx.ceramic.did.authenticated) {
throw new Error('Ceramic instance is not authenticated')
}
return { node: await ctx.createDoc(node.schema, input.content) }
},
})
mutations[`update${name}`] = mutationWithClientMutationId({
name: `Update${name}`,
inputFields: () => ({
id: { type: new GraphQLNonNull(GraphQLID) },
content: { type: new GraphQLNonNull(inputObjects[name]) },
}),
outputFields: () => ({
node: { type: new GraphQLNonNull(types[name]) },
}),
mutateAndGetPayload: async (
input: { id: string; content: Record<string, any> },
ctx: Context
) => {
const { id } = fromGlobalId(input.id)
return { node: await ctx.updateDoc(id, input.content) }
},
})
}
}
const indexFields: GraphQLFieldConfigMap<any, any> = {}
for (const [key, definition] of Object.entries(sortedObject(model.index))) {
const { name } = model.referenced[definition.schema]
indexFields[key] = {
type: types[name],
resolve: async (_, { did }: { did?: string }, ctx: Context): Promise<Doc | null> => {
const tile = await ctx.dataStore.getRecordDocument(definition.id, did)
return tile ? toDoc<any>(tile) : null
},
}
const definitionKey = pascalCase(key)
mutations[`set${definitionKey}`] = mutationWithClientMutationId({
name: `Set${definitionKey}`,
inputFields: () => ({
content: { type: new GraphQLNonNull(inputObjects[name]) },
}),
outputFields: () => ({}),
mutateAndGetPayload: async (input: { content: Record<string, any> }, ctx: Context) => {
await ctx.dataStore.set(definition.id, input.content)
return {}
},
})
}
for (const [collectionName, { item, schema }] of Object.entries(
sortedObject(model.collections)
)) {
let nodeType
if (item.type === 'object') {
nodeType = types[item.name]
} else if (item.type === 'reference') {
const refID = item.schemas[0]
const ref = model.referenced[refID]
nodeType = types[ref.name]
}
if (nodeType == null) {
throw new Error(`Missing node type for collection: ${collectionName}`)
}
const name = nodeType.name
const { connectionType, edgeType } = connectionDefinitions({ nodeType })
types[`${name}Connection`] = connectionType
types[`${name}Edge`] = edgeType
for (const [label, { owner, schemas }] of Object.entries(model.references)) {
if (schemas[0] === schema) {
const field = Object.keys(model.objects[owner].fields).find((key) => {
const data = model.objects[owner].fields[key]
return data.type === 'reference' && data.schemas[0] === schema
})
if (field == null) {
throw new Error(`Reference field not found for ${label}`)
}
mutations[`add${label}Edge`] = mutationWithClientMutationId({
name: `Add${label}Edge`,
inputFields: () => ({
id: { type: new GraphQLNonNull(GraphQLID) },
content: { type: new GraphQLNonNull(inputObjects[name]) },
}),
outputFields: () => ({
node: { type: new GraphQLNonNull(types[owner]) },
edge: { type: new GraphQLNonNull(edgeType) },
}),
mutateAndGetPayload: async (
input: { id: string; content: Record<string, any> },
ctx: Context
) => {
const { id } = fromGlobalId(input.id)
const tile = await ctx.loadTile(id)
const content = tile.content ?? {}
let handler
const existingID = content[field] as string | undefined
if (existingID == null) {
handler =
item.type === 'reference'
? await ctx.createReferenceConnection(schema, item.schemas[0])
: await ctx.createItemConnection(schema)
} else {
handler =
item.type === 'reference'
? await ctx.getReferenceConnection(existingID, item.schemas[0])
: await ctx.getItemConnection(existingID)
}
const edge = await handler.add(input.content)
if (existingID == null) {
await tile.update({ ...content, [field]: handler.id })
}
return { edge, node: toDoc(tile) }
},
})
}
}
}
const query = new GraphQLObjectType({
name: 'Query',
fields: Object.entries(sortedObject(model.roots)).reduce(
(acc, [key, { id, schema }]) => {
const { name } = model.referenced[schema]
acc[key] = {
type: new GraphQLNonNull(types[name]),
resolve: async (_self, _args, ctx: Context): Promise<any> => {
return await ctx.loadDoc(id)
},
}
return acc
},
{
index: {
type: new GraphQLNonNull(new GraphQLObjectType({ name: 'Index', fields: indexFields })),
args: {
did: { type: GraphQLString },
},
resolve: (_, args): { did?: string } => args,
},
node: nodeField,
} as GraphQLFieldConfigMap<any, any>
),
})
const mutation = new GraphQLObjectType({ name: 'Mutation', fields: mutations })
return new GraphQLSchema({ query, mutation })
} | the_stack |
'use strict';
import { GenericOAuth2Router } from '../common/generic-router';
import { AuthRequest, AuthResponse, IdentityProvider, EndpointDefinition, IdpOptions, LocalIdpConfig, CheckRefreshDecision, BooleanCallback, ErrorLink } from '../common/types';
import { OidcProfile, WickedUserInfo, Callback, WickedApi } from 'wicked-sdk';
const { debug, info, warn, error } = require('portal-env').Logger('portal-auth:local');
import * as wicked from 'wicked-sdk';
const Router = require('express').Router;
const qs = require('querystring');
import { utils } from '../common/utils';
import { failMessage, failError, failOAuth, makeError } from '../common/utils-fail';
export class LocalIdP implements IdentityProvider {
private genericFlow: GenericOAuth2Router;
private basePath: string;
private authMethodId: string;
private authMethodConfig: LocalIdpConfig;
private options: IdpOptions;
constructor(basePath: string, authMethodId: string, authMethodConfig: LocalIdpConfig, options: IdpOptions) {
debug(`constructor(${basePath}, ${authMethodId}, ...)`);
this.basePath = basePath;
this.genericFlow = new GenericOAuth2Router(basePath, authMethodId);
this.authMethodId = authMethodId;
this.authMethodConfig = authMethodConfig;
this.options = options;
this.genericFlow.initIdP(this);
}
public getType(): string {
return "local";
}
public supportsPrompt(): boolean {
// Ahem. This can be fixed with a "remember me" type of feature.
return false;
}
public getRouter() {
return this.genericFlow.getRouter();
}
public authorizeWithUi(req, res, next, authRequest: AuthRequest) {
// Render a login mask...
const prefillUsername = authRequest.prefill_username;
this.renderLogin(req, res, next, null, prefillUsername);
}
public authorizeByUserPass(user, pass, callback: Callback<AuthResponse>) {
debug('authorizeByUserPass()');
// loginUser returns an authResponse, so we can use that to verify that the user
// does not interactively have to change his password.
this.loginUser(user, pass, function (err, authResponse: AuthResponse) {
if (err)
return callback(err);
// Check for "mustChangePassword"; we won't allow this without the user having
// changed the password.
// if (authResponse.wickedUserInfo && authResponse.wickedUserInfo.mustChangePassword) {
// return failOAuth(400, 'invalid_request', 'Headless authentication now allowed, user must interactively update password first.', callback);
// } else {
return callback(null, authResponse);
// }
});
}
public checkRefreshToken(tokenInfo, apiInfo: WickedApi, callback: Callback<CheckRefreshDecision>) {
debug('checkRefreshToken()');
// Decide whether it's okay to refresh this token or not, e.g.
// by checking that the user is still valid in your database or such;
// for 3rd party IdPs, this may be tricky.
return callback(null, {
allowRefresh: true
});
}
public getErrorLinks(): ErrorLink {
return null;
}
public endpoints(): EndpointDefinition[] {
return [
{
method: 'post',
uri: '/login',
handler: this.loginHandler
},
{
method: 'get',
uri: '/signup',
handler: this.signupHandler
},
{
method: 'post',
uri: '/signup',
handler: this.signupPostHandler
},
{
method: 'get',
uri: '/forgotpassword',
handler: this.genericFlow.createForgotPasswordHandler(this.authMethodId)
},
{
method: 'post',
uri: '/forgotpassword',
handler: this.genericFlow.createForgotPasswordPostHandler(this.authMethodId)
},
{
method: 'post',
uri: '/changepassword',
handler: this.changePasswordHandler
}
];
}
private loginHandler = (req, res, next): void => {
debug(`POST ${this.authMethodId}/login`);
debug('loginHandler()');
// When you're done with whatever (like verifying username and password,
// or checking a callback from a 3rd party IdP), you must use the registered
// generic flow implementation object (genericFlow from the constructor) to
// pass back the same type of structure as in the authorizeByUserPass below.
const body = req.body;
const csrfToken = body._csrf;
const expectedCsrfToken = utils.getAndDeleteCsrfToken(req, 'login');
const instance = this;
if (!csrfToken || csrfToken !== expectedCsrfToken)
return this.renderLogin(req, res, next, 'Suspected login forging detected (CSRF protection).');
const username = req.body.username;
const password = req.body.password;
debug(`username: ${username}, password: ${password}`);
this.loginUser(username, password, (err, authResponse) => {
if (err) {
debug(err);
// Delay redisplay of login page a little
setTimeout(() => instance.renderLogin(req, res, next, 'Username or password invalid.', username), 500);
return;
}
if (authResponse.wickedUserInfo && authResponse.wickedUserInfo.mustChangePassword) {
// Force change the password
instance.forceChangePasswordFlow(req, res, next, authResponse);
} else {
// Continue as normal
instance.genericFlow.continueAuthorizeFlow(req, res, next, authResponse);
}
});
};
private forceChangePasswordFlow(req, res, next, authResponse: AuthResponse): void {
debug(`forceChangePasswordFlow()`);
const instance = this;
const viewModel = utils.createViewModel(req, instance.authMethodId, 'change_password');
const authSession = utils.getSession(req, instance.authMethodId);
authSession.tmpAuthResponse = authResponse;
const authRequest = utils.getAuthRequest(req, instance.authMethodId);
utils.render(req, res, 'force_change_password', viewModel, authRequest);
}
private changePasswordHandler = (req, res, next): void => {
debug(`POST ${this.authMethodId}/changepassword`);
const body = req.body;
const csrfToken = body._csrf;
const expectedCsrfToken = utils.getAndDeleteCsrfToken(req, 'change_password');
const instance = this;
if (!csrfToken || expectedCsrfToken !== csrfToken) {
setTimeout(() => instance.renderLogin(req, res, next,'CSRF validation failed, please try again.'), 500);
return;
}
// Recaptcha?
utils.verifyRecaptcha(req, (err) => {
if (err)
return failError(401, err, next);
const authSession = utils.getSession(req, instance.authMethodId);
if (!authSession.tmpAuthResponse) {
failMessage(400, 'Invalid session state. Forged password change request?', next);
return;
}
// Sanitize input; should be okay...
const password = body.password;
const password2 = body.password2;
if (!password)
return failMessage(400, 'Password cannot be empty', next);
if (password !== password2)
return failMessage(400, 'Passwords do not match', next);
const authResponse = authSession.tmpAuthResponse;
// Take this out of the session. It will go somewhere else in the generic part (see
// continueAuthorizeFlow()).
delete authSession.tmpAuthResponse;
wicked.getUser(authResponse.wickedUserInfo.id, function (err, userInfo) {
if (err) {
failError(500, err, next);
return;
}
wicked.patchUser(userInfo.id, {
email: userInfo.email,
groups: userInfo.groups,
password: password,
mustChangePassword: false
}, function (err, updatedUserInfo) {
if (err) {
failError(500, err, next);
return;
}
// Happy as can be, we can continue with the authorization.
instance.genericFlow.continueAuthorizeFlow(req, res, next, authResponse);
});
});
});
}
private signupHandler = (req, res, next) => {
debug(`GET ${this.authMethodId}/signup`);
debug('signupHandler()');
this.renderSignup(req, res, next, '');
};
private signupPostHandler = (req, res, next) => {
debug(`POST ${this.authMethodId}/signup`);
debug('signupPostHandler()');
const body = req.body;
const csrfToken = body._csrf;
const expectedCsrfToken = utils.getAndDeleteCsrfToken(req, 'signup');
const instance = this;
if (!csrfToken || expectedCsrfToken !== csrfToken)
return setTimeout(() => instance.renderSignup(req, res, next, 'CSRF validation failed, please try again.'), 500);
const email = body.email;
const password = body.password;
const password2 = body.password2;
if (!password)
return failMessage(400, 'Password cannot be empty', next);
if (password !== password2)
return failMessage(400, 'Passwords do not match', next);
// Is signup allowed for this API/auth method combination?
const apiId = utils.getAuthRequest(req, this.authMethodId).api_id;
this.checkSignupDisabled(apiId, (err, disableSignup) => {
if (err)
return failError(500, err, next);
if (disableSignup)
return failMessage(401, 'Signup is not allowed for this API or Authentication Method.', next);
// Recaptcha?
utils.verifyRecaptcha(req, (err) => {
if (err)
return failError(401, err, next);
// Let's give it a shot; wicked can still intervene here...
const emailValidated = this.authMethodConfig.trustUsers;
const userCreateInfo = {
email: email,
password: password,
groups: [],
validated: emailValidated
} as WickedUserInfo;
debug(`signupPostHandler: Attempting to create user ${email}`);
wicked.apiPost('/users', userCreateInfo, null, (err, userInfo: WickedUserInfo) => {
if (err)
return failError(500, err, next);
debug(`signupPostHandler: Successfully created user ${email} with id ${userInfo.id}`);
// Check whether we want to verify the email address or not
utils.createVerificationRequest(this.authMethodConfig.trustUsers, this.authMethodId, userInfo.email, (err) => {
if (err)
return failError(500, err, next);
const authResponse = instance.createAuthResponse(userInfo);
debug(`signupPostHandler: Successfully created an authResponse`);
debug(authResponse);
// We're practically logged in now, as the new user.
instance.genericFlow.continueAuthorizeFlow(req, res, next, authResponse);
});
});
});
});
};
private checkSignupDisabled(apiId: string, callback: BooleanCallback) {
debug(`checkSignupAllowed(${apiId})`);
const instance = this;
// This looks complicated, but we must find out whether signing up for using
// the API is allowed or not. This can be done in two places: On the registration
// pool (if the API has one), or directly on the auth method (with type local, this
// implementation).
utils.getApiRegistrationPool(apiId, (err, poolId) => {
if (err)
return callback(err);
// null is okay for poolId, then the API doesn't have a pool ID
if (poolId) {
// But now we have to retrieve that information as well
utils.getPoolInfo(poolId, (err, poolInfo) => {
if (err)
return callback(err);
const disableSignup = !!instance.authMethodConfig.disableSignup || !!poolInfo.disableRegister;
return callback(null, disableSignup);
});
} else {
const disableSignup = !!instance.authMethodConfig.disableSignup;
return callback(null, disableSignup);
}
});
}
private renderLogin(req, res, next, flashMessage: string, prefillUsername?: string) {
debug('renderLogin()');
const authRequest = utils.getAuthRequest(req, this.authMethodId);
const authSession = utils.getSession(req, this.authMethodId);
authSession.tmpAuthResponse = null;
const instance = this;
this.checkSignupDisabled(authRequest.api_id, (err, disableSignup) => {
if (err)
return failError(500, err, next);
const viewModel = utils.createViewModel(req, instance.authMethodId, 'login');
viewModel.errorMessage = flashMessage;
viewModel.disableSignup = disableSignup;
if (prefillUsername)
viewModel.prefillUsername = prefillUsername;
utils.render(req, res, 'login', viewModel, authRequest);
});
}
private makeAuthorizeUrl(req): string {
debug(`makeAuthorizeUrl()`);
let authRequest: AuthRequest;
try {
authRequest = utils.getAuthRequest(req, this.authMethodId);
} catch (ex) {
warn(`makeAuthorizeUrl: Could not get AuthRequest from request session`);
return null;
}
if (!authRequest.api_id) {
warn(`makeAuthorizeUrl: Auth Request does not contain an api_id`);
return null;
}
if (!authRequest.client_id) {
warn(`makeAuthorizeUrl: Auth Request does not contain a client_id`);
return null;
}
if (!authRequest.response_type) {
warn(`makeAuthorizeUrl: Auth Request does not contain a response_type`);
return null;
}
if (!authRequest.redirect_uri) {
warn(`makeAuthorizeUrl: Auth Request does not contain a redirect_uri`);
return null;
}
let authorizeUrl = `${this.authMethodId}/api/${authRequest.api_id}/authorize?` +
`client_id=${qs.escape(authRequest.client_id)}` +
`&response_type=${authRequest.response_type}` +
`&redirect_uri=${qs.escape(authRequest.redirect_uri)}`;
if (authRequest.state)
authorizeUrl += `&state=${qs.escape(authRequest.state)}`;
if (authRequest.namespace)
authorizeUrl += `&namespace=${qs.escape(authRequest.namespace)}`;
return authorizeUrl;
}
private renderSignup(req, res, next, flashMessage: string) {
debug('renderSignup()');
const authRequest = utils.getAuthRequest(req, this.authMethodId);
const instance = this;
this.checkSignupDisabled(authRequest.api_id, (err, disableSignup) => {
if (err)
return failError(500, err, next);
if (disableSignup)
return failMessage(403, 'Signup is not allowed.', next);
const viewModel = utils.createViewModel(req, this.authMethodId, 'signup');
viewModel.errorMessage = flashMessage;
viewModel.authorizeUrl = instance.makeAuthorizeUrl(req);
utils.render(req, res, 'signup', viewModel, authRequest);
});
}
private loginUser(username: string, password: string, callback: Callback<AuthResponse>) {
debug('loginUser()');
const instance = this;
wicked.apiPost('login', {
username: username,
password: password
}, null, function (err, userInfoList: WickedUserInfo[]) {
if (err)
return callback(err);
if (!Array.isArray(userInfoList))
return callback(makeError('loginUser: Did not return expected format (array).', 500));
if (userInfoList.length !== 1)
return callback(makeError(`loginUser: /login did not return user (array length ${userInfoList.length})`, 500));
debug('loginUser: /login successful');
const userShortInfo = userInfoList[0];
// Load the user to get all information (e.g., groups and validated status)
debug('userInfo: ' + JSON.stringify(userShortInfo));
wicked.getUser(userShortInfo.id, (err, userInfo) => {
if (err)
return callback(err);
const authResponse = instance.createAuthResponse(userInfo);
return callback(null, authResponse);
});
});
}
private createDefaultProfile(userInfo: WickedUserInfo): OidcProfile {
debug('createDefaultProfile()');
// For the local users, we don't have anything to put into the
// default profile except the user ID and the email address.
// For other IdPs, there may be other fields which can be prepopulated.
const oidcProfile = {
sub: userInfo.id,
email: userInfo.email,
email_verified: userInfo.validated,
} as OidcProfile;
debug(oidcProfile);
return oidcProfile;
}
private createAuthResponse(userInfo: WickedUserInfo): AuthResponse {
debug('createAuthResponse()');
return {
userId: userInfo.id,
wickedUserInfo: userInfo,
defaultGroups: userInfo.groups,
defaultProfile: this.createDefaultProfile(userInfo)
};
}
} | the_stack |
import {AttributeWithCacheKey, createAttributeWithCacheKey} from '../../../attribute-with-cache-key';
import {Graph} from '../../../graph';
import {OperatorImplementation, OperatorInitialization} from '../../../operators';
import {Tensor} from '../../../tensor';
import {ShapeUtil} from '../../../util';
import {getGlsl} from '../glsl-source';
import {WebGLInferenceHandler} from '../inference-handler';
import {ProgramInfo, TextureType} from '../types';
import {transpose, TransposeAttributes} from './transpose';
export interface SoftmaxAttributes extends AttributeWithCacheKey {
readonly axis: number;
}
const softmaxComputeMaxProgramMetadata = {
name: 'SoftmaxComputeMax',
inputNames: ['A'],
inputTypes: [TextureType.unpacked],
};
const softmaxComputeScaleProgramMetadata = {
name: 'SoftmaxComputeScale',
inputNames: ['A', 'Max'],
inputTypes: [TextureType.unpacked, TextureType.unpacked],
};
const softmaxProgramMetadata = {
name: 'SoftMax',
inputNames: ['A', 'Max', 'Norm'],
inputTypes: [TextureType.unpacked, TextureType.unpacked, TextureType.unpacked],
};
export const softmax: OperatorImplementation<SoftmaxAttributes> =
(inferenceHandler: WebGLInferenceHandler, inputs: Tensor[], attributes: SoftmaxAttributes): Tensor[] => {
validateInputs(inputs);
const inputShape = inputs[0].dims.slice();
const axis = ShapeUtil.normalizeAxis(attributes.axis, inputShape.length);
const logicalRowCount = ShapeUtil.sizeToDimension(inputShape, axis);
const featureCount = ShapeUtil.sizeFromDimension(inputShape, axis);
const output = computeSoftmax(inferenceHandler, inputs, attributes, logicalRowCount, featureCount);
return output;
};
export const parseSoftmaxAttributes: OperatorInitialization<SoftmaxAttributes> =
(node: Graph.Node): SoftmaxAttributes => createAttributeWithCacheKey({axis: node.attributes.getInt('axis', 1)});
export const parseSoftmaxAttributesV13: OperatorInitialization<SoftmaxAttributes> =
(node: Graph.Node): SoftmaxAttributes => createAttributeWithCacheKey({axis: node.attributes.getInt('axis', -1)});
// The "semantic" meaning of axis has changed in opset-13.
// Please compare: https://github.com/onnx/onnx/blob/master/docs/Operators.md#Softmax
// with https://github.com/onnx/onnx/blob/master/docs/Changelog.md#Softmax-11 for detailed explanations
// To account for the opset-13 behavior, our plan will be to transpose the "axis" dim to the innermost dim
// and perform softmax and then reverse the transpose. We can skip the transposing aspect if the axis is already
// the innermost dim
export const softmaxV13: OperatorImplementation<SoftmaxAttributes> =
(inferenceHandler: WebGLInferenceHandler, inputs: Tensor[], attributes: SoftmaxAttributes): Tensor[] => {
validateInputs(inputs);
const inputShape = inputs[0].dims.slice();
const axis = ShapeUtil.normalizeAxis(attributes.axis, inputShape.length);
const rank = inputShape.length;
const isTransposeRequired = (axis !== rank - 1) ? true : false;
const transposedInputShape: number[] = [];
let perm: number[] = [];
let transposedInputs: Tensor[] = [];
let transposeAttribute: TransposeAttributes;
if (isTransposeRequired) {
perm = Array.from({length: rank}).map((_, i) => i);
// swap the innermost dim with the dim corresponding to axis
perm[axis] = rank - 1;
perm[rank - 1] = axis;
perm.map(p => transposedInputShape.push(inputShape[p]));
transposeAttribute = createAttributeWithCacheKey({perm});
transposedInputs = transpose(inferenceHandler, inputs, transposeAttribute);
}
const logicalRowCount = isTransposeRequired ? ShapeUtil.sizeToDimension(transposedInputShape, rank - 1) :
ShapeUtil.sizeToDimension(inputShape, rank - 1);
const featureCount = isTransposeRequired ? ShapeUtil.sizeFromDimension(transposedInputShape, rank - 1) :
ShapeUtil.sizeFromDimension(inputShape, rank - 1);
const output = computeSoftmax(
inferenceHandler, isTransposeRequired ? transposedInputs : inputs, attributes, logicalRowCount, featureCount);
if (isTransposeRequired) {
const reversedOutput = transpose(inferenceHandler, output, transposeAttribute!);
return reversedOutput;
} else {
return output;
}
};
const computeSoftmax =
(inferenceHandler: WebGLInferenceHandler, inputs: Tensor[], attributes: SoftmaxAttributes, logicalRowCount: number,
featureCount: number): Tensor[] => {
const computeMaxProgramInfo =
createComputeMaxProgramInfo(inferenceHandler, inputs[0], logicalRowCount, featureCount, [logicalRowCount]);
const max = inferenceHandler.run(
{...softmaxComputeMaxProgramMetadata, cacheHint: attributes.cacheKey, get: () => computeMaxProgramInfo},
inputs);
const computeScaleProgramInfo = createComputScaleProgramInfo(
inferenceHandler, inputs[0], logicalRowCount, featureCount, computeMaxProgramInfo.output.dims,
[logicalRowCount]);
const scale = inferenceHandler.run(
{...softmaxComputeScaleProgramMetadata, cacheHint: attributes.cacheKey, get: () => computeScaleProgramInfo},
[inputs[0], max]);
const softMaxProgramInfo = createSoftMaxProgramInfo(
inferenceHandler, inputs[0], logicalRowCount, featureCount, computeMaxProgramInfo.output.dims,
computeScaleProgramInfo.output.dims);
const output = inferenceHandler.run(
{...softmaxProgramMetadata, cacheHint: attributes.cacheKey, get: () => softMaxProgramInfo},
[inputs[0], max, scale]);
return [output];
};
/**
* Create a texture that contains the maximum value of each of the 'N' rows
*/
const createComputeMaxProgramInfo =
(inferenceHandler: WebGLInferenceHandler, input: Tensor, logicalRowCount: number, featureCount: number,
outputShape: number[]): ProgramInfo => {
const [textureWidth, textureHeight] =
inferenceHandler.calculateTextureWidthAndHeight(input.dims, TextureType.unpacked);
const rank = outputShape.length;
if (logicalRowCount < 1 || featureCount < 1) {
throw new Error('Logical row count N and feature count D must be greater than or equal to 1');
}
if (outputShape.length !== 1) {
throw new Error('Dimensionality of the output should be 1');
}
if (outputShape[0] !== logicalRowCount) {
throw new Error('Shape of the output should be equal to logical row count');
}
const glsl = getGlsl(inferenceHandler.session.backend.glContext.version);
const shaderSource = `
float process(int[${rank}] indices) {
int logical_row_start_offset = indices[0] * ${featureCount};
float max = getColorAsFloat(${glsl.texture2D}(A, offsetToCoords(logical_row_start_offset, ${textureWidth},
${textureHeight} )));
for(int i=1; i<${featureCount}; ++i)
{
float current = getColorAsFloat(${glsl.texture2D}(A, offsetToCoords(logical_row_start_offset + i,
${textureWidth}, ${textureHeight})));
if(current > max)
max = current;
}
return max;
}`;
return {
...softmaxComputeMaxProgramMetadata,
output: {dims: outputShape, type: input.type, textureType: TextureType.unpacked},
shaderSource
};
};
/**
* Create a texture that contains the normalization factor for each of the 'N' rows
*/
const createComputScaleProgramInfo =
(inferenceHandler: WebGLInferenceHandler, input: Tensor, logicalRowCount: number, featureCount: number,
maxElementPerLogicalRow: readonly number[], outputShape: number[]): ProgramInfo => {
const [textureWidth, textureHeight] =
inferenceHandler.calculateTextureWidthAndHeight(input.dims, TextureType.unpacked);
const rank = outputShape.length;
if (logicalRowCount < 1 || featureCount < 1) {
throw new Error('Logical row count N and feature count D must be greater than or equal to 1');
}
if (outputShape.length !== 1) {
throw new Error('Dimensionality of the output should be 1');
}
if (outputShape[0] !== logicalRowCount) {
throw new Error('Shape of the output should be equal to logical row count');
}
if (maxElementPerLogicalRow.length !== 1) {
throw new Error('Dimensionality of the intermediate results should be 1');
}
if (maxElementPerLogicalRow[0] !== logicalRowCount) {
throw new Error('Shape of the intermediate results should be equal to logical row count');
}
const glsl = getGlsl(inferenceHandler.session.backend.glContext.version);
const shaderSource = `
float process(int[${rank}] indices) {
int logical_row_start_offset = indices[0] * ${featureCount};
float norm_factor = 0.0;
float max = _Max(indices);
for(int i=0; i<${featureCount}; ++i)
{
norm_factor += exp(getColorAsFloat(${glsl.texture2D}(A, offsetToCoords(logical_row_start_offset + i,
${textureWidth}, ${textureHeight}))) - max);
}
return norm_factor;
}`;
return {
...softmaxComputeScaleProgramMetadata,
output: {dims: outputShape, type: input.type, textureType: TextureType.unpacked},
shaderSource
};
};
const createSoftMaxProgramInfo =
(inferenceHandler: WebGLInferenceHandler, input: Tensor, logicalRowCount: number, featureCount: number,
maxElementPerLogicalRow: readonly number[], normalizationPerLogicalRow: readonly number[]): ProgramInfo => {
const [textureWidth, textureHeight] =
inferenceHandler.calculateTextureWidthAndHeight(input.dims, TextureType.unpacked);
const rank = input.dims.length;
if (logicalRowCount < 1 || featureCount < 1) {
throw new Error('Logical row count N and feature count D must be greater than or equal to 1');
}
if (maxElementPerLogicalRow.length !== 1 || normalizationPerLogicalRow.length !== 1) {
throw new Error('Dimensionality of the intermediate results should be 1');
}
if (maxElementPerLogicalRow[0] !== logicalRowCount || normalizationPerLogicalRow[0] !== logicalRowCount) {
throw new Error('Shape of the intermediate results should be equal to logical row count');
}
const shaderSource = `
float process(int[${rank}] indices) {
// get offset of current logical tensor index from the 2-D texture coordinates (TexCoords)
int offset = coordsToOffset(TexCoords, ${textureWidth}, ${textureHeight});
//determine the logical row for this index
int logical_row_index[1];
logical_row_index[0] = offset / ${featureCount};
float norm_factor = _Norm(logical_row_index);
// avoid possible division by 0
// if norm_facor is 0, all elements are zero
// if so, return 0
if(norm_factor == 0.0)
return 0.0;
return exp(_A(indices) - _Max(logical_row_index)) / norm_factor;
}`;
return {
...softmaxProgramMetadata,
output: {dims: input.dims, type: input.type, textureType: TextureType.unpacked},
shaderSource
};
};
const validateInputs = (inputs: Tensor[]): void => {
if (!inputs || inputs.length !== 1) {
throw new Error('Softmax requires 1 input.');
}
if (inputs[0].type !== 'float32' && inputs[0].type !== 'float64') {
throw new Error('Invalid input type');
}
}; | the_stack |
import React, { useCallback, useEffect, useState } from 'react';
import { Route, Switch, Redirect, useHistory, useParams } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { BackLink, ButtonLink, Form, Popconfirm, ValidatedTextInput } from '../ui';
import CategorySelect from '../reports/category-select';
import URL from './urls';
import { translate as $t, assert, NONE_CATEGORY_ID, notify, useKresusState } from '../../helpers';
import { actions, get } from '../../store';
import { Category, Rule } from '../../models';
import './rules.css';
import { LoadingMessage } from '../overlay';
const SharedForm = (props: {
formTitle: string;
formSubmitLabel: string;
initialLabel: string | null;
initialCategoryId: number | null;
onSubmit: (label: string | null, categoryId: number | null) => Promise<void>;
}) => {
const [label, setLabel] = useState<string | null>(props.initialLabel);
const [categoryId, setCategoryId] = useState<number | null>(props.initialCategoryId);
const propsOnSubmit = props.onSubmit;
const onSubmit = useCallback(async () => {
await propsOnSubmit(label, categoryId);
}, [propsOnSubmit, label, categoryId]);
const submitIsDisabled =
label === null || categoryId === null || categoryId === NONE_CATEGORY_ID;
return (
<Form center={true} onSubmit={onSubmit}>
<BackLink to={URL.list}>{$t('client.rules.back_to_list')}</BackLink>
<h3>{props.formTitle}</h3>
<p>{$t('client.rules.help')}</p>
<Form.Input id="rule-label" label={$t('client.rules.if_text_contains')}>
<ValidatedTextInput onChange={setLabel} initialValue={label} />
</Form.Input>
<Form.Input id="rule-category" label={$t('client.rules.apply_category')}>
<CategorySelect
value={categoryId === null ? NONE_CATEGORY_ID : categoryId}
onChange={setCategoryId}
/>
</Form.Input>
<input type="submit" value={props.formSubmitLabel} disabled={submitIsDisabled} />
</Form>
);
};
const NewForm = () => {
const history = useHistory();
const dispatch = useDispatch();
const onSubmit = useCallback(
async (label: string | null, categoryId: number | null) => {
try {
assert(categoryId !== null, 'categoryId must be set at this point');
assert(label !== null, 'label must be set at this point');
await actions.createRule(dispatch, { label, categoryId });
notify.success($t('client.rules.creation_success'));
history.push(URL.list);
} catch (err) {
notify.error($t('client.rules.creation_error', { err: err.message }));
}
},
[history, dispatch]
);
return (
<SharedForm
formTitle={$t('client.rules.creation_form_title')}
formSubmitLabel={$t('client.rules.create_rule')}
initialLabel={null}
initialCategoryId={null}
onSubmit={onSubmit}
/>
);
};
const EditForm = () => {
const history = useHistory();
const { ruleId: ruleIdStr } = useParams<{ ruleId: string }>();
const ruleId = Number.parseInt(ruleIdStr, 10);
const rule = useKresusState(state => {
if (Number.isNaN(ruleId)) {
return null;
}
const r = get.ruleById(state, ruleId);
return r ? r : null;
});
const dispatch = useDispatch();
const onSubmit = useCallback(
async (label: string | null, categoryId: number | null) => {
try {
assert(rule !== null, 'rule must be known');
assert(categoryId !== null, 'categoryId must be set at this point');
assert(label !== null, 'label must be set at this point');
await actions.updateRule(dispatch, rule, { label, categoryId });
notify.success($t('client.rules.edit_success'));
history.push(URL.list);
} catch (err) {
notify.error($t('client.rules.edit_error', { err: err.message }));
}
},
[rule, history, dispatch]
);
if (Number.isNaN(ruleId)) {
notify.error($t('client.rules.rule_not_found'));
history.push(URL.list);
return null;
}
if (rule === null) {
// Still loading the rules...
return null;
}
assert(rule.conditions.length > 0, 'must have at least a single condition');
const condition = rule.conditions[0];
assert(condition.type === 'label_matches_text', 'only know about label matches text rules!');
assert(rule.actions.length > 0, 'must have at least a single action');
const action = rule.actions[0];
assert(action.type === 'categorize', 'only know about categorize rules!');
return (
<SharedForm
formTitle={$t('client.rules.edition_form_title')}
formSubmitLabel={$t('client.rules.edit_rule')}
initialLabel={condition.value}
initialCategoryId={action.categoryId}
onSubmit={onSubmit}
/>
);
};
const RuleText = (props: { categoryToName: Map<number, string>; rule: Rule }) => {
const conditionsText = [];
let first = true;
for (const condition of props.rule.conditions) {
if (!first) {
conditionsText.push(<>{$t('client.rules.and')} </>);
} else {
first = false;
}
switch (condition.type) {
case 'label_matches_text':
conditionsText.push(
<>
{$t('client.rules.transaction_label_contains')}{' '}
<strong>{condition.value}</strong>
</>
);
break;
case 'label_matches_regexp':
conditionsText.push(
<>
{$t('client.rules.transaction_label_matches')}{' '}
<strong>{condition.value}</strong>
</>
);
break;
default:
assert(false, "unknown rule's condition type");
}
}
const actionsText = [];
first = true;
for (const action of props.rule.actions) {
if (!first) {
actionsText.push(<>{$t('client.rules.and')} </>);
} else {
first = false;
}
switch (action.type) {
case 'categorize':
actionsText.push(
<>
{$t('client.rules.categorize_as')}{' '}
<strong>{props.categoryToName.get(action.categoryId)}</strong>
</>
);
break;
default:
assert(false, "unknown rule's action type");
}
}
let i = 0;
return (
<p>
{$t('client.rules.If')}
{conditionsText.map(el => React.cloneElement(el, { ...el.props, key: i++ }))}
{$t('client.rules.then')}
{actionsText.map(el => React.cloneElement(el, { ...el.props, key: i++ }))}
</p>
);
};
const ListItem = (props: {
index: number;
numRules: number;
prevRuleId: number | null;
nextRuleId: number | null;
rule: Rule;
categoryToName: Map<number, string>;
}) => {
const dispatch = useDispatch();
const { prevRuleId, nextRuleId, index, numRules, rule } = props;
const onDelete = useCallback(async () => {
try {
await actions.deleteRule(dispatch, rule.id);
notify.success($t('client.rules.delete_success'));
} catch (err) {
notify.error($t('client.rules.delete_error', { err: err.message }));
}
}, [dispatch, rule]);
const onSwapPrev = useCallback(async () => {
try {
assert(prevRuleId !== null, 'must have a previous rule to swap with it');
await actions.swapRulesPositions(dispatch, rule.id, prevRuleId);
} catch (err) {
notify.error($t('client.rules.swap_error', { err: err.message }));
}
}, [dispatch, rule, prevRuleId]);
const onSwapNext = useCallback(async () => {
try {
assert(nextRuleId !== null, 'must have a next rule to swap with it');
await actions.swapRulesPositions(dispatch, rule.id, nextRuleId);
} catch (err) {
notify.error($t('client.rules.swap_error', { err: err.message }));
}
}, [dispatch, rule, nextRuleId]);
return (
<li>
<RuleText categoryToName={props.categoryToName} rule={props.rule} />
<div className="buttons">
<ButtonLink
className="primary"
to={URL.edit.url(props.rule.id)}
aria={$t('client.rules.edit_rule')}
icon="edit"
/>
<button
className="btn primary"
aria-label={$t('client.rules.move_up')}
title={$t('client.rules.move_up')}
onClick={onSwapPrev}
disabled={index === 0}>
<span className="fa fa-arrow-up" />
</button>
<button
className="btn primary"
aria-label={$t('client.rules.move_down')}
title={$t('client.rules.move_down')}
onClick={onSwapNext}
disabled={index === numRules - 1}>
<span className="fa fa-arrow-down" />
</button>
<Popconfirm
trigger={
<button
className="btn danger"
aria-label={$t('client.rules.delete')}
title={$t('client.rules.delete')}>
<span className="fa fa-trash" />
</button>
}
onConfirm={onDelete}>
<p>{$t('client.rules.delete_confirm')}</p>
</Popconfirm>
</div>
</li>
);
};
const List = (props: { categoryToName: Map<number, string> }) => {
const rules = useKresusState(state => get.rules(state));
const ruleItems = rules.map((rule, i) => {
const prevRuleId = i > 0 ? rules[i - 1].id : null;
const nextRuleId = i + 1 < rules.length ? rules[i + 1].id : null;
return (
<ListItem
key={rule.id}
index={i}
numRules={rules.length}
rule={rule}
prevRuleId={prevRuleId}
nextRuleId={nextRuleId}
categoryToName={props.categoryToName}
/>
);
});
const content = rules.length > 0 ? ruleItems : $t('client.rules.no_rules');
return <ul className="rules">{content}</ul>;
};
export default () => {
// Load the rules the first time we navigate within the family of
// components from the outside. This is not done in the List component
// because displaying the list after creating a rule would reload the list
// of rules every single time, which is unnecessary.
const [firstLoad, setFirstLoad] = useState(true);
const dispatch = useDispatch();
const loadRules = useCallback(async () => {
if (firstLoad) {
await actions.loadRules(dispatch);
setFirstLoad(false);
}
}, [dispatch, firstLoad, setFirstLoad]);
useEffect(() => {
void loadRules();
}, [loadRules]);
const categoryToName = useKresusState(state =>
get.categories(state).reduce((map: Map<number, string>, cat: Category) => {
map.set(cat.id, cat.label);
return map;
}, new Map())
);
if (firstLoad) {
return <LoadingMessage message={$t('client.rules.loading_rules')} />;
}
return (
<Switch>
<Route path={URL.new}>
<NewForm />
</Route>
<Route path={URL.edit.pattern}>
<EditForm />
</Route>
<Route path={URL.list}>
<ButtonLink
to={URL.new}
aria={$t('client.rules.new_rule')}
label={$t('client.rules.new_rule')}
icon="plus"
/>
<hr />
<List categoryToName={categoryToName} />
</Route>
<Redirect to={URL.list} push={false} />
</Switch>
);
}; | the_stack |
import * as TestHelper from 'roosterjs-editor-api/test/TestHelper';
import { DEFAULT_TABLE, DEFAULT_TABLE_MERGED, EXCEL_TABLE, WORD_TABLE } from './tableData';
import { TableResize } from '../../lib/TableResize';
import {
IEditor,
PluginEvent,
PluginEventType,
DOMEventHandlerFunction,
} from 'roosterjs-editor-types';
const VERTICAL_INSERTER = 'verticalInserter';
const HORIZONTAL_INSERTER = 'horizontalInserter';
const TABLE_RESIZER = 'tableResizer';
/* Used to specify mouse coordinates or cell locations in a table in this test set */
type Position = {
x: number;
y: number;
};
const enum ResizeState {
None,
Horizontal,
Vertical,
Both, // when resizing the whole table
}
interface TestTable {
htmlData: string;
rows: number[];
columns: number[];
width: number;
height: number;
cellWidth?: number;
cellHeight?: number;
}
/*******************************************************************
Test Table 1
(default table inserted from table control)
8.5____131.5____254.5____377.5/8.5
| (0, 0) | (0, 1) | (0, 2) |
|________|________|________|30.5
| (1, 0) | (1, 1) | (1, 2) |
|________|________|________|52.5
| (2, 0) | (2, 1) | (2, 2) |
|________|________|________|74.5
cell width: 123, cell height: 22 (getBoudingClientRect)
table width: 370, table height: 67 (getBoudingClientRect)
Test Table 2
(Excel table)
8.5_____76.2____143.8____211.5/8.5
| (0, 0) | (0, 1) | (0, 2) |
|________|________|________|30.5
| (1, 0) | (1, 1) | (1, 2) |
|________|________|________|52.5
| (2, 0) | (2, 1) | (2, 2) |
|________|________|________|74.5
cell width: 67.7, cell height: 22 (getBoudingClientRect)
table width: 204, table height: 67 (getBoudingClientRect)
Test Table 3
(Word table)
8.5_____98.9____189.3___279.7/8.5
| (0, 0) | (0, 1) | (0, 2) |
|________|________|________|50.4
| (1, 0) | (1, 1) | (1, 2) |
|________|________|________|92.4
| (2, 0) | (2, 1) | (2, 2) |
|________|________|________|135.5
cell width: 90.4, cell height: 41.9 (getBoudingClientRect)
table width: 272.2, table height: 128 (getBoudingClientRect)
Test Table 4
(Default table merged)
8.5_____131.5____254.5___377.5___500.5/8.5
| (0, 0) | (0, 1) | (0, 2) | (0, 3) |
|________|________|________|________|30.5
| (1, 0) | (1, 1) | (1, 2) |
| |_________________|________|71.5
| | (2, 0) | (2, 1) | (2, 2) |
|________|________|________|________|93.5
| (3, 0) | (3, 1) | (3, 2) | (3, 3) |
|________|________|________|________|115.5
table width: 493, table height: 108 (getBoudingClientRect)
*********************************************************************/
const defaultTable: TestTable = {
htmlData: DEFAULT_TABLE,
rows: [8.5, 30.5, 52.5, 74.5],
columns: [8.5, 131.5, 254.5, 377.5],
width: 370,
height: 67,
cellWidth: 123,
cellHeight: 22,
};
const defaultTableMerged: TestTable = {
htmlData: DEFAULT_TABLE_MERGED,
rows: [8.5, 30.5, 71.5, 93.5, 115.5],
columns: [8.5, 131.5, 254.5, 377.5, 500.5],
width: 493,
height: 108,
};
const excelTable: TestTable = {
htmlData: EXCEL_TABLE,
rows: [8.5, 30.5, 52.5, 74.5],
columns: [8.5, 76.2, 143.8, 211.5],
width: 204,
height: 67,
cellWidth: 67.7,
cellHeight: 22,
};
const wordTable: TestTable = {
htmlData: WORD_TABLE,
rows: [8.5, 50.4, 92.4, 135.5],
columns: [8.5, 98.9, 189.3, 279.7],
width: 272.2,
height: 128,
cellWidth: 90.4,
cellHeight: 41.9,
};
const testTables = [defaultTable, excelTable, wordTable, defaultTableMerged];
xdescribe('Table Resizer/Inserter tests', () => {
let editor: IEditor;
let plugin: TableResize;
const insideTheOffset = 5;
const TEST_ID = 'inserterTest';
let handler: Record<string, DOMEventHandlerFunction>;
let addDomEventHandler: jasmine.Spy;
beforeEach(() => {
editor = TestHelper.initEditor(TEST_ID);
plugin = new TableResize();
handler = null;
addDomEventHandler = jasmine
.createSpy('addDomEventHandler')
.and.callFake((handlerParam: Record<string, DOMEventHandlerFunction>) => {
handler = handlerParam;
return () => {
handler = null;
};
});
editor = <IEditor>(<any>{
...editor,
addDomEventHandler,
addUndoSnapshot: (f: () => void) => f(),
insertNode: (node: HTMLElement) => {
document.body.appendChild(node);
},
runAsync: (callback: () => void) => {
handler.resizeCells = callback;
},
getDocument: () => document,
select: () => {},
getDefaultFormat: () => {
return {
backgroundColor: 'black',
};
},
isDarkMode: () => false,
queryElements: (table: string, callback: (table: HTMLTableElement) => void) => {
const tables = document.getElementsByTagName(table);
const tableList = Array.from(tables);
tableList.forEach(table => {
callback(table as HTMLTableElement);
});
},
dispose: () => {},
});
plugin.initialize(editor);
});
afterEach(() => {
editor.dispose();
plugin.dispose();
TestHelper.removeElement(TEST_ID);
document.body = document.createElement('body');
});
function getCellRect(i: number, j: number): DOMRect | undefined {
const tables = editor.getDocument().getElementsByTagName('table');
if (!tables || tables.length < 1) {
return undefined;
}
const table = tables[0];
if (i >= table.rows.length || j >= table.rows[i].cells.length) {
return undefined;
}
const cell = table.rows[i].cells[j];
return cell.getBoundingClientRect();
}
function initialize(tableIndex: number, isRtl: boolean = false): DOMRect {
if (isRtl) {
editor.getDocument().body.style.direction = 'rtl';
}
const editorDiv = editor.getDocument().getElementById(TEST_ID);
editorDiv.innerHTML = testTables[tableIndex].htmlData;
const table = document.getElementsByTagName('table')[0];
return table.getBoundingClientRect();
}
function getCurrentTable(): HTMLTableElement {
return editor.getDocument().getElementsByTagName('table')[0] as HTMLTableElement;
}
function getTableRows(table: HTMLTableElement): number {
return table.rows.length;
}
function getTableColumns(table: HTMLTableElement): number {
return table.rows[0].cells.length;
}
function runInserterTest(inserterType: string, mouseEnd: Position) {
handler.mousemove(
new MouseEvent('mousemove', {
clientX: mouseEnd.x,
clientY: mouseEnd.y,
})
);
const inserter = editor.getDocument().getElementById(inserterType);
if (!!inserter) {
const table = getCurrentTable();
const rows = getTableRows(table);
const cols = getTableColumns(table);
inserter.dispatchEvent(new MouseEvent('click'));
const newRows = getTableRows(table);
const newCols = getTableColumns(table);
expect(newRows).toBe(inserterType == VERTICAL_INSERTER ? rows : rows + 1);
expect(newCols).toBe(inserterType == HORIZONTAL_INSERTER ? cols : cols + 1);
}
}
// inserter tests
it('adds a new row if the vertical inserter is detected and clicked', () => {
const rect = initialize(0);
runInserterTest(VERTICAL_INSERTER, { x: rect.right - insideTheOffset, y: rect.top });
});
it('adds a new column if the horizontal inserter is detected and clicked', () => {
const rect = initialize(0);
runInserterTest(HORIZONTAL_INSERTER, { x: rect.left, y: rect.bottom - insideTheOffset });
});
/************************ Resizer related tests ************************/
function getTableRectSet(table: HTMLTableElement): DOMRect[] {
const rectSet: DOMRect[] = [];
if (!!table) {
rectSet.push(table.getBoundingClientRect());
}
for (let i = 0; i < table.rows.length; i++) {
for (let j = 0; j < table.rows[i].cells.length; j++) {
rectSet.push(table.rows[i].cells[j].getBoundingClientRect());
}
}
return rectSet;
}
function runTableShapeTest(tableRectSet1: DOMRect[], tableRectSet2: DOMRect[]) {
expect(tableRectSet1.length).toBe(tableRectSet2.length);
const isSameRect = (rect1: DOMRect, rect2: DOMRect): boolean => {
return (
rect1.left == rect2.left &&
rect1.right == rect2.right &&
rect1.top == rect2.top &&
rect1.bottom == rect2.bottom
);
};
tableRectSet1.forEach((rect, i) => {
expect(isSameRect(rect, tableRectSet2[i])).toBe(true);
});
}
function moveAndResize(mouseStart: Position, mouseEnd: Position, resizeState: ResizeState) {
const editorDiv = editor.getDocument().getElementById(TEST_ID);
let resizerId: string;
switch (resizeState) {
case ResizeState.Both:
resizerId = TABLE_RESIZER;
break;
case ResizeState.Horizontal:
resizerId = 'horizontalResizer';
break;
case ResizeState.Vertical:
resizerId = 'verticalResizer';
break;
default:
resizerId = '';
}
// move mouse and show resizer
const mouseMoveEvent = new MouseEvent('mousemove', {
clientX: mouseStart.x,
clientY: mouseStart.y,
});
handler.mousemove(mouseMoveEvent);
let resizer = editor.getDocument().getElementById(resizerId);
if (!!resizer) {
const tableBeforeClick = getTableRectSet(getCurrentTable());
const mouseClickEvent = new MouseEvent('mousedown');
resizer.dispatchEvent(mouseClickEvent);
const tableAfterClick = getTableRectSet(getCurrentTable());
// validate the table doesn't shift after clicking on the resizer
runTableShapeTest(tableBeforeClick, tableAfterClick);
const mouseMoveResize = new MouseEvent('mousemove', {
clientX: mouseEnd.x,
clientY: mouseEnd.y,
});
const doc = editor.getDocument();
// this will assign handler.resizeCells with the actual handler
doc.dispatchEvent(mouseMoveResize);
handler.resizeCells(mouseMoveResize);
// release mouse and stop resizing
const mouseMoveEndEvent = new MouseEvent('mouseup');
editorDiv.dispatchEvent(mouseMoveEndEvent);
resizer = editor.getDocument().getElementById(resizerId);
expect(!!resizer).toBe(false);
}
}
/************************** Resizier removing tests **************************/
function removeResizerTest(pluginEvent: PluginEvent) {
plugin.onPluginEvent(pluginEvent);
const resizer = editor.getDocument().getElementById(TABLE_RESIZER);
expect(!!resizer).toBe(false);
}
it('removes table resisizer on input', () => {
const pluginEvent: PluginEvent = {
eventType: PluginEventType.Input,
rawEvent: null,
};
removeResizerTest(pluginEvent);
});
it('removes table resisizer on content change', () => {
const pluginEvent: PluginEvent = {
eventType: PluginEventType.ContentChanged,
source: null,
};
removeResizerTest(pluginEvent);
});
it('removes table resisizer on scrolling', () => {
const pluginEvent: PluginEvent = {
eventType: PluginEventType.Scroll,
scrollContainer: editor.getDocument().body as HTMLElement,
rawEvent: null,
};
removeResizerTest(pluginEvent);
});
/************************ Resizing row related tests ************************/
function resizeFirstRowTest(i: number) {
initialize(i);
const delta = 50;
const testTable = testTables[i];
const cellRect = getCellRect(0, 0);
const targetPos: number = testTable.rows[1] + delta;
moveAndResize(
{ x: cellRect.left + cellRect.width / 2, y: cellRect.bottom },
{ x: cellRect.left + cellRect.width / 2, y: targetPos },
ResizeState.Horizontal
);
}
function resizeLastRowTest(i: number) {
initialize(i);
const delta = 120;
const testTable = testTables[i];
const cellRect = getCellRect(2, 2);
const targetPos: number = testTable.rows[testTable.rows.length - 1] + delta;
moveAndResize(
{ x: cellRect.left + cellRect.width / 2, y: cellRect.bottom },
{ x: cellRect.left + cellRect.width / 2, y: targetPos },
ResizeState.Horizontal
);
}
it('resizes the first row correctly with default table', () => {
resizeFirstRowTest(0);
});
it('resizes the first row correctly with Excel table', () => {
resizeFirstRowTest(1);
});
it('resizes the first row correctly with Word table', () => {
resizeFirstRowTest(2);
});
it('resizes the last row correctly with default table', () => {
resizeLastRowTest(0);
});
it('resizes the last row correctly with Excel table', () => {
resizeLastRowTest(1);
});
it('resizes the last row correctly with Word table', () => {
resizeLastRowTest(2);
});
it('resizes the row correctly with merged cells', () => {
initialize(3);
const delta = 35;
const testTable = testTables[3];
const cellRect = getCellRect(1, 1);
const targetPos: number = testTable.rows[2] + delta;
moveAndResize(
{ x: cellRect.left + cellRect.width / 2, y: cellRect.bottom },
{ x: cellRect.left + cellRect.width / 2, y: targetPos },
ResizeState.Horizontal
);
});
/************************ Resizing column related tests ************************/
function resizeColumnToLeftTest(i: number) {
initialize(i);
const delta = 20;
const testTable = testTables[i];
const cellRect = getCellRect(0, 0);
const targetPos: number = testTable.columns[1] - delta;
moveAndResize(
{ x: cellRect.right, y: cellRect.top + cellRect.height / 2 },
{ x: targetPos, y: cellRect.top + cellRect.height / 2 + 50 },
ResizeState.Vertical
);
}
function resizeColumnToLeftTooNarrowTest(i: number) {
initialize(i);
const testTable = testTables[i];
const cellRect = getCellRect(0, 1);
const targetPos: number = testTable.columns[0] + 10;
moveAndResize(
{ x: cellRect.right, y: cellRect.top + cellRect.height / 2 },
{ x: targetPos, y: cellRect.top + cellRect.height / 2 - 20 },
ResizeState.Vertical
);
}
function resizeColumnToRightTest(i: number) {
initialize(i);
const delta = 30;
const testTable = testTables[i];
const cellRect = getCellRect(1, 1);
const targetPos: number = testTable.columns[2] + delta;
moveAndResize(
{ x: cellRect.right, y: cellRect.top + cellRect.height / 2 },
{ x: targetPos, y: cellRect.top + cellRect.height / 2 - 15 },
ResizeState.Vertical
);
}
function resizeColumnToRightTestTooNarrowTest(i: number) {
initialize(i);
const delta = 5;
const testTable = testTables[i];
const cellRect = getCellRect(2, 0);
const targetPos: number = testTable.columns[2] - delta;
moveAndResize(
{ x: cellRect.right, y: cellRect.top + cellRect.height / 2 },
{ x: targetPos, y: cellRect.top + cellRect.height / 2 + 17 },
ResizeState.Vertical
);
}
function resizeLastColumnToRightTest(i: number) {
initialize(i);
const delta = 350;
const testTable = testTables[i];
const cellRect = getCellRect(2, 2);
const targetPos: number = testTable.columns[testTable.columns.length - 1] + delta;
moveAndResize(
{ x: cellRect.right, y: cellRect.top + cellRect.height / 2 },
{ x: targetPos, y: cellRect.top + cellRect.height / 2 - 5 },
ResizeState.Vertical
);
}
it('resizes the column to the left correctly with default table', () => {
resizeColumnToLeftTest(0);
});
it('resizes the column to the left correctly with Excel table', () => {
resizeColumnToLeftTest(1);
});
it('resizes the column to the left correctly with Word table', () => {
resizeColumnToLeftTest(2);
});
it('resizes the column to the left correctly with merged cells', () => {
initialize(3);
const delta = 20;
const testTable = testTables[3];
const cellRect = getCellRect(1, 1);
const targetPos: number = testTable.columns[3] - delta;
moveAndResize(
{ x: cellRect.right, y: cellRect.top + cellRect.height / 2 },
{ x: targetPos, y: cellRect.top + cellRect.height / 2 + 50 },
ResizeState.Vertical
);
});
it('does not resize the column to the left correctly with merged cells since too narrow', () => {
initialize(3);
const testTable = testTables[3];
const cellRect = getCellRect(1, 1);
const targetPos: number = testTable.columns[2];
moveAndResize(
{ x: cellRect.right, y: cellRect.top + cellRect.height / 2 },
{ x: targetPos, y: cellRect.top + cellRect.height / 2 + 50 },
ResizeState.Vertical
);
});
it('does not resize the column to the left because it is too narrow with default table', () => {
resizeColumnToLeftTooNarrowTest(0);
});
it('does not resize the column to the left because it is too narrow with Excel table', () => {
resizeColumnToLeftTooNarrowTest(1);
});
it('does not resize the column to the left because it is too narrow with Word table', () => {
resizeColumnToLeftTooNarrowTest(2);
});
it('resizes the column to the right correctly with default table', () => {
resizeColumnToRightTest(0);
});
it('resizes the column to the right correctly with Excel table', () => {
resizeColumnToRightTest(1);
});
it('resizes the column to the right correctly with Word table', () => {
resizeColumnToRightTest(2);
});
it('does not resize the column to the right because it is too narrow with default table', () => {
resizeColumnToRightTestTooNarrowTest(0);
});
it('does not resize the column to the right because it is too narrow with Excel table', () => {
resizeColumnToRightTestTooNarrowTest(1);
});
it('does not resize the column to the right because it is too narrow with Word table', () => {
resizeColumnToRightTestTooNarrowTest(2);
});
it('resizes the last column to the right correctly with default table', () => {
resizeLastColumnToRightTest(0);
});
it('resizes the last column to the right correctly with Excel table', () => {
resizeLastColumnToRightTest(1);
});
it('resizes the last column to the right correctly with Word table', () => {
resizeLastColumnToRightTest(2);
});
/************************ Resizing table related tests ************************/
function resizeTableWiderTest(i: number) {
const tableRect = initialize(i);
const testTable = testTables[i];
const mouseStart = { x: tableRect.right, y: tableRect.bottom };
const mouseEnd = { x: 700, y: testTable.rows[3] };
moveAndResize(mouseStart, mouseEnd, ResizeState.Both);
}
function resizeTableNarrowerTest(i: number) {
const tableRect = initialize(i);
const testTable = testTables[i];
const mouseStart = { x: tableRect.right, y: tableRect.bottom };
const mouseEnd = { x: 300, y: testTable.rows[3] };
moveAndResize(mouseStart, mouseEnd, ResizeState.Both);
}
function resizeTableTallerTest(i: number) {
const tableRect = initialize(i);
const newBorderY = tableRect.bottom + 100;
const mouseStart = { x: tableRect.right, y: tableRect.bottom };
const mouseEnd = { x: tableRect.right, y: newBorderY };
moveAndResize(mouseStart, mouseEnd, ResizeState.Both);
}
function resizeTableNarrowerTallerTest(i: number) {
const tableRect = initialize(i);
const newBorderX = tableRect.left + tableRect.width * 0.7;
const newBorderY = tableRect.bottom + 100;
const mouseStart = { x: tableRect.right, y: tableRect.bottom };
const mouseEnd = { x: newBorderX, y: newBorderY };
moveAndResize(mouseStart, mouseEnd, ResizeState.Both);
}
function resizeTableWiderTallerTest(i: number) {
const tableRect = initialize(i);
const newBorderX = tableRect.left + tableRect.width * 2.0;
const newBorderY = tableRect.bottom + 250;
const mouseStart = { x: tableRect.right, y: tableRect.bottom };
const mouseEnd = { x: newBorderX, y: newBorderY };
moveAndResize(mouseStart, mouseEnd, ResizeState.Both);
}
it('resizes the table to be wider correctly with default table', () => {
resizeTableWiderTest(0);
});
it('resizes the table to be wider correctly with Excel table', () => {
resizeTableWiderTest(1);
});
it('resizes the table to be wider correctly with Word table', () => {
resizeTableWiderTest(2);
});
it('resizes the table to be narrower correctly with default table', () => {
resizeTableNarrowerTest(0);
});
it('resizes the table to be narrower correctly with Excel table', () => {
resizeTableNarrowerTest(1);
});
it('resizes the table to be narrower correctly with Word table', () => {
resizeTableNarrowerTest(2);
});
it('resizes the table to be taller correctly with default table', () => {
resizeTableTallerTest(0);
});
it('resizes the table to be taller correctly with Excel table', () => {
resizeTableTallerTest(1);
});
it('resizes the table to be taller correctly with Word table', () => {
resizeTableTallerTest(2);
});
it('resizes the table to be narrower and taller correctly with default table', () => {
resizeTableNarrowerTallerTest(0);
});
it('resizes the table to be narrower and taller correctly with Excel table', () => {
resizeTableNarrowerTallerTest(1);
});
it('resizes the table to be narrower and taller correctly with Word table', () => {
resizeTableNarrowerTallerTest(2);
});
it('resizes the table to be wider and taller correctly with default table', () => {
resizeTableWiderTallerTest(0);
});
it('resizes the table to be wider and taller correctly with Excel table', () => {
resizeTableWiderTallerTest(1);
});
it('resizes the table to be wider and taller correctly with Word table', () => {
resizeTableWiderTallerTest(2);
});
/************************ Other utilities ************************/
it('returns the actual plugin name', () => {
const expectedName = 'TableResize';
const pluginName = plugin.getName();
expect(pluginName).toBe(expectedName);
});
}); | the_stack |
import * as CloudFormation from 'aws-sdk/clients/cloudformation';
import * as CloudWatchLogs from 'aws-sdk/clients/cloudwatchlogs';
import * as AWS from 'aws-sdk/global';
import awaitSsmCommand from '../../common/functions/awaitSsmCommand';
// Name of testing stack is derived from env variable to ensure uniqueness
const testingStackName = 'RFDKInteg-DL-TestingTier' + process.env.INTEG_STACK_TAG?.toString();
const deadlineVersion = process.env.DEADLINE_VERSION?.toString();
const cloudformation = new CloudFormation();
const logs = new CloudWatchLogs();
const bastionRegex = /bastionId/;
const dbRegex = /DatabaseSecretARNDL(\d)/;
const logRegex = /logGroupNameDL(\d)/;
const certRegex = /CertSecretARNDL(\d)/;
const testCases: Array<Array<any>> = [
[ 'RFDK-created DB and EFS', 1 ],
[ 'User-created DB and EFS', 2 ],
[ 'User-created MongoDB', 3],
];
let bastionId: string;
let dbSecretARNs: Array<any> = [];
let logGroupNames: Array<any> = [];
let certSecretARNs: Array<any> = [];
beforeAll( () => {
// Query the TestingStack and await its outputs to use as test inputs
return new Promise<void>( (res,rej) => {
var params = {
StackName: testingStackName,
};
cloudformation.describeStacks(params, (err, data) => {
if (err) {
rej(err);
}
else {
var stackOutput = data.Stacks![0].Outputs!;
stackOutput.forEach( output => {
var outputKey = output.OutputKey!;
var outputValue = output.OutputValue!;
switch(true){
case bastionRegex.test(outputKey):
bastionId = outputValue;
break;
case dbRegex.test(outputKey):
var testId = dbRegex.exec(outputKey)![1];
dbSecretARNs[+testId] = outputValue;
break;
case logRegex.test(outputKey):
var testId = logRegex.exec(outputKey)![1];
logGroupNames[+testId] = outputValue;
break;
case certRegex.test(outputKey):
var testId = certRegex.exec(outputKey)![1];
certSecretARNs[+testId] = outputValue;
break;
default:
break;
}
});
res();
}
});
});
});
describe.each(testCases)('Deadline Repository tests (%s)', (_, id) => {
describe('DocumentDB tests', () => {
beforeAll( () => {
if( certSecretARNs[id]) {
//If the secretARN has been provided for the auth certificate, this command will fetch it to the instance before continuing the tests
var params = {
DocumentName: 'AWS-RunShellScript',
Comment: 'Execute Test Script fetch-cert.sh',
InstanceIds: [bastionId],
Parameters: {
commands: [
'sudo -i',
'su - ec2-user >/dev/null',
'cd ~ec2-user',
'./utilScripts/fetch-cert.sh \'' + AWS.config.region + '\' \'' + certSecretARNs[id] + '\'',
],
},
};
return awaitSsmCommand(bastionId, params);
}
else {
return;
}
});
// This removes the certification file used to authenticate to the render queue
afterAll( () => {
var params = {
DocumentName: 'AWS-RunShellScript',
Comment: 'Execute Test Script cleanup-cert.sh',
InstanceIds: [bastionId],
Parameters: {
commands: [
'sudo -i',
'su - ec2-user >/dev/null',
'cd ~ec2-user',
'./utilScripts/cleanup-cert.sh',
],
},
};
return awaitSsmCommand(bastionId, params);
});
test(`DL-${id}-1: Deadline DB is initialized`, async () => {
/**********************************************************************************************************
* TestID: DL-1
* Description: Confirm that Deadline database is initialized on render farm
* Input: Output from mongo CLI "listDatabases" call delivered via SSM command
* Expected result: Database list returned from bastion contains "deadline10db"
**********************************************************************************************************/
var params = {
DocumentName: 'AWS-RunShellScript',
Comment: 'Execute Test Script DL-read-docdb-response.sh',
InstanceIds: [bastionId],
Parameters: {
commands: [
'sudo -i',
'su - ec2-user >/dev/null',
'cd ~ec2-user',
'./testScripts/DL-read-docdb-response.sh \'' + AWS.config.region + '\' \'' + dbSecretARNs[id] + '\' \'' + certSecretARNs[id] + '\'',
],
},
};
return awaitSsmCommand(bastionId, params).then( response => {
var output = response.output;
var json = JSON.parse(<string> output);
expect(json.databases[0].name).toBe('deadline10db');
});
});
});
describe( 'EFS tests', () => {
let responseCode: number;
let output: string;
beforeAll( () => {
var params = {
DocumentName: 'AWS-RunShellScript',
Comment: 'Execute Test Script DL-read-repository-settings.sh',
InstanceIds: [bastionId],
Parameters: {
commands: [
'sudo -i',
'su - ec2-user >/dev/null',
'cd ~ec2-user',
'./testScripts/DL-read-repository-settings.sh "' + id.toString() + '"',
],
},
};
return awaitSsmCommand(bastionId, params).then( response => {
responseCode = response.responseCode;
output = response.output;
});
});
test(`DL-${id}-2: EFS is initialized`, () => {
/**********************************************************************************************************
* TestID: DL-2
* Description: Confirm that EFS is initialized on render farm and contains files
* Input: Response code from command to print contents of repository.ini delivered via SSM command
* Expected result: Response code 0, i.e. the script execution was successfuld and repository.ini exists
**********************************************************************************************************/
expect(responseCode).toEqual(0);
});
test(`DL-${id}-3: repository.ini version matches Deadline installer`, () => {
/**********************************************************************************************************
* TestID: DL-3
* Description: Confirm that the Deadline version installed matches the version of the passed-in installer
* Input: Output from command to print contents of repository.ini delivered via SSM command
* Expected result: Contents of repository.ini matches a regex string indicating the correct version number
**********************************************************************************************************/
let expectedVersion: string;
switch (deadlineVersion) {
// Special case for Deadline 10.1.18.5 since it appears as 10.1.18.4 due to known issues in Deadline's build pipeline
case '10.1.18.5':
expectedVersion = '10.1.18.4';
break;
default:
expectedVersion = deadlineVersion!;
break;
}
const regex = new RegExp('\\[DeadlineRepository\\]\nVersion=' + expectedVersion.replace('.', '\\.'));
expect(output).toEqual(expect.stringMatching(regex));
});
});
describe('CloudWatch LogGroup tests', () => {
let logStreamCount: number;
let cloudInitLogName: string;
let deadlineLogName: string;
beforeAll( () => {
var params = {
logGroupName: logGroupNames[id],
};
return new Promise<void>( (res,rej) => {
logs.describeLogStreams(params, (err, data) => {
if (err) {
rej(err);
}
else {
var logStreams = data.logStreams!;
logStreamCount = logStreams.length;
logStreams.forEach( logStream => {
var logStreamName = logStream.logStreamName!;
if(/cloud-init-output/.test(logStreamName)) {
cloudInitLogName = logStreamName;
}
else if( /deadlineRepositoryInstallationLogs/.test(logStreamName)) {
deadlineLogName = logStreamName;
}
});
}
res();
});
});
});
test(`DL-${id}-4: CloudWatch LogGroup contains two LogStreams`, () => {
/**********************************************************************************************************
* TestID: DL-4
* Description: Confirm that CloudWatch LogGroup has been created with two LogStreams
* Input: Output from cli call to describe LogGroup created during cdk deploy
* Expected result: LogGroup contains exactly two LogStreams
**********************************************************************************************************/
expect(logStreamCount).toEqual(2);
});
describe('cloud-init-output LogStream tests', () => {
let logEvents: Object;
beforeAll( () => {
return new Promise<void>( (res, rej) => {
var params = {
logGroupName: logGroupNames[id],
logStreamName: cloudInitLogName,
};
logs.getLogEvents(params, (err,data) => {
if (err) {
rej(err);
}
else {
logEvents = data.events!;
}
res();
});
});
});
test(`DL-${id}-5: cloud-init-output is initialized`, () => {
/**********************************************************************************************************
* TestID: DL-5
* Description: Confirm that cloud-init-output contains log events from cdk initizialization
* Input: Output from sdk call to describe cloud-init-output LogStream created during cdk deploy
* Expected result: Event log contains at least one entry where the message property matches a regex string
* indicating the cloud-init version used
**********************************************************************************************************/
expect(logEvents).toContainEqual(
{
ingestionTime: expect.anything(),
message: expect.stringMatching( /Cloud-init v. / ),
timestamp: expect.anything(),
},
);
});
test(`DL-${id}-6: cloud-init-output does not contain INSTALLER_DB_ARGS`, () => {
/**********************************************************************************************************
* TestID: DL-6
* Description: Confirm that cloud-init-output does not contain INSTALLER_DB_ARGS; this environment
* variable contains sensitive info that should not be exposed.
* Input: Output from sdk call to describe cloud-init-output LogStream created during cdk deploy
* Expected result: There is one expected instance of the INSTALLER_DB_ARGS variable so the test will fail
* if the variable appears outside of the specificed string
**********************************************************************************************************/
expect(logEvents).toContainEqual(
{
ingestionTime: expect.anything(),
message: expect.not.stringMatching( /\w*(?<!declare -A )INSTALLER_DB_ARGS/ ),
timestamp: expect.anything(),
},
);
});
});
describe('DeadlineRepositoryInstallationLogs LogStream tests', () => {
let logEvents: Object;
beforeAll( () => {
return new Promise<void>( (res, rej) => {
var params = {
logGroupName: logGroupNames[id],
logStreamName: deadlineLogName,
};
logs.getLogEvents(params, (err,data) => {
if (err) {
rej(err);
}
else {
logEvents = data.events!;
}
res();
});
});
});
test(`DL-${id}-7: DeadlineRepositoryInstallationLogs is initialized`, () => {
/**********************************************************************************************************
* TestID: DL-7
* Description: Confirm that deadlineRepositoryInstallationLogs contains log events from Deadline installation
* Input: Output from cli call to describe deadlineRepositoryInstallationLogs LogStream created during cdk deploy
* Expected result: Event log contains at least one entry where the message property matches a regex string
* indicating that the deadlinecommand.exe command was run during installation
**********************************************************************************************************/
expect(logEvents).toContainEqual(
{
ingestionTime: expect.anything(),
message: expect.stringMatching( /Executing \/tmp\/repoinstalltemp\/deadlinecommand.exe/ ),
timestamp: expect.anything(),
},
);
});
});
});
}); | the_stack |
import fetchMock from "fetch-mock-jest";
import { renderHook } from "@testing-library/react-hooks";
import createWrapper from "./tests/createWrapper";
import { setIndexLink } from "./tests/indexLinks";
import createInfiniteCachingClient from "./tests/createInfiniteCachingClient";
import {
useArchiveRepository,
useCreateRepository,
useDeleteRepository,
UseDeleteRepositoryOptions,
useRepositories,
UseRepositoriesRequest,
useRepository,
useRepositoryTypes,
useUnarchiveRepository,
useUpdateRepository,
} from "./repositories";
import { Repository } from "@scm-manager/ui-types";
import { QueryClient } from "react-query";
import { act } from "react-test-renderer";
describe("Test repository hooks", () => {
const heartOfGold: Repository = {
namespace: "spaceships",
name: "heartOfGold",
type: "git",
_links: {
delete: {
href: "/r/spaceships/heartOfGold",
},
update: {
href: "/r/spaceships/heartOfGold",
},
archive: {
href: "/r/spaceships/heartOfGold/archive",
},
unarchive: {
href: "/r/spaceships/heartOfGold/unarchive",
},
},
};
const repositoryCollection = {
_embedded: {
repositories: [heartOfGold],
},
_links: {},
};
afterEach(() => {
fetchMock.reset();
});
describe("useRepositories tests", () => {
const expectCollection = async (queryClient: QueryClient, request?: UseRepositoriesRequest) => {
const { result, waitFor } = renderHook(() => useRepositories(request), {
wrapper: createWrapper(undefined, queryClient),
});
await waitFor(() => {
return !!result.current.data;
});
expect(result.current.data).toEqual(repositoryCollection);
};
it("should return repositories", async () => {
const queryClient = createInfiniteCachingClient();
setIndexLink(queryClient, "repositories", "/repos");
fetchMock.get("/api/v2/repos", repositoryCollection, {
query: {
sortBy: "namespaceAndName",
},
});
await expectCollection(queryClient);
});
it("should return repositories with page", async () => {
const queryClient = createInfiniteCachingClient();
setIndexLink(queryClient, "repositories", "/repos");
fetchMock.get("/api/v2/repos", repositoryCollection, {
query: {
sortBy: "namespaceAndName",
page: "42",
},
});
await expectCollection(queryClient, {
page: 42,
});
});
it("should use repository from namespace", async () => {
const queryClient = createInfiniteCachingClient();
setIndexLink(queryClient, "repositories", "/repos");
fetchMock.get("/api/v2/spaceships", repositoryCollection, {
query: {
sortBy: "namespaceAndName",
},
});
await expectCollection(queryClient, {
namespace: {
namespace: "spaceships",
_links: {
repositories: {
href: "/spaceships",
},
},
},
});
});
it("should append search query", async () => {
const queryClient = createInfiniteCachingClient();
setIndexLink(queryClient, "repositories", "/repos");
fetchMock.get("/api/v2/repos", repositoryCollection, {
query: {
sortBy: "namespaceAndName",
q: "heart",
},
});
await expectCollection(queryClient, {
search: "heart",
});
});
it("should update repository cache", async () => {
const queryClient = createInfiniteCachingClient();
setIndexLink(queryClient, "repositories", "/repos");
fetchMock.get("/api/v2/repos", repositoryCollection, {
query: {
sortBy: "namespaceAndName",
},
});
await expectCollection(queryClient);
const repository = queryClient.getQueryData(["repository", "spaceships", "heartOfGold"]);
expect(repository).toEqual(heartOfGold);
});
it("should return nothing if disabled", () => {
const queryClient = createInfiniteCachingClient();
setIndexLink(queryClient, "repositories", "/repos");
const { result } = renderHook(() => useRepositories({ disabled: true }), {
wrapper: createWrapper(undefined, queryClient),
});
expect(result.current.isLoading).toBe(false);
expect(result.current.data).toBeFalsy();
expect(result.current.error).toBeFalsy();
});
});
describe("useCreateRepository tests", () => {
it("should create repository", async () => {
const queryClient = createInfiniteCachingClient();
setIndexLink(queryClient, "repositories", "/r");
fetchMock.postOnce("/api/v2/r", {
status: 201,
headers: {
Location: "/r/spaceships/heartOfGold",
},
});
fetchMock.getOnce("/api/v2/r/spaceships/heartOfGold", heartOfGold);
const { result, waitForNextUpdate } = renderHook(() => useCreateRepository(), {
wrapper: createWrapper(undefined, queryClient),
});
const repository = {
...heartOfGold,
contextEntries: [],
};
await act(() => {
const { create } = result.current;
create(repository, false);
return waitForNextUpdate();
});
expect(result.current.repository).toEqual(heartOfGold);
});
it("should append initialize param", async () => {
const queryClient = createInfiniteCachingClient();
setIndexLink(queryClient, "repositories", "/r");
fetchMock.postOnce("/api/v2/r?initialize=true", {
status: 201,
headers: {
Location: "/r/spaceships/heartOfGold",
},
});
fetchMock.getOnce("/api/v2/r/spaceships/heartOfGold", heartOfGold);
const { result, waitForNextUpdate } = renderHook(() => useCreateRepository(), {
wrapper: createWrapper(undefined, queryClient),
});
const repository = {
...heartOfGold,
contextEntries: [],
};
await act(() => {
const { create } = result.current;
create(repository, true);
return waitForNextUpdate();
});
expect(result.current.repository).toEqual(heartOfGold);
});
it("should fail without location header", async () => {
const queryClient = createInfiniteCachingClient();
setIndexLink(queryClient, "repositories", "/r");
fetchMock.postOnce("/api/v2/r", {
status: 201,
});
const { result, waitForNextUpdate } = renderHook(() => useCreateRepository(), {
wrapper: createWrapper(undefined, queryClient),
});
const repository = {
...heartOfGold,
contextEntries: [],
};
await act(() => {
const { create } = result.current;
create(repository, false);
return waitForNextUpdate();
});
expect(result.current.error).toBeDefined();
});
});
describe("useRepository tests", () => {
it("should return repository", async () => {
const queryClient = createInfiniteCachingClient();
setIndexLink(queryClient, "repositories", "/r");
fetchMock.get("/api/v2/r/spaceships/heartOfGold", heartOfGold);
const { result, waitFor } = renderHook(() => useRepository("spaceships", "heartOfGold"), {
wrapper: createWrapper(undefined, queryClient),
});
await waitFor(() => {
return !!result.current.data;
});
expect(result.current?.data?.type).toEqual("git");
});
});
describe("useRepositoryTypes tests", () => {
it("should return repository types", async () => {
const queryClient = createInfiniteCachingClient();
setIndexLink(queryClient, "repositoryTypes", "/rt");
fetchMock.get("/api/v2/rt", {
_embedded: {
repositoryTypes: [
{
name: "git",
displayName: "Git",
_links: {},
},
],
},
_links: {},
});
const { result, waitFor } = renderHook(() => useRepositoryTypes(), {
wrapper: createWrapper(undefined, queryClient),
});
await waitFor(() => {
return !!result.current.data;
});
expect(result.current.data).toBeDefined();
if (result.current?.data) {
expect(result.current?.data._embedded?.repositoryTypes[0].name).toEqual("git");
}
});
});
describe("useDeleteRepository tests", () => {
const queryClient = createInfiniteCachingClient();
beforeEach(() => {
queryClient.clear();
});
const deleteRepository = async (options?: UseDeleteRepositoryOptions) => {
fetchMock.deleteOnce("/api/v2/r/spaceships/heartOfGold", {
status: 204,
});
const { result, waitForNextUpdate } = renderHook(() => useDeleteRepository(options), {
wrapper: createWrapper(undefined, queryClient),
});
await act(() => {
const { remove } = result.current;
remove(heartOfGold);
return waitForNextUpdate();
});
return result.current;
};
const shouldRemoveQuery = async (queryKey: string[], data: unknown) => {
queryClient.setQueryData(queryKey, data);
await deleteRepository();
const queryState = queryClient.getQueryState(queryKey);
expect(queryState).toBeUndefined();
};
const shouldInvalidateQuery = async (queryKey: string[], data: unknown) => {
queryClient.setQueryData(queryKey, data);
await deleteRepository();
const queryState = queryClient.getQueryState(queryKey);
expect(queryState!.isInvalidated).toBe(true);
};
it("should delete repository", async () => {
const { isDeleted } = await deleteRepository();
expect(isDeleted).toBe(true);
});
it("should invalidate repository cache", async () => {
await shouldRemoveQuery(["repository", "spaceships", "heartOfGold"], heartOfGold);
});
it("should invalidate repository collection cache", async () => {
await shouldInvalidateQuery(["repositories"], repositoryCollection);
});
it("should call onSuccess callback", async () => {
let repo;
await deleteRepository({
onSuccess: (repository) => {
repo = repository;
},
});
expect(repo).toEqual(heartOfGold);
});
});
describe("useUpdateRepository tests", () => {
const queryClient = createInfiniteCachingClient();
beforeEach(() => {
queryClient.clear();
});
const updateRepository = async () => {
fetchMock.putOnce("/api/v2/r/spaceships/heartOfGold", {
status: 204,
});
const { result, waitForNextUpdate } = renderHook(() => useUpdateRepository(), {
wrapper: createWrapper(undefined, queryClient),
});
await act(() => {
const { update } = result.current;
update(heartOfGold);
return waitForNextUpdate();
});
return result.current;
};
const shouldInvalidateQuery = async (queryKey: string[], data: unknown) => {
queryClient.setQueryData(queryKey, data);
await updateRepository();
const queryState = queryClient.getQueryState(queryKey);
expect(queryState!.isInvalidated).toBe(true);
};
it("should update repository", async () => {
const { isUpdated } = await updateRepository();
expect(isUpdated).toBe(true);
});
it("should invalidate repository cache", async () => {
await shouldInvalidateQuery(["repository", "spaceships", "heartOfGold"], heartOfGold);
});
it("should invalidate repository collection cache", async () => {
await shouldInvalidateQuery(["repositories"], repositoryCollection);
});
});
describe("useArchiveRepository tests", () => {
const queryClient = createInfiniteCachingClient();
beforeEach(() => {
queryClient.clear();
});
const archiveRepository = async () => {
fetchMock.postOnce("/api/v2/r/spaceships/heartOfGold/archive", {
status: 204,
});
const { result, waitForNextUpdate } = renderHook(() => useArchiveRepository(), {
wrapper: createWrapper(undefined, queryClient),
});
await act(() => {
const { archive } = result.current;
archive(heartOfGold);
return waitForNextUpdate();
});
return result.current;
};
const shouldInvalidateQuery = async (queryKey: string[], data: unknown) => {
queryClient.setQueryData(queryKey, data);
await archiveRepository();
const queryState = queryClient.getQueryState(queryKey);
expect(queryState!.isInvalidated).toBe(true);
};
it("should archive repository", async () => {
const { isArchived } = await archiveRepository();
expect(isArchived).toBe(true);
});
it("should invalidate repository cache", async () => {
await shouldInvalidateQuery(["repository", "spaceships", "heartOfGold"], heartOfGold);
});
it("should invalidate repository collection cache", async () => {
await shouldInvalidateQuery(["repositories"], repositoryCollection);
});
});
describe("useUnarchiveRepository tests", () => {
const queryClient = createInfiniteCachingClient();
beforeEach(() => {
queryClient.clear();
});
const unarchiveRepository = async () => {
fetchMock.postOnce("/api/v2/r/spaceships/heartOfGold/unarchive", {
status: 204,
});
const { result, waitForNextUpdate } = renderHook(() => useUnarchiveRepository(), {
wrapper: createWrapper(undefined, queryClient),
});
await act(() => {
const { unarchive } = result.current;
unarchive(heartOfGold);
return waitForNextUpdate();
});
return result.current;
};
const shouldInvalidateQuery = async (queryKey: string[], data: unknown) => {
queryClient.setQueryData(queryKey, data);
await unarchiveRepository();
const queryState = queryClient.getQueryState(queryKey);
expect(queryState!.isInvalidated).toBe(true);
};
it("should unarchive repository", async () => {
const { isUnarchived } = await unarchiveRepository();
expect(isUnarchived).toBe(true);
});
it("should invalidate repository cache", async () => {
await shouldInvalidateQuery(["repository", "spaceships", "heartOfGold"], heartOfGold);
});
it("should invalidate repository collection cache", async () => {
await shouldInvalidateQuery(["repositories"], repositoryCollection);
});
});
}); | the_stack |
This class provides everything to render the D3.js graph.
*/
/*
@license
Parts of the code in this file are based loosely on code from this repository:
https://github.com/gaguri777/d3--directed-graph-creator
In the repository, it is stated that the code is licensed under the
MIT/X license. However, the repository does not include a copyright notice
typical for the MIT license. This is my best attempt at creating one myself,
in good faith, on behalf of the code creators, using the Open Source Intiative's
MIT license text:
Copyright (c) 2013-2014 Colorado Reed, Andreas Stuhlmüller
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import * as d3 from "d3";
import {
binaryArrayIncludes,
shortenText,
htmlDecode,
} from "./utils";
const prepareGraphObject = (graph) => {
const preparedGraphObject = {
...graph,
};
preparedGraphObject.nodes = graph.nodes.map((node) => {
node.title = htmlDecode(node.title);
return node;
});
preparedGraphObject.links = graph.links.map((link) => {
return {
source: graph.nodes.find((node) => node.id === link[0]),
target: graph.nodes.find((node) => node.id === link[1]),
};
});
return preparedGraphObject;
};
export default class GraphVisualization {
static #consts = {
selectedClass: "selected",
connectClass: "connect-node",
nodeClassName: "node",
graphClass: "graph",
activeEditId: "active-editing",
BACKSPACE_KEY: 8,
DELETE_KEY: 46,
ENTER_KEY: 13,
ESCAPE_KEY: 27,
C_KEY: 67,
S_KEY: 83,
nodeRadius: 50,
newNodeIndicatorSize: 4 * 50,
MAX_NODE_TEXT_LENGTH: 55,
};
#searchValue = "";
#onHighlight;
#onChange;
#openNote;
#nodes;
#links;
#screenPosition;
#initialNodePosition;
#parent;
#svg;
#idsOfAllNodesWithLinkedNote = [];
#updatedNodes = new Set();
#mouseDownNode = null;
#justDragged = false;
#justScaleTransGraph = false;
#lastKeyDown = -1;
#newLinkCreationInProgress = false;
#selection = new Set<any>();
#connectedNodeIdsOfSelection:number[] = [];
#titleRenderingEnabled = false;
#mainSVGGroup;
#gridLines;
#initialNodePositionIndicator;
#nodeHighlighterContainer;
#newLinkLine;
#linksContainer;
#nodesContainer;
#nodeDrag;
#inpIndicatorDrag;
#nodeHighlighterElements;
#nodeElements;
#linkElements;
#shiftKeyIsPressed = false;
#ctrlKeyIsPressed = false;
#sKeyIsPressed = false;
constructor({
parent,
graphObject,
onHighlight,
onChange,
initialFocusNoteId,
openNote,
}) {
const graphObjectPrepared = prepareGraphObject(graphObject);
this.#parent = parent;
const { width, height } = this.#parent.getBoundingClientRect();
/** MAIN SVG **/
const svg = d3.select(parent)
.append("svg")
.attr("width", width)
.attr("height", height);
this.#svg = svg;
this.#onHighlight = onHighlight;
this.#onChange = onChange;
this.#openNote = openNote;
this.#nodes = graphObjectPrepared.nodes;
this.#links = graphObjectPrepared.links;
// by default, we're using the screenPosition from the given data object ...
this.#screenPosition = graphObjectPrepared.screenPosition;
// ... we'll overwrite it if a valid note to focus is given
if (typeof initialFocusNoteId === "number" && !isNaN(initialFocusNoteId)) {
// set initial node in the center of the screen
const node = this.#nodes.find(
(node) => node.id === initialFocusNoteId,
);
if (typeof node === "object") {
const { width, height } = this.#svg.node().getBoundingClientRect();
const SCALE = 1.5;
this.#screenPosition = {
translateX: (-node.position.x * SCALE) + (width / 2),
translateY: (-node.position.y * SCALE) + (height / 2),
scale: SCALE,
};
}
}
this.#initialNodePosition = graphObjectPrepared.initialNodePosition;
this.#mainSVGGroup = svg.append("g")
.classed(GraphVisualization.#consts.graphClass, true);
const mainSVGGroup = this.#mainSVGGroup;
this.#gridLines = mainSVGGroup.append("g")
.classed("grid-lines", true);
this.#gridLines
.append("rect")
.attr("width", 100)
.attr("height", 40000)
.attr("x", -50)
.attr("y", -20000)
.classed("grid-line", true);
this.#gridLines
.append("rect")
.attr("width", 40000)
.attr("height", 100)
.attr("x", -20000)
.attr("y", -50)
.classed("grid-line", true);
this.#initialNodePositionIndicator = mainSVGGroup.append("g")
.classed("new-node-position-indicator", true)
.append("rect")
.attr("width", String(GraphVisualization.#consts.newNodeIndicatorSize))
.attr("height", String(GraphVisualization.#consts.newNodeIndicatorSize))
.attr("rx", 4)
.attr("ry", 4)
.on("mouseover", () => {
this.#onHighlight({
active: true,
type: "new-nodes-position-indicator",
});
})
.on("mouseout", () => {
this.#onHighlight({
active: false,
});
});
this.#nodeHighlighterContainer = mainSVGGroup.append("g")
.classed("note-highlighters", true);
// displayed when dragging between nodes - should be rendered in front of
// node highlighter circles, so this code is placed after node highlighter g
// creation code
this.#newLinkLine = mainSVGGroup.append("svg:path")
.attr("class", "link newLinkLine hidden")
.attr("d", "M0,0L0,0");
// svg nodes and links
this.#linksContainer = mainSVGGroup.append("g")
.classed("links", true);
this.#nodesContainer = mainSVGGroup.append("g")
.classed("notes", true);
// drag single nodes, but not, if shift key is pressed
this.#nodeDrag = d3.drag()
.subject((event) => {
return {
x: event.x,
y: event.y,
};
})
.filter(() => {
return (!this.#shiftKeyIsPressed)
&& (!this.#ctrlKeyIsPressed)
&& (!this.#sKeyIsPressed);
})
.on("drag", (e, d) => {
this.#justDragged = true;
const nodesToDrag = Array.from(this.#selection)
.filter((value) => !this.#isEdge(value));
// also drag mouse down node, regardless of if it's selected or not
if (!nodesToDrag.includes(d)) {
nodesToDrag.push(d);
}
nodesToDrag
.forEach((node) => {
node.position.x += e.dx;
node.position.y += e.dy;
this.#updatedNodes.add(node);
});
this.#updateGraph({ type: "NODE_DRAG", node: d });
this.#onChange();
});
// drag intitial node position indicator
this.#inpIndicatorDrag = d3.drag()
.subject((event) => {
return { x: event.x, y: event.y };
})
.on("drag", (e) => {
this.#initialNodePosition.x += e.dx;
this.#initialNodePosition.y += e.dy;
this.#onChange();
this.#updateGraph();
});
// listen for key events
d3.select(window)
.on("keydown", (e) => {
this.#svgKeyDown(e);
})
.on("keyup", (e) => {
this.#svgKeyUp(e);
});
svg.on("mouseup", () => {
this.#svgMouseUp();
});
svg.on("mousemove", (e) => {
this.#newPathMove(e, this.#mouseDownNode);
});
// listen for dragging
const zoom = d3.zoom();
zoom.on("zoom", (e) => {
if (e.shiftKey) {
// TODO the internal d3 state is still changing
return false;
} else {
this.#zoomed(e);
}
return true;
});
zoom.on("start", (e) => {
const ael = d3.select(
"#" + GraphVisualization.#consts.activeEditId,
).node();
if (ael) {
ael.blur();
}
if (!e.shiftKey) {
d3.select("body").style("cursor", "move");
}
});
svg.call(zoom).on("dblclick.zoom", null);
// when creating the graph, a zoom end event is initially dispatched.
// since this first one does not change anything, we don't want to fire the
// onChange event
let firstZoomEndHappened = false;
zoom.on("end", () => {
d3.select("body").style("cursor", "auto");
if (firstZoomEndHappened) {
this.#onChange();
} else {
firstZoomEndHappened = true;
}
});
const initialZoomTranform = d3.zoomIdentity
.translate(
this.#screenPosition.translateX,
this.#screenPosition.translateY,
)
.scale(this.#screenPosition.scale);
zoom.transform(svg, initialZoomTranform);
// listen for resize
window.onresize = () => this.#updateWindow(svg);
this.#updateConnectedNodeIds();
this.#updateGraph();
// by default, text rendering is activated, if the number of nodes is <= 500
if (this.#nodes.length <= 500) {
this.toggleTextRendering();
}
}
#updateConnectedNodeIds() {
this.#idsOfAllNodesWithLinkedNote = this.#links
.reduce((accumulator, link) => {
accumulator.push(link.source.id);
accumulator.push(link.target.id);
return accumulator;
}, [])
.sort((a, b) => a - b);
}
#newPathMove(e, originNode) {
if (!this.#newLinkCreationInProgress) {
return;
}
const newLinkEnd = {
x: d3.pointer(e, this.#mainSVGGroup.node())[0] - 1,
y: d3.pointer(e, this.#mainSVGGroup.node())[1] - 1,
};
this.#newLinkLine.attr(
"d",
"M" + originNode.position.x + "," + originNode.position.y
+ "L" + newLinkEnd.x + "," + newLinkEnd.y,
);
}
// insert svg line breaks: taken from
// http://stackoverflow.com/questions/13241475/how-do-i-include-newlines-in-labels-in-d3-charts
#insertTitleLinebreaks(gEl, title) {
const titleShortened = shortenText(
title,
GraphVisualization.#consts.MAX_NODE_TEXT_LENGTH,
);
const words = (titleShortened && titleShortened.split(/\s+/g)) || "";
const nwords = words.length;
const el = gEl.append("text")
.attr("text-anchor", "middle")
.attr("dy", "-" + (Math.max(nwords, 1) - 1) * 7.5);
for (let i = 0; i < words.length; i++) {
const tspan = el.append("tspan").text(words[i]);
if (i > 0) {tspan.attr("x", 0).attr("dy", "15");}
}
}
#getConnectedNodeIdsOfSelection(selection) {
return selection.reduce((accumulator, newValue) => {
if (this.#isEdge(newValue)) {
accumulator.push(newValue.source.id, newValue.target.id);
} else {
const linkedNoteIds = newValue.linkedNotes.map((node) => node.id);
accumulator.push(...linkedNoteIds);
}
return accumulator;
}, []);
}
#isEdge(value) {
return !!(value.source && value.target);
}
#select(values, addToOrRemoveFromExistingSelection = false) {
if (!addToOrRemoveFromExistingSelection) {
this.#selection = new Set(values);
} else {
values.forEach((value) => {
if (this.#selection.has(value)) {
this.#selection.delete(value);
} else {
this.#selection.add(value);
}
});
}
this.#connectedNodeIdsOfSelection
= this.#getConnectedNodeIdsOfSelection(
Array.from(this.#selection),
);
this.#updateGraph();
}
#handleMouseDownOnEdge(e, d) {
e.stopPropagation();
// when shift key is pressed down during mousedown,
// add edge to current selection
this.#select([d], e.shiftKey);
}
#handleMouseDownOnNode(e, d) {
e.stopPropagation();
this.#mouseDownNode = d;
if (e.shiftKey) {
this.#newLinkCreationInProgress = true;
// reposition dragged directed edge
this.#newLinkLine
.classed("hidden", false)
.attr(
"d",
"M" + d.position.x + "," + d.position.y
+ "L" + d.position.x + "," + d.position.y,
);
} else if (this.#sKeyIsPressed) {
this.#select([d], true);
}
}
// mouseup on nodes
#handleMouseUpOnNode(d3node, mouseUpNode) {
const consts = GraphVisualization.#consts;
// reset the states
this.#newLinkCreationInProgress = false;
d3node.classed(consts.connectClass, false);
const mouseDownNode = this.#mouseDownNode;
if (!mouseDownNode) return;
this.#newLinkLine.classed("hidden", true);
if (mouseDownNode !== mouseUpNode) {
// we're in a different node:
// create new edge for mousedown edge and add to graph
const newEdge = { source: mouseDownNode, target: mouseUpNode };
// check if such an edge is already there ...
const edgeAlreadyExists = this
.#linksContainer
.selectAll("path.link")
.filter(
(d) => {
return (
(d.source === newEdge.source && d.target === newEdge.target)
|| (d.source === newEdge.target && d.target === newEdge.source)
);
},
)
.size() !== 0;
// ... if not, create it
if (!edgeAlreadyExists) {
this.#links.push(newEdge);
this.#onChange();
this.#updateConnectedNodeIds();
this.#updateGraph();
}
} else {
// we're in the same node
if (this.#justDragged) {
// dragged, not clicked
this.#justDragged = false;
}
}
this.#mouseDownNode = null;
}
// mouseup on main svg
#svgMouseUp() {
if (this.#justScaleTransGraph) {
// dragged not clicked
this.#justScaleTransGraph = false;
}
// on mouse up, new link creation process is always over
this.#newLinkCreationInProgress = false;
this.#newLinkLine.classed("hidden", true);
}
// keydown on main svg
#svgKeyDown(e) {
const consts = GraphVisualization.#consts;
if (e.shiftKey) {
this.#shiftKeyIsPressed = true;
}
if (e.ctrlKey) {
this.#ctrlKeyIsPressed = true;
}
if (e.keyCode === consts.S_KEY) {
this.#sKeyIsPressed = true;
}
// make sure repeated key presses don't register for each keydown
if (this.#lastKeyDown !== -1) return;
this.#lastKeyDown = e.keyCode;
switch (e.keyCode) {
case consts.BACKSPACE_KEY:
case consts.DELETE_KEY:
// we cannot prevent default because then we cannot delete values from
// search input
// e.preventDefault();
// right now, we don't support deleting nodes from the graph view
// so let's consider only edges
Array.from(this.#selection)
.filter(this.#isEdge)
.forEach((edge) => {
this.#links.splice(this.#links.indexOf(edge), 1);
});
this.#onChange();
this.#select([]);
this.#updateConnectedNodeIds();
this.#updateGraph();
break;
case consts.ESCAPE_KEY:
case consts.C_KEY:
this.#select([]);
break;
}
}
#svgKeyUp(e) {
this.#shiftKeyIsPressed = e.shiftKey;
this.#ctrlKeyIsPressed = e.ctrlKey;
if (e.keyCode === GraphVisualization.#consts.S_KEY) {
this.#sKeyIsPressed = false;
}
this.#lastKeyDown = -1;
}
// call to propagate changes to graph
#updateGraph(event?):void {
const consts = GraphVisualization.#consts;
this.#initialNodePositionIndicator
.attr("x",
this.#initialNodePosition.x - (consts.newNodeIndicatorSize / 2),
)
.attr("y",
this.#initialNodePosition.y - (consts.newNodeIndicatorSize / 2),
)
.call(this.#inpIndicatorDrag);
/** ********************
node highlighter circles
***********************/
// create selection
this.#nodeHighlighterElements = this.#nodeHighlighterContainer
.selectAll("g.node-highlighter");
// append new node data
this.#nodeHighlighterElements = this.#nodeHighlighterElements
.data(
// append only the nodes that are search hits
this.#nodes.filter((node) => {
if (typeof this.#searchValue !== "string") return false;
if (this.#searchValue.length < 3) return false;
return node.title.toLowerCase().includes(this.#searchValue);
}),
(d) => d.id,
)
.attr(
"transform",
(d) => {
return "translate(" + d.position.x + "," + d.position.y + ")";
},
);
// add new node highlighters
const nodeHighlighterEnter = this.#nodeHighlighterElements
.enter();
nodeHighlighterEnter
.append("g")
.attr(
"transform",
(d) => {
return "translate(" + d.position.x + "," + d.position.y + ")";
},
)
.classed("node-highlighter", true)
.append("circle")
.attr("r", "320");
// remove old node highlighters
const nodeHighlighterExitSelection
= this.#nodeHighlighterElements.exit();
nodeHighlighterExitSelection.remove();
/** ********************
links
***********************/
// create link selection
this.#linkElements = this.#linksContainer
.selectAll("path.link")
.data(this.#links);
// update existing links
this.#linkElements
.classed(consts.selectedClass, (edge) => {
return this.#selection.has(edge);
})
.attr("d", (d) => {
return "M" + d.source.position.x + "," + d.source.position.y
+ "L" + d.target.position.x + "," + d.target.position.y;
})
.classed("connected-to-selected", (edge) => {
// only nodes can be connected to a link, links cannot be connected to
// other links
const idsOfSelectedNodes = Array.from(this.#selection)
.filter((val) => !this.#isEdge(val))
.map((val) => val.id);
return (
idsOfSelectedNodes.includes(edge.source.id)
|| idsOfSelectedNodes.includes(edge.target.id)
);
});
// add new links
this.#linkElements
.enter()
.append("path")
.classed("link", true)
.attr("d", (d) => {
return "M" + d.source.position.x + "," + d.source.position.y
+ "L" + d.target.position.x + "," + d.target.position.y;
})
.on("mouseover", (e, d) => {
this.#onHighlight({
active: true,
type: "edge",
titles: [d.source.title, d.target.title],
});
})
.on("mouseout", () => {
this.#onHighlight({
active: false,
});
})
.on("mousedown", (e, d) => {
this.#handleMouseDownOnEdge(e, d);
});
// remove old links
this.#linkElements
= this.#linkElements.exit().remove();
/** ********************
nodes
***********************/
// create node selection
this.#nodeElements = this.#nodesContainer.selectAll("g.node");
// append new node data
this.#nodeElements = this.#nodeElements
.data(
this.#nodes,
(d) => d.id,
);
// update node positions of moved/dragged nodes
this.#nodeElements
.filter((d) => {
if (event?.type === "INFLATION") return true;
const draggedNode = event?.type === "NODE_DRAG" && event.node;
const selectedNodeIds = Array.from(this.#selection)
.filter((value) => {
return !this.#isEdge(value);
})
.map((node) => node.id);
return draggedNode || selectedNodeIds.includes(d.id);
})
.attr(
"transform",
(d) => {
return "translate(" + d.position.x + "," + d.position.y + ")";
},
);
// update existing nodes
this.#nodeElements
.classed("unconnected", (d) => {
return !binaryArrayIncludes(
this.#idsOfAllNodesWithLinkedNote,
d.id,
);
})
.classed("selected", (node) => {
return this.#selection.has(node);
})
.classed("connected-to-selected", (node) => {
return this.#connectedNodeIdsOfSelection.includes(node.id);
});
// add new nodes
const nodeG = this.#nodeElements
.enter()
.append("g")
.classed(consts.nodeClassName, true)
.classed("new", (d) => {
const MAX_NEW_AGE = 1000 * 60 * 60 * 24 * 10; // 10 days
return Date.now() - d.creationTime < MAX_NEW_AGE;
})
.classed("hub", (d) => {
return d.linkedNotes.length > 7;
})
.classed("unconnected", (d) => {
return !binaryArrayIncludes(
this.#idsOfAllNodesWithLinkedNote,
d.id,
);
})
.attr(
"transform",
(d) => {
return "translate(" + d.position.x + "," + d.position.y + ")";
},
)
.on("mouseover", (e, d) => {
if (this.#newLinkCreationInProgress) {
d3.select(e.currentTarget).classed(consts.connectClass, true);
}
this.#onHighlight({
active: true,
type: "node",
title: d.title,
});
})
.on("mouseout", (e) => {
d3.select(e.currentTarget).classed(consts.connectClass, false);
this.#onHighlight({
active: false,
});
})
.on("mousedown", (e, d) => {
this.#handleMouseDownOnNode(e, d);
})
.on("mouseup", (e, d) => {
this.#handleMouseUpOnNode(d3.select(e.currentTarget), d);
})
.on("click", (e, d) => {
if (e.ctrlKey) {
this.#openNote(d.id);
}
})
.call(this.#nodeDrag);
nodeG.append("circle")
.attr("r", String(consts.nodeRadius));
// currently it's not possible to remove nodes in Graph View
/*
// remove old nodes
const nodeExitSelection = this.nodeElements.exit();
nodeExitSelection.remove();
*/
}
#zoomed(e) {
this.#justScaleTransGraph = true;
d3.select("." + GraphVisualization.#consts.graphClass)
.attr(
"transform",
"translate("
+ e.transform.x + "," + e.transform.y + ") "
+ "scale(" + e.transform.k + ")",
);
this.#screenPosition.translateX = e.transform.x;
this.#screenPosition.translateY = e.transform.y;
this.#screenPosition.scale = e.transform.k;
}
#updateWindow(svg) {
const { width, height } = this.#parent.getBoundingClientRect();
svg.attr("width", width).attr("height", height);
}
/** *****************
PUBLIC METHODS
********************/
getSaveData() {
const linksToTransmit = this.#links.map((link) => {
return [
link.source.id,
link.target.id,
];
});
const nodePositionUpdates = Array.from(this.#updatedNodes)
.map((node:any) => {
return {
id: node.id,
position: node.position,
};
});
const graphObject = {
nodePositionUpdates,
links: linksToTransmit,
screenPosition: this.#screenPosition,
initialNodePosition: this.#initialNodePosition,
};
return graphObject;
}
getSelectedNodeIds() {
return Array.from(this.#selection)
.filter((val) => !this.#isEdge(val))
.map((val) => val.id);
}
setSearchValue(newSearchValue) {
if (typeof newSearchValue === "string") {
this.#searchValue = newSearchValue;
}
this.#updateGraph();
}
inflateGraph(factor) {
this.#nodes
.forEach((node) => {
node.position.x *= factor;
node.position.y *= factor;
this.#updatedNodes.add(node);
});
this.#updateGraph({ type: "INFLATION" });
this.#onChange();
}
toggleTextRendering() {
if (!this.#titleRenderingEnabled) {
this.#titleRenderingEnabled = true;
d3.selectAll("g." + GraphVisualization.#consts.nodeClassName)
.each((d, i, nodes) => {
const domElement = nodes[i];
this.#insertTitleLinebreaks(d3.select(domElement), d.title);
});
} else {
d3.selectAll("text").remove();
this.#titleRenderingEnabled = false;
}
}
} | the_stack |
import {A_COLOR, A_POSITION, A_TEX_COORD, U_TEXTURE} from './constants';
import FrameBuffer from './FrameBuffer';
import Geometry from './Geometry';
import getUniformSetter from './get-uniform-setter';
import Label from './Label';
import Shader from './Shader';
import color2dFrag from './shaders/color-2d.frag';
import color2dVert from './shaders/color-2d.vert';
import image2dFrag from './shaders/image-2d.frag';
import image2dVert from './shaders/image-2d.vert';
import Texture from './Texture';
enum Side {
NONE, FRONT, BACK
}
enum BatchType {
MESH, LINES
}
enum BlendMode {
OVERLAP, LIGHT, PIGMENT
}
interface RendererState {
/** Viewport width. */
width: number;
/** Viewport height. */
height: number;
/** 2D draw color. */
color: { r: number, g: number, b: number, a: number };
/** 2D camera x. */
cameraX: number;
/** 2D camera y. */
cameraY: number;
/** 2D camera zoom. */
zoom: number;
blendMode: BlendMode;
}
export default class Renderer {
private static _sharedInstance?: Renderer;
static sharedInstance(): Renderer {
if (!Renderer._sharedInstance) {
Renderer._sharedInstance = new Renderer();
}
return Renderer._sharedInstance;
}
readonly SIDE_NONE = Side.NONE;
readonly SIDE_FRONT = Side.FRONT;
readonly SIDE_BACK = Side.BACK;
readonly BLEND_MODE_OVERLAP = BlendMode.OVERLAP;
readonly BLEND_MODE_LIGHT = BlendMode.LIGHT;
readonly BLEND_MODE_PIGMENT = BlendMode.PIGMENT;
readonly canvas: HTMLCanvasElement;
readonly gl: WebGL2RenderingContext;
attribLocations?: { [name: string]: number };
/** An 1x1 0xfff pixel. */
readonly BLANK_WHITE: Texture;
readonly IMAGE_2D_SHADER: Shader;
readonly COLOR_2D_SHADER: Shader;
private currentShader?: Shader;
private readonly frameBufferStack: FrameBuffer[] = [];
private currentFrameBuffer?: FrameBuffer;
private readonly batchSize: number;
private readonly batchPositionVertices: Float32Array;
private readonly batchTexCoordVertices: Float32Array;
private readonly batchColorVertices: Float32Array;
private readonly batchPositionBuffer: WebGLBuffer;
private readonly batchTexCoordBuffer: WebGLBuffer;
private readonly batchColorBuffer: WebGLBuffer;
private batchType: BatchType = BatchType.MESH;
private batchTexture?: Texture;
private batchIndex: number = 0;
private drawing2D: boolean = false;
public state: RendererState = {
width: 0,
height: 0,
color: {r: 1, g: 1, b: 1, a: 1},
cameraX: 0,
cameraY: 0,
zoom: 1,
blendMode: BlendMode.OVERLAP
};
private stateStack: RendererState[] = [];
constructor(target?: HTMLCanvasElement | WebGL2RenderingContext, batchSize: number = 2000) {
let canvas: HTMLCanvasElement;
let gl: WebGL2RenderingContext | null = null;
if (!target) {
canvas = document.createElement('canvas');
} else {
if (target instanceof HTMLCanvasElement) {
canvas = target;
} else {
canvas = target.canvas as HTMLCanvasElement;
gl = target;
}
}
if (!gl) {
gl = canvas.getContext('webgl2',
{
alpha: true,
antialias: false,
depth: true,
premultipliedAlpha: false,
preserveDrawingBuffer: false,
stencil: false
}
);
if (!gl) {
throw new Error('Failed to create WebGL2 rendering context');
}
}
this.canvas = canvas;
this.gl = gl;
this.state.width = canvas.width;
this.state.height = canvas.height;
gl.viewport(0, 0, this.state.width, this.state.height);
gl.enable(gl.BLEND);
this.BLANK_WHITE = this.createTextureFromRgbaPixels(1, 1, new Uint8Array([0xff, 0xff, 0xff, 0xff]));
this.IMAGE_2D_SHADER = this.createShader(image2dVert, image2dFrag);
this.COLOR_2D_SHADER = this.createShader(color2dVert, color2dFrag);
this.batchSize = batchSize;
this.batchPositionVertices = new Float32Array(batchSize * 3 * 2 * 2);
this.batchPositionBuffer = this.createDynamicDrawBuffer(this.batchPositionVertices);
this.batchTexCoordVertices = new Float32Array(batchSize * 3 * 2 * 2);
this.batchTexCoordBuffer = this.createDynamicDrawBuffer(this.batchTexCoordVertices);
this.batchColorVertices = new Float32Array(batchSize * 3 * 2 * 4);
this.batchColorBuffer = this.createDynamicDrawBuffer(this.batchColorVertices);
}
copyTo(
ctx: CanvasRenderingContext2D,
dx: number = 0,
dy: number = 0,
dw: number = this.state.width,
dh: number = this.state.height,
sx: number = 0,
sy: number = 0,
sw: number = this.state.width,
sh: number = this.state.height
) {
ctx.drawImage(this.canvas, sx, sy, sw, sh, dx, dy, dw, dh);
}
viewport(width: number, height: number) {
this.state.width = width;
this.state.height = height;
this.gl.viewport(0, 0, this.state.width, this.state.height);
}
resizeCanvas(width: number, height: number) {
if (this.canvas.width !== width || this.canvas.height !== height) {
this.canvas.width = width;
this.canvas.height = height;
}
this.viewport(width, height);
}
clearColor(r: number = 0, g: number = 0, b: number = 0, a: number = 0) {
const gl = this.gl;
gl.clearColor(r, g, b, a);
}
clear(color: boolean, depth: boolean, stencil: boolean) {
this.flush2D();
this.switchFrameBuffer();
const gl = this.gl;
let mask = 0;
if (color) {
mask |= gl.COLOR_BUFFER_BIT;
}
if (depth) {
mask |= gl.DEPTH_BUFFER_BIT;
}
if (stencil) {
mask |= gl.STENCIL_BUFFER_BIT;
}
gl.clear(mask);
}
depthTest(enabled: boolean) {
const gl = this.gl;
if (enabled) {
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
} else {
gl.disable(gl.DEPTH_TEST);
}
}
depthMask(enabled: boolean) {
this.gl.depthMask(enabled);
}
cullFace(side: Side) {
const gl = this.gl;
switch (side) {
case Side.NONE:
gl.disable(gl.CULL_FACE);
break;
case Side.FRONT:
gl.enable(gl.CULL_FACE);
gl.cullFace(gl.FRONT);
break;
case Side.BACK:
gl.enable(gl.CULL_FACE);
gl.cullFace(gl.BACK);
break;
}
}
blendMode(blendMode: BlendMode) {
if (blendMode === this.state.blendMode) {
return;
}
this.state.blendMode = blendMode;
this.flush2D();
const gl = this.gl;
switch (blendMode) {
case BlendMode.OVERLAP:
gl.blendEquation(gl.FUNC_ADD);
gl.blendFunc(gl.ONE, gl.ZERO);
break;
case BlendMode.LIGHT:
gl.blendEquation(gl.FUNC_ADD);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
break;
case BlendMode.PIGMENT: {
gl.blendEquationSeparate(gl.FUNC_ADD, gl.MAX);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
}
break;
}
}
useShader(shader?: Shader) {
if (shader !== this.currentShader) {
this.flush2D();
this.currentShader = shader;
if (shader) {
const gl = this.gl;
gl.useProgram(shader.program!);
}
}
}
uniform(name: string, value: any) {
const shader = this.currentShader;
if (!shader) {
return;
}
this.flush2D();
const uniform = shader.uniforms[name];
uniform?.setter(value);
}
save() {
if (this.stateStack.length > 999) {
throw new Error('State stack has reach a max size of 999');
}
const state = this.state;
const color = state.color;
this.stateStack.push({
width: state.width,
height: state.height,
color: {r: color.r, g: color.g, b: color.b, a: color.a},
cameraX: state.cameraX,
cameraY: state.cameraY,
zoom: state.zoom,
blendMode: state.blendMode
});
}
restore() {
const state = this.stateStack.pop();
if (!state) {
throw new Error('State stack is empty');
}
this.state.color.r = state.color.r;
this.state.color.g = state.color.g;
this.state.color.b = state.color.b;
this.state.color.a = state.color.a;
this.state.cameraX = state.cameraX;
this.state.cameraY = state.cameraY;
this.state.zoom = state.zoom;
this.viewport(state.width, state.height);
this.blendMode(state.blendMode);
}
private createDynamicDrawBuffer(vertices: Float32Array) {
const gl = this.gl;
const buffer = gl.createBuffer();
if (!buffer) {
throw new Error('Failed to create WebGL buffer');
}
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.DYNAMIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, null);
return buffer;
}
private createVBO(vertices: Float32Array) {
const gl = this.gl;
const vbo = gl.createBuffer();
if (!vbo) {
throw new Error('Failed to create WebGL buffer');
}
gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, null);
return vbo;
}
private createIBO(indices: number[]) {
const gl = this.gl;
const ibo = gl.createBuffer();
if (!ibo) {
throw new Error('Failed to create WebGL buffer');
}
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ibo);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
return ibo;
}
private bindVertexArrayAttribute(
location: GLint,
buffer: WebGLBuffer,
componentSize: GLint = 4,
type: GLenum = this.gl.FLOAT,
normalized: GLboolean = false,
stride: GLsizei = 0,
offset: GLintptr = 0
) {
const gl = this.gl;
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.enableVertexAttribArray(location);
gl.vertexAttribPointer(location, componentSize, type, normalized, stride, offset);
gl.bindBuffer(gl.ARRAY_BUFFER, null);
}
// ====================== texture ======================
createEmptyTexture(width: number = this.state.width, height: number = this.state.height, flipY: boolean = false): Texture {
if (width < 0 || height < 0) {
throw new Error('Negative width/height');
}
const gl = this.gl;
const texture = gl.createTexture();
if (!texture) {
throw new Error('Failed to create WebGL texture');
}
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
gl.bindTexture(gl.TEXTURE_2D, null);
const ret = new Texture(texture, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE);
ret.flipY = flipY;
return ret;
}
createTexture(image: TexImageSource): Texture {
const texture = this.createEmptyTexture(image.width, image.height);
const gl = this.gl;
gl.bindTexture(gl.TEXTURE_2D, texture.glTexture!);
gl.texImage2D(gl.TEXTURE_2D, texture.level, texture.internalFormat, texture.format, texture.type, image);
gl.bindTexture(gl.TEXTURE_2D, null);
return texture;
}
createTextureFromImageUrl(url: string): Promise<Texture> {
return new Promise((resolve, reject) => {
try {
const image = new Image();
image.onload = () => {
try {
const texture = this.createTexture(image);
texture.image = image;
resolve(texture);
} catch (e) {
reject(e);
}
};
image.onabort = image.onerror = (e: string | Event) => {
reject(e);
};
image.src = url;
} catch (e) {
reject(e);
}
});
}
createDepthTexture(width: number = this.state.width, height: number = this.state.height) {
if (width < 0 || height < 0) {
throw new Error('Negative width/height');
}
const gl = this.gl;
const texture = gl.createTexture();
if (!texture) {
throw new Error('Failed to create WebGL texture');
}
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT32F, width, height, 0, gl.DEPTH_COMPONENT, gl.FLOAT, null);
gl.bindTexture(gl.TEXTURE_2D, null);
return new Texture(texture, 0, gl.DEPTH_COMPONENT32F, width, height, 0, gl.DEPTH_COMPONENT, gl.FLOAT);
}
createTextureFromRgbaPixels(width: number, height: number, pixels: ArrayBufferView) {
const texture = this.createEmptyTexture(width, height);
const gl = this.gl;
gl.bindTexture(gl.TEXTURE_2D, texture.glTexture!);
gl.texImage2D(gl.TEXTURE_2D, texture.level, texture.internalFormat, width, height, texture.border, texture.format, texture.type, pixels);
gl.bindTexture(gl.TEXTURE_2D, null);
return texture;
}
setTextureFromPixels(texture: Texture, width: number, height: number, pixels: ArrayBufferView) {
const gl = this.gl;
if (!texture.glTexture) {
throw new Error('Texture has been deleted');
}
gl.bindTexture(gl.TEXTURE_2D, texture.glTexture);
gl.texImage2D(gl.TEXTURE_2D, texture.level, texture.internalFormat, width, height, texture.border, texture.format, texture.type, pixels);
gl.bindTexture(gl.TEXTURE_2D, null);
texture.width = width;
texture.height = height;
}
deleteTexture(texture: Texture) {
if (texture.glTexture) {
this.gl.deleteTexture(texture.glTexture);
texture.glTexture = undefined;
}
texture.width = 0;
texture.height = 0;
}
resizeTexture(texture: Texture,
width: number = this.state.width,
height: number = this.state.height,
recreate: boolean = false
) {
if (width < 0 || height < 0) {
throw new Error('Negative width/height');
}
if (texture.width === width && texture.height === height) {
return;
}
const gl = this.gl;
if (!texture.glTexture) {
throw new Error('Texture has been deleted');
}
gl.bindTexture(gl.TEXTURE_2D, texture.glTexture);
gl.texImage2D(gl.TEXTURE_2D, texture.level, texture.internalFormat, width, height, texture.border, texture.format, texture.type, null);
gl.bindTexture(gl.TEXTURE_2D, null);
texture.width = width;
texture.height = height;
}
// ====================== shader ======================
private createGlShader(src: string, type: GLenum): WebGLShader {
const gl = this.gl;
const shader = gl.createShader(type);
if (!shader) {
throw new Error('Failed to create WebGL shader');
}
gl.shaderSource(shader, src);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
throw new Error('Failed to compile WebGL shader:\n\n' + gl.getShaderInfoLog(shader));
}
return shader;
}
createShader(vertSrc: string, fragSrc: string): Shader {
const gl = this.gl;
const vertShader = this.createGlShader(vertSrc, gl.VERTEX_SHADER);
const fragShader = this.createGlShader(fragSrc, gl.FRAGMENT_SHADER);
const program = gl.createProgram();
if (!program) {
throw new Error('Failed to create WebGL program');
}
gl.attachShader(program, vertShader);
gl.attachShader(program, fragShader);
const attribLocations = this.attribLocations;
if (attribLocations) {
for (let attrName in attribLocations) {
if (attribLocations.hasOwnProperty(attrName)) {
gl.bindAttribLocation(program, attribLocations[attrName], attrName);
}
}
}
gl.linkProgram(program);
if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
throw new Error('Failed to link WebGL program:\n\n' + gl.getProgramInfoLog(program));
}
const shader = new Shader(vertShader, fragShader, program);
const numOfAttrs = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
for (let i = 0; i < numOfAttrs; ++i) {
const info = gl.getActiveAttrib(program, i);
if (!info) {
throw new Error('Failed to get WebGL attribute info');
}
const location = gl.getAttribLocation(program, info.name);
shader.registerAttribute(info.name, info.size, info.type, location);
}
const numOfUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
const samplerCounter = {count: 0};
for (let i = 0; i < numOfUniforms; ++i) {
const info = gl.getActiveUniform(program, i);
if (!info) {
throw new Error('Failed to get WebGL uniform info');
}
const location = gl.getUniformLocation(program, info.name);
if (location == null) {
throw new Error('Failed to get uniform location');
}
shader.registerUniform(
info.name,
info.size,
info.type,
location,
getUniformSetter(gl, info.name, info.size, info.type, location, samplerCounter)
);
}
return shader;
}
deleteShader(shader: Shader) {
const gl = this.gl;
if (shader.program) {
gl.deleteProgram(shader.program);
shader.program = undefined;
}
if (shader.vertShader) {
gl.deleteShader(shader.vertShader);
shader.vertShader = undefined;
}
if (shader.fragShader) {
gl.deleteShader(shader.fragShader);
shader.fragShader = undefined;
}
shader.uniforms = {};
shader.attributes = {};
}
// ====================== frame buffer ======================
createFrameBuffer(): FrameBuffer {
const gl = this.gl;
const frameBuffer = gl.createFramebuffer();
if (!frameBuffer) {
throw new Error('Failed to create WebGL frame buffer');
}
return new FrameBuffer(frameBuffer);
}
attachColorTexture(frameBuffer: FrameBuffer, texture: Texture | null) {
this.attachColorTextures(frameBuffer, texture ? [texture] : []);
}
attachColorTextures(frameBuffer: FrameBuffer, textures: Texture[]) {
const gl = this.gl;
if (!frameBuffer.glFrameBuffer) {
throw new Error('Frame buffer has been deleted');
}
gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer.glFrameBuffer);
frameBuffer.textures.length = textures.length;
textures.forEach((texture, index) => {
if (!texture.glTexture) {
throw new Error('Texture has been deleted');
}
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + index, gl.TEXTURE_2D, texture.glTexture, texture.level);
frameBuffer.textures[index] = texture;
});
gl.drawBuffers(textures.map((texture, index) => (gl.COLOR_ATTACHMENT0 + index)));
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
this.currentFrameBuffer = undefined;
}
attachDepthTexture(frameBuffer: FrameBuffer, texture: Texture | null) {
const gl = this.gl;
if (!frameBuffer.glFrameBuffer) {
throw new Error('Frame buffer has been deleted');
}
gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer.glFrameBuffer);
if (texture) {
if (!texture.glTexture) {
throw new Error('Texture has been deleted');
}
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, texture.glTexture, texture.level);
frameBuffer.depthTexture = texture;
} else {
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, null, 0);
frameBuffer.depthTexture = undefined;
}
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
this.currentFrameBuffer = undefined;
}
attachStencilTexture(frameBuffer: FrameBuffer, texture: Texture | null) {
const gl = this.gl;
if (!frameBuffer.glFrameBuffer) {
throw new Error('Frame buffer has been deleted');
}
gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer.glFrameBuffer);
if (texture) {
if (!texture.glTexture) {
throw new Error('Texture has been deleted');
}
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.TEXTURE_2D, texture.glTexture, texture.level);
frameBuffer.stencilTexture = texture;
} else {
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.TEXTURE_2D, null, 0);
frameBuffer.stencilTexture = undefined;
}
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
this.currentFrameBuffer = undefined;
}
deleteFrameBuffer(frameBuffer: FrameBuffer, deleteTexture: boolean = false) {
if (frameBuffer.glFrameBuffer) {
this.gl.deleteFramebuffer(frameBuffer.glFrameBuffer);
frameBuffer.glFrameBuffer = undefined;
}
if (deleteTexture) {
frameBuffer.textures.forEach(texture => this.deleteTexture(texture));
}
}
resizeFrameBuffer(frameBuffer: FrameBuffer, width: number = this.state.width, height: number = this.state.height) {
frameBuffer.textures.forEach(texture => this.resizeTexture(texture, width, height));
frameBuffer.depthTexture && this.resizeTexture(frameBuffer.depthTexture, width, height);
frameBuffer.stencilTexture && this.resizeTexture(frameBuffer.stencilTexture, width, height);
}
startCapture(frameBuffer: FrameBuffer) {
this.flush2D();
this.frameBufferStack.push(frameBuffer);
}
endCapture() {
this.flush2D();
this.frameBufferStack.pop();
}
private switchFrameBuffer() {
const stack = this.frameBufferStack;
const frameBuffer = stack.length ? stack[stack.length - 1] : undefined;
if (frameBuffer !== this.currentFrameBuffer) {
this.currentFrameBuffer = frameBuffer || undefined;
const gl = this.gl;
gl.bindFramebuffer(gl.FRAMEBUFFER, frameBuffer?.glFrameBuffer || null);
}
}
// ====================== 3d - geometry ======================
disposeGeometry(geometry: Geometry) {
const gl = this.gl;
if (geometry.vao) {
gl.deleteVertexArray(geometry.vao);
geometry.vao = undefined;
}
if (geometry.ibo) {
gl.deleteBuffer(geometry.ibo);
geometry.ibo = undefined;
}
geometry.attributes.forEach(attr => {
if (attr.vbo) {
gl.deleteBuffer(attr.vbo);
attr.vbo = undefined;
}
});
}
drawGeometry(geometry: Geometry) {
if (this.drawing2D) {
throw new Error('Renderer.end2D must be call before draw geometry');
}
const gl = this.gl;
if (!geometry.vao) {
const vao = gl.createVertexArray();
if (!vao) {
throw new Error('Failed to create Vertex Array Object');
}
geometry.vao = vao;
gl.bindVertexArray(vao);
const shader = this.currentShader;
if (!shader) {
throw new Error('Shader not set');
}
const attribLocations = this.attribLocations;
geometry.attributes.forEach(geoAttr => {
if (!geoAttr.vbo) {
geoAttr.vbo = this.createVBO(geoAttr.vertices);
}
if (attribLocations && attribLocations.hasOwnProperty(geoAttr.name)) {
this.bindVertexArrayAttribute(
attribLocations[geoAttr.name],
geoAttr.vbo,
geoAttr.componentSize
);
} else {
const attribute = shader.attributes[geoAttr.name];
if (attribute) {
this.bindVertexArrayAttribute(
attribute.location,
geoAttr.vbo,
geoAttr.componentSize
);
}
}
});
}
gl.bindVertexArray(geometry.vao);
if (!geometry.ibo) {
geometry.ibo = this.createIBO(geometry.indices);
}
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, geometry.ibo);
this.switchFrameBuffer();
switch (geometry.type) {
case Geometry.TYPE_TRIANGLES:
gl.drawElements(gl.TRIANGLES, geometry.indices.length, gl.UNSIGNED_SHORT, 0);
break;
case Geometry.TYPE_LINES:
gl.drawElements(gl.LINES, geometry.indices.length, gl.UNSIGNED_SHORT, 0);
break;
}
gl.bindVertexArray(null);
}
// ====================== 2D - instanced drawing ======================
begin2D() {
if (this.drawing2D) {
throw new Error('Renderer.end2D must be call before begin');
}
this.drawing2D = true;
}
end2D() {
if (!this.drawing2D) {
throw new Error('Renderer.begin2D must be call before end');
}
this.flush2D();
this.drawing2D = false;
}
setCameraPosition(x: number, y: number) {
this.state.cameraX = x;
this.state.cameraY = y;
}
centerCamera() {
this.setCameraPosition(this.state.width / 2, this.state.height / 2);
}
setZoom(zoom: number) {
this.state.zoom = zoom;
}
setColor(r: number, g: number, b: number, a: number = 1) {
this.state.color.r = r;
this.state.color.g = g;
this.state.color.b = b;
this.state.color.a = a;
}
private flush2D() {
if (!this.drawing2D) {
return;
}
if (this.batchIndex === 0) {
return;
}
switch (this.batchType) {
case BatchType.MESH:
this.flushMesh();
break;
case BatchType.LINES:
this.flushLines();
break;
}
}
private flushMesh() {
const texture = this.batchTexture;
const len = this.batchIndex;
this.batchIndex = 0;
const gl = this.gl;
let shader = this.currentShader;
if (!shader) {
shader = this.IMAGE_2D_SHADER;
}
if (!shader.program) {
throw new Error('Shader has been deleted');
}
gl.useProgram(shader.program);
// position
const aPosition = shader.attributes[A_POSITION];
if (aPosition) {
gl.bindBuffer(gl.ARRAY_BUFFER, this.batchPositionBuffer);
gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.batchPositionVertices);
const location = aPosition.location;
gl.enableVertexAttribArray(location);
gl.vertexAttribPointer(location, 2, gl.FLOAT, false, 0, 0);
}
// tex-coord
const aTexCoord = shader.attributes[A_TEX_COORD];
if (aTexCoord) {
gl.bindBuffer(gl.ARRAY_BUFFER, this.batchTexCoordBuffer);
gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.batchTexCoordVertices);
const location = aTexCoord.location;
gl.enableVertexAttribArray(location);
gl.vertexAttribPointer(location, 2, gl.FLOAT, false, 0, 0);
}
// color
const aColor = shader.attributes[A_COLOR];
if (aColor) {
gl.bindBuffer(gl.ARRAY_BUFFER, this.batchColorBuffer);
gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.batchColorVertices);
const location = aColor.location;
gl.enableVertexAttribArray(location);
gl.vertexAttribPointer(location, 4, gl.FLOAT, false, 0, 0);
}
// texture
shader.uniforms[U_TEXTURE]?.setter(texture?.glTexture);
// draw
this.switchFrameBuffer();
gl.drawArrays(gl.TRIANGLES, 0, len * 6);
}
private flushLines() {
const len = this.batchIndex;
this.batchIndex = 0;
const gl = this.gl;
let shader = this.currentShader;
if (!shader) {
shader = this.COLOR_2D_SHADER;
}
if (!shader.program) {
throw new Error('Shader has been deleted');
}
gl.useProgram(shader.program);
// position
gl.bindBuffer(gl.ARRAY_BUFFER, this.batchPositionBuffer);
gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.batchPositionVertices);
const positionLocation = shader.attributes[A_POSITION].location;
gl.enableVertexAttribArray(positionLocation);
gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
// color
gl.bindBuffer(gl.ARRAY_BUFFER, this.batchColorBuffer);
gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.batchColorVertices);
const colorLocation = shader.attributes[A_COLOR].location;
gl.enableVertexAttribArray(colorLocation);
gl.vertexAttribPointer(colorLocation, 4, gl.FLOAT, false, 0, 0);
// draw
this.switchFrameBuffer();
gl.drawArrays(gl.LINES, 0, len * 2);
}
drawLine(x0: number, y0: number, x1: number, y1: number) {
if (!this.drawing2D) {
throw new Error('Renderer.begin2D must be call before draw');
}
if (
this.batchIndex >= this.batchSize * 3
|| this.batchType !== BatchType.LINES
) {
this.flush2D();
}
this.batchType = BatchType.LINES;
const zoom = this.state.zoom;
const invW = 2 / this.state.width * zoom;
const invH = 2 / this.state.height * zoom;
const cameraX = this.state.cameraX;
const cameraY = this.state.cameraY;
const positionVertices = this.batchPositionVertices;
const index = this.batchIndex * 2 * 2;
positionVertices[index] = (x0 - cameraX) * invW;
positionVertices[index + 1] = (y0 - cameraY) * invH;
positionVertices[index + 2] = (x1 - cameraX) * invW;
positionVertices[index + 3] = (y1 - cameraY) * invH;
const colorIndex = this.batchIndex * 2 * 4;
const vertexColors = this.batchColorVertices;
const color = this.state.color;
for (let i = 0; i < 2; ++i) {
const offset = i * 4;
vertexColors[colorIndex + offset] = color.r;
vertexColors[colorIndex + 1 + offset] = color.g;
vertexColors[colorIndex + 2 + offset] = color.b;
vertexColors[colorIndex + 3 + offset] = color.a;
}
this.batchIndex += 1;
}
private pushCwQuadVertices(
texture: Texture,
x0: number,
y0: number,
x1: number,
y1: number,
x2: number,
y2: number,
x3: number,
y3: number,
texX0: number,
texY0: number,
texX1: number,
texY1: number,
texX2: number,
texY2: number,
texX3: number,
texY3: number
) {
if (!this.drawing2D) {
throw new Error('Renderer.begin2D must be call before draw');
}
if (
this.batchIndex >= this.batchSize
|| texture !== this.batchTexture
|| this.batchType !== BatchType.MESH
) {
this.flush2D();
}
this.batchType = BatchType.MESH;
this.batchTexture = texture;
const index = this.batchIndex * 3 * 2 * 2;
const positionVertices = this.batchPositionVertices;
const texCoordVertices = this.batchTexCoordVertices;
positionVertices[index] = x0;
positionVertices[index + 1] = y0;
positionVertices[index + 2] = x1;
positionVertices[index + 3] = y1;
positionVertices[index + 4] = x3;
positionVertices[index + 5] = y3;
positionVertices[index + 6] = x1;
positionVertices[index + 7] = y1;
positionVertices[index + 8] = x2;
positionVertices[index + 9] = y2;
positionVertices[index + 10] = x3;
positionVertices[index + 11] = y3;
if (texture.flipY) {
[texX0, texY0, texX3, texY3] = [texX3, texY3, texX0, texY0];
[texX1, texY1, texX2, texY2] = [texX2, texY2, texX1, texY1];
}
texCoordVertices[index] = texX0;
texCoordVertices[index + 1] = texY0;
texCoordVertices[index + 2] = texX1;
texCoordVertices[index + 3] = texY1;
texCoordVertices[index + 4] = texX3;
texCoordVertices[index + 5] = texY3;
texCoordVertices[index + 6] = texX1;
texCoordVertices[index + 7] = texY1;
texCoordVertices[index + 8] = texX2;
texCoordVertices[index + 9] = texY2;
texCoordVertices[index + 10] = texX3;
texCoordVertices[index + 11] = texY3;
const colorIndex = this.batchIndex * 3 * 2 * 4;
const vertexColors = this.batchColorVertices;
const color = this.state.color;
for (let i = 0; i < 2 * 3; ++i) {
const offset = i * 4;
vertexColors[colorIndex + offset] = color.r;
vertexColors[colorIndex + 1 + offset] = color.g;
vertexColors[colorIndex + 2 + offset] = color.b;
vertexColors[colorIndex + 3 + offset] = color.a;
}
this.batchIndex += 1;
}
drawCwQuad(
texture: Texture,
x0: number,
y0: number,
x1: number,
y1: number,
x2: number,
y2: number,
x3: number,
y3: number,
texX0: number = 0,
texY0: number = texture.height,
texX1: number = texture.width,
texY1: number = texture.height,
texX2: number = texture.width,
texY2: number = 0,
texX3: number = 0,
texY3: number = 0
) {
const zoom = this.state.zoom;
const invW = 2 / this.state.width * zoom;
const invH = 2 / this.state.height * zoom;
const invSW = 1 / texture.width;
const invSH = 1 / texture.height;
const cameraX = this.state.cameraX;
const cameraY = this.state.cameraY;
this.pushCwQuadVertices(
texture,
(x0 - cameraX) * invW,
(y0 - cameraY) * invH,
(x1 - cameraX) * invW,
(y1 - cameraY) * invH,
(x2 - cameraX) * invW,
(y2 - cameraY) * invH,
(x3 - cameraX) * invW,
(y3 - cameraY) * invH,
texX0 * invSW,
texY0 * invSH,
texX1 * invSW,
texY1 * invSH,
texX2 * invSW,
texY2 * invSH,
texX3 * invSW,
texY3 * invSH
);
}
drawRect(
texture: Texture,
dx: number = 0,
dy: number = 0,
dw: number = texture.width,
dh: number = texture.height,
flipX: boolean = false,
flipY: boolean = false,
sx: number = 0,
sy: number = 0,
sw: number = texture.width,
sh: number = texture.height
) {
const dstLeft = dx;
const dstRight = dx + dw;
const dstTop = dy + dh;
const dstBottom = dy;
let texLeft = sx;
let texRight = sx + sw;
let texTop = sy;
let texBottom = sy + sh;
if (flipX) {
[texLeft, texRight] = [texRight, texLeft];
}
if (flipY) {
[texTop, texBottom] = [texBottom, texTop];
}
this.drawCwQuad(
texture,
dstLeft,
dstBottom,
dstRight,
dstBottom,
dstRight,
dstTop,
dstLeft,
dstTop,
texLeft,
texBottom,
texRight,
texBottom,
texRight,
texTop,
texLeft,
texTop
);
}
draw(
texture: Texture,
dstX: number = 0,
dstY: number = 0,
dstW: number = texture.width,
dstH: number = texture.height,
flipX: boolean = false,
flipY: boolean = false,
srcX: number = 0,
srcY: number = 0,
srcW: number = texture.width,
srcH: number = texture.height,
dx: number = 0,
dy: number = 0,
ox: number = 0,
oy: number = 0,
rotation: number = 0,
sx: number = 1,
sy: number = 1
) {
const left = dstX;
const right = dstX + dstW;
const top = dstY + dstH;
const bottom = dstY;
const cosR = Math.cos(rotation);
const sinR = Math.sin(rotation);
const m11 = cosR * sx;
const m12 = -sinR * sy;
const m13 = -cosR * ox * sx + dx + ox + oy * sinR * sy;
const m21 = sinR * sx;
const m22 = cosR * sy;
const m23 = -cosR * oy * sy + dy - ox * sinR * sx + oy;
const v0x = left;
const v0y = bottom;
const v1x = right;
const v1y = bottom;
const v2x = right;
const v2y = top;
const v3x = left;
const v3y = top;
let texLeft = srcX;
let texRight = srcX + srcW;
let texTop = srcY;
let texBottom = srcY + srcH;
if (flipX) {
[texLeft, texRight] = [texRight, texLeft];
}
if (flipY) {
[texTop, texBottom] = [texBottom, texTop];
}
this.drawCwQuad(
texture,
m11 * v0x + m12 * v0y + m13,
m21 * v0x + m22 * v0y + m23,
m11 * v1x + m12 * v1y + m13,
m21 * v1x + m22 * v1y + m23,
m11 * v2x + m12 * v2y + m13,
m21 * v2x + m22 * v2y + m23,
m11 * v3x + m12 * v3y + m13,
m21 * v3x + m22 * v3y + m23,
texLeft,
texBottom,
texRight,
texBottom,
texRight,
texTop,
texLeft,
texTop
);
}
drawLabel(
label: Label,
dstX: number = 0,
dstY: number = 0,
dstW: number = label.width,
dstH: number = label.height,
flipX: boolean = false,
flipY: boolean = false,
srcX: number = 0,
srcY: number = 0,
srcW: number = label.width,
srcH: number = label.height,
dx: number = 0,
dy: number = 0,
ox: number = 0,
oy: number = 0,
rotation: number = 0,
sx: number = 1,
sy: number = 1
) {
this.draw(
label.texture(this),
dstX,
dstY,
dstW,
dstH,
flipX,
flipY,
srcX,
srcY,
srcW,
srcH,
dx,
dy,
ox,
oy,
rotation,
sx,
sy
);
}
} | the_stack |
import BigNumber from "bignumber.js";
import { BN } from "bn.js";
import * as testUtils from "./testUtils";
import { market, TOKEN_CODES } from "./testUtils";
import { OrderbookContract } from "../bindings/orderbook";
import { RenExBalancesContract } from "../bindings/ren_ex_balances";
import { RenExBrokerVerifierContract } from "../bindings/ren_ex_broker_verifier";
import { RenExSettlementContract } from "../bindings/ren_ex_settlement";
/// Submits and matches two orders, going through all the necessary steps first,
/// and verifying the funds have been transferred.
export async function settleOrders(
buy: any, sell: any, buyer: string, seller: string,
darknode: string, broker: string,
renExSettlement: RenExSettlementContract,
renExBalances: RenExBalancesContract,
tokenInstances: Map<number, testUtils.BasicERC20>,
orderbook: OrderbookContract,
renExBrokerVerifier: RenExBrokerVerifierContract,
returnIDs: boolean = false,
) {
// Tokens should be the same
new BN(buy.tokens).eq(new BN(sell.tokens)).should.be.true;
const tokens = new BN(buy.tokens);
const lowToken = new BN(tokens.toArrayLike(Buffer, "be", 8).slice(0, 4)).toNumber();
const highToken = new BN(tokens.toArrayLike(Buffer, "be", 8).slice(4, 8)).toNumber();
// Flip sell tokens
sell.tokens = market(highToken, lowToken);
// Set details for setup
buy.trader = buy.trader || buyer;
sell.trader = sell.trader || seller;
buy.fromToken = lowToken;
sell.fromToken = highToken;
const lowTokenInstance = tokenInstances.get(lowToken);
const highTokenInstance = tokenInstances.get(highToken);
const highDecimals = new BN(await highTokenInstance.decimals()).toNumber();
const lowDecimals = new BN(await lowTokenInstance.decimals()).toNumber();
for (const order of [buy, sell]) {
order.settlement = order.settlement !== undefined ? order.settlement : testUtils.Settlements.RenEx;
order.price = new BigNumber(order.price);
order.volume = new BigNumber(order.volume);
order.minimumVolume = order.minimumVolume ? new BigNumber(order.minimumVolume) : new BigNumber(0);
order.nonceHash = order.nonceHash || (order.nonce ?
(web3.utils.sha3 as any)(order.nonce, { encoding: "hex" }) :
testUtils.randomNonce());
order.expiry = 10000000000; // order.expiry || testUtils.secondsFromNow(1000);
order.tokens = `0x${order.tokens.toString("hex")}`;
const expectedID = await renExSettlement.hashOrder(
getPreBytes(order),
order.settlement,
order.tokens,
order.price.multipliedBy(10 ** 12),
order.volume.multipliedBy(10 ** 12),
order.minimumVolume.multipliedBy(10 ** 12)
);
if (order.orderID !== undefined) {
order.orderID.should.equal(expectedID);
} else {
order.orderID = expectedID;
}
}
// Approve and deposit
sell.deposit = sell.volume.multipliedBy(10 ** highDecimals);
buy.deposit = buy.volume.multipliedBy(buy.price).multipliedBy(10 ** lowDecimals).integerValue(BigNumber.ROUND_CEIL);
sell.opposite = buy.deposit; buy.opposite = sell.deposit;
for (const order of [buy, sell]) {
if (order.fromToken !== TOKEN_CODES.ETH &&
order.fromToken !== TOKEN_CODES.BTC &&
order.fromToken !== TOKEN_CODES.ALTBTC) {
// TODO: Remove hard-coded value
const fee = order.fromToken === 0x101 ? new BN(3) : new BN(0);
const deposit = new BN(order.deposit.multipliedBy(1.01).toFixed());
await tokenInstances.get(order.fromToken).transfer(order.trader, deposit);
const newDeposit = deposit.sub(deposit.mul(fee).div(new BN(1000)));
await tokenInstances.get(order.fromToken).approve(
renExBalances.address, newDeposit, { from: order.trader }
);
await renExBalances.deposit(
tokenInstances.get(order.fromToken).address, newDeposit, { from: order.trader }
);
} else {
const deposit = order.fromToken === TOKEN_CODES.ETH ? order.deposit : order.opposite;
await renExBalances.deposit(
tokenInstances.get(TOKEN_CODES.ETH).address,
deposit,
{ from: order.trader, value: deposit }
);
}
}
// Open orders
await testUtils.openOrder(orderbook, buy.settlement, broker, buy.trader, buy.orderID).should.not.be.rejected;
await testUtils.openOrder(orderbook, sell.settlement, broker, sell.trader, sell.orderID).should.not.be.rejected;
// Confirm the order traders are
for (const order of [buy, sell]) {
(await orderbook.orderTrader(order.orderID)).should.equal(order.trader);
}
// Submit order confirmation
await orderbook.confirmOrder(buy.orderID, sell.orderID, { from: darknode }).should.not.be.rejected;
// Submit details for each order, store the current balances
for (const order of [buy, sell]) {
await renExSettlement.submitOrder(
getPreBytes(order),
order.settlement,
order.tokens,
order.price.multipliedBy(10 ** 12),
order.volume.multipliedBy(10 ** 12),
order.minimumVolume.multipliedBy(10 ** 12)
);
// tslint:disable:max-line-length
order.lowBefore = new BigNumber(await renExBalances.traderBalances(order.trader, lowTokenInstance.address) as any);
order.highBefore = new BigNumber(await renExBalances.traderBalances(order.trader, highTokenInstance.address) as any);
}
// Submit the match
await renExSettlement.settle(buy.orderID, sell.orderID)
.should.not.be.rejected;
// Verify match details
const buyMatch = await renExSettlement.getMatchDetails(buy.orderID);
const settled: boolean = buyMatch.settled;
const priorityTokenFinal = new BigNumber(buyMatch.priorityVolume as any);
const secondaryTokenFinal = new BigNumber(buyMatch.secondaryVolume as any);
const priorityTokenFee = new BigNumber(buyMatch.priorityFee as any);
const secondaryTokenFee = new BigNumber(buyMatch.secondaryFee as any);
const priorityTokenAddress = buyMatch.priorityToken;
const secondaryTokenAddress = buyMatch.secondaryToken;
const priorityTokenVolume = priorityTokenFinal.plus(priorityTokenFee);
const secondaryTokenVolume = secondaryTokenFinal.plus(secondaryTokenFee);
settled.should.be.true;
// (buyMatch.priorityToken).should.bignumber.equal(lowToken);
// buyMatch.secondaryToken.should.bignumber.equal(highToken);
// buyMatch.priorityTokenAddress.should.equal(lowTokenInstance.address);
// buyMatch.secondaryTokenAddress.should.equal(highTokenInstance.address);
// Get balances after trade
const buyerLowAfter = new BigNumber(await renExBalances.traderBalances(buy.trader, lowTokenInstance.address) as any);
const sellerLowAfter = new BigNumber(await renExBalances.traderBalances(sell.trader, lowTokenInstance.address) as any);
const buyerHighAfter = new BigNumber(await renExBalances.traderBalances(buy.trader, highTokenInstance.address) as any);
const sellerHighAfter = new BigNumber(await renExBalances.traderBalances(sell.trader, highTokenInstance.address) as any);
// Withdraw balances (except for Atomic swaps)
if (buy.settlement === testUtils.Settlements.RenEx) {
// TODO: Remove hard-coded checks
if (buy.fromToken !== 0x101 && sell.fromToken !== 0x101) {
let sig1 = await testUtils.signWithdrawal(renExBrokerVerifier, broker, buy.trader, lowTokenInstance.address);
await renExBalances.withdraw(lowTokenInstance.address, buyerLowAfter.toFixed(), sig1, { from: buy.trader });
let sig2 = await testUtils.signWithdrawal(renExBrokerVerifier, broker, sell.trader, lowTokenInstance.address);
await renExBalances.withdraw(lowTokenInstance.address, sellerLowAfter.toFixed(), sig2, { from: sell.trader });
let sig3 = await testUtils.signWithdrawal(renExBrokerVerifier, broker, buy.trader, highTokenInstance.address);
await renExBalances.withdraw(highTokenInstance.address, buyerHighAfter.toFixed(), sig3, { from: buy.trader });
let sig4 = await testUtils.signWithdrawal(renExBrokerVerifier, broker, sell.trader, highTokenInstance.address);
await renExBalances.withdraw(highTokenInstance.address, sellerHighAfter.toFixed(), sig4, { from: sell.trader });
}
}
let feeNum = await renExSettlement.DARKNODE_FEES_NUMERATOR();
let feeDen = await renExSettlement.DARKNODE_FEES_DENOMINATOR();
// // Calculate fees (0.2%)
// const priorityFee = new BigNumber(buyMatch.priorityTokenVolume)
// .multipliedBy(feeNum)
// .dividedBy(feeDen)
// .integerValue(BigNumber.ROUND_CEIL);
// const secondFee = new BigNumber(buyMatch.secondaryTokenVolume)
// .multipliedBy(feeNum)
// .dividedBy(feeDen)
// .integerValue(BigNumber.ROUND_CEIL);
// Verify the correct transfer of funds occurred
if (buy.settlement === testUtils.Settlements.RenEx) {
// Low token
buy.lowBefore.minus(priorityTokenVolume).should.bignumber.equal(buyerLowAfter);
sell.lowBefore.plus(priorityTokenVolume).minus(priorityTokenFee).should.bignumber.equal(sellerLowAfter);
// High token
buy.highBefore.plus(secondaryTokenVolume).minus(secondaryTokenFee).should.bignumber.equal(buyerHighAfter);
sell.highBefore.minus(secondaryTokenVolume).should.bignumber.equal(sellerHighAfter);
} else {
if (highTokenInstance.address !== testUtils.NULL) {
buy.lowBefore.should.bignumber.equal(buyerLowAfter);
sell.lowBefore.should.bignumber.equal(sellerLowAfter);
buy.highBefore.minus(secondaryTokenFee).should.bignumber.equal(buyerHighAfter);
sell.highBefore.minus(secondaryTokenFee).should.bignumber.equal(sellerHighAfter);
} else if (lowTokenInstance.address !== testUtils.NULL) {
buy.lowBefore.minus(priorityTokenFee).should.bignumber.equal(buyerLowAfter);
sell.lowBefore.minus(priorityTokenFee).should.bignumber.equal(sellerLowAfter);
buy.highBefore.should.bignumber.equal(buyerHighAfter);
sell.highBefore.should.bignumber.equal(sellerHighAfter);
}
}
const priorityRet = new BigNumber(priorityTokenVolume).dividedBy(10 ** lowDecimals).toNumber();
const secondRet = new BigNumber(secondaryTokenVolume).dividedBy(10 ** highDecimals).toNumber();
if (returnIDs) {
return [
priorityRet, secondRet,
buy.orderID,
sell.orderID
];
} else {
return [priorityRet, secondRet];
}
}
function getPreBytes(order: any) {
const bytes = Buffer.concat([
new BN(order.type).toArrayLike(Buffer, "be", 1),
new BN(order.expiry).toArrayLike(Buffer, "be", 8),
new Buffer(order.nonceHash.slice(2), "hex"),
]);
return `0x${bytes.toString("hex")}`;
} | the_stack |
import React, { Component } from 'react'
import {
AsyncStorage,
ListView,
Image,
StyleSheet,
Text,
View,
TouchableNativeFeedback,
TouchableWithoutFeedback,
Alert,
StatusBar
} from 'react-native'
import {
getHomeURL
} from '../dao'
import {
standardColor
} from '../constant/colorConfig'
import Icon from 'react-native-vector-icons/Ionicons'
import { safeLogout } from '../dao/logout'
import { safeSignOn } from '../dao/signon'
import { fetchUser } from '../dao'
declare var global
/* tslint:disable */
const ListItems = [
{
text: '我收藏的',
iconName: 'md-star',
onPress: function () {
const { navigation, closeDrawer } = this.props
closeDrawer()
let URL = 'https://psnine.com/my/fav?page=1'
navigation.navigate('Favorite', {
URL,
title: '收藏'
})
}
},
{
text: '我发布的',
iconName: 'md-bookmarks',
onPress: function () {
const { navigation, closeDrawer } = this.props
closeDrawer()
let URL = 'https://psnine.com/my/issue?page=1'
navigation.navigate('Issue', {
URL,
title: '发布'
})
}
},
{
text: '我屏蔽的',
iconName: 'md-eye-off',
onPress: function () {
const { navigation, closeDrawer } = this.props
closeDrawer()
let URL = 'https://psnine.com/my/block'
navigation.navigate('UserBlock', {
URL,
title: '屏蔽'
})
}
},
// {
// text: '元素',
// iconName: 'md-snow',
// onPress: function () {
// const { navigation, closeDrawer } = this.props
// closeDrawer()
// let URL = 'https://psnine.com/my/element'
// navigation.navigate('UserElement', {
// URL,
// title: '元素'
// })
// }
// },
{
text: '图床',
iconName: 'md-image',
onPress: function () {
const { navigation, closeDrawer } = this.props
closeDrawer()
let URL = 'https://psnine.com/my/photo?page=1'
navigation.navigate('UserPhoto', {
URL,
title: '图床'
})
}
},
{
text: '明细',
iconName: 'md-podium',
onPress: function () {
const { navigation, closeDrawer } = this.props
closeDrawer()
let URL = 'https://psnine.com/my/account'
navigation.navigate('UserDetail', {
URL,
title: '明细'
})
}
},
{
text: '个性设定',
iconName: 'md-brush',
onPress: function () {
const { navigation, closeDrawer } = this.props
closeDrawer()
let URL = 'https://psnine.com/my/setting'
navigation.navigate('UserCustom', {
URL,
title: '个性设定'
})
}
},
{
text: '系统选项',
iconName: 'md-home'
},
{
text: '主题',
iconName: 'md-color-palette',
onPress: function() {
const { navigation, closeDrawer } = this.props
closeDrawer()
navigation.navigate('Theme')
}
},
{
text: '设置',
iconName: 'md-options',
onPress: function () {
const { navigation, closeDrawer } = this.props
closeDrawer()
navigation.navigate('Setting')
}
}
// {
// text: '关于',
// iconName: 'md-help-circle',
// onPress: function () {
// const { navigation, closeDrawer } = this.props;
// closeDrawer()
// navigation.navigate('About');
// }
// }
]
/* tslint:enable */
export default class NavigationDrawer extends Component<any, any> {
constructor(props) {
super(props)
let dataSource = new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2
})
const { modeInfo } = this.props
this.state = {
psnid: modeInfo.settingInfo.psnid,
userInfo: modeInfo.settingInfo.userInfo,
hasMessage: false,
dataSource: dataSource.cloneWithRows(ListItems)
}
}
componentWillMount() {
const { modeInfo } = this.props
this.setState({
psnid: modeInfo.settingInfo.psnid,
userInfo: modeInfo.settingInfo.userInfo
}, () => {
this.checkLoginState()
})
}
componentWillReceiveProps(nextProps) {
if (this.state.psnid !== nextProps.modeInfo.settingInfo.psnid && nextProps.modeInfo.settingInfo.psnid !== '') {
// console.log(this.state.psnid, nextProps.modeInfo.settingInfo.psnid)
this.setState({
psnid: nextProps.modeInfo.settingInfo.psnid,
userInfo: nextProps.modeInfo.settingInfo.userInfo
}, () => {
this.checkLoginState()
})
}
}
checkLoginState = async () => {
const psnid = this.state.psnid
if (!psnid)
return
const userInfo = await fetchUser(psnid)
await AsyncStorage.setItem('@userInfo', JSON.stringify(userInfo))
this.setState({
psnid,
userInfo,
hasMessage: userInfo.hasMessage
}, () => {
if (this.state.psnid !== '') {
if (this.state.userInfo.isSigned === false) {
this.pressSign()
}
}
})
}
pressLogin = () => {
const { navigation, closeDrawer } = this.props
const { psnid } = this.state
closeDrawer()
if (!psnid) {
navigation.navigate('Login', {
setLogin: this.setLogin
})
} else {
let URL = getHomeURL(this.state.psnid)
navigation.navigate('Home', {
URL,
title: this.state.psnid
})
}
}
pressLogout = async () => {
const { closeDrawer } = this.props
closeDrawer()
await safeLogout(this.state.psnid)
const backupInfo = {
psnid: '',
userInfo: {
avatar: require('../../art/avatar.jpg'),
platinum: '白',
gold: '金',
silver: '银',
bronze: '铜',
exp: ''
},
hasMessage: false
}
await this.setState(backupInfo)
Promise.all([
AsyncStorage.setItem('@userInfo', JSON.stringify(backupInfo.userInfo)),
AsyncStorage.setItem('@psnid', backupInfo.psnid)
]).then(() => {
const { modeInfo } = this.props
modeInfo.reloadSetting && modeInfo.reloadSetting()
}).catch(err => global.toast(err.toString())).then(() => {
global.toast && global.toast('登出成功', 2000)
})
}
setLogin = () => {
const { modeInfo } = this.props
modeInfo.reloadSetting && modeInfo.reloadSetting()
}
pressSign = async () => {
const { closeDrawer } = this.props
closeDrawer()
let data = await safeSignOn(this.state.psnid)
this.setState({
userInfo: Object.assign({}, this.state.userInfo, { isSigned: true })
})
global.toast && global.toast(data, 2000)
}
onMessageClick = () => {
const { navigation, closeDrawer } = this.props
closeDrawer()
if (this.state.psnid === '') {
global.toast && global.toast('未登录', 2000)
return
}
let URL = getHomeURL(this.state.psnid)
// alert(this.state.userInfo.nums)
navigation.navigate('Message', {
URL,
title: this.state.psnid,
nums: this.state.userInfo.nums
})
}
switch = () => {
const { closeDrawer, switchModeOnRoot } = this.props
closeDrawer()
switchModeOnRoot()
}
goToStatistics = () => {
const { navigation, closeDrawer } = this.props
closeDrawer()
if (this.state.psnid === '') {
global.toast && global.toast('未登录', 2000)
return
}
const { psnid } = this.state
let URL = getHomeURL(psnid)
// alert(this.state.userInfo.nums)
navigation.navigate('Stats', {
URL,
psnid: this.state.psnid,
title: `${this.state.psnid} 奖杯统计`
})
}
onUserLongPress = () => {
if (this.state.psnid === '') return
Alert.alert(
'提示',
'请选择操作',
[
{ text: '修改密码', onPress: () => {
const { navigation, closeDrawer } = this.props
closeDrawer()
let URL = 'https://psnine.com/my/pass'
navigation.navigate('Pass', {
URL,
title: '改密码'
})
}},
{
text: '退出', onPress: () => {
this.pressLogout()
}
}
]
)
}
renderHeader = () => {
const { modeInfo } = this.props
const { psnid, userInfo } = this.state
let toolActions: JSX.Element[] = []
const iconStyle = {
borderColor: '#fff',
borderWidth: 0,
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'transparent',
height: 30,
width: 30,
flex: 0,
marginLeft: 16
}
const color = '#fff'
const size = 24
const borderRadius = 12
if (psnid) {
let dot: any = undefined
if (this.state.hasMessage) {
dot = (
<View style={{ borderRadius: 4, position: 'absolute', top: 3, right: 3, backgroundColor: modeInfo.accentColor, height: 8, width: 8}} />
)
}
toolActions.push(
<TouchableNativeFeedback
background={TouchableNativeFeedback.SelectableBackgroundBorderless()}
key={'sign'}
onPress={() => {
if (dot) {
this.setState({
hasMessage: false
}, () => {
this.onMessageClick()
})
return
}
this.onMessageClick()
}}
>
<View borderRadius={borderRadius} style={iconStyle}>
<Icon name='md-notifications' size={size} color={color} />
{dot}
</View>
</TouchableNativeFeedback>
)
}
toolActions.push(
<TouchableNativeFeedback
background={TouchableNativeFeedback.SelectableBackgroundBorderless()}
key={'changeStyle'}
onPress={this.switch}
>
<View borderRadius={borderRadius} style={iconStyle}>
{this.props.modeInfo.isNightMode &&
<Icon name='md-sunny' size={size} color={color} /> ||
<Icon name='md-moon' size={size} color={color} />}
</View>
</TouchableNativeFeedback>
)
return (
<View style={[{
flex: 1,
padding: 20,
backgroundColor: this.props.modeInfo.standardColor
}]}>
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
<View style={{ flexDirection: 'column',
alignItems: 'flex-start', justifyContent: 'space-between', alignSelf: 'flex-start', alignContent: 'flex-start' }}>
<TouchableWithoutFeedback onPress={this.pressLogin} onLongPress={this.onUserLongPress}>
<View borderRadius={35} style={{ flexDirection: 'column', alignItems: 'center', backgroundColor: modeInfo.backgroundColor }}>
<Image
borderRadius={35}
source={userInfo.avatar}
style={{ width: 70, height: 70 }} />
</View>
</TouchableWithoutFeedback>
<Text style={[styles.menuText, { paddingTop: 5,
textAlign: 'center', alignSelf: psnid === '' ? 'center' : 'flex-start' }]}>{psnid === '' ? '请登录' : psnid}</Text>
{psnid && (
<View style={{flex: 1, width: 100}}>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', flex: 1 }}>
<Text style={{ color: color, fontSize: 12 }}>
{userInfo.exp.split('经验')[0] + ' '}
<Text style={{ flex: -1, color: color, fontSize: 12 }}>{userInfo.exp.split('经验')[1]}</Text></Text>
</View>
<View style={{ flex: 0, width: 200 }}>
<Text style={{ }}>
<Text style={{ flex: -1, color: color, textAlign: 'center', fontSize: 12 }}>{userInfo.platinum + ' '}</Text>
<Text style={{ flex: -1, color: color, textAlign: 'center', fontSize: 12 }}>{userInfo.gold + ' '}</Text>
<Text style={{ flex: -1, color: color, textAlign: 'center', fontSize: 12 }}>{userInfo.silver + ' '}</Text>
<Text style={{ flex: -1, color: color, textAlign: 'center', fontSize: 12 }}>{userInfo.bronze + ' '}</Text>
</Text>
</View>
</View>) || undefined}
</View>
<View style={{
paddingRight: toolActions.length === 4 ? 20 : 0, flex: 1,
flexDirection: 'row', alignSelf: 'flex-start', alignContent: 'flex-end', justifyContent: 'center', alignItems: 'flex-end' }}>
{ psnid && <TouchableNativeFeedback
background={TouchableNativeFeedback.SelectableBackgroundBorderless()}
key={'changeStyle'}
onPress={this.goToStatistics}
>
<View borderRadius={borderRadius} style={iconStyle}>
<Icon name='md-trophy' size={size} color={color} />
</View>
</TouchableNativeFeedback> || undefined }
{toolActions}
</View>
</View>
</View>
)
}
renderRow = (rowData, _, rowID) => {
const shouldSlice = this.state.psnid === ''
const targetListItems = shouldSlice ? ListItems.slice(-2) : ListItems
const item: any = targetListItems[rowID]
let iconName = item.iconName
const icon = <Icon name={iconName} size={25} style={{ marginLeft: 6 }} color={this.props.modeInfo.standardColor} />
if (rowData.text === '系统选项') {
return (
<View style={{ marginTop: 6 }}>
<View
style={{ backgroundColor: 'rgba(0,0,0,0.1)', height: rowID === '0' ? 0 : 1 }}
/>
</View>
)
}
return (
<View>
<TouchableNativeFeedback
onPress={() => item.onPress.bind(this)(rowData)}
>
<View pointerEvents={'box-only'} style={[styles.themeItem]}>
<View style={{width: 30, alignItems: 'center', justifyContent: 'center'}}>
{icon}
</View>
<Text style={[styles.themeName, { color: this.props.modeInfo.titleTextColor }]}>
{rowData.text}
</Text>
</View>
</TouchableNativeFeedback>
</View>
)
}
render() {
// console.log('navigationDrawer.js rendered');
return (
<View style={{
flex: 1,
backgroundColor: '#FAFAFA',
paddingTop: StatusBar.currentHeight || 24,
backgroundColor: this.props.modeInfo.standardColor}} {...this.props}>
<ListView
ref='themeslistview'
dataSource={this.state.psnid !== '' ? this.state.dataSource : this.state.dataSource.cloneWithRows(ListItems.slice(-2))}
renderRow={this.renderRow}
key={this.props.modeInfo.themeName}
keyboardDismissMode='on-drag'
keyboardShouldPersistTaps='always'
renderHeader={this.renderHeader}
enableEmptySections={true}
style={{ flex: 2, backgroundColor: this.props.modeInfo.backgroundColor }}
/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#FAFAFA'
},
header: {
flex: 1,
flexDirection: 'column',
backgroundColor: standardColor,
height: 180
},
userInfo: {
flex: 4
},
trophyRow: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-around',
marginLeft: 5,
marginTop: -60
},
row: {
flex: 1,
flexDirection: 'row',
justifyContent: 'space-around',
// marginLeft: 8,
paddingTop: -10
},
menuContainer: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-around',
paddingLeft: 2,
paddingRight: 0
},
menuText: {
fontSize: 14,
color: 'white'
},
homeTheme: {
fontSize: 16,
marginLeft: 16,
color: standardColor
},
themeItem: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
padding: 12
},
themeName: {
flex: 1,
fontSize: 16,
marginLeft: 16
},
themeIndicate: {
marginLeft: 16,
width: 20,
height: 20
},
separator: {
height: 1,
backgroundColor: '#eeeeee'
},
rowSeparator: {
backgroundColor: 'rgba(0, 0, 0, 0.1)',
height: 1,
marginLeft: 4
},
rowSeparatorHide: {
opacity: 0.0
},
platinum: {
color: '#fff'
},
gold: {
color: '#fff'
},
silver: {
color: '#fff'
},
bronze: {
color: '#fff'
}
}) | the_stack |
import {
CSSResultGroup,
html,
LitElement,
PropertyValues,
TemplateResult
} from 'lit';
import { property, state } from 'lit/decorators.js';
import { createRef, ref } from 'lit/directives/ref.js';
import { styleMap } from 'lit/directives/style-map.js';
import { ifNonEmpty } from '../../base/directives';
import { WithFocus } from '../../base/elements';
import { eventListener, vdsEvent } from '../../base/events';
import { ElementLogger } from '../../base/logger';
import { DEV_MODE } from '../../global/env';
import {
clampNumber,
getNumberOfDecimalPlaces,
round
} from '../../utils/number';
import { rafThrottle } from '../../utils/timing';
import { sliderElementStyles } from './styles';
export const SLIDER_ELEMENT_TAG_NAME = 'vds-slider';
/**
* The direction to move the thumb, associated with key symbols.
*/
export enum SliderKeyDirection {
Left = -1,
ArrowLeft = -1,
Up = -1,
ArrowUp = -1,
Right = 1,
ArrowRight = 1,
Down = 1,
ArrowDown = 1
}
/**
* A custom built `input[type="range"]` that is cross-browser friendly, ARIA friendly, mouse/touch
* friendly and easily styleable. This component allows users to input numeric values between a
* minimum and maxmimum value. Generally used in the player for volume or scrubber controls.
*
* @see https://github.com/carbon-design-system/carbon-web-components
* @tagname vds-slider
* @slot Used to pass in additional content inside the slider.
* @slot thumb-container - Used to pass content into the thumb container.
* @slot thumb - Used to pass content inside the thumb.
* @slot track - Used to pass content inside the track.
* @slot track-fill - Used to pass content inside the track fill.
* @csspart root - The component's root element, in this case the slider container (`<div>`).
* @csspart thumb-container - The container for the slider's handle.
* @csspart thumb - The slider's handle the user drags left/right (`<div>`).
* @csspart track - The path in which the thumb slides along (`<div>`).
* @csspart track-fill - The part of the track that is currently filled which fills left-to-right (`<div>`).
* @cssprop --vds-slider-fill-rate - The ratio of the slider that is filled such as `0.3`.
* @cssprop --vds-slider-fill-value - The current amount the slider is filled such as `30`.
* @cssprop --vds-slider-fill-percentage - The fill rate expressed as a precetange such as `30%`.
* @cssprop --vds-slider-thumb-width - The slider handle width.
* @cssprop --vds-slider-thumb-height - The slider handle height.
* @cssprop --vds-slider-thumb-bg - The background color of the slider handle.
* @cssprop --vds-slider-thumb-border-radius - The border radius of the slider handle.
* @cssprop --vds-slider-thumb-scale - The base scale of thumb when it is inactive, it'll scale to 1 when active.
* @cssprop --vds-slider-thumb-transition - The CSS transitions to use for the thumb, defaults to `transform 100ms ease-out 0s`.
* @cssprop --vds-slider-track-height - The height of the slider track.
* @cssprop --vds-slider-track-bg - The background color of the slider track.
* @cssprop --vds-slider-track-fill-bg - The background color of the slider track fill.
* @cssprop --vds-slider-active-color - The slider thumb and track fill background color when focused, active or being dragged.
* @cssprop --vds-slider-disabled-color - The slider thumb, track, and track fill background color when disabled.
* @example
* ```html
* <vds-slider
* min="0"
* max="100"
* value="50"
* ></vds-slider>
* ```
* @example
* ```css
* vds-slider {
* --vds-slider-active-color: #ff2a5d;
* }
*
* vds-slider::part(thumb) {
* box-shadow: transparent 0px 0px 0px 1px inset;
* }
*
* vds-slider::part(track),
* vds-slider::part(track-fill) {
* border-radius: 3px;
* }
* ```
*/
export class SliderElement extends WithFocus(LitElement) {
static override get styles(): CSSResultGroup {
return [sliderElementStyles];
}
static get parts(): string[] {
return ['root', 'thumb', 'track', 'track-fill'];
}
// -------------------------------------------------------------------------------------------
// Properties
// -------------------------------------------------------------------------------------------
/* c8 ignore next */
protected readonly _logger = DEV_MODE && new ElementLogger(this);
/**
* ♿ **ARIA:** The `aria-label` property of the slider.
*/
@property({ reflect: true })
label: string | undefined;
/**
* The lowest slider value in the range of permitted values.
*/
@property({ reflect: true, type: Number })
min = 0;
/**
* The greatest slider value in the range of permitted values.
*/
@property({ reflect: true, type: Number })
max = 100;
/**
* Whether the slider should be hidden.
*/
@property({ reflect: true, type: Boolean })
override hidden = false;
/**
* Whether the slider should be disabled (not-interactable).
*/
@property({ reflect: true, type: Boolean })
disabled = false;
/**
* The current slider value.
*/
@property({ reflect: true, type: Number })
value = 50;
/**
* ♿ **ARIA:** Alternative value for minimum value (defaults to `min`). This can
* be used when expressing slider as a percentage (0-100), and wishing to detail more
* information for better accessibility.
*/
valueMin: string | undefined;
/**
* ♿ **ARIA:** Alternative value for current value (defaults to `value`). This can
* be used when expressing slider as a percentage (0-100), and wishing to detail more
* information for better accessibility.
*/
@property({ attribute: 'value-now' })
valueNow: string | undefined;
/**
* ♿ **ARIA:** Alternative value for maximum value (defaults to `max`). This can
* be used when expressing slider as a percentage (0-100), and wishing to detail more
* information for better accessibility.
*/
@property({ attribute: 'value-max' })
valueMax: string | undefined;
/**
* ♿ **ARIA:** Human-readable text alternative for the current value. Defaults to
* `value:max` ratio as a percentage.
*/
@property({ attribute: 'value-text' })
valueText: string | undefined;
/**
* ♿ **ARIA:** Indicates the orientation of the slider.
*/
@property({ reflect: true })
orientation: 'horizontal' | 'vertical' = 'horizontal';
/**
* A number that specifies the granularity that the slider value must adhere to.
*/
@property({ type: Number, reflect: true })
step = 1;
/**
* ♿ **ARIA:** A number that specifies the number of steps taken when interacting with
* the slider via keyboard.
*/
@property({ attribute: 'keyboard-step', type: Number })
keyboardStep = 1;
/**
* ♿ **ARIA:** A number that will be used to multiply the `keyboardStep` when the `Shift` key
* is held down and the slider value is changed by pressing `LeftArrow` or `RightArrow`. Think
* of it as `keyboardStep * shiftKeyMultiplier`.
*/
@property({ attribute: 'shift-key-multiplier', type: Number })
shiftKeyMultiplier = 5;
@state()
protected _isDragging = false;
/**
* Whether the slider thumb is currently being dragged.
*
* @default false
*/
get isDragging(): boolean {
return this._isDragging;
}
/**
* The current value to range ratio.
*
* @default 0.5
* @example
* `min` = 0
* `max` = 10
* `value` = 5
* `range` = 10 (max - min)
* `fillRate` = 0.5 (result)
*/
get fillRate(): number {
const range = this.max - this.min;
return this.value / range;
}
/**
* The fill rate expressed as a percentage (`fillRate * 100`).
*
* @default 50
*/
get fillPercent(): number {
return this.fillRate * 100;
}
// -------------------------------------------------------------------------------------------
// Lifecycle
// -------------------------------------------------------------------------------------------
protected override update(changedProperties: PropertyValues) {
if (changedProperties.has('value')) {
this._updateValue(this.value);
}
if (changedProperties.has('disabled') && this.disabled) {
this._isDragging = false;
this.removeAttribute('dragging');
}
super.update(changedProperties);
}
override disconnectedCallback() {
this._handlePointerMove.cancel();
super.disconnectedCallback();
}
// -------------------------------------------------------------------------------------------
// Render (Root/Slider)
// -------------------------------------------------------------------------------------------
protected readonly _rootRef = createRef<HTMLDivElement>();
/**
* The component's root element.
*/
get rootElement() {
return this._rootRef.value;
}
protected override render(): TemplateResult {
return this._renderSlider();
}
protected _renderSlider(): TemplateResult {
return html`
<div
id="root"
role="presentation"
part="root"
style=${styleMap({
'--vds-slider-fill-value': String(this.value),
'--vds-slider-fill-rate': String(this.fillRate),
'--vds-slider-fill-percent': `${this.fillPercent}%`
})}
@pointerdown=${this._handleSliderPointerMove}
${ref(this._rootRef)}
>
${this._renderSliderChildren()}
</div>
`;
}
protected _renderSliderChildren(): TemplateResult {
return html`${this._renderThumbContainer()}${this._renderTrack()}${this._renderTrackFill()}${this._renderInput()}${this._renderDefaultSlot()}`;
}
protected _renderDefaultSlot(): TemplateResult {
return html`<slot></slot>`;
}
protected _handleSliderPointerMove(event: PointerEvent) {
if (this.disabled) return;
this._startDragging(event);
this._handlePointerMove(event);
}
// -------------------------------------------------------------------------------------------
// Render (Thumb Container)
// -------------------------------------------------------------------------------------------
protected readonly _thumbContainerRef = createRef<HTMLDivElement>();
/**
* The thumb container element.
*/
get thumbContainerElement() {
return this._thumbContainerRef.value;
}
protected _renderThumbContainer(): TemplateResult {
return html`
<div
id="thumb-container"
role="slider"
tabindex="0"
aria-label=${ifNonEmpty(this.label)}
aria-valuemin=${this._getValueMin()}
aria-valuenow=${this._getValueNow()}
aria-valuemax=${this._getValueMax()}
aria-valuetext=${this._getValueText()}
aria-orientation=${this.orientation}
aria-disabled=${this.disabled}
aria-hidden=${this.hidden}
autocomplete="off"
part="thumb-container"
@keydown=${this._handleThumbContainerKeydown}
@pointerdown=${this._handleThumbContainerPointerDown}
${ref(this._thumbContainerRef)}
>
${this._renderThumb()} ${this._renderThumbContainerSlot()}
</div>
`;
}
protected _getValueMin(): string {
return this.valueMin ?? String(this.min);
}
protected _getValueNow(): string {
return this.valueNow ?? String(this.value);
}
protected _getValueMax(): string {
return this.valueMax ?? String(this.max);
}
protected _getValueText(): string {
return this.valueText ?? this._getValueTextFallback();
}
protected _getValueTextFallback(): string {
return `${round((this.value / this.max) * 100, 2)}%`;
}
protected _renderThumbContainerSlot(): TemplateResult {
return html`<slot name="thumb-container"></slot> `;
}
protected _handleThumbContainerKeydown(event: KeyboardEvent) {
if (this.disabled) return;
const { key, shiftKey } = event;
const isValidKey = Object.keys(SliderKeyDirection).includes(key);
if (!isValidKey) return;
const modifiedStep = !shiftKey
? this.keyboardStep
: this.keyboardStep * this.shiftKeyMultiplier;
const direction = Number(SliderKeyDirection[key]);
const diff = modifiedStep * direction;
const steps = (this.value + diff) / this.step;
const value = this.step * steps;
this._updateValue(value);
this._dispatchValueChange(event);
}
protected _handleThumbContainerPointerDown(event: PointerEvent) {
if (this.disabled) return;
this._startDragging(event);
}
// -------------------------------------------------------------------------------------------
// Render (Thumb)
// -------------------------------------------------------------------------------------------
protected readonly _thumbRef = createRef<HTMLDivElement>();
/**
* The thumb element.
*/
get thumbElement() {
return this._thumbRef.value;
}
protected _renderThumb(): TemplateResult {
return html`
<div id="thumb" part="thumb" ${ref(this._thumbRef)}>
${this._renderThumbSlot()}
</div>
`;
}
protected _renderThumbSlot(): TemplateResult {
return html`<slot name="thumb"></slot>`;
}
// -------------------------------------------------------------------------------------------
// Render (Track)
// -------------------------------------------------------------------------------------------
protected readonly _trackRef = createRef<HTMLDivElement>();
/**
* The track element.
*/
get trackElement() {
return this._trackRef.value;
}
protected _renderTrack(): TemplateResult {
return html`
<div id="track" part="track" ${ref(this._trackRef)}>
${this._renderTrackSlot()}
</div>
`;
}
protected _renderTrackSlot(): TemplateResult {
return html`<slot name="track"></slot>`;
}
// -------------------------------------------------------------------------------------------
// Render (Track Fill)
// -------------------------------------------------------------------------------------------
protected readonly _trackFillRef = createRef<HTMLDivElement>();
/**
* The track fill element.
*/
get trackFillElement() {
return this._trackFillRef.value;
}
protected _renderTrackFill(): TemplateResult {
return html`
<div id="track-fill" part="track-fill" ${ref(this._trackFillRef)}>
${this._renderTrackFillSlot()}
</div>
`;
}
protected _renderTrackFillSlot(): TemplateResult {
return html`<slot name="track-fill"></slot>`;
}
// -------------------------------------------------------------------------------------------
// Render (Input)
// -------------------------------------------------------------------------------------------
/**
* Why? Used to emit native `input` events.
*/
protected _renderInput(): TemplateResult {
return html`
<input
type="hidden"
min="${this.min}"
max="${this.max}"
value="${this.value}"
/>
`;
}
// -------------------------------------------------------------------------------------------
// Drag
// -------------------------------------------------------------------------------------------
protected _startDragging(event: PointerEvent) {
if (this._isDragging) return;
this._isDragging = true;
this.setAttribute('dragging', '');
this._updateValueBasedOnThumbPosition(event);
/* c8 ignore start */
if (DEV_MODE) {
this._logger
.debugGroup('started dragging')
.appendWithLabel('Event', event)
.end();
}
/* c8 ignore stop */
this.dispatchEvent(
vdsEvent('vds-slider-drag-start', {
originalEvent: event,
detail: this.value
})
);
}
protected _stopDragging(event: PointerEvent) {
if (!this._isDragging) return;
this._isDragging = false;
this._dispatchValueChange.cancel();
this.removeAttribute('dragging');
this._updateValueBasedOnThumbPosition(event);
/* c8 ignore start */
if (DEV_MODE) {
this._logger
.debugGroup('stopped dragging')
.appendWithLabel('Event', event)
.end();
}
/* c8 ignore stop */
this.dispatchEvent(
vdsEvent('vds-slider-drag-end', {
originalEvent: event,
detail: this.value
})
);
}
// -------------------------------------------------------------------------------------------
// Document (Pointer Events)
// -------------------------------------------------------------------------------------------
@eventListener('pointerup', { target: document })
protected _handleDocumentPointerUp(event: PointerEvent) {
if (this.disabled || !this._isDragging) return;
this._stopDragging(event);
}
@eventListener('pointermove', { target: document })
protected _handleDocumentPointerMove(event: PointerEvent) {
if (this.disabled || !this._isDragging) {
this._handlePointerMove.cancel();
return;
}
this._handlePointerMove(event);
}
protected readonly _handlePointerMove = rafThrottle((event: PointerEvent) => {
if (this.disabled || !this._isDragging) return;
this._updateValueBasedOnThumbPosition(event);
this._dispatchValueChange(event);
});
protected _updateValue(value: number) {
this.value = clampNumber(
this.min,
round(value, getNumberOfDecimalPlaces(this.step)),
this.max
);
}
protected _updateValueByRate(rate: number) {
const boundRate = clampNumber(0, rate, 1);
const range = this.max - this.min;
const fill = range * boundRate;
const stepRatio = Math.round(fill / this.step);
const steps = this.step * stepRatio;
const value = this.min + steps;
this._updateValue(value);
}
protected _updateValueBasedOnThumbPosition(event: PointerEvent) {
const thumbClientX = event.clientX;
const { left: trackLeft, width: trackWidth } =
this.trackElement!.getBoundingClientRect();
const thumbPositionRate = (thumbClientX - trackLeft) / trackWidth;
// Calling this will update `this.value`.
this._updateValueByRate(thumbPositionRate);
}
protected _lastDispatchedValue = this.value;
protected readonly _dispatchValueChange = rafThrottle((event: Event) => {
if (this.value === this._lastDispatchedValue) return;
this.dispatchEvent(
vdsEvent('vds-slider-value-change', {
detail: this.value,
originalEvent: event
})
);
this._lastDispatchedValue = this.value;
});
} | the_stack |
import { DefaultButton, IButtonProps, ActionButton, Button, BaseButton, PrimaryButton } from 'office-ui-fabric-react/lib/Button';
import { Image } from 'office-ui-fabric-react/lib/Image';
import * as React from 'react';
import { WebApiTeam } from 'TFS/Core/Contracts';
import { WorkItem, WorkItemType } from 'TFS/WorkItemTracking/Contracts';
import { WorkItemFormNavigationService } from 'TFS/WorkItemTracking/Services';
import { workItemService } from '../dal/azureDevOpsWorkItemService';
import { itemDataService } from '../dal/itemDataService';
import { IFeedbackItemDocument } from '../interfaces/feedback';
// TODO (enpolat) : import { TelemetryEvents, TelemetryEventProperties, appInsightsClient } from '../utilities/appInsightsClient'
import { FocusTrapCallout, DirectionalHint } from 'office-ui-fabric-react/lib/Callout';
import { List } from 'office-ui-fabric-react/lib/List';
import { getBoardUrl } from '../utilities/boardUrlHelper';
import { Icon } from 'office-ui-fabric-react/lib/Icon';
import Dialog, { DialogType, DialogFooter } from 'office-ui-fabric-react/lib/Dialog';
import { SearchBox } from 'office-ui-fabric-react/lib/SearchBox';
import ActionItem from './actionItem';
export interface ActionItemDisplayProps extends IButtonProps {
feedbackItemId: string;
feedbackItemTitle: string;
team: WebApiTeam;
boardId: string;
boardTitle: string;
defaultIteration: string;
defaultAreaPath: string;
actionItems: WorkItem[];
nonHiddenWorkItemTypes: WorkItemType[];
allWorkItemTypes: WorkItemType[];
allowAddNewActionItem: boolean;
onUpdateActionItem: (feedbackItemId: IFeedbackItemDocument) => void;
}
export interface ActionItemDisplayState {
isLinkedWorkItemLoaded: boolean;
isLinkExistingItemDialogHidden: boolean;
isWorkItemTypeListCalloutVisible: boolean;
linkedWorkItem: WorkItem;
workItemSearchTextboxHasErrors: boolean;
initialRender: boolean;
}
export default class ActionItemDisplay extends React.Component<ActionItemDisplayProps, ActionItemDisplayState> {
constructor(props: ActionItemDisplayProps) {
super(props);
this.state = {
isWorkItemTypeListCalloutVisible: false,
isLinkExistingItemDialogHidden: true,
isLinkedWorkItemLoaded: false,
linkedWorkItem: null,
workItemSearchTextboxHasErrors: false,
initialRender: true,
};
}
componentDidMount() {
if(this.state.initialRender) {
this.setState({ initialRender: false });
}
}
private addActionItemButtonWrapper: HTMLElement | null;
private createAndLinkActionItem = async (workItemTypeName: string) => {
const workItemNavSvc = await WorkItemFormNavigationService.getService();
const workItem = await workItemNavSvc.openNewWorkItem(workItemTypeName, {
'System.AssignedTo': VSS.getWebContext().user.name,
'Tags': 'feedback;reflect-hub',
'Title': '',
'Description': `${this.props.feedbackItemTitle}`,
'priority': 1,
'System.History': `Created by Retrospectives |` +
` Team [ ${this.props.team.name} ] Retrospective [ ${this.props.boardTitle} ] Item [ ${this.props.feedbackItemTitle} ]` +
` Link [ ${getBoardUrl(this.props.team.id, this.props.boardId)} ]`,
'System.AreaPath': this.props.defaultAreaPath,
'System.IterationPath': this.props.defaultIteration,
});
if (workItem) {
const updatedFeedbackItem = await itemDataService.addAssociatedActionItem(this.props.boardId, this.props.feedbackItemId, workItem.id);
// TODO (enpolat) : appInsightsClient.trackEvent(TelemetryEvents.WorkItemCreated, { [TelemetryEventProperties.WorkItemType]: workItemTypeName });
this.props.onUpdateActionItem(updatedFeedbackItem);
}
}
private renderAllWorkItemCards = () => {
return this.props.actionItems.map((item) => {
return this.renderWorkItemCard(item, false);
});
}
private renderWorkItemCard = (item: WorkItem, areActionIconsHidden: boolean) => {
return (
<ActionItem
key={item.id}
feedbackItemId={this.props.feedbackItemId}
boardId={this.props.boardId}
actionItem={item}
nonHiddenWorkItemTypes={this.props.nonHiddenWorkItemTypes}
allWorkItemTypes={this.props.allWorkItemTypes}
onUpdateActionItem={this.props.onUpdateActionItem}
areActionIconsHidden={areActionIconsHidden}
shouldFocus={!this.state.initialRender} />
);
}
private addActionItem = (workItemTypeName: string) => {
this.createAndLinkActionItem(workItemTypeName);
}
private onRenderWorkItemTypeIcon = (iconLocation: string, workItemType: string): JSX.Element => {
return <Image src={iconLocation} className="work-item-icon" aria-label={`icon for work item type ${workItemType}`} />;
}
private hideSelectorCallout = () => {
this.setState({
isWorkItemTypeListCalloutVisible: false,
});
}
private toggleSelectorCallout = () => {
this.setState((prevState) => {
return { isWorkItemTypeListCalloutVisible: !prevState.isWorkItemTypeListCalloutVisible };
});
}
private handleKeyPressSelectorButton = (event: React.KeyboardEvent<HTMLDivElement>) => {
if (event.keyCode === 13) {
this.toggleSelectorCallout();
}
}
private handleClickWorkItemType = (event: React.MouseEvent<Button | HTMLAnchorElement | HTMLButtonElement | HTMLDivElement | BaseButton | HTMLSpanElement>, item: WorkItemType) => {
event && event.stopPropagation();
this.hideSelectorCallout();
this.addActionItem(item.name)
}
private handleInputChange = async (event?: React.ChangeEvent<HTMLInputElement>, newValue?: string) => {
if (!newValue || !newValue.trim()) {
this.setState({
isLinkedWorkItemLoaded: false,
workItemSearchTextboxHasErrors: false,
});
return;
}
const workItemId = Number(newValue.trim());
if (!workItemId) {
this.setState({
workItemSearchTextboxHasErrors: true,
isLinkedWorkItemLoaded: false,
});
return;
}
const workItem = await workItemService.getWorkItemsByIds([workItemId]);
this.setState({
isLinkedWorkItemLoaded: true,
linkedWorkItem: workItem[0] ? workItem[0] : null,
workItemSearchTextboxHasErrors: false,
});
}
private linkExistingWorkItem = async () => {
this.linkExistingItemDialogDismiss();
if (this.state.linkedWorkItem) {
const updatedFeedbackItem = await itemDataService.addAssociatedActionItem(this.props.boardId, this.props.feedbackItemId, this.state.linkedWorkItem.id);
// TODO (enpolat) : appInsightsClient.trackEvent(TelemetryEvents.ExistingWorkItemLinked, { [TelemetryEventProperties.WorkItemType]: this.state.linkedWorkItem.fields['System.WorkItemType'] });
this.props.onUpdateActionItem(updatedFeedbackItem);
}
}
private handleLinkExistingWorkItemClick = (mouseEvent: React.MouseEvent<Button | HTMLAnchorElement | HTMLButtonElement | HTMLDivElement | BaseButton> = undefined) => {
if (mouseEvent) {
mouseEvent.stopPropagation();
}
this.setState({
isLinkedWorkItemLoaded: false,
linkedWorkItem: null,
isLinkExistingItemDialogHidden: false,
workItemSearchTextboxHasErrors: false,
});
}
private linkExistingItemDialogDismiss = () => {
this.setState({
isLinkExistingItemDialogHidden: true,
});
}
public render(): JSX.Element {
const { disabled, checked } = this.props;
return (
<div className="action-items">
{this.props.allowAddNewActionItem &&
<div className="add-action-item-wrapper">
<div className="feedback-spacer" />
<div
ref={(div) => this.addActionItemButtonWrapper = div}>
<ActionButton
// @ts-ignore TS2769
componentRef={(actionButton: HTMLElement) => this.addActionItemButton = actionButton}
className="add-action-item-button"
ariaLabel="Add work item"
data-automation-id="actionItemDataAutomation"
disabled={disabled}
checked={checked}
iconProps={{ iconName: 'Add' }}
text="Add work item"
onKeyPress={this.handleKeyPressSelectorButton}
onClick={this.toggleSelectorCallout}
/>
</div>
{this.state.isWorkItemTypeListCalloutVisible &&
<FocusTrapCallout
className="add-action-item-callout"
ariaLabel="List of available work item types"
target={this.addActionItemButtonWrapper}
directionalHint={DirectionalHint.rightCenter}
gapSpace={0}
focusTrapProps={{ isClickableOutsideFocusTrap: true }}
isBeakVisible={false}
onDismiss={this.hideSelectorCallout}
>
<div
className="add-action-item-list-container"
data-is-scrollable={true}
>
<DefaultButton
className="add-action-item-list-item"
onClick={this.handleLinkExistingWorkItemClick}
onKeyDown={(e) => {
if (e.keyCode === 13) {
e.stopPropagation();
this.handleLinkExistingWorkItemClick();
}
}}
>
<Icon iconName="Link" className="work-item-icon" />
<div className="add-action-item-list-item-text">
Link existing work item
</div>
</DefaultButton>
<div role="separator" className="work-item-list-divider" />
<List
className="add-action-item-list-items"
items={this.props.nonHiddenWorkItemTypes}
onRenderCell={(item: WorkItemType) => {
return (
<DefaultButton
className="add-action-item-list-item"
onClick={(e) => this.handleClickWorkItemType(e, item)}
tabIndex={0}
ariaLabel={`Add work item type ${item.name}`}>
{this.onRenderWorkItemTypeIcon(item.icon.url, item.name)}
<div className="add-action-item-list-item-text">
{item.name}
</div>
</DefaultButton>
);
}}
/>
</div>
</FocusTrapCallout>
}
</div>
}
{this.renderAllWorkItemCards()}
<Dialog
hidden={this.state.isLinkExistingItemDialogHidden}
onDismiss={this.linkExistingItemDialogDismiss}
dialogContentProps={{
type: DialogType.normal,
title: 'Link existing work item',
}}
modalProps={{
isBlocking: true,
containerClassName: 'retrospectives-link-existing-work-item-dialog',
className: 'retrospectives-dialog-modal',
}}>
<SearchBox
autoFocus={true}
placeholder="Enter the exact work item id"
aria-label="Enter the exact work item id"
onChange={this.handleInputChange}
className="work-item-id-input"
/>
<div className="error-container">
{
this.state.workItemSearchTextboxHasErrors && <span className="input-validation-message">Work item ids have to be positive numbers only.</span>
}
</div>
<div className="output-container">
{
this.state.isLinkedWorkItemLoaded && this.state.linkedWorkItem && this.renderWorkItemCard(this.state.linkedWorkItem, true)
}
{
this.state.isLinkedWorkItemLoaded && !this.state.linkedWorkItem &&
<div className="work-item-not-found">The work item you are looking for was not found. Please verify the id.</div>
}
</div>
<DialogFooter>
<PrimaryButton disabled={!this.state.linkedWorkItem} onClick={this.linkExistingWorkItem} text="Link work item" />
<DefaultButton onClick={this.linkExistingItemDialogDismiss} text="Cancel" />
</DialogFooter>
</Dialog>
</div>
);
}
} | the_stack |
// IMPORTANT
// This file was generated by https://github.com/Bolisov/google-api-typings-generator. Please do not edit it manually.
// In case of any problems please post issue to https://github.com/Bolisov/google-api-typings-generator
// Generated from: https://www.googleapis.com/discovery/v1/apis/toolresults/v1beta3/rest
/// <reference types="gapi.client" />
declare namespace gapi.client {
/** Load Cloud Tool Results API v1beta3 */
function load(name: "toolresults", version: "v1beta3"): PromiseLike<void>;
function load(name: "toolresults", version: "v1beta3", callback: () => any): void;
const projects: toolresults.ProjectsResource;
namespace toolresults {
interface AndroidAppInfo {
/** The name of the app. Optional */
name?: string;
/** The package name of the app. Required. */
packageName?: string;
/** The internal version code of the app. Optional. */
versionCode?: string;
/** The version name of the app. Optional. */
versionName?: string;
}
interface AndroidInstrumentationTest {
/** The java package for the test to be executed. Required */
testPackageId?: string;
/** The InstrumentationTestRunner class. Required */
testRunnerClass?: string;
/**
* Each target must be fully qualified with the package name or class name, in one of these formats: - "package package_name" - "class
* package_name.class_name" - "class package_name.class_name#method_name"
*
* If empty, all targets in the module will be run.
*/
testTargets?: string[];
/**
* The flag indicates whether Android Test Orchestrator will be used to run test or not. Test orchestrator is used if either: - orchestrator_option field
* is USE_ORCHESTRATOR, and test runner is compatible with orchestrator. Or - orchestrator_option field is unspecified or ORCHESTRATOR_OPTION_UNSPECIFIED,
* and test runner is compatible with orchestrator.
*/
useOrchestrator?: boolean;
}
interface AndroidRoboTest {
/** The initial activity that should be used to start the app. Optional */
appInitialActivity?: string;
/** The java package for the bootstrap. Optional */
bootstrapPackageId?: string;
/** The runner class for the bootstrap. Optional */
bootstrapRunnerClass?: string;
/** The max depth of the traversal stack Robo can explore. Optional */
maxDepth?: number;
/** The max number of steps/actions Robo can execute. Default is no limit (0). Optional */
maxSteps?: number;
}
interface AndroidTest {
/** Infomation about the application under test. */
androidAppInfo?: AndroidAppInfo;
/** An Android instrumentation test. */
androidInstrumentationTest?: AndroidInstrumentationTest;
/** An Android robo test. */
androidRoboTest?: AndroidRoboTest;
/** Max time a test is allowed to run before it is automatically cancelled. */
testTimeout?: Duration;
}
interface Any {
/**
* A URL/resource name whose content describes the type of the serialized protocol buffer message.
*
* For URLs which use the scheme `http`, `https`, or no scheme, the following restrictions and interpretations apply:
*
* * If no scheme is provided, `https` is assumed. * The last segment of the URL's path must represent the fully qualified name of the type (as in
* `path/google.protobuf.Duration`). The name should be in a canonical form (e.g., leading "." is not accepted). * An HTTP GET on the URL must yield a
* [google.protobuf.Type][] value in binary format, or produce an error. * Applications are allowed to cache lookup results based on the URL, or have them
* precompiled into a binary to avoid any lookup. Therefore, binary compatibility needs to be preserved on changes to types. (Use versioned type names to
* manage breaking changes.)
*
* Schemes other than `http`, `https` (or the empty scheme) might be used with implementation specific semantics.
*/
typeUrl?: string;
/** Must be a valid serialized protocol buffer of the above specified type. */
value?: string;
}
interface AppStartTime {
/**
* Optional. The time from app start to reaching the developer-reported "fully drawn" time. This is only stored if the app includes a call to
* Activity.reportFullyDrawn(). See https://developer.android.com/topic/performance/launch-time.html#time-full
*/
fullyDrawnTime?: Duration;
/**
* The time from app start to the first displayed activity being drawn, as reported in Logcat. See
* https://developer.android.com/topic/performance/launch-time.html#time-initial
*/
initialDisplayTime?: Duration;
}
interface BasicPerfSampleSeries {
perfMetricType?: string;
perfUnit?: string;
sampleSeriesLabel?: string;
}
interface BatchCreatePerfSamplesRequest {
/** The set of PerfSamples to create should not include existing timestamps */
perfSamples?: PerfSample[];
}
interface BatchCreatePerfSamplesResponse {
perfSamples?: PerfSample[];
}
interface CPUInfo {
/** description of the device processor ie '1.8 GHz hexa core 64-bit ARMv8-A' */
cpuProcessor?: string;
/** the CPU clock speed in GHz */
cpuSpeedInGhz?: number;
/** the number of CPU cores */
numberOfCores?: number;
}
interface Duration {
/**
* Signed fractions of a second at nanosecond resolution of the span of time. Durations less than one second are represented with a 0 `seconds` field and
* a positive or negative `nanos` field. For durations of one second or more, a non-zero value for the `nanos` field must be of the same sign as the
* `seconds` field. Must be from -999,999,999 to +999,999,999 inclusive.
*/
nanos?: number;
/**
* Signed seconds of the span of time. Must be from -315,576,000,000 to +315,576,000,000 inclusive. Note: these bounds are computed from: 60 sec/min * 60
* min/hr * 24 hr/day * 365.25 days/year * 10000 years
*/
seconds?: string;
}
interface Execution {
/**
* The time when the Execution status transitioned to COMPLETE.
*
* This value will be set automatically when state transitions to COMPLETE.
*
* - In response: set if the execution state is COMPLETE. - In create/update request: never set
*/
completionTime?: Timestamp;
/**
* The time when the Execution was created.
*
* This value will be set automatically when CreateExecution is called.
*
* - In response: always set - In create/update request: never set
*/
creationTime?: Timestamp;
/**
* A unique identifier within a History for this Execution.
*
* Returns INVALID_ARGUMENT if this field is set or overwritten by the caller.
*
* - In response always set - In create/update request: never set
*/
executionId?: string;
/**
* Classify the result, for example into SUCCESS or FAILURE
*
* - In response: present if set by create/update request - In create/update request: optional
*/
outcome?: Outcome;
/**
* Lightweight information about execution request.
*
* - In response: present if set by create - In create: optional - In update: optional
*/
specification?: Specification;
/**
* The initial state is IN_PROGRESS.
*
* The only legal state transitions is from IN_PROGRESS to COMPLETE.
*
* A PRECONDITION_FAILED will be returned if an invalid transition is requested.
*
* The state can only be set to COMPLETE once. A FAILED_PRECONDITION will be returned if the state is set to COMPLETE multiple times.
*
* If the state is set to COMPLETE, all the in-progress steps within the execution will be set as COMPLETE. If the outcome of the step is not set, the
* outcome will be set to INCONCLUSIVE.
*
* - In response always set - In create/update request: optional
*/
state?: string;
/**
* TestExecution Matrix ID that the TestExecutionService uses.
*
* - In response: present if set by create - In create: optional - In update: never set
*/
testExecutionMatrixId?: string;
}
interface FailureDetail {
/** If the failure was severe because the system (app) under test crashed. */
crashed?: boolean;
/** If an app is not installed and thus no test can be run with the app. This might be caused by trying to run a test on an unsupported platform. */
notInstalled?: boolean;
/** If a native process (including any other than the app) crashed. */
otherNativeCrash?: boolean;
/** If the test overran some time limit, and that is why it failed. */
timedOut?: boolean;
/** If the robo was unable to crawl the app; perhaps because the app did not start. */
unableToCrawl?: boolean;
}
interface FileReference {
/**
* The URI of a file stored in Google Cloud Storage.
*
* For example: http://storage.googleapis.com/mybucket/path/to/test.xml or in gsutil format: gs://mybucket/path/to/test.xml with version-specific info,
* gs://mybucket/path/to/test.xml#1360383693690000
*
* An INVALID_ARGUMENT error will be returned if the URI format is not supported.
*
* - In response: always set - In create/update request: always set
*/
fileUri?: string;
}
interface GraphicsStats {
/** Histogram of frame render times. There should be 154 buckets ranging from [5ms, 6ms) to [4950ms, infinity) */
buckets?: GraphicsStatsBucket[];
/** Total "high input latency" events. */
highInputLatencyCount?: string;
/** Total frames with slow render time. Should be <= total_frames. */
jankyFrames?: string;
/** Total "missed vsync" events. */
missedVsyncCount?: string;
/** 50th percentile frame render time in milliseconds. */
p50Millis?: string;
/** 90th percentile frame render time in milliseconds. */
p90Millis?: string;
/** 95th percentile frame render time in milliseconds. */
p95Millis?: string;
/** 99th percentile frame render time in milliseconds. */
p99Millis?: string;
/** Total "slow bitmap upload" events. */
slowBitmapUploadCount?: string;
/** Total "slow draw" events. */
slowDrawCount?: string;
/** Total "slow UI thread" events. */
slowUiThreadCount?: string;
/** Total frames rendered by package. */
totalFrames?: string;
}
interface GraphicsStatsBucket {
/** Number of frames in the bucket. */
frameCount?: string;
/** Lower bound of render time in milliseconds. */
renderMillis?: string;
}
interface History {
/**
* A short human-readable (plain text) name to display in the UI. Maximum of 100 characters.
*
* - In response: present if set during create. - In create request: optional
*/
displayName?: string;
/**
* A unique identifier within a project for this History.
*
* Returns INVALID_ARGUMENT if this field is set or overwritten by the caller.
*
* - In response always set - In create request: never set
*/
historyId?: string;
/**
* A name to uniquely identify a history within a project. Maximum of 100 characters.
*
* - In response always set - In create request: always set
*/
name?: string;
}
interface Image {
/** An error explaining why the thumbnail could not be rendered. */
error?: Status;
/**
* A reference to the full-size, original image.
*
* This is the same as the tool_outputs entry for the image under its Step.
*
* Always set.
*/
sourceImage?: ToolOutputReference;
/**
* The step to which the image is attached.
*
* Always set.
*/
stepId?: string;
/** The thumbnail. */
thumbnail?: Thumbnail;
}
interface InconclusiveDetail {
/**
* If the end user aborted the test execution before a pass or fail could be determined. For example, the user pressed ctrl-c which sent a kill signal to
* the test runner while the test was running.
*/
abortedByUser?: boolean;
/**
* If the test runner could not determine success or failure because the test depends on a component other than the system under test which failed.
*
* For example, a mobile test requires provisioning a device where the test executes, and that provisioning can fail.
*/
infrastructureFailure?: boolean;
}
interface ListExecutionsResponse {
/**
* Executions.
*
* Always set.
*/
executions?: Execution[];
/**
* A continuation token to resume the query at the next item.
*
* Will only be set if there are more Executions to fetch.
*/
nextPageToken?: string;
}
interface ListHistoriesResponse {
/** Histories. */
histories?: History[];
/**
* A continuation token to resume the query at the next item.
*
* Will only be set if there are more histories to fetch.
*
* Tokens are valid for up to one hour from the time of the first list request. For instance, if you make a list request at 1PM and use the token from
* this first request 10 minutes later, the token from this second response will only be valid for 50 minutes.
*/
nextPageToken?: string;
}
interface ListPerfSampleSeriesResponse {
/** The resulting PerfSampleSeries sorted by id */
perfSampleSeries?: PerfSampleSeries[];
}
interface ListPerfSamplesResponse {
/**
* Optional, returned if result size exceeds the page size specified in the request (or the default page size, 500, if unspecified). It indicates the last
* sample timestamp to be used as page_token in subsequent request
*/
nextPageToken?: string;
perfSamples?: PerfSample[];
}
interface ListScreenshotClustersResponse {
/** The set of clustres associated with an execution Always set */
clusters?: ScreenshotCluster[];
}
interface ListStepThumbnailsResponse {
/**
* A continuation token to resume the query at the next item.
*
* If set, indicates that there are more thumbnails to read, by calling list again with this value in the page_token field.
*/
nextPageToken?: string;
/**
* A list of image data.
*
* Images are returned in a deterministic order; they are ordered by these factors, in order of importance: * First, by their associated test case. Images
* without a test case are considered greater than images with one. * Second, by their creation time. Images without a creation time are greater than
* images with one. * Third, by the order in which they were added to the step (by calls to CreateStep or UpdateStep).
*/
thumbnails?: Image[];
}
interface ListStepsResponse {
/**
* A continuation token to resume the query at the next item.
*
* If set, indicates that there are more steps to read, by calling list again with this value in the page_token field.
*/
nextPageToken?: string;
/** Steps. */
steps?: Step[];
}
interface MemoryInfo {
/** Maximum memory that can be allocated to the process in KiB */
memoryCapInKibibyte?: string;
/** Total memory available on the device in KiB */
memoryTotalInKibibyte?: string;
}
interface Outcome {
/**
* More information about a FAILURE outcome.
*
* Returns INVALID_ARGUMENT if this field is set but the summary is not FAILURE.
*
* Optional
*/
failureDetail?: FailureDetail;
/**
* More information about an INCONCLUSIVE outcome.
*
* Returns INVALID_ARGUMENT if this field is set but the summary is not INCONCLUSIVE.
*
* Optional
*/
inconclusiveDetail?: InconclusiveDetail;
/**
* More information about a SKIPPED outcome.
*
* Returns INVALID_ARGUMENT if this field is set but the summary is not SKIPPED.
*
* Optional
*/
skippedDetail?: SkippedDetail;
/**
* More information about a SUCCESS outcome.
*
* Returns INVALID_ARGUMENT if this field is set but the summary is not SUCCESS.
*
* Optional
*/
successDetail?: SuccessDetail;
/**
* The simplest way to interpret a result.
*
* Required
*/
summary?: string;
}
interface PerfEnvironment {
/** CPU related environment info */
cpuInfo?: CPUInfo;
/** Memory related environment info */
memoryInfo?: MemoryInfo;
}
interface PerfMetricsSummary {
appStartTime?: AppStartTime;
/** A tool results execution ID. */
executionId?: string;
/** Graphics statistics for the entire run. Statistics are reset at the beginning of the run and collected at the end of the run. */
graphicsStats?: GraphicsStats;
/** A tool results history ID. */
historyId?: string;
/** Describes the environment in which the performance metrics were collected */
perfEnvironment?: PerfEnvironment;
/** Set of resource collected */
perfMetrics?: string[];
/** The cloud project */
projectId?: string;
/** A tool results step ID. */
stepId?: string;
}
interface PerfSample {
/** Timestamp of collection */
sampleTime?: Timestamp;
/** Value observed */
value?: number;
}
interface PerfSampleSeries {
/** Basic series represented by a line chart */
basicPerfSampleSeries?: BasicPerfSampleSeries;
/** A tool results execution ID. */
executionId?: string;
/** A tool results history ID. */
historyId?: string;
/** The cloud project */
projectId?: string;
/** A sample series id */
sampleSeriesId?: string;
/** A tool results step ID. */
stepId?: string;
}
interface ProjectSettings {
/**
* The name of the Google Cloud Storage bucket to which results are written.
*
* By default, this is unset.
*
* In update request: optional In response: optional
*/
defaultBucket?: string;
/**
* The name of the project's settings.
*
* Always of the form: projects/{project-id}/settings
*
* In update request: never set In response: always set
*/
name?: string;
}
interface PublishXunitXmlFilesRequest {
/**
* URI of the Xunit XML files to publish.
*
* The maximum size of the file this reference is pointing to is 50MB.
*
* Required.
*/
xunitXmlFiles?: FileReference[];
}
interface Screen {
/** File reference of the png file. Required. */
fileReference?: string;
/** Locale of the device that the screenshot was taken on. Required. */
locale?: string;
/** Model of the device that the screenshot was taken on. Required. */
model?: string;
/** OS version of the device that the screenshot was taken on. Required. */
version?: string;
}
interface ScreenshotCluster {
/** A string that describes the activity of every screen in the cluster. */
activity?: string;
/** A unique identifier for the cluster. */
clusterId?: string;
/**
* A singular screen that represents the cluster as a whole. This screen will act as the "cover" of the entire cluster. When users look at the clusters,
* only the key screen from each cluster will be shown. Which screen is the key screen is determined by the ClusteringAlgorithm
*/
keyScreen?: Screen;
/** Full list of screens. */
screens?: Screen[];
}
interface SkippedDetail {
/** If the App doesn't support the specific API level. */
incompatibleAppVersion?: boolean;
/** If the App doesn't run on the specific architecture, for example, x86. */
incompatibleArchitecture?: boolean;
/** If the requested OS version doesn't run on the specific device model. */
incompatibleDevice?: boolean;
}
interface Specification {
/** An Android mobile test execution specification. */
androidTest?: AndroidTest;
}
interface StackTrace {
/** Exception cluster ID */
clusterId?: string;
/**
* The stack trace message.
*
* Required
*/
exception?: string;
/** Exception report ID */
reportId?: string;
}
interface Status {
/** The status code, which should be an enum value of [google.rpc.Code][]. */
code?: number;
/** A list of messages that carry the error details. There is a common set of message types for APIs to use. */
details?: Any[];
/**
* A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the
* [google.rpc.Status.details][] field, or localized by the client.
*/
message?: string;
}
interface Step {
/**
* The time when the step status was set to complete.
*
* This value will be set automatically when state transitions to COMPLETE.
*
* - In response: set if the execution state is COMPLETE. - In create/update request: never set
*/
completionTime?: Timestamp;
/**
* The time when the step was created.
*
* - In response: always set - In create/update request: never set
*/
creationTime?: Timestamp;
/**
* A description of this tool For example: mvn clean package -D skipTests=true
*
* - In response: present if set by create/update request - In create/update request: optional
*/
description?: string;
/**
* How much the device resource is used to perform the test.
*
* This is the device usage used for billing purpose, which is different from the run_duration, for example, infrastructure failure won't be charged for
* device usage.
*
* PRECONDITION_FAILED will be returned if one attempts to set a device_usage on a step which already has this field set.
*
* - In response: present if previously set. - In create request: optional - In update request: optional
*/
deviceUsageDuration?: Duration;
/**
* If the execution containing this step has any dimension_definition set, then this field allows the child to specify the values of the dimensions.
*
* The keys must exactly match the dimension_definition of the execution.
*
* For example, if the execution has `dimension_definition = ['attempt', 'device']` then a step must define values for those dimensions, eg.
* `dimension_value = ['attempt': '1', 'device': 'Nexus 6']`
*
* If a step does not participate in one dimension of the matrix, the value for that dimension should be empty string. For example, if one of the tests is
* executed by a runner which does not support retries, the step could have `dimension_value = ['attempt': '', 'device': 'Nexus 6']`
*
* If the step does not participate in any dimensions of the matrix, it may leave dimension_value unset.
*
* A PRECONDITION_FAILED will be returned if any of the keys do not exist in the dimension_definition of the execution.
*
* A PRECONDITION_FAILED will be returned if another step in this execution already has the same name and dimension_value, but differs on other data
* fields, for example, step field is different.
*
* A PRECONDITION_FAILED will be returned if dimension_value is set, and there is a dimension_definition in the execution which is not specified as one of
* the keys.
*
* - In response: present if set by create - In create request: optional - In update request: never set
*/
dimensionValue?: StepDimensionValueEntry[];
/**
* Whether any of the outputs of this step are images whose thumbnails can be fetched with ListThumbnails.
*
* - In response: always set - In create/update request: never set
*/
hasImages?: boolean;
/**
* Arbitrary user-supplied key/value pairs that are associated with the step.
*
* Users are responsible for managing the key namespace such that keys don't accidentally collide.
*
* An INVALID_ARGUMENT will be returned if the number of labels exceeds 100 or if the length of any of the keys or values exceeds 100 characters.
*
* - In response: always set - In create request: optional - In update request: optional; any new key/value pair will be added to the map, and any new
* value for an existing key will update that key's value
*/
labels?: StepLabelsEntry[];
/**
* A short human-readable name to display in the UI. Maximum of 100 characters. For example: Clean build
*
* A PRECONDITION_FAILED will be returned upon creating a new step if it shares its name and dimension_value with an existing step. If two steps represent
* a similar action, but have different dimension values, they should share the same name. For instance, if the same set of tests is run on two different
* platforms, the two steps should have the same name.
*
* - In response: always set - In create request: always set - In update request: never set
*/
name?: string;
/**
* Classification of the result, for example into SUCCESS or FAILURE
*
* - In response: present if set by create/update request - In create/update request: optional
*/
outcome?: Outcome;
/**
* How long it took for this step to run.
*
* If unset, this is set to the difference between creation_time and completion_time when the step is set to the COMPLETE state. In some cases, it is
* appropriate to set this value separately: For instance, if a step is created, but the operation it represents is queued for a few minutes before it
* executes, it would be appropriate not to include the time spent queued in its run_duration.
*
* PRECONDITION_FAILED will be returned if one attempts to set a run_duration on a step which already has this field set.
*
* - In response: present if previously set; always present on COMPLETE step - In create request: optional - In update request: optional
*/
runDuration?: Duration;
/**
* The initial state is IN_PROGRESS. The only legal state transitions are * IN_PROGRESS -> COMPLETE
*
* A PRECONDITION_FAILED will be returned if an invalid transition is requested.
*
* It is valid to create Step with a state set to COMPLETE. The state can only be set to COMPLETE once. A PRECONDITION_FAILED will be returned if the
* state is set to COMPLETE multiple times.
*
* - In response: always set - In create/update request: optional
*/
state?: string;
/**
* A unique identifier within a Execution for this Step.
*
* Returns INVALID_ARGUMENT if this field is set or overwritten by the caller.
*
* - In response: always set - In create/update request: never set
*/
stepId?: string;
/** An execution of a test runner. */
testExecutionStep?: TestExecutionStep;
/** An execution of a tool (used for steps we don't explicitly support). */
toolExecutionStep?: ToolExecutionStep;
}
interface StepDimensionValueEntry {
key?: string;
value?: string;
}
interface StepLabelsEntry {
key?: string;
value?: string;
}
interface SuccessDetail {
/** If a native process other than the app crashed. */
otherNativeCrash?: boolean;
}
interface TestCaseReference {
/** The name of the class. */
className?: string;
/**
* The name of the test case.
*
* Required.
*/
name?: string;
/** The name of the test suite to which this test case belongs. */
testSuiteName?: string;
}
interface TestExecutionStep {
/**
* Issues observed during the test execution.
*
* For example, if the mobile app under test crashed during the test, the error message and the stack trace content can be recorded here to assist
* debugging.
*
* - In response: present if set by create or update - In create/update request: optional
*/
testIssues?: TestIssue[];
/**
* List of test suite overview contents. This could be parsed from xUnit XML log by server, or uploaded directly by user. This references should only be
* called when test suites are fully parsed or uploaded.
*
* The maximum allowed number of test suite overviews per step is 1000.
*
* - In response: always set - In create request: optional - In update request: never (use publishXunitXmlFiles custom method instead)
*/
testSuiteOverviews?: TestSuiteOverview[];
/**
* The timing break down of the test execution.
*
* - In response: present if set by create or update - In create/update request: optional
*/
testTiming?: TestTiming;
/**
* Represents the execution of the test runner.
*
* The exit code of this tool will be used to determine if the test passed.
*
* - In response: always set - In create/update request: optional
*/
toolExecution?: ToolExecution;
}
interface TestIssue {
/** A brief human-readable message describing the issue. Required. */
errorMessage?: string;
/** Severity of issue. Required. */
severity?: string;
/** Deprecated in favor of stack trace fields inside specific warnings. */
stackTrace?: StackTrace;
/** Type of issue. Required. */
type?: string;
/** Warning message with additional details of the issue. Should always be a message from com.google.devtools.toolresults.v1.warnings Required. */
warning?: Any;
}
interface TestSuiteOverview {
/**
* Number of test cases in error, typically set by the service by parsing the xml_source.
*
* - In create/response: always set - In update request: never
*/
errorCount?: number;
/**
* Number of failed test cases, typically set by the service by parsing the xml_source. May also be set by the user.
*
* - In create/response: always set - In update request: never
*/
failureCount?: number;
/**
* The name of the test suite.
*
* - In create/response: always set - In update request: never
*/
name?: string;
/**
* Number of test cases not run, typically set by the service by parsing the xml_source.
*
* - In create/response: always set - In update request: never
*/
skippedCount?: number;
/**
* Number of test cases, typically set by the service by parsing the xml_source.
*
* - In create/response: always set - In update request: never
*/
totalCount?: number;
/**
* If this test suite was parsed from XML, this is the URI where the original XML file is stored.
*
* Note: Multiple test suites can share the same xml_source
*
* Returns INVALID_ARGUMENT if the uri format is not supported.
*
* - In create/response: optional - In update request: never
*/
xmlSource?: FileReference;
}
interface TestTiming {
/**
* How long it took to run the test process.
*
* - In response: present if previously set. - In create/update request: optional
*/
testProcessDuration?: Duration;
}
interface Thumbnail {
/**
* The thumbnail's content type, i.e. "image/png".
*
* Always set.
*/
contentType?: string;
/**
* The thumbnail file itself.
*
* That is, the bytes here are precisely the bytes that make up the thumbnail file; they can be served as an image as-is (with the appropriate content
* type.)
*
* Always set.
*/
data?: string;
/**
* The height of the thumbnail, in pixels.
*
* Always set.
*/
heightPx?: number;
/**
* The width of the thumbnail, in pixels.
*
* Always set.
*/
widthPx?: number;
}
interface Timestamp {
/**
* Non-negative fractions of a second at nanosecond resolution. Negative second values with fractions must still have non-negative nanos values that count
* forward in time. Must be from 0 to 999,999,999 inclusive.
*/
nanos?: number;
/** Represents seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive. */
seconds?: string;
}
interface ToolExecution {
/**
* The full tokenized command line including the program name (equivalent to argv in a C program).
*
* - In response: present if set by create request - In create request: optional - In update request: never set
*/
commandLineArguments?: string[];
/**
* Tool execution exit code. This field will be set once the tool has exited.
*
* - In response: present if set by create/update request - In create request: optional - In update request: optional, a FAILED_PRECONDITION error will be
* returned if an exit_code is already set.
*/
exitCode?: ToolExitCode;
/**
* References to any plain text logs output the tool execution.
*
* This field can be set before the tool has exited in order to be able to have access to a live view of the logs while the tool is running.
*
* The maximum allowed number of tool logs per step is 1000.
*
* - In response: present if set by create/update request - In create request: optional - In update request: optional, any value provided will be appended
* to the existing list
*/
toolLogs?: FileReference[];
/**
* References to opaque files of any format output by the tool execution.
*
* The maximum allowed number of tool outputs per step is 1000.
*
* - In response: present if set by create/update request - In create request: optional - In update request: optional, any value provided will be appended
* to the existing list
*/
toolOutputs?: ToolOutputReference[];
}
interface ToolExecutionStep {
/**
* A Tool execution.
*
* - In response: present if set by create/update request - In create/update request: optional
*/
toolExecution?: ToolExecution;
}
interface ToolExitCode {
/**
* Tool execution exit code. A value of 0 means that the execution was successful.
*
* - In response: always set - In create/update request: always set
*/
number?: number;
}
interface ToolOutputReference {
/**
* The creation time of the file.
*
* - In response: present if set by create/update request - In create/update request: optional
*/
creationTime?: Timestamp;
/**
* A FileReference to an output file.
*
* - In response: always set - In create/update request: always set
*/
output?: FileReference;
/**
* The test case to which this output file belongs.
*
* - In response: present if set by create/update request - In create/update request: optional
*/
testCase?: TestCaseReference;
}
interface ClustersResource {
/** Retrieves a single screenshot cluster by its ID */
get(request: {
/** Data format for the response. */
alt?: string;
/**
* A Cluster id
*
* Required.
*/
clusterId: string;
/**
* An Execution id.
*
* Required.
*/
executionId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/**
* A History id.
*
* Required.
*/
historyId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* A Project id.
*
* Required.
*/
projectId: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<ScreenshotCluster>;
/**
* Lists Screenshot Clusters
*
* Returns the list of screenshot clusters corresponding to an execution. Screenshot clusters are created after the execution is finished. Clusters are
* created from a set of screenshots. Between any two screenshots, a matching score is calculated based off their metadata that determines how similar
* they are. Screenshots are placed in the cluster that has screens which have the highest matching scores.
*/
list(request: {
/** Data format for the response. */
alt?: string;
/**
* An Execution id.
*
* Required.
*/
executionId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/**
* A History id.
*
* Required.
*/
historyId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* A Project id.
*
* Required.
*/
projectId: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<ListScreenshotClustersResponse>;
}
interface PerfMetricsSummaryResource {
/**
* Creates a PerfMetricsSummary resource. Returns the existing one if it has already been created.
*
* May return any of the following error code(s): - NOT_FOUND - The containing Step does not exist
*/
create(request: {
/** Data format for the response. */
alt?: string;
/** A tool results execution ID. */
executionId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** A tool results history ID. */
historyId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** The cloud project */
projectId: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** A tool results step ID. */
stepId: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<PerfMetricsSummary>;
}
interface SamplesResource {
/**
* Creates a batch of PerfSamples - a client can submit multiple batches of Perf Samples through repeated calls to this method in order to split up a
* large request payload - duplicates and existing timestamp entries will be ignored. - the batch operation may partially succeed - the set of elements
* successfully inserted is returned in the response (omits items which already existed in the database).
*
* May return any of the following canonical error codes: - NOT_FOUND - The containing PerfSampleSeries does not exist
*/
batchCreate(request: {
/** Data format for the response. */
alt?: string;
/** A tool results execution ID. */
executionId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** A tool results history ID. */
historyId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** The cloud project */
projectId: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** A sample series id */
sampleSeriesId: string;
/** A tool results step ID. */
stepId: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<BatchCreatePerfSamplesResponse>;
/**
* Lists the Performance Samples of a given Sample Series - The list results are sorted by timestamps ascending - The default page size is 500 samples;
* and maximum size allowed 5000 - The response token indicates the last returned PerfSample timestamp - When the results size exceeds the page size,
* submit a subsequent request including the page token to return the rest of the samples up to the page limit
*
* May return any of the following canonical error codes: - OUT_OF_RANGE - The specified request page_token is out of valid range - NOT_FOUND - The
* containing PerfSampleSeries does not exist
*/
list(request: {
/** Data format for the response. */
alt?: string;
/** A tool results execution ID. */
executionId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** A tool results history ID. */
historyId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** The default page size is 500 samples, and the maximum size is 5000. If the page_size is greater than 5000, the effective page size will be 5000 */
pageSize?: number;
/** Optional, the next_page_token returned in the previous response */
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** The cloud project */
projectId: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** A sample series id */
sampleSeriesId: string;
/** A tool results step ID. */
stepId: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<ListPerfSamplesResponse>;
}
interface PerfSampleSeriesResource {
/**
* Creates a PerfSampleSeries.
*
* May return any of the following error code(s): - ALREADY_EXISTS - PerfMetricSummary already exists for the given Step - NOT_FOUND - The containing Step
* does not exist
*/
create(request: {
/** Data format for the response. */
alt?: string;
/** A tool results execution ID. */
executionId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** A tool results history ID. */
historyId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** The cloud project */
projectId: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** A tool results step ID. */
stepId: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<PerfSampleSeries>;
/**
* Gets a PerfSampleSeries.
*
* May return any of the following error code(s): - NOT_FOUND - The specified PerfSampleSeries does not exist
*/
get(request: {
/** Data format for the response. */
alt?: string;
/** A tool results execution ID. */
executionId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** A tool results history ID. */
historyId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** The cloud project */
projectId: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** A sample series id */
sampleSeriesId: string;
/** A tool results step ID. */
stepId: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<PerfSampleSeries>;
/**
* Lists PerfSampleSeries for a given Step.
*
* The request provides an optional filter which specifies one or more PerfMetricsType to include in the result; if none returns all. The resulting
* PerfSampleSeries are sorted by ids.
*
* May return any of the following canonical error codes: - NOT_FOUND - The containing Step does not exist
*/
list(request: {
/** Data format for the response. */
alt?: string;
/** A tool results execution ID. */
executionId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** Specify one or more PerfMetricType values such as CPU to filter the result */
filter?: string;
/** A tool results history ID. */
historyId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** The cloud project */
projectId: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** A tool results step ID. */
stepId: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<ListPerfSampleSeriesResponse>;
samples: SamplesResource;
}
interface ThumbnailsResource {
/**
* Lists thumbnails of images attached to a step.
*
* May return any of the following canonical error codes: - PERMISSION_DENIED - if the user is not authorized to read from the project, or from any of the
* images - INVALID_ARGUMENT - if the request is malformed - NOT_FOUND - if the step does not exist, or if any of the images do not exist
*/
list(request: {
/** Data format for the response. */
alt?: string;
/**
* An Execution id.
*
* Required.
*/
executionId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/**
* A History id.
*
* Required.
*/
historyId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* The maximum number of thumbnails to fetch.
*
* Default value: 50. The server will use this default if the field is not set or has a value of 0.
*
* Optional.
*/
pageSize?: number;
/**
* A continuation token to resume the query at the next item.
*
* Optional.
*/
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* A Project id.
*
* Required.
*/
projectId: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/**
* A Step id.
*
* Required.
*/
stepId: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<ListStepThumbnailsResponse>;
}
interface StepsResource {
/**
* Creates a Step.
*
* The returned Step will have the id set.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to write to project - INVALID_ARGUMENT - if the request is malformed - FAILED_PRECONDITION - if the
* step is too large (more than 10Mib) - NOT_FOUND - if the containing Execution does not exist
*/
create(request: {
/** Data format for the response. */
alt?: string;
/**
* A Execution id.
*
* Required.
*/
executionId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/**
* A History id.
*
* Required.
*/
historyId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* A Project id.
*
* Required.
*/
projectId: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/**
* A unique request ID for server to detect duplicated requests. For example, a UUID.
*
* Optional, but strongly recommended.
*/
requestId?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Step>;
/**
* Gets a Step.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to read project - INVALID_ARGUMENT - if the request is malformed - NOT_FOUND - if the Step does not
* exist
*/
get(request: {
/** Data format for the response. */
alt?: string;
/**
* A Execution id.
*
* Required.
*/
executionId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/**
* A History id.
*
* Required.
*/
historyId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* A Project id.
*
* Required.
*/
projectId: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/**
* A Step id.
*
* Required.
*/
stepId: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Step>;
/**
* Retrieves a PerfMetricsSummary.
*
* May return any of the following error code(s): - NOT_FOUND - The specified PerfMetricsSummary does not exist
*/
getPerfMetricsSummary(request: {
/** Data format for the response. */
alt?: string;
/** A tool results execution ID. */
executionId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** A tool results history ID. */
historyId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** The cloud project */
projectId: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** A tool results step ID. */
stepId: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<PerfMetricsSummary>;
/**
* Lists Steps for a given Execution.
*
* The steps are sorted by creation_time in descending order. The step_id key will be used to order the steps with the same creation_time.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to read project - INVALID_ARGUMENT - if the request is malformed - FAILED_PRECONDITION - if an
* argument in the request happens to be invalid; e.g. if an attempt is made to list the children of a nonexistent Step - NOT_FOUND - if the containing
* Execution does not exist
*/
list(request: {
/** Data format for the response. */
alt?: string;
/**
* A Execution id.
*
* Required.
*/
executionId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/**
* A History id.
*
* Required.
*/
historyId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* The maximum number of Steps to fetch.
*
* Default value: 25. The server will use this default if the field is not set or has a value of 0.
*
* Optional.
*/
pageSize?: number;
/**
* A continuation token to resume the query at the next item.
*
* Optional.
*/
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* A Project id.
*
* Required.
*/
projectId: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<ListStepsResponse>;
/**
* Updates an existing Step with the supplied partial entity.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to write project - INVALID_ARGUMENT - if the request is malformed - FAILED_PRECONDITION - if the
* requested state transition is illegal (e.g try to upload a duplicate xml file), if the updated step is too large (more than 10Mib) - NOT_FOUND - if the
* containing Execution does not exist
*/
patch(request: {
/** Data format for the response. */
alt?: string;
/**
* A Execution id.
*
* Required.
*/
executionId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/**
* A History id.
*
* Required.
*/
historyId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* A Project id.
*
* Required.
*/
projectId: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/**
* A unique request ID for server to detect duplicated requests. For example, a UUID.
*
* Optional, but strongly recommended.
*/
requestId?: string;
/**
* A Step id.
*
* Required.
*/
stepId: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Step>;
/**
* Publish xml files to an existing Step.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to write project - INVALID_ARGUMENT - if the request is malformed - FAILED_PRECONDITION - if the
* requested state transition is illegal, e.g try to upload a duplicate xml file or a file too large. - NOT_FOUND - if the containing Execution does not
* exist
*/
publishXunitXmlFiles(request: {
/** Data format for the response. */
alt?: string;
/**
* A Execution id.
*
* Required.
*/
executionId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/**
* A History id.
*
* Required.
*/
historyId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* A Project id.
*
* Required.
*/
projectId: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/**
* A Step id. Note: This step must include a TestExecutionStep.
*
* Required.
*/
stepId: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Step>;
perfMetricsSummary: PerfMetricsSummaryResource;
perfSampleSeries: PerfSampleSeriesResource;
thumbnails: ThumbnailsResource;
}
interface ExecutionsResource {
/**
* Creates an Execution.
*
* The returned Execution will have the id set.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to write to project - INVALID_ARGUMENT - if the request is malformed - NOT_FOUND - if the
* containing History does not exist
*/
create(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/**
* A History id.
*
* Required.
*/
historyId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* A Project id.
*
* Required.
*/
projectId: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/**
* A unique request ID for server to detect duplicated requests. For example, a UUID.
*
* Optional, but strongly recommended.
*/
requestId?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Execution>;
/**
* Gets an Execution.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to write to project - INVALID_ARGUMENT - if the request is malformed - NOT_FOUND - if the Execution
* does not exist
*/
get(request: {
/** Data format for the response. */
alt?: string;
/**
* An Execution id.
*
* Required.
*/
executionId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/**
* A History id.
*
* Required.
*/
historyId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* A Project id.
*
* Required.
*/
projectId: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Execution>;
/**
* Lists Histories for a given Project.
*
* The executions are sorted by creation_time in descending order. The execution_id key will be used to order the executions with the same creation_time.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to read project - INVALID_ARGUMENT - if the request is malformed - NOT_FOUND - if the containing
* History does not exist
*/
list(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/**
* A History id.
*
* Required.
*/
historyId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* The maximum number of Executions to fetch.
*
* Default value: 25. The server will use this default if the field is not set or has a value of 0.
*
* Optional.
*/
pageSize?: number;
/**
* A continuation token to resume the query at the next item.
*
* Optional.
*/
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* A Project id.
*
* Required.
*/
projectId: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<ListExecutionsResponse>;
/**
* Updates an existing Execution with the supplied partial entity.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to write to project - INVALID_ARGUMENT - if the request is malformed - FAILED_PRECONDITION - if the
* requested state transition is illegal - NOT_FOUND - if the containing History does not exist
*/
patch(request: {
/** Data format for the response. */
alt?: string;
/** Required. */
executionId: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** Required. */
historyId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/** A Project id. Required. */
projectId: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/**
* A unique request ID for server to detect duplicated requests. For example, a UUID.
*
* Optional, but strongly recommended.
*/
requestId?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<Execution>;
clusters: ClustersResource;
steps: StepsResource;
}
interface HistoriesResource {
/**
* Creates a History.
*
* The returned History will have the id set.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to write to project - INVALID_ARGUMENT - if the request is malformed - NOT_FOUND - if the
* containing project does not exist
*/
create(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* A Project id.
*
* Required.
*/
projectId: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/**
* A unique request ID for server to detect duplicated requests. For example, a UUID.
*
* Optional, but strongly recommended.
*/
requestId?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<History>;
/**
* Gets a History.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to read project - INVALID_ARGUMENT - if the request is malformed - NOT_FOUND - if the History does
* not exist
*/
get(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/**
* A History id.
*
* Required.
*/
historyId: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* A Project id.
*
* Required.
*/
projectId: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<History>;
/**
* Lists Histories for a given Project.
*
* The histories are sorted by modification time in descending order. The history_id key will be used to order the history with the same modification
* time.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to read project - INVALID_ARGUMENT - if the request is malformed - NOT_FOUND - if the History does
* not exist
*/
list(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/**
* If set, only return histories with the given name.
*
* Optional.
*/
filterByName?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/**
* The maximum number of Histories to fetch.
*
* Default value: 20. The server will use this default if the field is not set or has a value of 0. Any value greater than 100 will be treated as 100.
*
* Optional.
*/
pageSize?: number;
/**
* A continuation token to resume the query at the next item.
*
* Optional.
*/
pageToken?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* A Project id.
*
* Required.
*/
projectId: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<ListHistoriesResponse>;
executions: ExecutionsResource;
}
interface ProjectsResource {
/**
* Gets the Tool Results settings for a project.
*
* May return any of the following canonical error codes:
*
* - PERMISSION_DENIED - if the user is not authorized to read from project
*/
getSettings(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* A Project id.
*
* Required.
*/
projectId: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<ProjectSettings>;
/**
* Creates resources for settings which have not yet been set.
*
* Currently, this creates a single resource: a Google Cloud Storage bucket, to be used as the default bucket for this project. The bucket is created in
* an FTL-own storage project. Except for in rare cases, calling this method in parallel from multiple clients will only create a single bucket. In order
* to avoid unnecessary storage charges, the bucket is configured to automatically delete objects older than 90 days.
*
* The bucket is created with the following permissions: - Owner access for owners of central storage project (FTL-owned) - Writer access for
* owners/editors of customer project - Reader access for viewers of customer project The default ACL on objects created in the bucket is: - Owner access
* for owners of central storage project - Reader access for owners/editors/viewers of customer project See Google Cloud Storage documentation for more
* details.
*
* If there is already a default bucket set and the project can access the bucket, this call does nothing. However, if the project doesn't have the
* permission to access the bucket or the bucket is deleted, a new bucket will be created.
*
* May return any canonical error codes, including the following:
*
* - PERMISSION_DENIED - if the user is not authorized to write to project - Any error code raised by Google Cloud Storage
*/
initializeSettings(request: {
/** Data format for the response. */
alt?: string;
/** Selector specifying which fields to include in a partial response. */
fields?: string;
/** API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */
key?: string;
/** OAuth 2.0 token for the current user. */
oauth_token?: string;
/** Returns response with indentations and line breaks. */
prettyPrint?: boolean;
/**
* A Project id.
*
* Required.
*/
projectId: string;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
* Overrides userIp if both are provided.
*/
quotaUser?: string;
/** IP address of the site where the request originates. Use this if you want to enforce per-user limits. */
userIp?: string;
}): Request<ProjectSettings>;
histories: HistoriesResource;
}
}
} | the_stack |
import {
Allure,
AllureGroup,
AllureRuntime,
AllureStep,
AllureTest,
AttachmentOptions,
ContentType,
ExecutableItemWrapper,
LabelName,
} from "allure-js-commons";
import { World as CucumberWorld, Formatter } from "cucumber";
import { CucumberAllureInterface } from "./CucumberAllureInterface";
import { examplesToSensibleFormat } from "./events/Example";
import { GherkinDocument } from "./events/GherkinDocument";
import { GherkinStep } from "./events/GherkinStep";
import { GherkinTestCase } from "./events/GherkinTestCase";
import { Result } from "./events/Result";
import { SourceLocation } from "./events/SourceLocation";
import { TestHookDefinition } from "./events/TestHookDefinition";
import {
applyExample,
hash,
statusTextToAllure,
statusTextToStage,
stripIndent,
} from "./utilities";
export { Allure } from "allure-js-commons";
export interface World extends CucumberWorld {
allure: Allure;
}
export class CucumberJSAllureFormatterConfig {
exceptionFormatter?: (message: string) => string;
labels?: { [key: string]: RegExp[] };
links?: {
issue?: {
pattern: RegExp[];
urlTemplate: string;
};
tms?: {
pattern: RegExp[];
urlTemplate: string;
};
};
}
export class CucumberJSAllureFormatter extends Formatter {
public readonly allureInterface: Allure;
currentAfter: ExecutableItemWrapper | null = null;
currentBefore: ExecutableItemWrapper | null = null;
currentGroup: AllureGroup | null = null;
currentTest: AllureTest | null = null;
private readonly afterHooks: TestHookDefinition[];
private readonly beforeHooks: TestHookDefinition[];
private readonly exceptionFormatter: (message: string) => string;
private readonly featureMap: Map<string, GherkinDocument> = new Map();
private readonly labels: { [key: string]: RegExp[] };
private readonly links: {
issue?: {
pattern: RegExp[];
urlTemplate: string;
};
tms?: {
pattern: RegExp[];
urlTemplate: string;
};
};
private readonly sourceMap: Map<string, string[]> = new Map();
private stepStack: AllureStep[] = [];
private readonly stepsMap: Map<string, SourceLocation[]> = new Map();
constructor(
options: any,
private readonly allureRuntime: AllureRuntime,
config: CucumberJSAllureFormatterConfig,
) {
super(options);
options.eventBroadcaster
.on("source", this.onSource.bind(this))
.on("gherkin-document", this.onGherkinDocument.bind(this))
.on("test-case-prepared", this.onTestCasePrepared.bind(this))
.on("test-case-started", this.onTestCaseStarted.bind(this))
.on("test-step-started", this.onTestStepStarted.bind(this))
.on("test-step-attachment", this.onTestStepAttachment.bind(this))
.on("test-step-finished", this.onTestStepFinished.bind(this))
.on("test-case-finished", this.onTestCaseFinished.bind(this));
this.labels = config.labels || {};
this.links = config.links || {};
this.exceptionFormatter = (message): string => {
if (config.exceptionFormatter !== undefined) {
try {
return config.exceptionFormatter(message);
} catch (e) {
// eslint-disable-next-line no-console,@typescript-eslint/restrict-template-expressions
console.warn(`Error in exceptionFormatter: ${e}`);
}
}
return message;
};
this.allureInterface = new CucumberAllureInterface(this, this.allureRuntime);
options.supportCodeLibrary.World.prototype.allure = this.allureInterface;
this.beforeHooks = options.supportCodeLibrary.beforeTestCaseHookDefinitions;
this.afterHooks = options.supportCodeLibrary.afterTestCaseHookDefinitions;
}
get currentStep(): AllureStep | null {
if (this.stepStack.length > 0) {
return this.stepStack[this.stepStack.length - 1];
}
return null;
}
onGherkinDocument(data: { uri: string; document: GherkinDocument }): void {
// "ScenarioOutline"
data.document.caseMap = new Map<number, GherkinTestCase>();
data.document.stepMap = new Map<number, GherkinStep>();
if (data.document.feature !== undefined) {
for (const test of data.document.feature.children || []) {
test.stepMap = new Map();
if (test.type === "Background") {
data.document.stepMap = new Map();
for (const step of test.steps) {
step.isBackground = true;
data.document.stepMap.set(step.location!.line, step);
}
} else {
for (const step of test.steps) {
test.stepMap.set(step.location!.line, step);
}
}
if (test.type === "ScenarioOutline") {
for (const example of examplesToSensibleFormat(test.examples || [])) {
const copy = { ...test };
copy.example = example;
data.document.caseMap.set(example.line, copy);
}
} else {
data.document.caseMap.set(test.location!.line, test);
}
}
}
this.featureMap.set(data.uri, data.document);
}
onSource(data: { uri: string; data: string; media: { encoding: string; type: string } }): void {
this.sourceMap.set(data.uri, data.data.split(/\n/));
}
onTestCaseFinished(data: { result: Result } & SourceLocation): void {
if (this.currentTest === null || this.currentGroup === null) {
throw new Error("No current test info");
}
this.currentTest.status = statusTextToAllure(data.result.status);
this.currentTest.stage = statusTextToStage(data.result.status);
this.setException(this.currentTest, data.result.exception);
this.currentTest.endTest();
this.currentGroup.endGroup();
}
onTestCasePrepared(data: { steps: SourceLocation[] } & SourceLocation): void {
this.stepsMap.clear();
this.stepsMap.set(SourceLocation.toKey(data), data.steps);
this.currentBefore = null;
this.currentAfter = null;
}
onTestCaseStarted(data: SourceLocation): void {
const feature = this.featureMap.get(data.sourceLocation!.uri);
if (feature === undefined || feature.feature === undefined) {
throw new Error("Unknown feature");
}
const test =
feature.caseMap === undefined ? undefined : feature.caseMap.get(data.sourceLocation!.line);
if (test === undefined) {
throw new Error("Unknown scenario");
}
this.currentGroup = this.allureRuntime.startGroup();
this.currentTest = this.currentGroup.startTest(
applyExample(test.name || "Unnamed test", test.example),
);
const info = {
uri: data.sourceLocation!.uri,
f: feature.feature.name,
t: test.name,
a: null as any,
};
if (test.example !== undefined) {
info.a = test.example.arguments;
for (const prop in test.example.arguments) {
if (!test.example.arguments[prop]) {
continue;
}
this.currentTest.addParameter(prop, test.example.arguments[prop]);
}
}
this.currentTest.historyId = hash(JSON.stringify(info));
this.currentTest.addLabel(LabelName.THREAD, `${process.pid}`); // parallel tests support
this.currentTest.fullName = `${data.sourceLocation!.uri}:${feature.feature.name}:${
test.name || "unknown"
}`;
this.currentTest.addLabel(LabelName.FEATURE, feature.feature.name);
// this.currentTest.addLabel(LabelName.STORY, feature.feature.name);
this.currentTest.description = stripIndent(test.description || "");
for (const tag of [...(test.tags || []), ...feature.feature.tags]) {
this.currentTest.addLabel(LabelName.TAG, tag.name);
for (const label in this.labels) {
if (!this.labels[label]) {
continue;
}
for (const reg of this.labels[label]) {
const match = tag.name.match(reg);
if (match != null && match.length > 1) {
this.currentTest.addLabel(label, match[1]);
}
}
}
if (this.links.issue) {
for (const reg of this.links.issue.pattern) {
const match = tag.name.match(reg);
if (match != null && match.length > 1) {
this.currentTest.addIssueLink(
this.links.issue.urlTemplate.replace("%s", match[1]),
match[1],
);
}
}
}
if (this.links.tms) {
for (const reg of this.links.tms.pattern) {
const match = tag.name.match(reg);
if (match != null && match.length > 1) {
this.currentTest.addTmsLink(
this.links.tms.urlTemplate.replace("%s", match[1]),
match[1],
);
}
}
}
}
}
onTestStepAttachment(data: {
index: number;
data: string;
media: { type: string };
testCase: SourceLocation;
}): void {
if (this.currentStep === null) {
throw new Error("There is no step to add attachment to");
}
const type: ContentType = data.media.type as ContentType;
let content: string | Buffer = data.data;
if ([ContentType.JPEG, ContentType.PNG, ContentType.WEBM].includes(type)) {
content = Buffer.from(content, "base64");
}
const file = this.allureRuntime.writeAttachment(content, { contentType: type });
this.currentStep.addAttachment("attached", type, file);
}
onTestStepFinished(data: { index: number; result: Result; testCase: SourceLocation }): void {
const currentStep = this.currentStep; // eslint-disable-line prefer-destructuring
if (currentStep === null) {
throw new Error("No current step defined");
}
currentStep.status = statusTextToAllure(data.result.status);
currentStep.stage = statusTextToStage(data.result.status);
this.setException(currentStep, data.result.exception);
currentStep.endStep();
this.popStep();
}
onTestStepStarted(data: { index: number; testCase: SourceLocation }): void {
const location = (this.stepsMap.get(SourceLocation.toKey(data.testCase)) || [])[data.index];
const feature = this.featureMap.get(data.testCase.sourceLocation!.uri);
if (feature === undefined) {
throw new Error("Unknown feature");
}
const test =
feature.caseMap === undefined
? undefined
: feature.caseMap.get(data.testCase.sourceLocation!.line);
if (test === undefined) {
throw new Error("Unknown scenario");
}
let step: GherkinStep | undefined;
if (location.sourceLocation !== undefined && feature.stepMap !== undefined) {
step =
test.stepMap.get(location.sourceLocation.line) ||
feature.stepMap.get(location.sourceLocation.line);
} else {
if (location.actionLocation === undefined) {
location.actionLocation = {
uri: "unknown",
line: -1,
};
}
step = {
location: { line: -1 },
text: `${location.actionLocation.uri}:${location.actionLocation.line}`,
keyword: "",
};
}
if (step === undefined) {
throw new Error("Unknown step");
}
let stepText = applyExample(`${step.keyword || ""}${step.text || "unknown"}`, test.example);
const isAfter = this.afterHooks.find(({ uri, line }) => {
if (location.actionLocation === undefined) {
return false;
}
return uri === location.actionLocation.uri && line === location.actionLocation.line;
});
const isBefore = this.beforeHooks.find(({ uri, line }) => {
if (location.actionLocation === undefined) {
return false;
}
return uri === location.actionLocation.uri && line === location.actionLocation.line;
});
if (step.isBackground) {
if (this.currentBefore === null) {
this.currentBefore = this.currentGroup!.addBefore();
}
} else if (isBefore) {
if (this.currentBefore === null) {
this.currentBefore = this.currentGroup!.addBefore();
}
stepText = `Before: ${isBefore.code.name || step.text || "unknown"}`;
} else if (isAfter) {
if (this.currentAfter === null) {
this.currentAfter = this.currentGroup!.addAfter();
}
stepText = `After: ${isAfter.code.name || step.text || "unknown"}`;
} else {
if (this.currentBefore !== null) {
this.currentBefore = null;
}
if (this.currentAfter !== null) {
this.currentAfter = null;
}
}
const allureStep = (this.currentAfter || this.currentBefore || this.currentTest)!.startStep(
stepText,
);
this.pushStep(allureStep);
if (step.argument !== undefined) {
if (step.argument.content !== undefined) {
const file = this.allureRuntime.writeAttachment(step.argument.content, {
contentType: ContentType.TEXT,
});
allureStep.addAttachment("Text", ContentType.TEXT, file);
}
if (step.argument.rows !== undefined) {
const file = this.allureRuntime.writeAttachment(
step.argument.rows
.map((row) => row.cells.map((cell) => cell.value.replace(/\t/g, " ")).join("\t"))
.join("\n"),
{ contentType: ContentType.TSV },
);
allureStep.addAttachment("Table", ContentType.TSV, file);
}
}
}
popStep(): void {
this.stepStack.pop();
}
pushStep(step: AllureStep): void {
this.stepStack.push(step);
}
writeAttachment(
content: Buffer | string,
options: ContentType | string | AttachmentOptions,
): string {
return this.allureRuntime.writeAttachment(content, options);
}
private setException(target: ExecutableItemWrapper, exception?: Error | string): void {
if (exception !== undefined) {
if (typeof exception === "string") {
target.detailsMessage = this.exceptionFormatter(exception);
} else {
target.detailsMessage = this.exceptionFormatter(
exception.message || "Error.message === undefined",
);
target.detailsTrace = exception.stack || "";
}
}
}
} | the_stack |
import { Environment, HighestMigrationId } from '@mockoon/commons';
import { promises as fs } from 'fs';
import { resolve } from 'path';
import { validate as validateUUID } from 'uuid';
import { Settings } from '../../src/shared/models/settings.model';
import clipboard from '../libs/clipboard';
import dialogs from '../libs/dialogs';
import environments from '../libs/environments';
import file from '../libs/file';
import menu from '../libs/menu';
import modals from '../libs/modals';
import routes from '../libs/routes';
import utils from '../libs/utils';
describe('Schema validation', () => {
describe('Settings', () => {
it('should prepare the broken settings', async () => {
await file.editSettingsAndReload({
welcomeShown: true,
logSizeLimit: 10000,
maxLogsPerEnvironment: 50,
truncateRouteName: true,
environmentMenuSize: 100,
routeMenuSize: 200,
fakerLocale: 'en',
fakerSeed: null,
lastChangelog: '9999.9.9',
environments: [
null,
'unknown',
{ uuid: '', path: '/home/username/file1.json' }
],
enableTelemetry: true,
unknown: true
} as unknown);
});
it('should verify saved properties (missing, invalid, unknown)', async () => {
await utils.waitForAutosave();
const fileContent: Settings = JSON.parse(
(await fs.readFile('./tmp/storage/settings.json')).toString()
);
// add missing properties with default
expect(fileContent.logsMenuSize).toEqual(150);
expect(fileContent.bannerDismissed).toHaveLength(0);
// remove unknown values
expect((fileContent as any).unknown).toEqual(undefined);
// remove invalid values
expect(fileContent.environments).toHaveLength(0);
});
});
describe('Unable to migrate, repair', () => {
it('should open the environment', async () => {
await environments.open('schema-broken-repair');
});
it('should fail migration and repair if too broken (route object missing)', async () => {
await utils.checkToastDisplayed(
'warning',
'Migration of environment "Missing route object" failed. The environment was automatically repaired and migrated to the latest version.'
);
await utils.waitForAutosave();
await file.verifyObjectPropertyInFile(
'./tmp/storage/schema-broken-repair.json',
[
'lastMigration',
// indirectly verify that it's an array
'routes.0'
],
[HighestMigrationId, undefined]
);
await environments.close(1);
});
});
describe('Environments', () => {
it('should verify initial properties (missing, invalid, unknown)', async () => {
const fileContent: Environment = JSON.parse(
(await fs.readFile('./tmp/storage/schema-broken.json')).toString()
);
expect(fileContent.routes[0].uuid).toEqual('non-uuid');
expect(fileContent.name).toEqual(undefined);
expect(fileContent.routes[0].responses[0].rulesOperator).toEqual('DUMMY');
expect(fileContent.routes[0].enabled).toEqual(null);
expect(fileContent.routes[0].responses[0].statusCode).toEqual(99);
// allow empty body
expect(fileContent.routes[0].responses[0].body).toEqual('');
// allow enum in target
expect(fileContent.routes[0].responses[0].rules[1].target).toEqual(
'invalid'
);
// invalid array item
expect(fileContent.routes[0].responses[0].headers).toHaveLength(2);
expect(
(fileContent.routes[0].responses[0].headers[0] as any).unknown
).toEqual(true);
});
it('should open the environment', async () => {
await environments.open('schema-broken');
});
it('should verify saved properties (missing, invalid, unknown)', async () => {
await utils.waitForAutosave();
const fileContent: Environment = JSON.parse(
(await fs.readFile('./tmp/storage/schema-broken.json')).toString()
);
expect(validateUUID(fileContent.routes[0].uuid)).toEqual(true);
expect(fileContent.name).toEqual('New environment');
expect(fileContent.routes[0].responses[0].rulesOperator).toEqual('OR');
expect(fileContent.routes[0].enabled).toEqual(true);
expect(fileContent.routes[0].responses[0].statusCode).toEqual(200);
// allow empty body
expect(fileContent.routes[0].responses[0].body).toEqual('');
// allow enum in target
expect(fileContent.routes[0].responses[0].rules[1].target).toEqual(
'body'
);
// strip invalid array item
expect(fileContent.routes[0].responses[0].headers).toHaveLength(1);
expect(fileContent.routes[0].responses[0].headers[0].key).toEqual(
'Content-Type'
);
await environments.close(1);
});
});
describe('Route', () => {
it('should import the broken route and fix the schema', async () => {
const fileContent = await fs.readFile(
'./test/data/res/schema-validation/route-broken.json',
'utf-8'
);
await clipboard.write(fileContent);
await dialogs.save(
resolve('./tmp/storage/new-environment-route-broken.json')
);
await menu.click('MENU_NEW_ROUTE_CLIPBOARD');
await browser.pause(500);
await environments.assertCount(1);
await routes.assertCount(1);
await utils.waitForAutosave();
const envFileContent: Environment = JSON.parse(
(
await fs.readFile('./tmp/storage/new-environment-route-broken.json')
).toString()
);
// verify that properties exists
expect(validateUUID(envFileContent.uuid)).toEqual(true);
expect(validateUUID(envFileContent.routes[0].uuid)).toEqual(true);
expect(envFileContent.routes[0].enabled).toEqual(true);
expect(envFileContent.routes[0].responses[0].statusCode).toEqual(200);
});
});
describe('UUID deduplication (environment)', () => {
const initialUUID = 'a93e9c88-62f9-40a7-be4f-9645e1988d8a';
it('should prepare the settings', async () => {
await file.editSettingsAndReload({
environments: [
{
uuid: 'a93e9c88-62f9-40a7-be4f-9645e1988d8a',
path: resolve('./tmp/storage/schema-uuid-dedup-1.json')
},
{
uuid: 'a93e9c88-62f9-40a7-be4f-9645e1988d8a',
path: resolve('./tmp/storage/schema-uuid-dedup-2.json')
}
]
});
});
it('should deduplicate UUIDs at launch', async () => {
await utils.waitForAutosave();
const env0Content: Environment = JSON.parse(
(await fs.readFile('./tmp/storage/schema-uuid-dedup-1.json')).toString()
);
const env1Content: Environment = JSON.parse(
(await fs.readFile('./tmp/storage/schema-uuid-dedup-2.json')).toString()
);
expect(env0Content.uuid).toEqual(initialUUID);
expect(env0Content.routes[0].uuid).not.toEqual(initialUUID);
expect(validateUUID(env0Content.routes[0].uuid)).toEqual(true);
expect(env0Content.routes[0].responses[0].uuid).not.toEqual(initialUUID);
expect(validateUUID(env0Content.routes[0].responses[0].uuid)).toEqual(
true
);
expect(env1Content.uuid).not.toEqual(initialUUID);
expect(validateUUID(env1Content.uuid)).toEqual(true);
expect(env1Content.routes[0].uuid).not.toEqual(initialUUID);
expect(validateUUID(env1Content.routes[0].uuid)).toEqual(true);
expect(env1Content.routes[0].responses[0].uuid).not.toEqual(initialUUID);
expect(validateUUID(env1Content.routes[0].responses[0].uuid)).toEqual(
true
);
await file.verifyObjectPropertyInFile(
'./tmp/storage/settings.json',
['environments.0.uuid', 'environments.1.uuid'],
[initialUUID, env1Content.uuid]
);
});
it('should deduplicate UUIDs when opening another environment', async () => {
await fs.copyFile(
'./test/data/res/schema-validation/uuid-dedup/env-to-load-1.json',
'./tmp/storage/env-to-load-1.json'
);
await browser.pause(500);
await environments.open('env-to-load-1');
await environments.assertCount(3);
await environments.assertActiveMenuEntryText('uuid dedup load');
await utils.waitForAutosave();
const envContent: Environment = JSON.parse(
(await fs.readFile('./tmp/storage/env-to-load-1.json')).toString()
);
expect(envContent.uuid).not.toEqual(initialUUID);
expect(validateUUID(envContent.uuid)).toEqual(true);
expect(envContent.routes[0].uuid).not.toEqual(initialUUID);
expect(validateUUID(envContent.routes[0].uuid)).toEqual(true);
expect(envContent.routes[0].responses[0].uuid).not.toEqual(initialUUID);
expect(validateUUID(envContent.routes[0].responses[0].uuid)).toEqual(
true
);
await environments.close(1);
await environments.close(1);
await environments.close(1);
});
});
describe('Missing mockoon format identifier', () => {
it('should prompt before opening an environment where identifier (lastmigration) is missing', async () => {
await fs.copyFile(
'./test/data/res/schema-validation/missing-identifier.json',
'./tmp/storage/missing-identifier.json'
);
await environments.open('missing-identifier', false);
await modals.assertTitle('Confirm opening');
});
it('should not open the file if cancel is clicked', async () => {
await $('.modal-footer .btn:last-of-type').click();
await environments.assertCount(0);
});
it('should open the file and fix the schema if confirm is clicked', async () => {
await environments.open('missing-identifier', false);
await modals.assertTitle('Confirm opening');
await $('.modal-footer .btn:first-of-type').click();
await environments.assertCount(1);
await environments.assertActiveMenuEntryText('missing identifier');
await utils.waitForAutosave();
await file.verifyObjectPropertyInFile(
'./tmp/storage/missing-identifier.json',
['lastMigration'],
[HighestMigrationId]
);
});
});
}); | the_stack |
import { AdaptiveDialog } from './adaptiveDialog';
import { BotComponent } from 'botbuilder';
import { ComponentDeclarativeTypes } from 'botbuilder-dialogs-declarative';
import { ConditionalSelector, FirstSelector, MostSpecificSelector, RandomSelector, TrueSelector } from './selectors';
import { Configuration, ServiceCollection } from 'botbuilder-dialogs-adaptive-runtime-core';
import { DynamicBeginDialogDeserializer } from './dynamicBeginDialogDeserializer';
import { Expression } from 'adaptive-expressions';
import { HasPendingActionsFunction, IsDialogActiveFunction } from './functions';
import { ResourceMultiLanguageGenerator, TemplateEngineLanguageGenerator } from './generators';
import {
BeginDialog,
BeginSkill,
BreakLoop,
CancelAllDialogs,
CancelDialog,
ContinueConversation,
ContinueConversationLater,
ContinueLoop,
DeleteActivity,
DeleteProperties,
DeleteProperty,
DynamicBeginDialog,
EditActions,
EditArray,
EmitEvent,
EndDialog,
EndTurn,
ForEach,
ForEachPage,
GetActivityMembers,
GetConversationMembers,
GetConversationReference,
GotoAction,
HttpRequest,
IfCondition,
LogAction,
RepeatDialog,
ReplaceDialog,
SendActivity,
SendHandoffActivity,
SetProperties,
SetProperty,
SignOutUser,
SwitchCondition,
TelemetryTrackEventAction,
TraceActivity,
ThrowException,
UpdateActivity,
} from './actions';
import {
OnActivity,
OnAssignEntity,
OnBeginDialog,
OnCancelDialog,
OnChooseEntity,
OnChooseIntent,
OnChooseProperty,
OnCommandActivity,
OnCommandResultActivity,
OnCondition,
OnContinueConversation,
OnConversationUpdateActivity,
OnDialogEvent,
OnEndOfActions,
OnEndOfConversationActivity,
OnError,
OnEventActivity,
OnHandoffActivity,
OnInstallationUpdateActivity,
OnIntent,
OnInvokeActivity,
OnMessageActivity,
OnMessageDeleteActivity,
OnMessageReactionActivity,
OnMessageUpdateActivity,
OnQnAMatch,
OnRepromptDialog,
OnTypingActivity,
OnUnknownIntent,
} from './conditions';
import {
Ask,
AttachmentInput,
ChoiceInput,
ConfirmInput,
DateTimeInput,
NumberInput,
OAuthInput,
TextInput,
} from './input';
import {
AgeEntityRecognizer,
ChannelMentionEntityRecognizer,
ConfirmationEntityRecognizer,
CrossTrainedRecognizerSet,
CurrencyEntityRecognizer,
DateTimeEntityRecognizer,
DimensionEntityRecognizer,
EmailEntityRecognizer,
EntityRecognizerSet,
GuidEntityRecognizer,
HashtagEntityRecognizer,
IpEntityRecognizer,
MentionEntityRecognizer,
MultiLanguageRecognizer,
NumberEntityRecognizer,
OrdinalEntityRecognizer,
PercentageEntityRecognizer,
PhoneNumberEntityRecognizer,
RecognizerSet,
RegexEntityRecognizer,
RegexRecognizer,
TemperatureEntityRecognizer,
UrlEntityRecognizer,
} from './recognizers';
export class AdaptiveBotComponent extends BotComponent {
configureServices(services: ServiceCollection, _configuration: Configuration): void {
Expression.functions.add(IsDialogActiveFunction.functionName, new IsDialogActiveFunction());
Expression.functions.add(IsDialogActiveFunction.functionAlias, new IsDialogActiveFunction());
Expression.functions.add(HasPendingActionsFunction.functionName, new HasPendingActionsFunction());
services.composeFactory<ComponentDeclarativeTypes[]>('declarativeTypes', (declarativeTypes) =>
declarativeTypes.concat(
{
getDeclarativeTypes() {
return [
// Adaptive Dialog
{ kind: AdaptiveDialog.$kind, type: AdaptiveDialog },
// Actions
{ kind: BeginDialog.$kind, type: BeginDialog },
{ kind: BeginSkill.$kind, type: BeginSkill },
{ kind: BreakLoop.$kind, type: BreakLoop },
{ kind: CancelAllDialogs.$kind, type: CancelAllDialogs },
{ kind: CancelDialog.$kind, type: CancelDialog },
{ kind: ContinueConversation.$kind, type: ContinueConversation },
{ kind: ContinueConversationLater.$kind, type: ContinueConversation },
{ kind: ContinueLoop.$kind, type: ContinueLoop },
{ kind: DeleteActivity.$kind, type: DeleteActivity },
{ kind: DeleteProperties.$kind, type: DeleteProperties },
{ kind: DeleteProperty.$kind, type: DeleteProperty },
{ kind: EditActions.$kind, type: EditActions },
{ kind: EditArray.$kind, type: EditArray },
{ kind: EmitEvent.$kind, type: EmitEvent },
{ kind: EndDialog.$kind, type: EndDialog },
{ kind: EndTurn.$kind, type: EndTurn },
{ kind: ForEach.$kind, type: ForEach },
{ kind: ForEachPage.$kind, type: ForEachPage },
{ kind: GetActivityMembers.$kind, type: GetActivityMembers },
{ kind: GetConversationMembers.$kind, type: GetConversationMembers },
{ kind: GetConversationReference.$kind, type: GetConversationReference },
{ kind: GotoAction.$kind, type: GotoAction },
{ kind: HttpRequest.$kind, type: HttpRequest },
{ kind: IfCondition.$kind, type: IfCondition },
{ kind: LogAction.$kind, type: LogAction },
{ kind: RepeatDialog.$kind, type: RepeatDialog },
{ kind: ReplaceDialog.$kind, type: ReplaceDialog },
{ kind: SendActivity.$kind, type: SendActivity },
{ kind: SendHandoffActivity.$kind, type: SendHandoffActivity },
{ kind: SetProperties.$kind, type: SetProperties },
{ kind: SetProperty.$kind, type: SetProperty },
{ kind: SignOutUser.$kind, type: SignOutUser },
{ kind: SwitchCondition.$kind, type: SwitchCondition },
{ kind: TelemetryTrackEventAction.$kind, type: TelemetryTrackEventAction },
{ kind: ThrowException.$kind, type: ThrowException },
{ kind: TraceActivity.$kind, type: TraceActivity },
{ kind: UpdateActivity.$kind, type: UpdateActivity },
// Trigger conditions
{ kind: OnActivity.$kind, type: OnActivity },
{ kind: OnAssignEntity.$kind, type: OnAssignEntity },
{ kind: OnBeginDialog.$kind, type: OnBeginDialog },
{ kind: OnCancelDialog.$kind, type: OnCancelDialog },
{ kind: OnChooseEntity.$kind, type: OnChooseEntity },
{ kind: OnChooseIntent.$kind, type: OnChooseIntent },
{ kind: OnChooseProperty.$kind, type: OnChooseProperty },
{ kind: OnCommandActivity.$kind, type: OnCommandActivity },
{ kind: OnCommandResultActivity.$kind, type: OnCommandResultActivity },
{ kind: OnCondition.$kind, type: OnCondition },
{ kind: OnContinueConversation.$kind, type: OnContinueConversation },
{ kind: OnConversationUpdateActivity.$kind, type: OnConversationUpdateActivity },
{ kind: OnDialogEvent.$kind, type: OnDialogEvent },
{ kind: OnEndOfActions.$kind, type: OnEndOfActions },
{ kind: OnEndOfConversationActivity.$kind, type: OnEndOfConversationActivity },
{ kind: OnError.$kind, type: OnError },
{ kind: OnEventActivity.$kind, type: OnEventActivity },
{ kind: OnHandoffActivity.$kind, type: OnHandoffActivity },
{ kind: OnInstallationUpdateActivity.$kind, type: OnInstallationUpdateActivity },
{ kind: OnIntent.$kind, type: OnIntent },
{ kind: OnInvokeActivity.$kind, type: OnInvokeActivity },
{ kind: OnMessageActivity.$kind, type: OnMessageActivity },
{ kind: OnMessageDeleteActivity.$kind, type: OnMessageDeleteActivity },
{ kind: OnMessageReactionActivity.$kind, type: OnMessageReactionActivity },
{ kind: OnMessageUpdateActivity.$kind, type: OnMessageUpdateActivity },
{ kind: OnQnAMatch.$kind, type: OnQnAMatch },
{ kind: OnRepromptDialog.$kind, type: OnRepromptDialog },
{ kind: OnTypingActivity.$kind, type: OnTypingActivity },
{ kind: OnUnknownIntent.$kind, type: OnUnknownIntent },
// Inputs
{ kind: Ask.$kind, type: Ask },
{ kind: AttachmentInput.$kind, type: AttachmentInput },
{ kind: ChoiceInput.$kind, type: ChoiceInput },
{ kind: ConfirmInput.$kind, type: ConfirmInput },
{ kind: DateTimeInput.$kind, type: DateTimeInput },
{ kind: NumberInput.$kind, type: NumberInput },
{ kind: OAuthInput.$kind, type: OAuthInput },
{ kind: TextInput.$kind, type: TextInput },
// Recognizers
{ kind: CrossTrainedRecognizerSet.$kind, type: CrossTrainedRecognizerSet },
{ kind: MultiLanguageRecognizer.$kind, type: MultiLanguageRecognizer },
{ kind: RecognizerSet.$kind, type: RecognizerSet },
{ kind: RegexRecognizer.$kind, type: RegexRecognizer },
{ kind: AgeEntityRecognizer.$kind, type: AgeEntityRecognizer },
{ kind: ChannelMentionEntityRecognizer.$kind, type: ChannelMentionEntityRecognizer },
{ kind: ConfirmationEntityRecognizer.$kind, type: ConfirmationEntityRecognizer },
{ kind: CurrencyEntityRecognizer.$kind, type: CurrencyEntityRecognizer },
{ kind: DateTimeEntityRecognizer.$kind, type: DateTimeEntityRecognizer },
{ kind: DimensionEntityRecognizer.$kind, type: DimensionEntityRecognizer },
{ kind: EmailEntityRecognizer.$kind, type: EmailEntityRecognizer },
{ kind: EntityRecognizerSet.$kind, type: EntityRecognizerSet },
{ kind: GuidEntityRecognizer.$kind, type: GuidEntityRecognizer },
{ kind: HashtagEntityRecognizer.$kind, type: HashtagEntityRecognizer },
{ kind: IpEntityRecognizer.$kind, type: IpEntityRecognizer },
{ kind: MentionEntityRecognizer.$kind, type: MentionEntityRecognizer },
{ kind: NumberEntityRecognizer.$kind, type: NumberEntityRecognizer },
{ kind: OrdinalEntityRecognizer.$kind, type: OrdinalEntityRecognizer },
{ kind: PercentageEntityRecognizer.$kind, type: PercentageEntityRecognizer },
{ kind: PhoneNumberEntityRecognizer.$kind, type: PhoneNumberEntityRecognizer },
{ kind: RegexEntityRecognizer.$kind, type: RegexEntityRecognizer },
{ kind: TemperatureEntityRecognizer.$kind, type: TemperatureEntityRecognizer },
{ kind: UrlEntityRecognizer.$kind, type: UrlEntityRecognizer },
// Generators
{ kind: TemplateEngineLanguageGenerator.$kind, type: TemplateEngineLanguageGenerator },
{ kind: ResourceMultiLanguageGenerator.$kind, type: ResourceMultiLanguageGenerator },
// Selectors
{ kind: ConditionalSelector.$kind, type: ConditionalSelector },
{ kind: FirstSelector.$kind, type: FirstSelector },
{ kind: RandomSelector.$kind, type: RandomSelector },
{ kind: TrueSelector.$kind, type: TrueSelector },
{ kind: MostSpecificSelector.$kind, type: MostSpecificSelector },
];
},
},
{
getDeclarativeTypes(resourceExplorer) {
return resourceExplorer
.getResources('.schema')
.map((schema) => schema.id.replace(/.schema$/, ''))
.filter((resourceId) => resourceId.endsWith('.dialog'))
.map((resourceId) => ({
kind: resourceId,
type: DynamicBeginDialog,
loader: new DynamicBeginDialogDeserializer(resourceExplorer, resourceId),
}));
},
}
)
);
}
} | the_stack |
describe('Toolbox', () => {
beforeEach(() => {
cy.visit('/');
cy.getByTestId('card-top').as('card-top');
cy.getByTestId('card-bottom').as('card-bottom');
cy.getByTestId('root-container').as('root-container');
cy.getByTestId('frame-container').as('frame-container');
});
describe('Test Toolbox Button', () => {
beforeEach(() => {
cy.getByTestId('toolbox-button')
.as('toolbox-button')
.should('have.attr', 'draggable', 'true');
});
it('should be possible to drag buttons to the bottom of the card', () => {
cy.getByTestId('card-bottom-button').as('target-button');
// we verify that there only is one button in the CardBottom component
cy.get('@card-bottom').children().should('have.length', 1);
// we drag the button from the toolbox over the button inside the CardBottom
cy.get('@toolbox-button').dragOver('@target-button', {
position: 'right',
});
// the success DropIndicator should be visible
cy.getDropIndicator('success').should('exist');
// we trigger the drop
cy.get('@toolbox-button').drop();
// there should be two components now
cy.get('@card-bottom').children().should('have.length', 2);
// and both should be buttons
cy.get('@target-button').parent().find('button').should('have.length', 2);
// we now drop a button to the left of the target button
cy.get('@toolbox-button').dragAndDrop('@target-button', {
position: 'left',
});
// there should be three components now
cy.get('@target-button').parent().children().should('have.length', 3);
// and all of them should be buttons
cy.get('@target-button').parent().find('button').should('have.length', 3);
// the @target-button should be in the middle
cy.get('@card-bottom')
.children()
.then((children) => children[1])
.contains('Only buttons down here');
});
it('should not be possible to drag buttons to the top of the card', () => {
cy.getByTestId('card-top-text-1').as('target-text');
// we verify that CardTop has currently only 2 elements inside
cy.get('@card-top').children().should('have.length', 2);
// we drag the button to the CardTop
cy.get('@toolbox-button').dragOver('@target-text');
// the error indicator should indicate that it is not possible to drop here
cy.getDropIndicator('error').should('exist');
// we trigger the drop
cy.get('@toolbox-button').drop();
// there still should only be 2 children
cy.get('@card-top').children().should('have.length', 2);
});
it('should be possible to drop buttons anywhere else', () => {
cy.getByTestId('frame-button').as('target-button');
// there should be only one button in the editor
cy.get('@root-container').contains('Click me').should('have.length', 1);
// let's first drop next to the "Click me" button
cy.get('@toolbox-button').dragAndDrop('@target-button', {
position: 'right',
});
// there should now be two buttons
cy.get('@root-container')
.find('button:contains("Click me")')
.should('have.length', 2);
// we now drop the button below "Hi world!"
cy.getByTestId('frame-text').as('target-text');
cy.get('@toolbox-button').dragAndDrop('@target-text', {
position: 'below',
});
// there should now be three buttons
cy.get('@root-container')
.find('button:contains("Click me")')
.should('have.length', 3);
// lastly we try to drop the button inside the Container
// this time we do not want to drop the button on one element already inside the container
// but directly into the container
// before we drag & drop there should be only one element inside the container
cy.get('@frame-container').children().should('have.length', 1);
// we drop inside the container
cy.get('@toolbox-button').dragAndDrop('@frame-container', {
position: 'inside',
});
// there now should be two elements inside the container
cy.get('@frame-container').children().should('have.length', 2);
});
});
describe('Test Toolbox Text', () => {
beforeEach(() => {
cy.getByTestId('toolbox-text')
.as('toolbox-text')
.should('have.attr', 'draggable', 'true');
});
// this is basically the same test as the button test
it('should be possible to drop texts inside the CardTop component', () => {
cy.getByTestId('card-top-text-2').as('target-text');
// before we start we verify that CardTop currently has 2 elements
cy.get('@card-top').children().should('have.length', 2);
// this time we test if it's possible to drop between elements by dropping above the second element
cy.get('@toolbox-text').dragAndDrop('@target-text', {
position: 'above',
});
// we now should have 3 elements
cy.get('@card-top').children().should('have.length', 3);
// the element in the middle should be the dropped element
cy.get('@card-top')
.children()
.then(($children) => $children[1])
.contains('Hi world');
});
// this too, is basically the same test as the one we used to test the Toolbox Button
it('should not be possible to drop texts inside the CardBottom component', () => {
// before we start we verify that the CardBottom currently has only one element
cy.get('@card-bottom').children().should('have.length', 1);
// we drag the Text from the toolbox over the CardBottom component
cy.get('@toolbox-text').dragOver('@card-bottom', {
position: 'inside',
});
// the error indicator should be visible (in the button test, we tested for existence which in our case is the same as being visible)
cy.getDropIndicator('error').should('be.visible');
// we drop the text (inside the CardBottom)...
cy.get('@toolbox-text').drop();
// ... which should not be possible. That's why we verify that the CardBottom still only has one element
cy.get('@card-bottom').children().should('have.length', 1);
});
const numberOfElements = 25;
// because we do not want to copy the whole button test, we try to test something different
// TODO cypress or craft get slower which each Text element dropped. Investigate whether it's cypress, or craft
// currently my money is on cypress
it(`should be possible to drop ${numberOfElements} texts somewhere under root`, () => {
// before we drop $numberOfElements elements we verify that we start with 4 elements
cy.get('@root-container').children().should('have.length', 4);
for (let count = 0; count < numberOfElements; count++) {
cy.get('@toolbox-text').dragAndDrop('@root-container', {
position: 'inside',
});
// we add the wait (for 1ms) here, otherwise cypress tries to bulk run the drag and drop and seems to freeze
cy.wait(1);
}
// afterwards there should be $numberOfElements + the starting 4 elements under root
cy.get('@root-container')
.children()
.should('have.length', numberOfElements + 4);
});
});
describe('Test Toolbox Container', () => {
beforeEach(() => {
cy.getByTestId('toolbox-container')
.as('toolbox-container')
.should('have.attr', 'draggable', 'true');
});
it('should neither be possible to drop Container inside CardTop nor CardBottom', () => {
[
{
cardPosition: 'top',
expectedChildren: 2,
},
{
cardPosition: 'bottom',
expectedChildren: 1,
},
].forEach(({ cardPosition, expectedChildren }) => {
// like in the other tests we first verify the number of children
cy.get(`@card-${cardPosition}`)
.children()
.should('have.length', expectedChildren);
// then drag the container over the CardTop or CardBottom component
cy.get('@toolbox-container').dragOver(`@card-${cardPosition}`, {
position: 'inside',
});
// we expect the error drop indicator to exist
cy.getDropIndicator('error').should('exist');
cy.get('@toolbox-container').drop();
// after dropping we expect the number of children to be the same as before
cy.get(`@card-${cardPosition}`)
.children()
.should('have.length', expectedChildren);
});
});
// in this test we want to test if ware able to nest containers (drop Containers inside Containers)
it('should be possible to nest Containers', () => {
// again: before we start we verify the number of elements under root
cy.get('@root-container').children().should('have.length', 4);
// the first container will be dropped under root
cy.get('@toolbox-container').dragAndDrop('@root-container', {
position: 'inside',
});
// the first container we dropped, is the first container under root
cy.get('@root-container')
.children()
.then(($children) => $children[0])
.as('first-container');
// we drop the second container inside the first container
cy.get('@toolbox-container').dragAndDrop('@first-container', {
position: 'inside',
});
cy.get('@first-container')
.children()
.then(($children) => $children[0])
.as('second-container');
// and the third container is dropped inside the second container
cy.get('@toolbox-container').dragAndDrop('@second-container', {
position: 'inside',
});
// we now verify that we dropped correctly
cy.get('@root-container').children().should('have.length', 5);
cy.get('@first-container').children().should('have.length', 1);
cy.get('@second-container').children().should('have.length', 1);
});
});
describe('Test Toolbox Card', () => {
beforeEach(() => {
cy.getByTestId('toolbox-card')
.as('toolbox-card')
.should('have.attr', 'draggable', 'true');
});
it('should not be possible to drop the Card in CardTop or CardBottom', () => {
[
{
cardPosition: 'top',
expectedChildren: 2,
},
{
cardPosition: 'bottom',
expectedChildren: 1,
},
].forEach(({ cardPosition, expectedChildren }) => {
// like in the other tests we first verify the number of children
cy.get(`@card-${cardPosition}`)
.children()
.should('have.length', expectedChildren);
// then drag the Card over the CardTop or CardBottom component
cy.get('@toolbox-card').dragOver(`@card-${cardPosition}`, {
position: 'inside',
});
// we expect the error drop indicator to exist
cy.getDropIndicator('error').should('exist');
cy.get('@toolbox-card').drop();
// after dropping we expect the number of children to be the same as before
cy.get(`@card-${cardPosition}`)
.children()
.should('have.length', expectedChildren);
});
});
it('should be possible to drop the Card in root as the last element', () => {
cy.get('@root-container').children().should('have.length', 4);
cy.get('@toolbox-card').dragAndDrop('@frame-container', {
position: 'below',
});
cy.get('@root-container').children().should('have.length', 5);
cy.get('@root-container')
.children()
.then(($children) => $children[$children.length - 1])
.within(() => {
cy.contains('Only texts');
cy.contains('are allowed up here');
cy.contains('Only buttons down here');
});
});
});
describe('Test Toolbox when editor is disabled', () => {
it('should not be possible to drag elements when the editor is disabled', () => {
// first we disable the editor
cy.contains('Enable').click();
// since we want to reuse the "toolbox-component" alias we use cy.wrap().each()
cy.wrap(['button', 'text', 'container', 'card']).each((component) => {
cy.get('@root-container').children().should('have.length', 4);
// none of the components should have the 'draggable' attribute
cy.getByTestId(`toolbox-${component}`)
.as(`toolbox-component`)
.should('not.have.attr', 'draggable');
// it should not be possible to drag the elements.
cy.get('@toolbox-component').dragAndDrop('@root-container', {
position: 'inside',
});
cy.get('@root-container').children().should('have.length', 4);
});
});
});
}); | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as msRestAzure from "@azure/ms-rest-azure-js";
import * as Models from "../models";
import * as Mappers from "../models/dedicatedCloudServicesMappers";
import * as Parameters from "../models/parameters";
import { VMwareCloudSimpleClientContext } from "../vMwareCloudSimpleClientContext";
/** Class representing a DedicatedCloudServices. */
export class DedicatedCloudServices {
private readonly client: VMwareCloudSimpleClientContext;
/**
* Create a DedicatedCloudServices.
* @param {VMwareCloudSimpleClientContext} client Reference to the service client.
*/
constructor(client: VMwareCloudSimpleClientContext) {
this.client = client;
}
/**
* Returns list of dedicated cloud services within a subscription
* @summary Implements list of dedicatedCloudService objects within subscription method
* @param [options] The optional parameters
* @returns Promise<Models.DedicatedCloudServicesListBySubscriptionResponse>
*/
listBySubscription(options?: Models.DedicatedCloudServicesListBySubscriptionOptionalParams): Promise<Models.DedicatedCloudServicesListBySubscriptionResponse>;
/**
* @param callback The callback
*/
listBySubscription(callback: msRest.ServiceCallback<Models.DedicatedCloudServiceListResponse>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
listBySubscription(options: Models.DedicatedCloudServicesListBySubscriptionOptionalParams, callback: msRest.ServiceCallback<Models.DedicatedCloudServiceListResponse>): void;
listBySubscription(options?: Models.DedicatedCloudServicesListBySubscriptionOptionalParams | msRest.ServiceCallback<Models.DedicatedCloudServiceListResponse>, callback?: msRest.ServiceCallback<Models.DedicatedCloudServiceListResponse>): Promise<Models.DedicatedCloudServicesListBySubscriptionResponse> {
return this.client.sendOperationRequest(
{
options
},
listBySubscriptionOperationSpec,
callback) as Promise<Models.DedicatedCloudServicesListBySubscriptionResponse>;
}
/**
* Returns list of dedicated cloud services within a resource group
* @summary Implements list of dedicatedCloudService objects within RG method
* @param resourceGroupName The name of the resource group
* @param [options] The optional parameters
* @returns Promise<Models.DedicatedCloudServicesListByResourceGroupResponse>
*/
listByResourceGroup(resourceGroupName: string, options?: Models.DedicatedCloudServicesListByResourceGroupOptionalParams): Promise<Models.DedicatedCloudServicesListByResourceGroupResponse>;
/**
* @param resourceGroupName The name of the resource group
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.DedicatedCloudServiceListResponse>): void;
/**
* @param resourceGroupName The name of the resource group
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, options: Models.DedicatedCloudServicesListByResourceGroupOptionalParams, callback: msRest.ServiceCallback<Models.DedicatedCloudServiceListResponse>): void;
listByResourceGroup(resourceGroupName: string, options?: Models.DedicatedCloudServicesListByResourceGroupOptionalParams | msRest.ServiceCallback<Models.DedicatedCloudServiceListResponse>, callback?: msRest.ServiceCallback<Models.DedicatedCloudServiceListResponse>): Promise<Models.DedicatedCloudServicesListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
options
},
listByResourceGroupOperationSpec,
callback) as Promise<Models.DedicatedCloudServicesListByResourceGroupResponse>;
}
/**
* Returns Dedicate Cloud Service
* @summary Implements dedicatedCloudService GET method
* @param resourceGroupName The name of the resource group
* @param dedicatedCloudServiceName dedicated cloud Service name
* @param [options] The optional parameters
* @returns Promise<Models.DedicatedCloudServicesGetResponse>
*/
get(resourceGroupName: string, dedicatedCloudServiceName: string, options?: msRest.RequestOptionsBase): Promise<Models.DedicatedCloudServicesGetResponse>;
/**
* @param resourceGroupName The name of the resource group
* @param dedicatedCloudServiceName dedicated cloud Service name
* @param callback The callback
*/
get(resourceGroupName: string, dedicatedCloudServiceName: string, callback: msRest.ServiceCallback<Models.DedicatedCloudService>): void;
/**
* @param resourceGroupName The name of the resource group
* @param dedicatedCloudServiceName dedicated cloud Service name
* @param options The optional parameters
* @param callback The callback
*/
get(resourceGroupName: string, dedicatedCloudServiceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DedicatedCloudService>): void;
get(resourceGroupName: string, dedicatedCloudServiceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DedicatedCloudService>, callback?: msRest.ServiceCallback<Models.DedicatedCloudService>): Promise<Models.DedicatedCloudServicesGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
dedicatedCloudServiceName,
options
},
getOperationSpec,
callback) as Promise<Models.DedicatedCloudServicesGetResponse>;
}
/**
* Create dedicate cloud service
* @summary Implements dedicated cloud service PUT method
* @param resourceGroupName The name of the resource group
* @param dedicatedCloudServiceName dedicated cloud Service name
* @param dedicatedCloudServiceRequest Create Dedicated Cloud Service request
* @param [options] The optional parameters
* @returns Promise<Models.DedicatedCloudServicesCreateOrUpdateResponse>
*/
createOrUpdate(resourceGroupName: string, dedicatedCloudServiceName: string, dedicatedCloudServiceRequest: Models.DedicatedCloudService, options?: msRest.RequestOptionsBase): Promise<Models.DedicatedCloudServicesCreateOrUpdateResponse>;
/**
* @param resourceGroupName The name of the resource group
* @param dedicatedCloudServiceName dedicated cloud Service name
* @param dedicatedCloudServiceRequest Create Dedicated Cloud Service request
* @param callback The callback
*/
createOrUpdate(resourceGroupName: string, dedicatedCloudServiceName: string, dedicatedCloudServiceRequest: Models.DedicatedCloudService, callback: msRest.ServiceCallback<Models.DedicatedCloudService>): void;
/**
* @param resourceGroupName The name of the resource group
* @param dedicatedCloudServiceName dedicated cloud Service name
* @param dedicatedCloudServiceRequest Create Dedicated Cloud Service request
* @param options The optional parameters
* @param callback The callback
*/
createOrUpdate(resourceGroupName: string, dedicatedCloudServiceName: string, dedicatedCloudServiceRequest: Models.DedicatedCloudService, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DedicatedCloudService>): void;
createOrUpdate(resourceGroupName: string, dedicatedCloudServiceName: string, dedicatedCloudServiceRequest: Models.DedicatedCloudService, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DedicatedCloudService>, callback?: msRest.ServiceCallback<Models.DedicatedCloudService>): Promise<Models.DedicatedCloudServicesCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
dedicatedCloudServiceName,
dedicatedCloudServiceRequest,
options
},
createOrUpdateOperationSpec,
callback) as Promise<Models.DedicatedCloudServicesCreateOrUpdateResponse>;
}
/**
* Delete dedicate cloud service
* @summary Implements dedicatedCloudService DELETE method
* @param resourceGroupName The name of the resource group
* @param dedicatedCloudServiceName dedicated cloud service name
* @param [options] The optional parameters
* @returns Promise<Models.DedicatedCloudServicesDeleteResponse>
*/
deleteMethod(resourceGroupName: string, dedicatedCloudServiceName: string, options?: msRest.RequestOptionsBase): Promise<Models.DedicatedCloudServicesDeleteResponse> {
return this.beginDeleteMethod(resourceGroupName,dedicatedCloudServiceName,options)
.then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.DedicatedCloudServicesDeleteResponse>;
}
/**
* Patch dedicated cloud service's properties
* @summary Implements dedicatedCloudService PATCH method
* @param resourceGroupName The name of the resource group
* @param dedicatedCloudServiceName dedicated cloud service name
* @param [options] The optional parameters
* @returns Promise<Models.DedicatedCloudServicesUpdateResponse>
*/
update(resourceGroupName: string, dedicatedCloudServiceName: string, options?: Models.DedicatedCloudServicesUpdateOptionalParams): Promise<Models.DedicatedCloudServicesUpdateResponse>;
/**
* @param resourceGroupName The name of the resource group
* @param dedicatedCloudServiceName dedicated cloud service name
* @param callback The callback
*/
update(resourceGroupName: string, dedicatedCloudServiceName: string, callback: msRest.ServiceCallback<Models.DedicatedCloudService>): void;
/**
* @param resourceGroupName The name of the resource group
* @param dedicatedCloudServiceName dedicated cloud service name
* @param options The optional parameters
* @param callback The callback
*/
update(resourceGroupName: string, dedicatedCloudServiceName: string, options: Models.DedicatedCloudServicesUpdateOptionalParams, callback: msRest.ServiceCallback<Models.DedicatedCloudService>): void;
update(resourceGroupName: string, dedicatedCloudServiceName: string, options?: Models.DedicatedCloudServicesUpdateOptionalParams | msRest.ServiceCallback<Models.DedicatedCloudService>, callback?: msRest.ServiceCallback<Models.DedicatedCloudService>): Promise<Models.DedicatedCloudServicesUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
dedicatedCloudServiceName,
options
},
updateOperationSpec,
callback) as Promise<Models.DedicatedCloudServicesUpdateResponse>;
}
/**
* Delete dedicate cloud service
* @summary Implements dedicatedCloudService DELETE method
* @param resourceGroupName The name of the resource group
* @param dedicatedCloudServiceName dedicated cloud service name
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginDeleteMethod(resourceGroupName: string, dedicatedCloudServiceName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
resourceGroupName,
dedicatedCloudServiceName,
options
},
beginDeleteMethodOperationSpec,
options);
}
/**
* Returns list of dedicated cloud services within a subscription
* @summary Implements list of dedicatedCloudService objects within subscription method
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.DedicatedCloudServicesListBySubscriptionNextResponse>
*/
listBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.DedicatedCloudServicesListBySubscriptionNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listBySubscriptionNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.DedicatedCloudServiceListResponse>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listBySubscriptionNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DedicatedCloudServiceListResponse>): void;
listBySubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DedicatedCloudServiceListResponse>, callback?: msRest.ServiceCallback<Models.DedicatedCloudServiceListResponse>): Promise<Models.DedicatedCloudServicesListBySubscriptionNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listBySubscriptionNextOperationSpec,
callback) as Promise<Models.DedicatedCloudServicesListBySubscriptionNextResponse>;
}
/**
* Returns list of dedicated cloud services within a resource group
* @summary Implements list of dedicatedCloudService objects within RG method
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.DedicatedCloudServicesListByResourceGroupNextResponse>
*/
listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.DedicatedCloudServicesListByResourceGroupNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.DedicatedCloudServiceListResponse>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.DedicatedCloudServiceListResponse>): void;
listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.DedicatedCloudServiceListResponse>, callback?: msRest.ServiceCallback<Models.DedicatedCloudServiceListResponse>): Promise<Models.DedicatedCloudServicesListByResourceGroupNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByResourceGroupNextOperationSpec,
callback) as Promise<Models.DedicatedCloudServicesListByResourceGroupNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listBySubscriptionOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.VMwareCloudSimple/dedicatedCloudServices",
urlParameters: [
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion,
Parameters.filter,
Parameters.top,
Parameters.skipToken
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.DedicatedCloudServiceListResponse
},
default: {
bodyMapper: Mappers.CSRPError
}
},
serializer
};
const listByResourceGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.VMwareCloudSimple/dedicatedCloudServices",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName
],
queryParameters: [
Parameters.apiVersion,
Parameters.filter,
Parameters.top,
Parameters.skipToken
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.DedicatedCloudServiceListResponse
},
default: {
bodyMapper: Mappers.CSRPError
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.VMwareCloudSimple/dedicatedCloudServices/{dedicatedCloudServiceName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.dedicatedCloudServiceName0
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.DedicatedCloudService
},
default: {
bodyMapper: Mappers.CSRPError
}
},
serializer
};
const createOrUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.VMwareCloudSimple/dedicatedCloudServices/{dedicatedCloudServiceName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.dedicatedCloudServiceName1
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "dedicatedCloudServiceRequest",
mapper: {
...Mappers.DedicatedCloudService,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.DedicatedCloudService
},
default: {
bodyMapper: Mappers.CSRPError
}
},
serializer
};
const updateOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.VMwareCloudSimple/dedicatedCloudServices/{dedicatedCloudServiceName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.dedicatedCloudServiceName0
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: {
tags: [
"options",
"tags"
]
},
mapper: {
...Mappers.PatchPayload,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.DedicatedCloudService
},
default: {
bodyMapper: Mappers.CSRPError
}
},
serializer
};
const beginDeleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.VMwareCloudSimple/dedicatedCloudServices/{dedicatedCloudServiceName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.dedicatedCloudServiceName0
],
queryParameters: [
Parameters.apiVersion
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
204: {
headersMapper: Mappers.DedicatedCloudServicesDeleteHeaders
},
default: {
bodyMapper: Mappers.CSRPError
}
},
serializer
};
const listBySubscriptionNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.DedicatedCloudServiceListResponse
},
default: {
bodyMapper: Mappers.CSRPError
}
},
serializer
};
const listByResourceGroupNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.DedicatedCloudServiceListResponse
},
default: {
bodyMapper: Mappers.CSRPError
}
},
serializer
}; | the_stack |
import { mount, ReactWrapper, shallow } from 'enzyme';
import React from 'react';
import { act } from 'react-dom/test-utils';
import { Else, Fallback, If, Then } from '../src';
import type { ExtendablePromise } from '../src/types';
const waitForComponentToPaint = async (wrapped: ReactWrapper) => {
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 0));
wrapped.update();
});
};
describe('<If /> component', () => {
describe('Truthy cases', () => {
describe('With NODE_ENV === test', () => {
test('GIVEN <Then /> THEN renders children', () => {
const wrapped = shallow(
<If condition={true}>
<Then>
<span>Then</span>
</Then>
</If>
);
expect(wrapped).toMatchSnapshot();
expect(wrapped.containsMatchingElement(<span>Then</span>)).toBe(true);
});
test('GIVEN <Then /> & <Else /> THEN renders children of <Then />', () => {
const wrapped = shallow(
<If condition={true}>
<Then>
<span>Then</span>
</Then>
<Else>
<span>Else</span>
</Else>
</If>
);
expect(wrapped).toMatchSnapshot();
expect(wrapped.containsMatchingElement(<span>Then</span>)).toBe(true);
expect(wrapped.containsMatchingElement(<span>Else</span>)).toBe(false);
});
test('GIVEN multiple <Then /> blocks THEN renders only first <Then /> block', () => {
const wrapped = shallow(
<If condition={true}>
<Then>
<span>Then1</span>
</Then>
<Then>
<span>Then2</span>
</Then>
</If>
);
expect(wrapped).toMatchSnapshot();
expect(wrapped.containsMatchingElement(<span>Then1</span>)).toBe(true);
expect(wrapped.containsMatchingElement(<span>Then2</span>)).toBe(false);
});
test('GIVEN <Else /> before <Then /> THEN renders <Then /> block', () => {
const wrapped = shallow(
<If condition={true}>
<Else>
<span>Else</span>
</Else>
<Then>
<span>Then</span>
</Then>
</If>
);
expect(wrapped).toMatchSnapshot();
expect(wrapped.containsMatchingElement(<span>Then</span>)).toBe(true);
expect(wrapped.containsMatchingElement(<span>Else</span>)).toBe(false);
});
test('GIVEN w/o children THEN renders null', () => {
const wrapped = shallow(<If condition={true} />);
expect(wrapped).toMatchSnapshot();
expect(wrapped.html()).toBeNull();
});
});
describe('With NODE_ENV === production', () => {
beforeEach(() => {
// @ts-expect-error __DEV__ is exposed by Jest
global.__DEV__ = false;
});
afterAll(() => {
// @ts-expect-error __DEV__ is exposed by Jest
global.__DEV__ = true;
});
test('GIVEN content w/o <Then /> nor <Else /> THEN renders empty block in production', () => {
const wrapped = shallow(
<If condition={true}>
<span>Not Then nor Else</span>
</If>
);
expect(wrapped).toMatchSnapshot();
expect(wrapped.containsMatchingElement(<span>Not Then nor Else</span>)).toBe(true);
});
});
describe('With condition as a function', () => {
test('GIVEN <Then /> THEN renders children of <Then />', () => {
const wrapped = shallow(
<If condition={() => true}>
<Then>
<span>Then</span>
</Then>
</If>
);
expect(wrapped).toMatchSnapshot();
expect(wrapped.containsMatchingElement(<span>Then</span>)).toBe(true);
});
test('GIVEN <Then /> & <Else /> THEN does not render children of <Else />', () => {
const wrapped = shallow(
<If condition={() => true}>
<Then>
<span>Then</span>
</Then>
<Else>
<span>Else</span>
</Else>
</If>
);
expect(wrapped).toMatchSnapshot();
expect(wrapped.containsMatchingElement(<span>Then</span>)).toBe(true);
expect(wrapped.containsMatchingElement(<span>Else</span>)).toBe(false);
});
test('GIVEN multiple <Then /> blocks THEN renders only first <Then /> block', () => {
const wrapped = shallow(
<If condition={() => true}>
<Then>
<span>Then1</span>
</Then>
<Then>
<span>Then2</span>
</Then>
</If>
);
expect(wrapped).toMatchSnapshot();
expect(wrapped.containsMatchingElement(<span>Then1</span>)).toBe(true);
expect(wrapped.containsMatchingElement(<span>Then2</span>)).toBe(false);
});
test('GIVEN <Else /> before <Then /> THEN renders <Then /> block', () => {
const wrapped = shallow(
<If condition={() => true}>
<Else>
<span>Else</span>
</Else>
<Then>
<span>Then</span>
</Then>
</If>
);
expect(wrapped).toMatchSnapshot();
expect(wrapped.containsMatchingElement(<span>Then</span>)).toBe(true);
expect(wrapped.containsMatchingElement(<span>Else</span>)).toBe(false);
});
});
describe('With condition as a promise', () => {
test('GIVEN pending promise THEN renders <Fallback /> block', () => {
// eslint-disable-next-line @typescript-eslint/no-empty-function
const pendingPromise = new Promise(() => {});
const wrapped: ReactWrapper = mount(
<If condition={pendingPromise}>
<Fallback>
<span>Fallback</span>
</Fallback>
<Then>
<span>Then</span>
</Then>
<Else>
<span>Else</span>
</Else>
</If>
);
expect(wrapped).toMatchSnapshot();
expect(wrapped.containsMatchingElement(<span>Fallback</span>)).toBe(true);
expect(wrapped.containsMatchingElement(<span>Then</span>)).toBe(false);
expect(wrapped.containsMatchingElement(<span>Else</span>)).toBe(false);
});
test('GIVEN resolved promise THEN renders <THEN /> block', async () => {
const wrapped: ReactWrapper = mount(
<If condition={Promise.resolve()}>
<Fallback>
<span>Fallback</span>
</Fallback>
<Then>
<span>Then</span>
</Then>
<Else>
<span>Else</span>
</Else>
</If>
);
await waitForComponentToPaint(wrapped);
expect(wrapped).toMatchSnapshot();
expect(wrapped.containsMatchingElement(<span>Fallback</span>)).toBe(false);
expect(wrapped.containsMatchingElement(<span>Then</span>)).toBe(true);
expect(wrapped.containsMatchingElement(<span>Else</span>)).toBe(false);
});
test('GIVEN resolved promise THEN can retrieve return value inside THEN block', async () => {
const returnValue = 'RETURN_VALUE';
const wrapped: ReactWrapper = mount(
<If condition={Promise.resolve(returnValue)}>
<Then>{(something: any) => <span>{something}</span>}</Then>
</If>
);
await waitForComponentToPaint(wrapped);
expect(wrapped.containsMatchingElement(<span>{returnValue}</span>)).toBe(true);
});
test('GIVEN promise with extra properties THEN should forward these properties to function param inside <Then />', async () => {
const extendedPromise: ExtendablePromise<void> = Promise.resolve();
extendedPromise.testValue = 1;
const wrapped: ReactWrapper = mount(
<If condition={extendedPromise}>
<Then>
{(data: any, history: any, promise: any) => {
data;
history; // 'skip declared but value never read' error
return <span>{promise.testValue}</span>;
}}
</Then>
</If>
);
await waitForComponentToPaint(wrapped);
expect(wrapped.containsMatchingElement(<span>{extendedPromise.testValue}</span>));
});
});
});
describe('Falsy condition', () => {
describe('With NODE_ENV === test', () => {
test('GIVEN <Then /> THEN renders null', () => {
const wrapped = shallow(
<If condition={false}>
<Then>
<span>Then</span>
</Then>
</If>
);
expect(wrapped).toMatchSnapshot();
expect(wrapped.containsMatchingElement(<span>Then</span>)).toBe(false);
expect(wrapped.html()).toBe('');
});
test('GIVEN <Then /> & <Else /> THEN renders children of <Else />', () => {
const wrapped = shallow(
<If condition={false}>
<Then>
<span>Then</span>
</Then>
<Else>
<span>Else</span>
</Else>
</If>
);
expect(wrapped).toMatchSnapshot();
expect(wrapped.containsMatchingElement(<span>Then</span>)).toBe(false);
expect(wrapped.containsMatchingElement(<span>Else</span>)).toBe(true);
});
test('GIVEN multiple <Else /> THEN renders only first <Else /> block', () => {
const wrapped = shallow(
<If condition={false}>
<Else>
<span>Else1</span>
</Else>
<Else>
<span>Else2</span>
</Else>
</If>
);
expect(wrapped).toMatchSnapshot();
expect(wrapped.containsMatchingElement(<span>Else1</span>)).toBe(true);
expect(wrapped.containsMatchingElement(<span>Else2</span>)).toBe(false);
});
test('GIVEN multiple <Else /> before <Then /> THEN renders <Else /> block', () => {
const wrapped = shallow(
<If condition={false}>
<Else>
<span>Else</span>
</Else>
<Then>
<span>Then</span>
</Then>
</If>
);
expect(wrapped).toMatchSnapshot();
expect(wrapped.containsMatchingElement(<span>Else</span>)).toBe(true);
expect(wrapped.containsMatchingElement(<span>Then</span>)).toBe(false);
});
test('GIVEN w/o children THEN renders null', () => {
const wrapped = shallow(<If condition={false} />);
expect(wrapped).toMatchSnapshot();
expect(wrapped.html()).toBeNull();
});
});
describe('With NODE_ENV === production', () => {
beforeEach(() => {
// @ts-expect-error __DEV__ is exposed by Jest
global.__DEV__ = false;
});
afterAll(() => {
// @ts-expect-error __DEV__ is exposed by Jest
global.__DEV__ = true;
});
test('GIVEN content w/o <Then /> nor <Else /> THEN renders empty block in production', () => {
const wrapped = shallow(
<If condition={false}>
<span>Not Then nor Else</span>
</If>
);
expect(wrapped).toMatchSnapshot();
expect(wrapped.containsMatchingElement(<span>Not Then nor Else</span>)).toBe(false);
});
});
describe('With child as function', () => {
test('GIVEN <Else /> THEN renders children returned by function', () => {
const wrapped = mount(
<If condition={false}>
<Else>{() => <span>Else</span>}</Else>
</If>
);
expect(wrapped).toMatchSnapshot();
expect(wrapped.containsMatchingElement(<span>Else</span>)).toBe(true);
});
test('GIVEN <Else /> THEN renders children returned by function', () => {
const wrapped = mount(
<If condition={() => false}>
<Else>{() => <span>Else</span>}</Else>
</If>
);
expect(wrapped).toMatchSnapshot();
expect(wrapped.containsMatchingElement(<span>Else</span>)).toBe(true);
});
test('GIVEN body that should not evaluate THEN should not render', () => {
// @ts-expect-error called should just be declared
let called = false;
const wrapped = mount(
<If condition={false}>
<Then>
{() => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
called = true;
<div>Bad</div>;
}}
</Then>
<Else>
<div>Ok</div>
</Else>
</If>
);
expect(wrapped).toMatchSnapshot();
expect(wrapped.containsMatchingElement(<div>Ok</div>)).toBe(true);
expect(wrapped.containsMatchingElement(<div>Bad</div>)).toBe(false);
});
test('GIVEN body that should not evaluate THEN should not render', () => {
// @ts-expect-error called should just be declared
let called = false;
const wrapped = mount(
<If condition={() => false}>
<Then>
{() => {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
called = true;
<div>Bad</div>;
}}
</Then>
<Else>
<div>Ok</div>
</Else>
</If>
);
expect(wrapped).toMatchSnapshot();
expect(wrapped.containsMatchingElement(<div>Ok</div>)).toBe(true);
expect(wrapped.containsMatchingElement(<div>Bad</div>)).toBe(false);
});
});
describe('With condition as a promise', () => {
test('GIVEN rejected promise THEN renders <ELSE /> block', async () => {
const wrapped: ReactWrapper = mount(
// eslint-disable-next-line prefer-promise-reject-errors
<If condition={Promise.reject()}>
<Fallback>
<span>Fallback</span>
</Fallback>
<Then>
<span>Then</span>
</Then>
<Else>
<span>Else</span>
</Else>
</If>
);
expect(wrapped.containsMatchingElement(<span>Fallback</span>)).toBe(true);
expect(wrapped.containsMatchingElement(<span>Then</span>)).toBe(false);
expect(wrapped.containsMatchingElement(<span>Else</span>)).toBe(false);
await waitForComponentToPaint(wrapped);
expect(wrapped).toMatchSnapshot();
expect(wrapped.containsMatchingElement(<span>Fallback</span>)).toBe(false);
expect(wrapped.containsMatchingElement(<span>Then</span>)).toBe(false);
expect(wrapped.containsMatchingElement(<span>Else</span>)).toBe(true);
});
test('GIVEN rejected promise THEN can retrieve error inside ELSE block', async () => {
const caughtError = 'CAUGHT_ERROR';
const wrapped: ReactWrapper = mount(
<If condition={Promise.reject(caughtError)}>
<Else>{(something: any) => <span>{something}</span>}</Else>
</If>
);
await waitForComponentToPaint(wrapped);
expect(wrapped.containsMatchingElement(<span>{caughtError}</span>)).toBe(true);
});
test('GIVEN promise with extra properties THEN should forward these properties to function param inside <Else />', async () => {
// eslint-disable-next-line prefer-promise-reject-errors
const extendedPromise: ExtendablePromise<void> = Promise.reject();
extendedPromise.testValue = 'TEST_VALUE';
const wrapped: ReactWrapper = mount(
<If condition={extendedPromise}>
<Else>
{(data: any, history: any, promise: any) => {
data;
history; // 'skip declared but value never read' error
return <span>{promise.testValue}</span>;
}}
</Else>
</If>
);
await waitForComponentToPaint(wrapped);
expect(wrapped.containsMatchingElement(<span>{extendedPromise.testValue}</span>));
});
});
});
}); | the_stack |
import * as ui from "../../ui";
import * as csx from '../../base/csx';
import * as React from "react";
import * as tab from "./tab";
import { server, cast } from "../../../socket/socketClient";
import * as commands from "../../commands/commands";
import * as utils from "../../../common/utils";
import * as d3 from "d3";
import { Types } from "../../../socket/socketContract";
import * as types from "../../../common/types";
import { IconType } from "../../../common/types";
import * as $ from "jquery";
import * as styles from "../../styles/styles";
import * as onresize from "onresize";
import { Clipboard } from "../../components/clipboard";
import * as typeIcon from "../../components/typeIcon";
import * as gls from "../../base/gls";
import * as typestyle from "typestyle";
import { MarkDown } from "../../markdown/markdown";
import { blackHighlightColor } from "../../styles/styles";
export interface Props extends tab.TabProps {
}
export interface State {
files?: types.DocumentedType[];
selected?: types.DocumentedType | null;
filtered?: types.DocumentedType[];
filter?: string;
selectedDoesNotMatchFilter?: boolean;
}
export namespace DocumentationViewStyles {
export const header = typestyle.style({
cursor: 'pointer',
$nest: {
'&:hover': {
textDecoration: 'underline'
}
}
});
export const folderName = typestyle.style({
padding: "2px",
fontSize: '.5em',
'-webkit-user-select': 'none',
maxWidth: '200px', overflow: 'hidden', textOverflow: 'ellipsis'
});
}
export class DocumentationView extends ui.BaseComponent<Props, State> {
constructor(props: Props) {
super(props);
this.filePath = utils.getFilePathFromUrl(props.url);
this.state = {
filtered: [],
files: [],
selected: null,
};
}
refs: {
[string: string]: any;
root: HTMLDivElement;
graphRoot: HTMLDivElement;
controlRoot: HTMLDivElement;
}
filePath: string;
componentDidMount() {
/**
* Initial load + load on project change
*/
this.loadData();
this.disposible.add(
cast.activeProjectFilePathsUpdated.on(() => {
this.loadData();
})
);
/**
* If a file is selected and it gets edited, reload the file module information
*/
const isFilePathOfSignificance = (filePath: string) => !!this.state.selected && this.state.selected.location.filePath === filePath;
const reloadSelectedDebounced = utils.debounce((filePath) => {
if (!isFilePathOfSignificance(filePath)) return;
server.getUpdatedModuleInformation({
filePath
}).then((res) => {
if (!isFilePathOfSignificance(filePath)) return;
const files = this.state.files.map(f => { return (f.location.filePath === filePath) ? res : f });
this.setState({ files, selected: res });
this.filter();
})
}, 3000);
this.disposible.add(
commands.fileContentsChanged.on((res) => {
if (!isFilePathOfSignificance(res.filePath)) return;
reloadSelectedDebounced(res.filePath);
})
);
/**
* Handle focus to inform tab container
*/
const focused = () => {
this.props.onFocused();
}
this.refs.root.addEventListener('focus', focused);
this.disposible.add({
dispose: () => {
this.refs.root.removeEventListener('focus', focused);
}
})
// Listen to tab events
const api = this.props.api;
this.disposible.add(api.resize.on(this.resize));
this.disposible.add(api.focus.on(this.focus));
this.disposible.add(api.save.on(this.save));
this.disposible.add(api.close.on(this.close));
this.disposible.add(api.gotoPosition.on(this.gotoPosition));
// Listen to search tab events
this.disposible.add(api.search.doSearch.on(this.search.doSearch));
this.disposible.add(api.search.hideSearch.on(this.search.hideSearch));
this.disposible.add(api.search.findNext.on(this.search.findNext));
this.disposible.add(api.search.findPrevious.on(this.search.findPrevious));
this.disposible.add(api.search.replaceNext.on(this.search.replaceNext));
this.disposible.add(api.search.replacePrevious.on(this.search.replacePrevious));
this.disposible.add(api.search.replaceAll.on(this.search.replaceAll));
}
render() {
return (
<div
ref="root"
tabIndex={0}
style={csx.extend(csx.vertical, csx.flex, csx.newLayerParent, styles.someChildWillScroll, { color: styles.textColor })}
onKeyPress={this.handleKey}>
<div style={{ overflow: 'hidden', padding: '10px 0px 10px 10px', display: 'flex' }}>
<gls.FlexHorizontal style={{}}>
<gls.Content style={{ width: '200px', overflow: 'auto' }}>
<typeIcon.SectionHeader text="Files" />
<gls.SmallVerticalSpace />
{
this.renderFiles()
}
</gls.Content>
<gls.FlexVertical style={{ marginLeft: '5px', overflow: 'auto' }}>
{
this.state.selected && this.state.selectedDoesNotMatchFilter &&
<gls.Content style={{ backgroundColor: '#111', padding: '5px' }}>
Note: Nothing in the selected module matches the filter, so showing it all
</gls.Content>
}
{
this.state.selected
? this.renderSelectedNode()
: 'Select a module from the left to view its documentation 🌹'
}
<div style={{ marginTop: '10px', marginRight: '10px' }}>
<hr />
<typeIcon.TypeIconLegend />
</div>
</gls.FlexVertical>
</gls.FlexHorizontal>
</div>
</div>
);
}
renderFiles() {
/** For two items in different file paths we render the folder name in between */
const toRender: {
folder?: string,
type?: types.DocumentedType,
}[] = [];
let lastKnownFolder = ''
this.state.filtered.forEach(type => {
const folder = utils.getDirectory(type.name);
if (folder !== lastKnownFolder) {
toRender.push({
folder
});
lastKnownFolder = folder;
}
toRender.push({
type
});
});
return toRender.map((item, i) => {
if (item.type) {
const file = item.type;
const name = utils.getFileName(file.name);
const backgroundColor = this.state.selected && this.state.selected.name === file.name
? blackHighlightColor
: 'transparent';
return (
<div
title={file.name}
key={i}
style={{ cursor: 'pointer', backgroundColor, paddingTop: '2px', paddingBottom: '2px', paddingLeft: '2px' }}
onClick={() => this.handleRootSelected(file)}>
<typeIcon.DocumentedTypeHeader name={name} icon={file.icon} />
</div>
)
}
else {
const folder = item.folder;
return (
<div
title={folder}
key={i}
className={DocumentationViewStyles.folderName}>
{folder}
</div>
)
}
});
}
renderSelectedNode() {
const node = this.state.selected;
return this.renderNode(node);
}
renderNode(node: types.DocumentedType, i = 0) {
return (
<div key={i} style={{ paddingTop: '5px' }}>
<gls.InlineBlock className={DocumentationViewStyles.header} onClick={() => this.handleNodeClick(node)}>
<typeIcon.DocumentedTypeHeader name={node.name} icon={node.icon} />
</gls.InlineBlock>
{
node.comment &&
<div style={{ padding: '5px', backgroundColor: blackHighlightColor }}>
<MarkDown markdown={node.comment} />
</div>
}
{
node.subItems && !!node.subItems.length &&
<div style={{ border: '1px solid grey', marginTop: '5px', padding: '5px' }}>
{node.subItems.map((n, i) => this.renderNode(n, i))}
</div>
}
</div>
);
}
handleNodeClick = (node: types.DocumentedType) => {
commands.doOpenOrFocusFile.emit({
filePath: node.location.filePath,
position: node.location.position
});
}
handleRootSelected = (node: types.DocumentedType) => {
this.setState({ selected: node });
setTimeout(() => this.filter());
}
handleKey = (e: any) => {
let unicode = e.charCode;
if (String.fromCharCode(unicode).toLowerCase() === "r") {
this.loadData();
}
}
loadData = () => {
server.getTopLevelModuleNames({}).then(res => {
this.setState({ files: res.files, selected: null });
this.filter();
})
}
filter = () => {
const filter = (this.state.filter || '').toLowerCase();
if (!filter) {
const filtered = this.state.files;
const selected = this.state.selected && filtered.find(f => f.name == this.state.selected.name);
this.setState({ filtered, selected, selectedDoesNotMatchFilter: false });
return;
}
/**
* Does the name match or does some subItem name match
*/
const doesNameMatchRecursive = (type: types.DocumentedType) => {
return type.name.toLowerCase().indexOf(filter) !== -1 || type.subItems.some(t => doesNameMatchRecursive(t));
}
/**
* Only leaves in the subItems that match
*/
const mapChildrenRecursive = (item: types.DocumentedType) => {
let subItems =
item.subItems
.filter(doesNameMatchRecursive)
.map(mapChildrenRecursive);
const result: types.DocumentedType = {
name: item.name,
icon: item.icon,
comment: item.comment,
location: item.location,
subItems,
}
return result;
}
const filtered =
this.state.files
.filter(f => {
return doesNameMatchRecursive(f);
})
.map(mapChildrenRecursive);
this.setState({ filtered })
// Also filter inside the selected if possible
const selected = this.state.selected && filtered.find(f => f.name == this.state.selected.name);
if (this.state.selected && !selected) {
this.setState({ selectedDoesNotMatchFilter: true });
}
else {
this.setState({ selected, selectedDoesNotMatchFilter: false });
}
}
/**
* TAB implementation
*/
resize = () => {
// Not needed
}
focus = () => {
this.refs.root.focus();
}
save = () => {
}
close = () => {
}
gotoPosition = (position: EditorPosition) => {
}
search = {
doSearch: (options: FindOptions) => {
this.setState({ filter: options.query });
this.filter();
},
hideSearch: () => {
this.setState({ filter: '' });
this.filter();
},
findNext: (options: FindOptions) => {
},
findPrevious: (options: FindOptions) => {
},
replaceNext: ({newText}: { newText: string }) => {
},
replacePrevious: ({newText}: { newText: string }) => {
},
replaceAll: ({newText}: { newText: string }) => {
}
}
} | the_stack |
import {WebGLVertexArrayObject} from '../../WebGL2';
export class EXT_blend_minmax {
MAX_EXT: number;
MIN_EXT: number;
constructor(nativeInstance) {
this.MAX_EXT = nativeInstance.MAX_EXT;
this.MIN_EXT = nativeInstance.MIN_EXT;
}
}
export class ANGLE_instanced_arrays {
VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: number;
private nativeInstance;
constructor(nativeInstance) {
this.nativeInstance = nativeInstance;
this.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE = nativeInstance.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE;
}
public drawArraysInstancedANGLE(mode: number, first: number, count: number, primcount: number) {
this.nativeInstance.drawArraysInstancedANGLEWithModeFirstCountPrimcount(mode, first, count, primcount);
}
public drawElementsInstancedANGLE(mode: number, count: number, type: number, offset: number, primcount: number) {
this.nativeInstance.drawElementsInstancedANGLEWithModeCountTypeOffsetPrimcount(mode, count, type, offset, primcount);
}
public vertexAttribDivisorANGLE(index: number, divisor: number) {
this.nativeInstance.vertexAttribDivisorANGLEWithIndexDivisor(index, divisor);
}
}
export class EXT_color_buffer_float {
R11F_G11F_B10F: number;
R16F: number;
R32F: number;
RG16F: number;
RG32F: number;
RGB16F: number;
RGBA32F: number;
constructor(nativeInstance) {
this.R11F_G11F_B10F = nativeInstance.R11F_G11F_B10F;
this.R16F = nativeInstance.R16F;
this.R32F = nativeInstance.R32F;
this.RG16F = nativeInstance.RG16F;
this.RG32F = nativeInstance.RG32F;
this.RGB16F = nativeInstance.RGB16F;
this.RGBA32F = nativeInstance.RGBA32F;
}
}
export class EXT_color_buffer_half_float {
FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: number;
RGB16F_EXT: number;
RGBA16F_EXT: number;
UNSIGNED_NORMALIZED_EXT: number;
constructor(nativeInstance) {
this.FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT =
nativeInstance.FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT;
this.RGB16F_EXT = nativeInstance.RGB16F_EXT;
this.RGBA16F_EXT = nativeInstance.RGBA16F_EXT;
this.UNSIGNED_NORMALIZED_EXT = nativeInstance.UNSIGNED_NORMALIZED_EXT;
}
}
export class EXT_sRGB {
FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number;
SRGB8_ALPHA8_EXT: number;
SRGB_ALPHA_EXT: number;
SRGB_EXT: number;
constructor(nativeInstance) {
this.FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT =
nativeInstance.FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT;
this.SRGB8_ALPHA8_EXT = nativeInstance.SRGB8_ALPHA8_EXT;
this.SRGB_ALPHA_EXT = nativeInstance.SRGB_ALPHA_EXT;
this.SRGB_EXT = nativeInstance.SRGB_EXT;
}
}
export class EXT_shader_texture_lod {
constructor(nativeInstance) {
}
}
export class EXT_texture_filter_anisotropic {
MAX_TEXTURE_MAX_ANISOTROPY_EXT: number;
TEXTURE_MAX_ANISOTROPY_EXT: number;
constructor(nativeInstance) {
this.MAX_TEXTURE_MAX_ANISOTROPY_EXT =
nativeInstance.MAX_TEXTURE_MAX_ANISOTROPY_EXT;
this.TEXTURE_MAX_ANISOTROPY_EXT = nativeInstance.TEXTURE_MAX_ANISOTROPY_EXT;
}
}
export class OES_element_index_uint {
UNSIGNED_INT: number;
constructor(nativeInstance) {
this.UNSIGNED_INT = nativeInstance.UNSIGNED_INT;
}
}
export class OES_fbo_render_mipmap {
constructor(nativeInstance) {
}
}
export class OES_standard_derivatives {
constructor(nativeInstance) {
}
}
export class OES_texture_float {
constructor(nativeInstance) {
}
}
export class OES_texture_float_linear {
constructor(nativeInstance) {
}
}
export class OES_texture_half_float {
HALF_FLOAT_OES: number;
constructor(nativeInstance) {
this.HALF_FLOAT_OES = nativeInstance.HALF_FLOAT_OES;
}
}
export class OES_texture_half_float_linear {
constructor(nativeInstance) {
}
}
export class OES_vertex_array_object {
VERTEX_ARRAY_BINDING_OES: number;
private nativeInstance: any;
constructor(nativeInstance) {
this.nativeInstance = nativeInstance;
this.VERTEX_ARRAY_BINDING_OES = nativeInstance.VERTEX_ARRAY_BINDING_OES;
}
bindVertexArrayOES(arrayObject: WebGLVertexArrayObject): void {
const value = arrayObject ? arrayObject.native : 0;
this.nativeInstance.bindVertexArrayOESWithArrayObject(value);
}
createVertexArrayOES(): WebGLVertexArrayObject {
return new WebGLVertexArrayObject(this.nativeInstance.createVertexArrayOES());
}
deleteVertexArrayOESWithArrayObject(arrayObject: WebGLVertexArrayObject): void {
const value = arrayObject ? arrayObject.native : 0;
this.nativeInstance.deleteVertexArrayOESWithArrayObject(value);
}
isVertexArrayOESWithArrayObject(arrayObject: WebGLVertexArrayObject): boolean {
const value = arrayObject ? arrayObject.native : 0;
return this.nativeInstance.isVertexArrayOESWithArrayObject(value);
}
}
export class WEBGL_color_buffer_float {
FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT: number;
RGB32F_EXT: number;
RGBA32F_EXT: number;
UNSIGNED_NORMALIZED_EXT: number;
constructor(nativeInstance) {
this.FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT =
nativeInstance.FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT;
this.RGB32F_EXT = nativeInstance.RGB32F_EXT;
this.RGBA32F_EXT = nativeInstance.RGBA32F_EXT;
this.UNSIGNED_NORMALIZED_EXT = nativeInstance.UNSIGNED_NORMALIZED_EXT;
}
}
export class WEBGL_compressed_texture_etc {
COMPRESSED_R11_EAC: number;
COMPRESSED_RG11_EAC: number;
COMPRESSED_RGB8_ETC2: number;
COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2: number;
COMPRESSED_RGBA8_ETC2_EAC: number;
COMPRESSED_SIGNED_R11_EAC: number;
COMPRESSED_SIGNED_RG11_EAC: number;
COMPRESSED_SRGB8_ALPHA8_ETC2_EAC: number;
COMPRESSED_SRGB8_ETC2: number;
COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2: number;
constructor(nativeInstance) {
this.COMPRESSED_R11_EAC = nativeInstance.COMPRESSED_R11_EAC;
this.COMPRESSED_RG11_EAC = nativeInstance.COMPRESSED_RG11_EAC;
this.COMPRESSED_RGB8_ETC2 = nativeInstance.COMPRESSED_RGB8_ETC2;
this.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 =
nativeInstance.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2;
this.COMPRESSED_RGBA8_ETC2_EAC = nativeInstance.COMPRESSED_RGBA8_ETC2_EAC;
this.COMPRESSED_SIGNED_R11_EAC = nativeInstance.COMPRESSED_SIGNED_R11_EAC;
this.COMPRESSED_SIGNED_RG11_EAC = nativeInstance.COMPRESSED_SIGNED_RG11_EAC;
this.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC =
nativeInstance.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC;
this.COMPRESSED_SRGB8_ETC2 = nativeInstance.COMPRESSED_SRGB8_ETC2;
this.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 =
nativeInstance.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2;
}
}
export class WEBGL_compressed_texture_etc1 {
COMPRESSED_RGB_ETC1_WEBGL: number;
constructor(nativeInstance) {
this.COMPRESSED_RGB_ETC1_WEBGL = nativeInstance.COMPRESSED_RGB_ETC1_WEBGL;
}
}
export class WEBGL_compressed_texture_pvrtc {
COMPRESSED_RGBA_PVRTC_2BPPV1_IMG: number;
COMPRESSED_RGBA_PVRTC_4BPPV1_IMG: number;
COMPRESSED_RGB_PVRTC_2BPPV1_IMG: number;
COMPRESSED_RGB_PVRTC_4BPPV1_IMG: number;
constructor(nativeInstance) {
this.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG =
nativeInstance.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
this.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG =
nativeInstance.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
this.COMPRESSED_RGB_PVRTC_2BPPV1_IMG =
nativeInstance.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
this.COMPRESSED_RGB_PVRTC_4BPPV1_IMG =
nativeInstance.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
}
}
export class WEBGL_depth_texture {
UNSIGNED_INT_24_8_WEBGL: number;
constructor(nativeInstance) {
this.UNSIGNED_INT_24_8_WEBGL = nativeInstance.UNSIGNED_INT_24_8_WEBGL;
}
}
export class WEBGL_lose_context {
private nativeInstance: any;
constructor(nativeInstance) {
this.nativeInstance = nativeInstance;
}
public loseContext() {
this.nativeInstance.loseContext();
}
public restoreContext() {
this.nativeInstance.restoreContext();
}
}
export class EXT_disjoint_timer_query {
QUERY_COUNTER_BITS_EXT;
CURRENT_QUERY_EXT;
QUERY_RESULT_EXT;
QUERY_RESULT_AVAILABLE_EXT;
TIME_ELAPSED_EXT;
TIMESTAMP_EXT;
GPU_DISJOINT_EXT;
private nativeInstance: any;
constructor(nativeInstance) {
this.nativeInstance = nativeInstance;
this.QUERY_COUNTER_BITS_EXT = nativeInstance.QUERY_COUNTER_BITS_EXT;
this.CURRENT_QUERY_EXT = nativeInstance.CURRENT_QUERY_EXT;
this.QUERY_RESULT_EXT = nativeInstance.QUERY_RESULT_EXT;
this.QUERY_RESULT_AVAILABLE_EXT = nativeInstance.QUERY_RESULT_AVAILABLE_EXT;
this.TIME_ELAPSED_EXT = nativeInstance.TIME_ELAPSED_EXT;
this.TIMESTAMP_EXT = nativeInstance.TIMESTAMP_EXT;
this.GPU_DISJOINT_EXT = nativeInstance.GPU_DISJOINT_EXT;
}
/*
public createQueryEXT(){
return this.nativeInstance.
}
public deleteQueryEXT(query: WebGLQuery){
this.nativeInstance.
}
public isQueryEXT(query: WebGLQuery){
return this.nativeInstance.
}
public beginQueryEXT(target: number, query: number){
this.nativeInstance.
}
public endQueryEXT(target: number){
this.nativeInstance.
}
public queryCounterEXT(query: WebGLQuery, target: number){
return this.nativeInstance.
}
public getQueryEXT(target: number, pname: number){
return this.nativeInstance.
}
public getQueryObjectEXT(query: WebGLQuery, pname: number){
return this.nativeInstance.
}
*/
}
export class WEBGL_compressed_texture_atc {
COMPRESSED_RGB_ATC_WEBGL;
COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL;
COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL;
private nativeInstance: any;
constructor(nativeInstance) {
this.COMPRESSED_RGB_ATC_WEBGL = nativeInstance.COMPRESSED_RGB_ATC_WEBGL;
this.COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL = nativeInstance.COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL;
this.COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL = nativeInstance.COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL;
}
}
export class WEBGL_compressed_texture_s3tc {
COMPRESSED_RGB_S3TC_DXT1_EXT;
COMPRESSED_RGBA_S3TC_DXT1_EXT;
COMPRESSED_RGBA_S3TC_DXT3_EXT;
COMPRESSED_RGBA_S3TC_DXT5_EXT;
private nativeInstance: any;
constructor(nativeInstance) {
this.COMPRESSED_RGB_S3TC_DXT1_EXT = nativeInstance.COMPRESSED_RGB_S3TC_DXT1_EXT;
this.COMPRESSED_RGBA_S3TC_DXT1_EXT = nativeInstance.COMPRESSED_RGBA_S3TC_DXT1_EXT;
this.COMPRESSED_RGBA_S3TC_DXT3_EXT = nativeInstance.COMPRESSED_RGBA_S3TC_DXT3_EXT;
this.COMPRESSED_RGBA_S3TC_DXT5_EXT = nativeInstance.COMPRESSED_RGBA_S3TC_DXT5_EXT;
}
}
export class WEBGL_compressed_texture_s3tc_srgb {
COMPRESSED_SRGB_S3TC_DXT1_EXT;
COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
private nativeInstance: any;
constructor(nativeInstance) {
this.COMPRESSED_SRGB_S3TC_DXT1_EXT = nativeInstance.COMPRESSED_SRGB_S3TC_DXT1_EXT;
this.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT = nativeInstance.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
this.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT = nativeInstance.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
this.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT = nativeInstance.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
}
}
export class WEBGL_draw_buffers {
COLOR_ATTACHMENT0_WEBGL;
COLOR_ATTACHMENT1_WEBGL;
COLOR_ATTACHMENT2_WEBGL;
COLOR_ATTACHMENT3_WEBGL;
COLOR_ATTACHMENT4_WEBGL;
COLOR_ATTACHMENT5_WEBGL;
COLOR_ATTACHMENT6_WEBGL;
COLOR_ATTACHMENT7_WEBGL;
COLOR_ATTACHMENT8_WEBGL;
COLOR_ATTACHMENT9_WEBGL;
COLOR_ATTACHMENT10_WEBGL;
COLOR_ATTACHMENT11_WEBGL;
COLOR_ATTACHMENT12_WEBGL;
COLOR_ATTACHMENT13_WEBGL;
COLOR_ATTACHMENT14_WEBGL;
COLOR_ATTACHMENT15_WEBGL;
DRAW_BUFFER0_WEBGL;
DRAW_BUFFER1_WEBGL;
DRAW_BUFFER2_WEBGL;
DRAW_BUFFER3_WEBGL;
DRAW_BUFFER4_WEBGL;
DRAW_BUFFER5_WEBGL;
DRAW_BUFFER6_WEBGL;
DRAW_BUFFER7_WEBGL;
DRAW_BUFFER8_WEBGL;
DRAW_BUFFER9_WEBGL;
DRAW_BUFFER10_WEBGL;
DRAW_BUFFER11_WEBGL;
DRAW_BUFFER12_WEBGL;
DRAW_BUFFER13_WEBGL;
DRAW_BUFFER14_WEBGL;
DRAW_BUFFER15_WEBGL;
MAX_COLOR_ATTACHMENTS_WEBGL;
MAX_DRAW_BUFFERS_WEBGL;
private nativeInstance: any;
constructor(nativeInstance) {
this.nativeInstance = nativeInstance;
this.COLOR_ATTACHMENT0_WEBGL = nativeInstance.COLOR_ATTACHMENT0_EXT;
this.COLOR_ATTACHMENT1_WEBGL = nativeInstance.COLOR_ATTACHMENT1_EXT;
this.COLOR_ATTACHMENT2_WEBGL = nativeInstance.COLOR_ATTACHMENT2_EXT;
this.COLOR_ATTACHMENT3_WEBGL = nativeInstance.COLOR_ATTACHMENT3_EXT;
this.COLOR_ATTACHMENT4_WEBGL = nativeInstance.COLOR_ATTACHMENT4_EXT;
this.COLOR_ATTACHMENT5_WEBGL = nativeInstance.COLOR_ATTACHMENT5_EXT;
this.COLOR_ATTACHMENT6_WEBGL = nativeInstance.COLOR_ATTACHMENT6_EXT;
this.COLOR_ATTACHMENT7_WEBGL = nativeInstance.COLOR_ATTACHMENT7_EXT;
this.COLOR_ATTACHMENT8_WEBGL = nativeInstance.COLOR_ATTACHMENT8_EXT;
this.COLOR_ATTACHMENT9_WEBGL = nativeInstance.COLOR_ATTACHMENT9_EXT;
this.COLOR_ATTACHMENT10_WEBGL = nativeInstance.COLOR_ATTACHMENT10_EXT;
this.COLOR_ATTACHMENT11_WEBGL = nativeInstance.COLOR_ATTACHMENT11_EXT;
this.COLOR_ATTACHMENT12_WEBGL = nativeInstance.COLOR_ATTACHMENT12_EXT;
this.COLOR_ATTACHMENT13_WEBGL = nativeInstance.COLOR_ATTACHMENT13_EXT;
this.COLOR_ATTACHMENT14_WEBGL = nativeInstance.COLOR_ATTACHMENT14_EXT;
this.COLOR_ATTACHMENT15_WEBGL = nativeInstance.COLOR_ATTACHMENT15_EXT;
this.DRAW_BUFFER0_WEBGL = nativeInstance.DRAW_BUFFER0_EXT;
this.DRAW_BUFFER1_WEBGL = nativeInstance.DRAW_BUFFER1_EXT;
this.DRAW_BUFFER2_WEBGL = nativeInstance.DRAW_BUFFER2_EXT;
this.DRAW_BUFFER3_WEBGL = nativeInstance.DRAW_BUFFER3_EXT;
this.DRAW_BUFFER4_WEBGL = nativeInstance.DRAW_BUFFER4_EXT;
this.DRAW_BUFFER5_WEBGL = nativeInstance.DRAW_BUFFER5_EXT;
this.DRAW_BUFFER6_WEBGL = nativeInstance.DRAW_BUFFER6_EXT;
this.DRAW_BUFFER7_WEBGL = nativeInstance.DRAW_BUFFER7_EXT;
this.DRAW_BUFFER8_WEBGL = nativeInstance.DRAW_BUFFER8_EXT;
this.DRAW_BUFFER9_WEBGL = nativeInstance.DRAW_BUFFER9_EXT;
this.DRAW_BUFFER10_WEBGL = nativeInstance.DRAW_BUFFER10_EXT;
this.DRAW_BUFFER11_WEBGL = nativeInstance.DRAW_BUFFER11_EXT;
this.DRAW_BUFFER12_WEBGL = nativeInstance.DRAW_BUFFER12_EXT;
this.DRAW_BUFFER13_WEBGL = nativeInstance.DRAW_BUFFER13_EXT;
this.DRAW_BUFFER14_WEBGL = nativeInstance.DRAW_BUFFER14_EXT;
this.DRAW_BUFFER15_WEBGL = nativeInstance.DRAW_BUFFER15_EXT;
this.MAX_COLOR_ATTACHMENTS_WEBGL = nativeInstance.MAX_COLOR_ATTACHMENTS_EXT;
this.MAX_DRAW_BUFFERS_WEBGL = nativeInstance.MAX_DRAW_BUFFERS_EXT;
}
drawBuffersWEBGL(buffers: number[]): void {
this.nativeInstance.drawBuffersWEBGLWithBuffers(buffers);
}
} | the_stack |
import { $$log, $$hex } from "../utils/debug";
import { compress, getCompressedSize, decompress } from "../utils/compression";
import { toTiles, fromTiles } from "../utils/img/tiler";
import { RGBA5551fromRGBA32, RGBA5551toRGBA32 } from "../utils/img/RGBA5551";
import { arrayBuffersEqual, copyRange } from "../utils/arrays";
import { createContext } from "../utils/canvas";
import { makeDivisibleBy } from "../utils/number";
import { Game } from "../types";
import { romhandler } from "../romhandler";
interface IOffsetInfo {
upper: number;
lower: number;
}
interface IAnimationFsReadInfo {
compressionType: number;
decompressed: ArrayBuffer;
compressed?: ArrayBuffer;
}
let _animFSOffsets: { [game: string]: IOffsetInfo[] } = {};
_animFSOffsets[Game.MP2_USA] = [
// 0x16EC470
{ upper: 0x000546C6, lower: 0x000546CA },
];
let _animfsCache: { [index: number]: IAnimationFsReadInfo }[][] | null;
export const animationfs = {
getROMOffset() {
let romView = romhandler.getDataView();
let patchOffsets = animationfs.getPatchOffsets();
if (!patchOffsets)
return null;
let romOffset = patchOffsets[0];
let upper = romView.getUint16(romOffset.upper) << 16;
let lower = romView.getUint16(romOffset.lower);
let offset = upper | lower;
if (lower & 0x8000)
offset = offset - 0x00010000; // Account for signed addition workaround.
$$log(`AnimationFS.getROMOffset -> ${$$hex(offset)}`);
return offset;
},
setROMOffset(newOffset: number, buffer: ArrayBuffer) {
let romView = new DataView(buffer);
let patchOffsets = animationfs.getPatchOffsets();
if (!patchOffsets)
return;
let upper = (newOffset & 0xFFFF0000) >>> 16;
let lower = newOffset & 0x0000FFFF;
if (lower & 0x8000)
upper += 1; // ASM adjust for the signed addition.
for (let i = 0; i < patchOffsets.length; i++) {
romView.setUint16(patchOffsets[i].upper, upper);
romView.setUint16(patchOffsets[i].lower, lower);
}
$$log(`AnimationFS.setROMOffset -> ${$$hex((upper << 16) | lower)}`);
},
getPatchOffsets() {
return _animFSOffsets[romhandler.getROMGame()!];
},
get(set: number, entry: number, index: number) {
return _animfsCache![set][entry][index].decompressed;
},
write(set: number, entry: number, tileBuffer: ArrayBuffer, index: number) {
let compressed = compress(3, new DataView(tileBuffer));
if (!_animfsCache![set])
_animfsCache![set] = [];
if (!_animfsCache![set][entry])
_animfsCache![set][entry] = {};
_animfsCache![set][entry][index] = {
compressionType: 3,
decompressed: tileBuffer,
compressed,
};
},
_createOrderedTiles(imgData: ImageData, width: number, height: number) {
let tileXCount = width / 64;
let tileYCount = height / 48;
let tiles32 = toTiles(imgData.data, tileXCount, tileYCount, 64 * 4, 48);
let tiles16 = tiles32.map(tile32 => {
return RGBA5551fromRGBA32(tile32, 64, 48);
});
let orderedTiles = [];
for (let y = tileYCount - 1; y >= 0; y--) {
for (let x = 0; x < tileXCount; x++) {
orderedTiles.push(tiles16[(y * tileXCount) + x]);
}
}
return orderedTiles;
},
writeAnimationBackground(set: number, entry: number, mainImgData: ImageData, animImgData: ImageData, width: number, height: number) {
$$log(`AnimationFS.writeAnimationBackground, set: ${set}, entry: ${entry}, img is ${width}x${height}`);
let orderedMainTiles = animationfs._createOrderedTiles(mainImgData, width, height);
let orderedAnimTiles = animationfs._createOrderedTiles(animImgData, width, height);
animationfs.clearSetEntry(set, entry);
// Write the tiles that are different to the sparse tree.
for (let i = 0; i < orderedAnimTiles.length; i++) {
if (!arrayBuffersEqual(orderedMainTiles[i], orderedAnimTiles[i]))
animationfs.write(set, entry, orderedAnimTiles[i], i + 1);
}
},
_unorderTiles(tiles: any[], tileXCount: number, tileYCount: number) {
let unordered = [];
for (let y = tileYCount - 1; y >= 0; y--) {
for (let x = 0; x < tileXCount; x++) {
unordered.push(tiles[(y * tileXCount) + x]);
}
}
return unordered;
},
_readAnimationBackground(set: number, entry: number, orderedMainTiles: ArrayBuffer[], width: number, height: number) {
let orderedAnimBgTiles = [];
for (let i = 0; i < orderedMainTiles.length; i++) {
if (_animfsCache![set][entry].hasOwnProperty(i + 1))
orderedAnimBgTiles.push(new DataView(_animfsCache![set][entry][i + 1].decompressed));
else
orderedAnimBgTiles.push(new DataView(orderedMainTiles[i]));
}
let tileWidth = 64;
let tileHeight = 48;
let tileXCount = width / 64;
let tileYCount = height / 48;
orderedAnimBgTiles = animationfs._unorderTiles(orderedAnimBgTiles, tileXCount, tileYCount);
let bgBufferRGBA16 = fromTiles(orderedAnimBgTiles, tileXCount, tileYCount, tileWidth * 2, tileHeight);
let bgBufferRGBA32 = RGBA5551toRGBA32(bgBufferRGBA16, width, height);
let bgArr = new Uint8Array(bgBufferRGBA32);
let canvasCtx = createContext(width, height);
let bgImageData = canvasCtx.createImageData(width, height);
for (let i = 0; i < bgArr.byteLength; i++) {
bgImageData.data[i] = bgArr[i];
}
canvasCtx.putImageData(bgImageData, 0, 0);
return canvasCtx.canvas.toDataURL();
},
readAnimationBackgrounds(set: number, mainImgData: ImageData, width: number, height: number) {
let entries = animationfs.getSetEntryCount(set);
let orderedMainTiles = animationfs._createOrderedTiles(mainImgData, width, height);
let bgs = [];
for (let entry = 0; entry < entries; entry++) {
bgs.push(animationfs._readAnimationBackground(set, entry, orderedMainTiles, width, height));
}
return bgs;
},
clearCache() {
_animfsCache = null;
},
extract() {
let startingOffset = animationfs.getROMOffset();
if (startingOffset === null) {
return null;
}
let view = romhandler.getDataView();
_animfsCache = animationfs._extractSets(view, startingOffset);
return _animfsCache;
},
extractAsync(): Promise<void> {
return new Promise((resolve, reject) => {
animationfs.extract();
resolve();
});
},
_extractSets(view: DataView, offset: number) {
let sets = [];
let count = view.getUint32(offset) - 1; // Extra offset
for (let i = 0; i < count; i++) {
let setOffset = view.getUint32(offset + 4 + (i * 4));
sets.push(animationfs._extractSetEntries(view, offset + setOffset));
}
return sets;
},
_extractSetEntries(view: DataView, offset: number) {
let setEntries = [];
let count = view.getUint32(offset);
for (let i = 0; i < count; i++) {
let setEntryOffset = view.getUint32(offset + 4 + (i * 4));
setEntries.push(animationfs._extractTiles(view, offset + setEntryOffset));
}
return setEntries;
},
_extractTiles(view: DataView, offset: number) {
let tiles: { [index: number]: IAnimationFsReadInfo } = {};
let count = view.getUint32(offset) - 1; // Extra offset
for (let i = 0; i < count; i++) {
let tileOffset = view.getUint32(offset + 4 + (i * 4));
let tile = animationfs._readTile(view, offset + tileOffset);
tiles[tile.index] = {
compressionType: tile.compressionType,
compressed: tile.compressed,
decompressed: tile.decompressed,
};
}
return tiles;
},
_readTile(view: DataView, offset: number) {
let index = view.getUint32(offset);
let compressionType = view.getUint32(offset + 4); // 3
let decompressedSize = view.getUint32(offset + 8); // 0x1800
let buffer = view.buffer;
let fileStartOffset = offset + 12;
let fileStartView = new DataView(buffer, fileStartOffset);
let compressedSize = getCompressedSize(compressionType, fileStartView, decompressedSize)!; // TODO perf
return {
index,
compressionType,
compressed: buffer.slice(fileStartOffset, fileStartOffset + compressedSize),
decompressed: decompress(compressionType, fileStartView, decompressedSize)
};
},
pack(buffer: ArrayBuffer, offset: number = 0) {
let view = new DataView(buffer, offset);
let setCount = animationfs.getSetCount();
view.setUint32(0, setCount + 1); // Extra offset
let curSetIndexOffset = 4;
let curSetWriteOffset = 4 + ((setCount + 1) * 4);
for (let s = 0; s < setCount; s++) {
view.setUint32(curSetIndexOffset, curSetWriteOffset);
curSetIndexOffset += 4;
curSetWriteOffset = animationfs._writeSet(s, view, curSetWriteOffset);
curSetWriteOffset = makeDivisibleBy(curSetWriteOffset, 4);
}
view.setUint32(curSetIndexOffset, curSetWriteOffset); // Extra offset
return curSetWriteOffset;
},
_writeSet(s: number, view: DataView, offset: number) {
let setEntryCount = animationfs.getSetEntryCount(s);
view.setUint32(offset, setEntryCount); // No extra offsets at middle layer
let curSetEntryIndexOffset = offset + 4;
let curSetEntryWriteOffset = offset + 4 + (setEntryCount * 4);
for (let e = 0; e < setEntryCount; e++) {
view.setUint32(curSetEntryIndexOffset, curSetEntryWriteOffset - offset);
curSetEntryIndexOffset += 4;
curSetEntryWriteOffset = animationfs._writeTiles(s, e, view, curSetEntryWriteOffset);
curSetEntryWriteOffset = makeDivisibleBy(curSetEntryWriteOffset, 4);
}
return curSetEntryWriteOffset;
},
_writeTiles(s: number, e: number, view: DataView, offset: number) {
let tileCount = animationfs.getSetEntryTileCount(s, e);
view.setUint32(offset, tileCount + 1); // Extra offset
let curTileIndexOffset = offset + 4;
let curTileWriteOffset = offset + 4 + ((tileCount + 1) * 4);
for (let t in _animfsCache![s][e]) {
if (!_animfsCache![s][e].hasOwnProperty(t))
continue;
view.setUint32(curTileIndexOffset, curTileWriteOffset - offset);
curTileIndexOffset += 4;
curTileWriteOffset = animationfs._writeTile(s, e, t, view, curTileWriteOffset);
curTileWriteOffset = makeDivisibleBy(curTileWriteOffset, 4);
}
view.setUint32(curTileIndexOffset, curTileWriteOffset - offset);
return curTileWriteOffset;
},
_writeTile(s: number, e: number, t: string, view: DataView, offset: number) {
const tile = _animfsCache![s][e][t as any];
view.setUint32(offset, parseInt(t));
view.setUint32(offset + 4, 3); // Compression type
view.setUint32(offset + 8, tile.decompressed.byteLength); // Decompressed size
copyRange(view, tile.compressed!, offset + 12, 0, tile.compressed!.byteLength);
return offset + 12 + tile.compressed!.byteLength;
},
getSetCount() {
return _animfsCache!.length;
},
getSetEntryCount(set: number) {
return _animfsCache![set].length;
},
// This is exposed so that we can blow away animations for a stock board (count = 0)
setSetEntryCount(set: number, count: number) {
return _animfsCache![set].length = count;
},
clearSetEntry(set: number, entry: number) {
return _animfsCache![set][entry] = {};
},
getSetEntryTileCount(set: number, entry: number) {
return Object.keys(_animfsCache![set][entry]).length;
},
getByteLength() {
let byteLen = 0;
let setCount = animationfs.getSetCount();
byteLen += 4; // Count of sets
byteLen += 4 * (setCount + 1); // Set offsets + the extra offset
for (let s = 0; s < setCount; s++) {
let setEntryCount = animationfs.getSetEntryCount(s);
byteLen += 4; // Count of set entries
byteLen += 4 * setEntryCount; // Set entry offsets (no extra offset)
for (let e = 0; e < setEntryCount; e++) {
let tileCount = animationfs.getSetEntryTileCount(s, e);
byteLen += 4; // Count of tiles
byteLen += 4 * (tileCount + 1); // Tile offsets + the extra offset
for (let t in _animfsCache![s][e]) {
if (!_animfsCache![s][e].hasOwnProperty(t))
continue;
let tile = _animfsCache![s][e][t];
byteLen += 4; // Index
byteLen += 4; // Compression type
byteLen += 4; // Decompressed size
byteLen += tile.compressed!.byteLength;
byteLen = makeDivisibleBy(byteLen, 4);
}
}
}
return byteLen;
}
}; | the_stack |
import React from 'react';
import {Link, RouteComponentProps} from 'react-router-dom';
import {throttle} from 'lodash';
import {Channel, Presence, Socket} from 'phoenix';
import {Box, Flex} from 'theme-ui';
import {Replayer, ReplayerEvents} from 'rrweb';
import {Alert, Button, Paragraph, Text} from '../common';
import {ArrowLeftOutlined} from '../icons';
import {SOCKET_URL} from '../../socket';
import * as API from '../../api';
import logger from '../../logger';
import Spinner from '../Spinner';
import ConversationDetailsSidebar from '../conversations/ConversationDetailsSidebar';
import StartConversationButton from '../conversations/StartConversationButton';
import ConversationSidebar from './ConversationSidebar';
import {Conversation, Customer} from '../../types';
import 'rrweb/dist/replay/rrweb-replay.min.css';
type Props = RouteComponentProps<{session: string}> & {};
type State = {
loading: boolean;
events: Array<any>;
customer: Customer | null;
conversation: Conversation | null;
scale: number;
isCustomerActive: boolean;
isCustomerConnected: boolean;
};
class LiveSessionViewer extends React.Component<Props, State> {
socket: Socket | null = null;
channels: Array<Channel> = [];
replayer!: Replayer; // TODO: start off as null?
container: any;
state: State = {
loading: true,
events: [],
customer: null,
conversation: null,
scale: 1,
isCustomerActive: true,
isCustomerConnected: true,
};
// TODO: move a bunch of logic from here into separate functions
async componentDidMount() {
const {session: sessionId} = this.props.match.params;
const {
customer,
account_id: accountId,
customer_id: customerId,
} = await API.fetchBrowserSession(sessionId);
const conversation = await this.findExistingConversation(
accountId,
customerId
);
this.setState({customer, conversation});
const root = document.getElementById('SessionPlayer') as Element;
this.replayer = new Replayer([], {root: root, liveMode: true});
this.replayer.on(ReplayerEvents.FullsnapshotRebuilded, () => {
logger.debug('Full snapshot done!');
// TODO: don't wait until this point to set `loading: false`...
// we should probably do something like:
// loading -> connecting to socket -> listening for events -> etc
this.setIframeScale(() => this.setState({loading: false}));
});
// Socket connection below only necessary for live view
this.socket = new Socket(SOCKET_URL, {
params: {token: API.getAccessToken()},
});
this.socket.connect();
// TODO: attempt refreshing access token?
this.socket.onError(
throttle(
() =>
logger.error('Error connecting to socket. Try refreshing the page.'),
30 * 1000 // throttle every 30 secs
)
);
this.listenForNewEvents(accountId, sessionId);
this.listenForDisconnection(accountId, sessionId);
window.addEventListener('resize', this.handleWindowResize);
}
componentWillUnmount() {
window.removeEventListener('resize', this.handleWindowResize);
if (this.replayer && this.replayer.pause) {
this.replayer.pause();
}
if (this.channels && this.channels.length) {
this.channels.map((ch) => ch.leave());
}
if (this.socket && this.socket.disconnect) {
this.socket.disconnect();
}
}
listenForNewEvents = (accountId: string, sessionId: string) => {
if (!this.socket) {
return;
}
const channel = this.socket.channel(
`events:admin:${accountId}:${sessionId}`,
{}
);
channel.on('replay:event:emitted', (data) => {
logger.debug('New event emitted!', data);
this.replayer.addEvent(data.event);
});
channel
.join()
.receive('ok', (res) => {
logger.debug('Joined channel successfully', res);
this.replayer.startLive();
setTimeout(() => this.setIframeScale(), 100);
setTimeout(() => this.setState({loading: false}), 60 * 1000);
})
.receive('error', (err) => {
logger.error('Unable to join', err);
});
this.channels.push(channel);
};
listenForDisconnection = (accountId: string, sessionId: string) => {
if (!this.socket) {
return;
}
const channel = this.socket.channel(`events:admin:${accountId}:all`, {});
channel
.join()
.receive('ok', (res: any) => {
logger.debug('Joined session channel successfully!', res);
})
.receive('error', (err: any) => {
logger.debug('Unable to join session channel!', err);
});
const presence = new Presence(channel);
presence.onSync(() => {
const records = presence.list().map(({metas}) => {
const [info] = metas;
return info;
});
const session = records.find((r) => r.session_id === sessionId);
const isCustomerConnected = !!session;
const isCustomerActive = isCustomerConnected && session.active;
this.setState({isCustomerActive, isCustomerConnected});
});
this.channels.push(channel);
};
findExistingConversation = async (
accountId: string,
customerId?: string | null
) => {
if (!customerId) {
return null;
}
const conversations = await API.fetchCustomerConversations(
customerId,
accountId
);
const [recent] = conversations;
if (recent && recent.id) {
return recent;
}
return null;
};
setIframeScale = (cb?: () => void) => {
if (!this.replayer || !this.replayer.iframe) {
this.setState({scale: 1}, cb);
}
const iframeWidth = Number(this.replayer.iframe.width);
const iframeHeight = Number(this.replayer.iframe.height);
const {
clientWidth: containerWidth,
clientHeight: containerHeight,
} = this.container;
const scaleX = containerWidth / iframeWidth;
const scaleY = containerHeight / iframeHeight;
logger.debug('Setting iframe scale:', {
containerWidth,
containerHeight,
iframeWidth,
iframeHeight,
scaleX,
scaleY,
});
const scale = scaleX < scaleY ? scaleX : scaleY;
if (Number.isFinite(scale)) {
this.setState({scale: scale || 1}, cb);
} else {
this.setState({scale: 1}, cb);
}
};
handleWindowResize = () => {
logger.debug('Handling resize...');
this.setIframeScale();
};
renderStatusAlert() {
const {loading, isCustomerConnected, isCustomerActive} = this.state;
if (loading) {
return (
<Alert
message={
<Text>Loading the current session... this may take a minute.</Text>
}
type="info"
showIcon
/>
);
} else if (!isCustomerConnected) {
return (
<Alert
message={<Text>The customer has disconnected.</Text>}
type="error"
showIcon
/>
);
} else if (!isCustomerActive) {
return (
<Alert
message={<Text>The customer is currently inactive.</Text>}
type="warning"
showIcon
/>
);
} else {
return (
<Alert
message={<Text>The customer is currently active.</Text>}
type="success"
showIcon
/>
);
}
}
render() {
const {
loading,
scale = 1,
conversation,
customer,
isCustomerActive,
isCustomerConnected,
} = this.state;
const hasAdditionalDetails = !!(conversation || customer);
return (
<Flex>
<Box
p={4}
mr={hasAdditionalDetails ? 360 : 0}
sx={{maxWidth: 960, width: '100%', flex: 1}}
>
<Box mb={4}>
<Box mb={3}>
<Paragraph>
<Flex sx={{justifyContent: 'space-between'}}>
<Link to="/sessions/list">
<Button icon={<ArrowLeftOutlined />}>
Back to all sessions
</Button>
</Link>
{!loading && customer && (
<StartConversationButton
customerId={customer.id}
isDisabled={!!conversation}
onInitializeNewConversation={(conversation) =>
this.setState({conversation})
}
/>
)}
</Flex>
</Paragraph>
<Alert
message={
<Text>
Note: This is an experimental feature! Let us know if you
notice any issues or bugs.
</Text>
}
type="warning"
showIcon
/>
<Box mt={3}>{this.renderStatusAlert()}</Box>
</Box>
</Box>
<Flex className="rr-block" sx={{maxWidth: 960}}>
<Box sx={{flex: 1, border: 'none'}}>
{/* TODO: figure out the best way to style this */}
{loading && (
<Flex
sx={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
height: '100%',
}}
>
<Spinner size={40} />
</Flex>
)}
<Box
mx={2}
style={{
position: 'relative',
height: 480,
visibility: loading ? 'hidden' : 'visible',
opacity: isCustomerActive && isCustomerConnected ? 1 : 0.6,
}}
ref={(el) => (this.container = el)}
>
{/*
TODO: see https://github.com/rrweb-io/rrweb-player/blob/master/src/Player.svelte
for an example of how we could possibly style this better...
*/}
<div
id="SessionPlayer"
style={{
transform: `scale(${scale})`,
transformOrigin: 'top left',
}}
></div>
</Box>
</Box>
</Flex>
</Box>
{hasAdditionalDetails && (
<Box
sx={{
width: 360,
height: '100%',
overflowY: conversation ? null : 'scroll',
position: 'absolute',
right: 0,
}}
>
{conversation ? (
<ConversationSidebar conversationId={conversation.id} />
) : customer ? (
<ConversationDetailsSidebar customer={customer} />
) : null}
</Box>
)}
</Flex>
);
}
}
export default LiveSessionViewer; | the_stack |
import {each, isEqual, isObjectLike, clone, has, isNil, get} from 'lodash';
import {RootState} from '../../data/reducers';
import {polyfill} from 'react-lifecycles-compat';
import {
BasicProps,
ContainerSetDataOption, FormItemState,
runTimeType
} from '../../types';
import {TriggerEventItem} from '../Trigger/Trigger';
import {getRuntimeContext} from '../util/util';
import {isExpression, parseExpressionString} from '../util/vm';
import React from 'react';
export type WrapperComponentType<T> =
React.ComponentClass<T> |
React.StatelessComponent<T> |
React.ClassicComponentClass<T>;
export interface ConnectTools<Props> extends BasicProps {
/**
* RCRE引擎执行当前组件的上下文
*/
env: Props;
/**
* ExpressionString执行环境
*/
runTime: runTimeType;
/**
* 注册事件
* @param {string} event
* @param args
*/
registerEvent: (event: string, args: Object) => void;
/**
* 当有name属性时,使用这个函数来更新name所对应的值
* @param value
*/
updateNameValue: (value: any, options?: ContainerSetDataOption) => void;
/**
* 当有name属性时,使用这个函数来清空name所对应的值
*/
clearNameValue: () => void;
/**
* 从name中获取数据
*/
getNameValue: (name: string) => any;
/**
* 是否绑定了某个事件
* @param {string} event
* @return {boolean}
*/
hasTriggerEvent: (event: string) => boolean;
/**
* 开启debounce模式,connect组件缓存的cache
*/
debounceCache: { [key: string]: any };
/**
* 是否正处于debounce状态
*/
isDebouncing: boolean;
form: {
/**
* 更新FormItem的状态
*/
$setFormItem: (payload: Partial<FormItemState>) => void;
/**
* 清空FormItem的状态
*/
$deleteFormItem: (formItemName: string) => void;
/**
* 获取FormItem的信息
* @param {string} name
* @returns {SET_FORM_ITEM_PAYLOAD}
*/
$getFormItem: (name: string) => FormItemState;
/**
* 是否处于Form组件下
*/
isUnderForm?: boolean;
};
/**
* 动态生成React组件
* @param {object} config
* @param {object} props
* @returns {React.ReactNode}
*/
createReactNode: (config: any, props: object) => React.ReactNode;
}
export interface CommonOptions {
// 属性映射
propsMapping?: object;
/**
* 解析传入配置的方式
*/
parseOptions?: {
// 跳过的属性
blackList?: string[];
// 是否递归解析
isDeep?: boolean;
// 只解析以下的属性
whiteList?: string[];
};
/**
* 手动设置数,默认为value
*/
nameKey?: string;
/**
* 收集name时跳过的属性
*/
collectNameBlackList?: string[];
/**
* 只要container组件更新,该组件一定会更新
*/
forceUpdate?: boolean;
/**
* 满足一定条件就清空组件的值
*/
autoClearCondition?: (value: any, props: any) => boolean;
/**
* 如果一个组件持有多个name,则需要实现这个函数来给Connect组件提供所有可能出现的name值
* @param props
*/
getAllNameKeys?: (props: any) => string[];
/**
* 设置自动数据更新使用的回调函数,默认为onChange
*/
defaultNameCallBack?: string;
/**
* 在Container读取组件的值,并赋值到value属性之前进行一些数据处理
* @param value
* @returns {any}
*/
beforeGetData?: (value: any, props: any) => any;
/**
* 在Container获取到组件通过updateNameValue函数写入的值之前进行一些数据处理
* @param value
* @returns {any}
*/
beforeSetData?: (value: any, props: any) => any;
/**
* 获取默认值
* @param value
* @returns {any}
*/
getDefaultValue?: (value: any, props: any) => any;
/**
* 告诉框架当前name属性绑定的值是否合法
* @param value
* @param props
*/
isNameValid?: (value: any, props: any) => boolean;
}
export interface BasicConnectProps {
// 只清楚表单状态,而不清空组件数据
clearFormStatusOnlyWhenDestroy?: boolean;
// 组件销毁不清除组件状态
disableClearWhenDestroy?: boolean;
// 非表单模式下,开启此功能组件销毁自动清除数据
clearWhenDestory?: boolean;
clearWhenDestroy?: boolean;
tools: ConnectTools<BasicConnectProps>;
type: any;
/**
* name属性绑定的值
*/
name?: string;
/**
* 组件的值
*/
value?: any;
/**
* 组件默认值
*/
defaultValue?: any;
/**
* 延迟一定时间同步数据
*/
debounce?: number;
/**
* 组件禁用, 组件的验证规则也会自动跳过
*/
disabled?: boolean;
/**
* 如果组件配置了autoClearCondition, 可以使用这个属性来关闭它
*/
disabledAutoClear?: boolean;
trigger?: TriggerEventItem[];
}
enum ValidateDecision {
SKIP = 0, // 跳过本次验证
BREAK = 1, // 阻止所有的验证
PASS = 2 // 触发验证
}
class BasicConnect extends React.Component<BasicConnectProps & BasicProps, {}> {
public options: CommonOptions;
public debounceCache: { [key: string]: any };
public debounceTimer: any;
public isDebouncing: boolean;
public constructor(props: BasicConnectProps & BasicProps, options: CommonOptions) {
super(props);
this.debounceCache = {};
this.isDebouncing = false;
this.options = options;
let name = props.name;
let runTime = getRuntimeContext(props.containerContext, props.rcreContext, {
iteratorContext: props.iteratorContext
});
if (isExpression(name)) {
name = parseExpressionString(name, runTime);
}
let value;
let state: RootState = props.rcreContext.store.getState();
// 设置默认值的逻辑
if ((props.hasOwnProperty('defaultValue') &&
props.defaultValue !== null &&
props.defaultValue !== undefined) &&
name &&
!has(runTime.$data, name)) {
let defaultValue = props.defaultValue;
runTime.$data = state.$rcre.container[props.containerContext.model];
if (isExpression(defaultValue)) {
defaultValue = parseExpressionString(defaultValue, runTime);
}
if (options.getDefaultValue) {
defaultValue = options.getDefaultValue(defaultValue, props);
}
props.containerContext.$setData(name, defaultValue);
value = defaultValue;
} else if (name) {
let existValue = get(state.$rcre.container[props.containerContext.model], name);
value = existValue;
if (!isNil(existValue) && props.debounce) {
this.debounceCache[name] = existValue;
}
}
if (props.formItemContext && name) {
props.formItemContext.initControlElements(name, {
type: props.type,
disabled: props.disabled,
value: value
});
}
}
componentWillUnmount() {
if (this.props.name) {
if (this.props.formContext && this.props.formContext.$form && this.props.clearFormStatusOnlyWhenDestroy) {
this.props.formContext.$deleteFormItem(this.props.name);
} else if (this.props.formContext && this.props.formContext.$form && !this.props.disableClearWhenDestroy) {
this.props.containerContext.$deleteData(this.props.name);
} else if (this.props.clearWhenDestory || this.props.clearWhenDestroy) {
this.props.containerContext.$deleteData(this.props.name);
}
if (this.props.formItemContext) {
// 清空FormItem中监听的状态
this.props.formItemContext.deleteControlElements(this.props.name);
}
}
}
/**
* 执行一些属性的转换
*/
public applyPropsMapping<infoType extends any>(info: infoType, mapping: object) {
each(mapping, (newKey, prevKey) => {
if (info.hasOwnProperty(prevKey)) {
info[newKey] = info[prevKey];
delete info[prevKey];
}
});
}
public updateNameValue = (value: any, options: ContainerSetDataOption = {}) => {
let name = this.props.name || options.name;
if (name) {
if (typeof this.options.beforeSetData === 'function') {
value = this.options.beforeSetData(value, this.props);
}
if (typeof this.props.debounce === 'number' && !options.skipDebounce) {
this.debounceCache[name] = value;
clearTimeout(this.debounceTimer);
this.debounceTimer = setTimeout(() => {
this.isDebouncing = false;
this.props.containerContext.$setData(name!, this.debounceCache[name!], options);
}, this.props.debounce);
this.isDebouncing = true;
this.forceUpdate();
return;
}
this.props.containerContext.$setData(name, value, options);
}
}
public clearNameValue = (name?: string) => {
name = name || this.props.name;
if (name) {
this.props.containerContext.$deleteData(name);
}
}
public getFormItemControl = (name: string) => {
if (!this.props.formContext) {
console.warn(name + '组件没有在form组件内部');
return null;
}
return this.props.formContext.$getFormItem(name);
}
/**
* 组件name的变更是否会触发FormItem验证
* +----------------+-----------------+-----------------+
* | prev | next | action |
* +----------------------------------------------------+
* | name exist | name not exist | delete form |
* +----------------------------------------------------+
* | name not exist | name exist | validate form |
* +----------------------------------------------------+
* | name not exist | name not exist | skip |
* +----------------------------------------------------+
* | name exist | name exist | validate form |
* +----------------+-----------------+-----------------+
* @param nextProps
*/
private shouldNameTriggerValidate(nextProps: BasicConnectProps & BasicProps): ValidateDecision {
// 前后都没有name属性跳过
if (!this.props.name && !nextProps.name) {
return ValidateDecision.SKIP;
}
// 之前有,现在name没了,销毁
if (this.props.name && !nextProps.name) {
// delete
this.props.containerContext.$deleteData(this.props.name);
return ValidateDecision.SKIP;
}
if (this.props.name === nextProps.name) {
return ValidateDecision.SKIP;
}
if (this.props.name && nextProps.name && this.props.name !== nextProps.name) {
// 清空旧的数据
this.props.containerContext.$deleteData(this.props.name);
}
// 剩下都可以
return ValidateDecision.PASS;
}
private shouldDisabledTriggerValidate(nextProps: BasicConnectProps & BasicProps): ValidateDecision {
if (!this.props.formContext || !nextProps.formContext) {
return ValidateDecision.SKIP;
}
// disabled都没变化的情况跳过
if (!this.props.disabled && !nextProps.disabled) {
return ValidateDecision.SKIP;
}
// disabled都没变化的情况跳过
if (this.props.disabled && nextProps.disabled) {
return ValidateDecision.SKIP;
}
// 之前是false,现在改成true,需要强制设置formItem为验证成功
if (!this.props.disabled && nextProps.disabled && nextProps.name) {
nextProps.formContext.$setFormItem({
formItemName: nextProps.name,
valid: true,
status: 'success',
errorMsg: ''
});
// 这里直接跳过验证,不再进行下一步操作
return ValidateDecision.BREAK;
}
// 剩下的情况就是触发验证了
return ValidateDecision.PASS;
}
private shouldValueTriggerValidate(nextProps: BasicConnectProps & BasicProps): ValidateDecision {
if (!this.props.formContext || !nextProps.formContext) {
return ValidateDecision.SKIP;
}
let nextValue = nextProps.name ? nextProps.containerContext.$getData(nextProps.name) : undefined;
let prevValue = this.props.name ? this.props.containerContext.$getData(this.props.name) : undefined;
if (prevValue === nextValue) {
return ValidateDecision.SKIP;
}
return ValidateDecision.PASS;
}
/**
* 处理值变更,name变更,以及disabled变更这三种情况所触发的表单验证
* @param nextProps
*/
private shouldValidateFormItem(nextProps: BasicConnectProps & BasicProps) {
if (!this.props.formContext || !nextProps.formContext) {
return;
}
if (!nextProps.formItemContext || !this.props.formItemContext) {
return;
}
let list = [this.shouldNameTriggerValidate, this.shouldDisabledTriggerValidate, this.shouldValueTriggerValidate];
let shouldValidate = false;
for (let func of list) {
let decision: ValidateDecision = func.call(this, nextProps);
if (decision === ValidateDecision.SKIP) {
continue;
}
if (decision === ValidateDecision.BREAK) {
return;
}
if (decision === ValidateDecision.PASS) {
shouldValidate = true;
break;
}
}
if (shouldValidate && nextProps.name) {
let nextValue = nextProps.containerContext.$getData(nextProps.name);
nextProps.formItemContext.$validateFormItem(nextProps.name, nextValue);
}
}
public componentWillUpdate(nextProps: BasicConnectProps & BasicProps) {
let nameKey = this.options.nameKey || 'value';
if (this.props.name && nextProps.name) {
let nextValue = nextProps.containerContext.$getData(nextProps.name) || nextProps[nameKey];
let prevValue = this.props.containerContext.$getData(this.props.name) || this.props[nameKey];
if (!isEqual(prevValue, nextValue) && this.props.debounce) {
this.debounceCache[this.props.name] = nextValue;
}
}
if (typeof this.options.autoClearCondition === 'function' && !this.props.disabledAutoClear && nextProps.name) {
let value = nextProps.containerContext.$getData(nextProps.name) || nextProps[nameKey];
let clear = this.options.autoClearCondition(value, nextProps);
if (clear) {
this.clearNameValue(this.props.name);
}
}
this.shouldValidateFormItem(nextProps);
}
public hasTriggerEvent(event: string) {
if (!Array.isArray(this.props.trigger)) {
return false;
}
for (let eventItem of this.props.trigger) {
if (event === eventItem.event) {
return true;
}
}
return false;
}
/**
* 在Connect组件上清除不需要传递到RCRE之外的属性
*/
public muteParentInfo(mute: any) {
mute = clone(mute);
delete mute.type;
delete mute.trigger;
delete mute.gridCount;
delete mute.show;
delete mute.hidden;
delete mute.gridWidth;
delete mute.gridPaddingLeft;
delete mute.gridPaddingRight;
delete mute.gridPosition;
delete mute.defaultValue;
delete mute.clearFormStatusOnlyWhenDestroy;
delete mute.clearWhenDestroy;
delete mute.disableSync;
delete mute.disableClearWhenDestroy;
delete mute.rcreContext;
delete mute.triggerContext;
delete mute.containerContext;
delete mute.iteratorContext;
delete mute.formContext;
delete mute.formItemContext;
return mute;
}
/**
* 转换带有~的内部属性
* @param {Q} config
* @returns {Q}
*/
public transformInnerProperty(config: any) {
for (let key in config) {
if (config.hasOwnProperty(key)) {
if (key[0] === '~') {
config[key.substring(1)] = config[key];
delete config[key];
}
// @ts-ignore
if (config[key] === null && isExpression(this.props[key])) {
delete config[key];
}
}
}
return config;
}
public prepareRender(options: CommonOptions, props: BasicConnectProps & BasicProps = this.props) {
props = clone(props);
let mutedInfo = this.muteParentInfo(props);
mutedInfo = this.transformInnerProperty(mutedInfo);
let nameKey = options.nameKey || 'value';
let value = props[nameKey];
if (this.props.debounce && this.props.name) {
value = this.debounceCache[props.name!];
} else if (props.name) {
value = props.containerContext.$getData(props.name);
}
if (typeof options.beforeGetData === 'function') {
value = options.beforeGetData(value, props);
}
if (value !== undefined) {
mutedInfo[nameKey] = value;
}
if (isObjectLike(value)) {
let cloneValue = clone(value);
mutedInfo[nameKey] = cloneValue;
props[nameKey] = cloneValue;
}
return {
props: mutedInfo,
runTime: getRuntimeContext(props.containerContext, props.rcreContext, {
iteratorContext: props.iteratorContext,
formContext: props.formContext
}),
env: props,
debounceCache: this.debounceCache,
updateNameValue: this.updateNameValue,
registerEvent: this.props.triggerContext ? this.props.triggerContext.eventHandle : () => {
},
clearNameValue: this.clearNameValue,
getNameValue: this.props.containerContext.$getData
};
}
public async TEST_simulateEvent(event: string, args: Object = {}) {
if (!this.props.triggerContext) {
console.warn('Connect: 组件没有绑定事件');
return null;
}
return this.props.triggerContext.eventHandle(event, args);
}
public async TEST_simulateEventOnce(event: string, args: Object = {}, index: number) {
if (!this.props.triggerContext) {
console.warn('Connect: 组件没有绑定事件');
return null;
}
return this.props.triggerContext.eventHandle(event, args, {
// 只触发指定index的事件
index: index
});
}
public TEST_setData(value: any) {
if (this.props.name) {
return this.props.containerContext.$setData(this.props.name, value);
}
throw new Error('can not get component name');
}
public TEST_getData() {
return this.props;
}
public TEST_getNameValue(name: string) {
return this.props.containerContext.$getData(name);
}
public TEST_isNameValid() {
if (!this.options.isNameValid) {
return true;
}
if (!this.props.name) {
return true;
}
let value = this.props.containerContext.$getData(this.props.name);
return this.options.isNameValid(value, this.props);
}
}
polyfill(BasicConnect);
export {
BasicConnect
}; | the_stack |
import { createHeap } from "../structsGenerator/consts";
import type {
AllocatorInitOpts,
AllocatorStats,
Pow2,
AllocatorState,
} from "./functionalInterfaces";
const STATE_FREE = 0;
const STATE_USED = 1;
const STATE_TOP = 2;
const STATE_END = 3;
const STATE_ALIGN = 4;
const STATE_FLAGS = 5;
const STATE_MIN_SPLIT = 6;
/**
* @deprecated
*/
const MASK_COMPACT = 1;
const MASK_SPLIT = 2;
const SIZEOF_STATE = 7 * 4;
const MEM_BLOCK_SIZE = 0;
const MEM_BLOCK_NEXT = 1;
const MEM_BLOCK_PREV = 2;
const MEM_BLOCK_FLAGS = 3;
const SIZEOF_MEM_BLOCK_HEADER =
// MEM_BLOCK_SIZE
4 +
// MEM_BLOCK_NEXT
4 +
// MEM_BLOCK_PREV
4 +
// PADDING_OR_PLACEHOLDER
4;
// eg: 16 + 1 + 7 = 24
const MIN_MIN_SPLIT = align(SIZEOF_MEM_BLOCK_HEADER + 1, 8);
export function allocatorInit(
options: Readonly<AllocatorInitOpts>,
useShareArrayBuffer = false
): Readonly<AllocatorState> {
invariant(options.align >= 8, "align must be >= 8");
invariant(options.align % 8 === 0, "align must be multiplication of 8");
invariant(
options.minSplit >= MIN_MIN_SPLIT,
`illegal min split threshold: ${options.minSplit}, require at least ${MIN_MIN_SPLIT}`
);
const buf = useShareArrayBuffer
? new SharedArrayBuffer(options.size)
: new ArrayBuffer(options.size);
const state = new Uint32Array(buf, options.start, SIZEOF_STATE / 4);
const top = initialTop(options.start, options.align as Pow2);
const resolvedEnd =
options.end != null
? Math.min(options.end, buf.byteLength)
: buf.byteLength;
set_align(state, options.align);
set_doCompact(state, options.compact);
set_doSplit(state, options.split);
set_minSplit(state, options.minSplit);
set_end(state, resolvedEnd);
set_top(state, top);
set__free(state, 0);
set__used(state, 0);
if (top >= resolvedEnd) {
throw new Error(
`insufficient address range (0x${options.start.toString(
16
)} - 0x${resolvedEnd.toString(16)})`
);
}
return {
options,
...createHeap(buf),
state,
};
}
/**
* For testing purposes
*/
export function listAllAllocatedPointers(allocatorState: AllocatorState) {
const pointers: Array<{
blockPointer: number;
pointer: number;
size: number;
}> = [];
const { u32, state } = allocatorState;
let iteratedBlock = get__used(state);
while (iteratedBlock !== 0) {
pointers.push({
blockPointer: iteratedBlock,
pointer: iteratedBlock + SIZEOF_MEM_BLOCK_HEADER,
size: readBlockSize(u32, iteratedBlock),
});
iteratedBlock = readBlockNext(u32, iteratedBlock);
}
return pointers;
}
interface ForTestingBlock {
blockPointer: number;
dataPointer: number;
next: number;
prev: number;
size: number;
dataSize: number;
}
/**
* For testing purposes
*/
export function listAllocatedBlocks(
allocatorState: AllocatorState
): ForTestingBlock[] {
const blocks: ForTestingBlock[] = [];
const { u32, state } = allocatorState;
let iteratedBlock = get__used(state);
while (iteratedBlock !== 0) {
blocks.push({
blockPointer: iteratedBlock,
dataPointer: iteratedBlock + SIZEOF_MEM_BLOCK_HEADER,
size: readBlockSize(u32, iteratedBlock),
dataSize: readBlockSize(u32, iteratedBlock) - SIZEOF_MEM_BLOCK_HEADER,
next: readBlockNext(u32, iteratedBlock),
prev: readBlockPrev(u32, iteratedBlock),
});
iteratedBlock = readBlockNext(u32, iteratedBlock);
}
return blocks;
}
/**
* For testing purposes
*/
export function listFreeBlocks(
allocatorState: AllocatorState
): ForTestingBlock[] {
const blocks: ForTestingBlock[] = [];
const { u32, state } = allocatorState;
let iteratedBlock = get__free(state);
while (iteratedBlock !== 0) {
blocks.push({
blockPointer: iteratedBlock,
dataPointer: iteratedBlock + SIZEOF_MEM_BLOCK_HEADER,
size: readBlockSize(u32, iteratedBlock),
dataSize: readBlockSize(u32, iteratedBlock) - SIZEOF_MEM_BLOCK_HEADER,
next: readBlockNext(u32, iteratedBlock),
prev: readBlockPrev(u32, iteratedBlock),
});
iteratedBlock = readBlockNext(u32, iteratedBlock);
}
return blocks;
}
/**
* When we want to create allocator from an existing array buffer
* The array buffer is expected to already be initialized!
* @param buf
* @param start
*/
export function loadAllocator(
buf: ArrayBuffer | SharedArrayBuffer,
start: number
): Readonly<AllocatorState> {
const state = new Uint32Array(buf, start, SIZEOF_STATE / 4);
const options: AllocatorInitOpts = {
start,
end: get_end(state),
size: buf.byteLength,
align: get_align(state),
split: get_doSplit(state),
minSplit: get_minSplit(state),
compact: get_doCompact(state),
};
return {
options,
...createHeap(buf),
state,
};
}
export function calloc(
allocatorState: AllocatorState,
bytes: number,
fill = 0
): number {
const addr = malloc(allocatorState, bytes);
if (addr !== 0) {
allocatorState.u8.fill(fill, addr, addr + bytes);
}
return addr;
}
export function malloc(allocatorState: AllocatorState, bytes: number): number {
if (bytes <= 0) {
return 0;
}
const state = allocatorState.state;
const u32 = allocatorState.u32;
const paddedSize = align(bytes + SIZEOF_MEM_BLOCK_HEADER, get_align(state));
const end = get_end(state);
let top = get_top(state);
let itrBlock = get__free(state);
let prev = 0;
// look for suitable pointer in freelist blocks before eating more of the heap/top
// one day this will be a search tree
while (itrBlock) {
const itrBlockSize = readBlockSize(u32, itrBlock);
// blocks in used list are ordered by address, ascending
// when we reach to top, means we are in the end of the list
// the itrBlock is the last block physically before top
const isTop = itrBlock + itrBlockSize >= top;
// If we are in top, or the block is in a good size, we can use it
// if it's top and the block is small, we can enlarge it in-place
if (isTop || itrBlockSize >= paddedSize) {
// Check if have enough memory
if (isTop && itrBlock + paddedSize > end) {
return 0;
}
removeBlockFromList(u32, itrBlock);
// Block was the first in list
if (prev === 0) {
set__free(state, readBlockNext(u32, itrBlock));
}
// add block to the beginning of used blocks list
setBlockPrev(u32, get__used(state), itrBlock);
setBlockNext(u32, itrBlock, get__used(state));
setBlockPrev(u32, itrBlock, 0);
set__used(state, itrBlock);
// We are the last block, so we can enlarge the block into top
// Resize-up the block to the requested size
if (isTop) {
set_top(state, itrBlock + setBlockSize(u32, itrBlock, paddedSize));
} else if (get_doSplit(state)) {
const excess = itrBlockSize - paddedSize;
if (excess >= get_minSplit(state)) {
splitBlock(state, u32, itrBlock, excess);
}
}
return blockDataAddress(itrBlock);
}
prev = itrBlock;
itrBlock = readBlockNext(u32, itrBlock);
}
// We didn't use any block from the free-list,
// try to create new block from top
const newBlock = top;
top = newBlock + paddedSize;
if (top <= end) {
initBlock(u32, newBlock, paddedSize, get__used(state), 0);
setBlockPrev(u32, get__used(state), newBlock);
set__used(state, newBlock);
set_top(state, top);
return blockDataAddress(newBlock);
}
// Out of memory / memory is fragmented, no free block big enough
return 0;
}
export function realloc(
allocatorState: AllocatorState,
ptr: number,
bytes: number
): number {
if (bytes <= 0) {
return 0;
}
const { state, u32, u8 } = allocatorState;
const originalBlockAddr = blockSelfAddress(ptr);
let maybeNewAddr = 0;
let blockEnd = 0;
const newWishedPaddedSize = align(
bytes + SIZEOF_MEM_BLOCK_HEADER,
get_align(state)
);
const originalBlockSize = readBlockSize(u32, originalBlockAddr);
blockEnd = originalBlockAddr + originalBlockSize;
const isTop = blockEnd === get_top(state);
// no change is needed
if (newWishedPaddedSize === originalBlockSize) {
// noop
maybeNewAddr = originalBlockAddr;
} else if (
// The block is the last one before top
isTop &&
// we need to shrink
(newWishedPaddedSize < originalBlockSize ||
// we need to enlarge and we have enough memory on top for it
(newWishedPaddedSize > originalBlockSize &&
originalBlockAddr + newWishedPaddedSize <= get_end(state)))
) {
// very easy, no matter if we need to enlarge or shrink.
// just change the block size & move top
set_top(
state,
originalBlockAddr +
setBlockSize(u32, originalBlockAddr, newWishedPaddedSize)
);
maybeNewAddr = originalBlockAddr;
}
// Smaller size is needed, try to split, or leave it as is
else if (newWishedPaddedSize < originalBlockSize) {
const excess = originalBlockSize - newWishedPaddedSize;
if (get_doSplit(state) && excess >= get_minSplit(state)) {
splitBlock(state, u32, originalBlockAddr, excess);
} else {
// here we just stay with the same block size
// noop
}
maybeNewAddr = originalBlockAddr;
} else {
// fallback to free & malloc
const newAllocatedBlock = malloc(allocatorState, bytes);
if (newAllocatedBlock === 0) {
// OOM :(
// short circuit return
return 0;
} else {
maybeNewAddr = blockSelfAddress(newAllocatedBlock);
u8.copyWithin(
blockDataAddress(maybeNewAddr),
blockDataAddress(originalBlockAddr),
blockEnd
);
// Free only after the data copy
free(allocatorState, blockDataAddress(originalBlockAddr));
}
}
return blockDataAddress(maybeNewAddr);
}
export function free(
allocatorState: AllocatorState,
blockDataSpacePtr: number
): boolean {
const state = allocatorState.state;
const u32 = allocatorState.u32;
const blockToFree = blockSelfAddress(blockDataSpacePtr);
const firstUsedBlock = get__used(state);
const next = readBlockNext(u32, blockToFree);
const prev = readBlockPrev(u32, blockToFree);
// This block is the first one in the used-list
if (blockToFree === firstUsedBlock) {
set__used(state, next);
if (next !== 0) {
setBlockPrev(u32, next, 0);
}
} else {
if (prev !== 0) {
setBlockNext(u32, prev, next);
}
if (next !== 0) {
setBlockPrev(u32, next, prev);
}
}
tryToMergeWithOtherFreeBlocksMeldToTopInsertToFreeList(
state,
u32,
blockToFree
);
return true;
}
function isBlockConsecutivePrev(
u32: Uint32Array,
blockToCheck: number,
prevBlock: number
): boolean {
return prevBlock + readBlockSize(u32, prevBlock) === blockToCheck;
}
function isBlockConsecutiveNext(
u32: Uint32Array,
blockToCheck: number,
nextBlock: number
): boolean {
return blockToCheck + readBlockSize(u32, blockToCheck) === nextBlock;
}
function isBlockConsecutiveTop(
u32: Uint32Array,
blockToCheck: number,
top: number
) {
return blockToCheck + readBlockSize(u32, blockToCheck) === top;
}
export function freeAll(allocatorState: AllocatorState): void {
const state = allocatorState.state;
const options = allocatorState.options;
set__free(state, 0);
set__used(state, 0);
set_top(state, initialTop(options.start, get_align(state) as Pow2));
}
export function stats(
allocatorState: Readonly<AllocatorState>
): Readonly<AllocatorStats> {
const listStats = (block: number) => {
let count = 0;
let size = 0;
while (block) {
count++;
size += readBlockSize(allocatorState.u32, block);
block = readBlockNext(allocatorState.u32, block);
}
return { count, size };
};
const free = listStats(get__free(allocatorState.state));
return {
free,
used: listStats(get__used(allocatorState.state)),
top: get_top(allocatorState.state),
available:
get_end(allocatorState.state) - get_top(allocatorState.state) + free.size,
total: allocatorState.u8.buffer.byteLength,
};
}
/**
* To be used after ArrayBuffer change
*/
export function setEnd(allocatorState: AllocatorState, newEnd: number) {
set_end(allocatorState.state, newEnd);
}
// export function release() {
// // NOOP
// // delete this.u8;
// // delete this.u32;
// // delete this.state;
// // delete this.buf;
// // return true;
// }
function invariant(assertionResult: boolean, message: string): void {
if (!assertionResult) {
throw new Error("Invariant: " + message);
}
}
/**
* Exported for testing proposes only
* @private
* @param state
*/
function get_align(state: Uint32Array): Pow2 {
return <Pow2>state[STATE_ALIGN];
}
function set_align(state: Uint32Array, x: Pow2): void {
state[STATE_ALIGN] = x;
}
/**
* Exported for testing proposes only
* @private
* @param state
*/
export function get_end(state: Uint32Array): number {
return state[STATE_END];
}
function set_end(state: Uint32Array, x: number): void {
state[STATE_END] = x;
}
/**
* Exported for testing proposes only
* @private
* @param state
*/
export function get_top(state: Uint32Array): number {
return state[STATE_TOP];
}
function set_top(state: Uint32Array, x: number): void {
state[STATE_TOP] = x;
}
/**
* Exported for testing proposes only
* @private
* @param state
*/
export function get__free(state: Uint32Array): number {
return state[STATE_FREE];
}
function set__free(state: Uint32Array, block: number): void {
state[STATE_FREE] = block;
}
/**
* Exported for testing proposes only
* @private
* @param state
*/
export function get__used(state: Uint32Array): number {
return state[STATE_USED];
}
function set__used(state: Uint32Array, block: number): void {
state[STATE_USED] = block;
}
/**
* Exported for testing proposes only
* @private
* @param state
*/
export function get_doCompact(state: Uint32Array): boolean {
return !!(state[STATE_FLAGS] & MASK_COMPACT);
}
function set_doCompact(state: Uint32Array, flag: boolean): void {
if (flag) {
state[STATE_FLAGS] |= 1 << (MASK_COMPACT - 1);
} else {
state[STATE_FLAGS] &= ~MASK_COMPACT;
}
}
/**
* Exported for testing proposes only
* @private
* @param state
*/
export function get_doSplit(state: Uint32Array): boolean {
return !!(state[STATE_FLAGS] & MASK_SPLIT);
}
function set_doSplit(state: Uint32Array, flag: boolean): void {
if (flag) {
state[STATE_FLAGS] |= 1 << (MASK_SPLIT - 1);
} else {
state[STATE_FLAGS] &= ~MASK_SPLIT;
}
}
/**
* Exported for testing proposes only
* @private
* @param state
*/
function get_minSplit(state: Uint32Array): number {
return state[STATE_MIN_SPLIT];
}
function set_minSplit(state: Uint32Array, x: number): void {
state[STATE_MIN_SPLIT] = x;
}
function initialTop(start: number, _align: Pow2): number {
return (
align(start + SIZEOF_STATE + SIZEOF_MEM_BLOCK_HEADER, _align) -
SIZEOF_MEM_BLOCK_HEADER
);
}
/**
* Exported for testing proposes only
* @private
* @param state
* @param u32
* @param block
*/
export function readBlockSize(u32: Uint32Array, block: number): number {
return u32[(block >> 2) + MEM_BLOCK_SIZE];
}
/**
* Sets & returns given block size.
*
* @param block -
* @param size -
*/
function setBlockSize(u32: Uint32Array, block: number, size: number): number {
u32[(block >> 2) + MEM_BLOCK_SIZE] = size;
return size;
}
/**
* Exported for testing proposes only
* @private
* @param u32
* @param block
*/
export function readBlockNext(u32: Uint32Array, block: number): number {
return u32[(block >> 2) + MEM_BLOCK_NEXT];
}
/**
* Sets block next pointer to `next`. Use zero to indicate list end.
*
* @param block -
*/
function setBlockNext(u32: Uint32Array, block: number, next: number): void {
u32[(block >> 2) + MEM_BLOCK_NEXT] = next;
}
/**
* Exported for testing proposes only
* @private
* @param u32
* @param block
*/
export function readBlockPrev(u32: Uint32Array, block: number): number {
return u32[(block >> 2) + MEM_BLOCK_PREV];
}
/**
* Sets block next pointer to `next`. Use zero to indicate list end.
*
* @param block -
*/
function setBlockPrev(u32: Uint32Array, block: number, prev: number): void {
u32[(block >> 2) + MEM_BLOCK_PREV] = prev;
}
/**
* Initializes block header with given `size` and `next` pointer. Returns `block`.
*
* @param block -
* @param size -
* @param next -
*/
function initBlock(
u32: Uint32Array,
block: number,
size: number,
next: number,
prev: number
): number {
const idx = block >>> 2;
u32[idx + MEM_BLOCK_SIZE] = size;
u32[idx + MEM_BLOCK_NEXT] = next;
u32[idx + MEM_BLOCK_PREV] = prev;
u32[idx + MEM_BLOCK_FLAGS] = 0;
return block;
}
function removeBlockFromList(u32: Uint32Array, block: number): void {
const prev = readBlockPrev(u32, block);
const next = readBlockNext(u32, block);
if (prev !== 0) {
setBlockNext(u32, prev, next);
}
if (next !== 0) {
setBlockPrev(u32, next, prev);
}
}
function splitBlock(
stateU32: Uint32Array,
u32: Uint32Array,
blockToSplitFrom: number,
howMuchToSplitIntoNewBlock: number
): void {
const blockSizeAfterSplit =
readBlockSize(u32, blockToSplitFrom) - howMuchToSplitIntoNewBlock;
const splittedBlockPtr = blockToSplitFrom + blockSizeAfterSplit;
setBlockSize(u32, blockToSplitFrom, blockSizeAfterSplit);
initBlock(u32, splittedBlockPtr, howMuchToSplitIntoNewBlock, 0, 0);
// revisit: we may simply insert this block, do need to the whole afterRemovedFromUsedListFindBetterName
// As we are sure it's not going to merge/meld it because it's a split
tryToMergeWithOtherFreeBlocksMeldToTopInsertToFreeList(
stateU32,
u32,
splittedBlockPtr
);
}
function tryToMergeWithOtherFreeBlocksMeldToTopInsertToFreeList(
stateU32: Uint32Array,
u32: Uint32Array,
blockThatIsNowFree: number
) {
let nextBlockItr = get__free(stateU32);
let prev = 0;
// We don't want to mutate blockThatIsNowFree
let blockNowFreeMaybeMergedWithPrev = blockThatIsNowFree;
// find possible before & after blocks
while (nextBlockItr) {
if (blockNowFreeMaybeMergedWithPrev <= nextBlockItr) {
break;
}
prev = nextBlockItr;
nextBlockItr = readBlockNext(u32, nextBlockItr);
}
// first, we try to insert the block and merge it with prev if applicable
if (prev !== 0) {
if (isBlockConsecutivePrev(u32, blockNowFreeMaybeMergedWithPrev, prev)) {
// merge current block and the prev block
setBlockSize(
u32,
prev,
readBlockSize(u32, prev) +
readBlockSize(u32, blockNowFreeMaybeMergedWithPrev)
);
blockNowFreeMaybeMergedWithPrev = prev;
} else {
// insert block. nextBlockItr may be zero!
setBlockNext(u32, prev, blockNowFreeMaybeMergedWithPrev);
if (nextBlockItr !== 0) {
setBlockPrev(u32, nextBlockItr, blockNowFreeMaybeMergedWithPrev);
}
setBlockNext(u32, blockNowFreeMaybeMergedWithPrev, nextBlockItr);
setBlockPrev(u32, blockNowFreeMaybeMergedWithPrev, prev);
}
} else {
// prev is 0, insert at the beginning of free-list. nextBlockItr may be zero!
if (nextBlockItr !== 0) {
setBlockPrev(u32, nextBlockItr, blockNowFreeMaybeMergedWithPrev);
}
set__free(stateU32, blockNowFreeMaybeMergedWithPrev);
setBlockNext(u32, blockNowFreeMaybeMergedWithPrev, nextBlockItr);
// prev = 0
setBlockPrev(u32, blockNowFreeMaybeMergedWithPrev, 0);
}
// now let's see if we can meld into top
if (
isBlockConsecutiveTop(
u32,
blockNowFreeMaybeMergedWithPrev,
get_top(stateU32)
)
) {
// may be 0!
const theNewLastBlockInList = readBlockPrev(
u32,
blockNowFreeMaybeMergedWithPrev
);
set_top(stateU32, blockNowFreeMaybeMergedWithPrev);
if (theNewLastBlockInList === 0) {
set__free(stateU32, 0);
} else {
setBlockNext(u32, theNewLastBlockInList, 0);
}
}
// Then we try to merge with next
else if (
nextBlockItr !== 0 &&
isBlockConsecutiveNext(u32, blockNowFreeMaybeMergedWithPrev, nextBlockItr)
) {
// may be zero, but it's ok!
const nextOfNext = readBlockNext(u32, nextBlockItr);
setBlockSize(
u32,
blockNowFreeMaybeMergedWithPrev,
readBlockSize(u32, blockNowFreeMaybeMergedWithPrev) +
readBlockSize(u32, nextBlockItr)
);
if (nextOfNext !== 0) {
setBlockPrev(u32, nextOfNext, blockNowFreeMaybeMergedWithPrev);
}
setBlockNext(u32, blockNowFreeMaybeMergedWithPrev, nextOfNext);
}
}
/**
* Returns a block's data address, based on given alignment.
*
* @param blockAddress -
*/
function blockDataAddress(blockAddress: number): number {
return blockAddress + SIZEOF_MEM_BLOCK_HEADER;
}
/**
* Returns block start address for given data address and alignment.
*
* @param dataAddress -
*/
function blockSelfAddress(dataAddress: number): number {
return dataAddress - SIZEOF_MEM_BLOCK_HEADER;
}
/**
* Aligns `addr` to next multiple of `size`. The latter must be a power
* of 2.
*
* @param addr - value to align
* @param size - alignment value
*/
export function align(addr: number, size: Pow2): number {
return size--, (addr + size) & ~size;
} | the_stack |
declare module "@matrix-org/olm" {
export class Account {
constructor();
free(): void;
create(): void;
identity_keys(): string;
sign(message: string | Uint8Array): string;
one_time_keys(): string;
mark_keys_as_published(): void;
max_number_of_one_time_keys(): number;
generate_one_time_keys(number_of_keys: number): void;
remove_one_time_keys(session: Session): void;
generate_fallback_key(): void;
fallback_key(): string;
pickle(key: string | Uint8Array): string;
unpickle(key: string | Uint8Array, pickle: string): void;
}
export class Session {
constructor();
free(): void;
pickle(key: string | Uint8Array): string;
unpickle(key: string | Uint8Array, pickle: string): void;
create_outbound(account: Account, their_identity_key: string, their_one_time_key: string): void;
create_inbound(account: Account, one_time_key_message: string): void;
create_inbound_from(account: Account, identity_key: string, one_time_key_message: string): void;
session_id(): string;
has_received_message(): boolean;
matches_inbound(one_time_key_message: string): boolean;
matches_inbound_from(identity_key: string, one_time_key_message: string): boolean;
encrypt(plaintext: string): object;
decrypt(message_type: number, message: string): string;
describe(): string;
}
export class Utility {
constructor();
free(): void;
sha256(input: string | Uint8Array): string;
ed25519_verify(key: string, message: string | Uint8Array, signature: string): void;
}
export class InboundGroupSession {
constructor();
free(): void;
pickle(key: string | Uint8Array): string;
unpickle(key: string | Uint8Array, pickle: string): void;
create(session_key: string): string;
import_session(session_key: string): string;
decrypt(message: string): object;
session_id(): string;
first_known_index(): number;
export_session(message_index: number): string;
}
export class OutboundGroupSession {
constructor();
free(): void;
pickle(key: string | Uint8Array): string;
unpickle(key: string | Uint8Array, pickle: string): void;
create(): void;
encrypt(plaintext: string): string;
session_id(): string;
session_key(): string;
message_index(): number;
}
export class PkEncryption {
constructor();
free(): void;
set_recipient_key(key: string): void;
encrypt(plaintext: string): object;
}
export class PkDecryption {
constructor();
free(): void;
init_with_private_key(key: Uint8Array): string;
generate_key(): string;
get_private_key(): Uint8Array;
pickle(key: string | Uint8Array): string;
unpickle(key: string | Uint8Array, pickle: string): string;
decrypt(ephemeral_key: string, mac: string, ciphertext: string): string;
}
export class PkSigning {
constructor();
free(): void;
init_with_seed(seed: Uint8Array): string;
generate_seed(): Uint8Array;
sign(message: string): string;
}
export class SAS {
constructor();
free(): void;
get_pubkey(): string;
set_their_key(their_key: string): void;
generate_bytes(info: string, length: number): Uint8Array;
calculate_mac(input: string, info: string): string;
calculate_mac_long_kdf(input: string, info: string): string;
}
export function init(opts?: object): Promise<void>;
export function get_library_version(): [number, number, number];
export const PRIVATE_KEY_LENGTH: number;
}
declare module "@thirdroom/hydrogen-view-sdk" {
import type * as Olm from "@matrix-org/olm";
export type SubscriptionHandle = () => undefined;
export abstract class BaseObservable<T> {
onSubscribeFirst(): void;
onUnsubscribeLast(): void;
subscribe(handler: T): SubscriptionHandle;
unsubscribe(handler?: T): undefined;
unsubscribeAll(): void;
get hasSubscriptions(): boolean;
}
interface IWaitHandle<T> {
promise: Promise<T>;
dispose(): void;
}
export abstract class BaseObservableValue<T> extends BaseObservable<(value: T) => void> {
emit(argument: T): void;
abstract get(): T;
waitFor(predicate: (value: T) => boolean): IWaitHandle<T>;
}
export class ObservableValue<T> extends BaseObservableValue<T> {
constructor(initialValue: T);
get(): T;
set(value: T): void;
}
export class RetainedObservableValue<T> extends ObservableValue<T> {
constructor(initialValue: T, freeCallback: () => void);
}
export interface IMapObserver<K, V> {
onReset(): void;
onAdd(key: K, value: V): void;
onUpdate(key: K, value: V, params: any): void;
onRemove(key: K, value: V): void;
}
export abstract class BaseObservableMap<K, V> extends BaseObservable<IMapObserver<K, V>> {
emitReset(): void;
emitAdd(key: K, value: V): void;
emitUpdate(key: K, value: V, params: any): void;
emitRemove(key: K, value: V): void;
abstract [Symbol.iterator](): Iterator<[K, V]>;
abstract get size(): number;
abstract get(key: K): V | undefined;
sortValues(comparator: ListComparator<V>): SortedMapList<V>;
mapValues<K, V, M>(mapper: Mapper<K, V, M>, updater?: Updater<V, M>): MappedMap<K, V, M>;
filterValues(filter: (value: V, key: K) => boolean): FilteredMap<K, V>;
join(...otherMaps: BaseObservableMap<any, any>[]): JoinedMap<any, any>;
}
export class ObservableMap<K, V> extends BaseObservableMap<K, V> {
constructor(initialValues?: (readonly [K, V])[]);
update(key: K, params?: any): boolean;
add(key: K, value: V): boolean;
remove(key: K): boolean;
set(key: K, value: V): boolean;
reset(): void;
get(key: K): V | undefined;
get size(): number;
[Symbol.iterator](): IterableIterator<[K, V]>;
values(): IterableIterator<V>;
keys(): IterableIterator<K>;
}
export type Mapper<K, V, M> = (value: V, emitUpdate: (key: K) => void) => M;
export type Updater<V, M> = (mappedValue: M, params: any, value: V) => void;
export class MappedMap<K, V, M> extends BaseObservableMap<K, M> {
constructor(source: BaseObservableMap<K, V>, mapper: Mapper<K, V, M>, updater?: Updater<V, M>);
onAdd(key: K, value: V): void;
onRemove(key: K, value: V): void;
onUpdate(key: K, value: V, params: any): void;
onReset(): void;
get(key: K): M | undefined;
get size(): number;
[Symbol.iterator](): IterableIterator<[K, M]>;
}
export type Filter<K, V> = (value: V, key: K) => boolean;
export class FilteredMap<K, V> extends BaseObservableMap<K, V> {
constructor(source: BaseObservableMap<K, V>, filter: Filter<K, V>);
setFilter(filter: Filter<K, V>): void;
onAdd(key: K, value: V): void;
onRemove(key: K, value: V): void;
onUpdate(key: K, value: V, params: any): void;
onReset(): void;
get(key: K): V | undefined;
get size(): number;
[Symbol.iterator](): IterableIterator<[K, V]>;
}
export class JoinedMap<K, V> extends BaseObservableMap<K, V> {
constructor(sources: BaseObservableMap<any, any>[]);
onAdd(key: K, value: V): void;
onRemove(key: K, value: V): void;
onUpdate(key: K, value: V, params: any): void;
onReset(): void;
get(key: K): V | undefined;
get size(): number;
[Symbol.iterator](): IterableIterator<[K, V]>;
}
export interface IListObserver<T> {
onReset(list: BaseObservableList<T>): void;
onAdd(index: number, value: T, list: BaseObservableList<T>): void;
onUpdate(index: number, value: T, params: any, list: BaseObservableList<T>): void;
onRemove(index: number, value: T, list: BaseObservableList<T>): void;
onMove(from: number, to: number, value: T, list: BaseObservableList<T>): void;
}
export abstract class BaseObservableList<T> extends BaseObservable<IListObserver<T>> implements Iterable<T> {
emitReset(): void;
emitAdd(index: number, value: T): void;
emitUpdate(index: number, value: T, params?: any): void;
emitRemove(index: number, value: T): void;
emitMove(fromIdx: number, toIdx: number, value: T): void;
abstract [Symbol.iterator](): Iterator<T>;
abstract get length(): number;
}
export class ObservableArray<T> extends BaseObservableList<T> {
constructor(initialValues?: T[]);
append(item: T): void;
remove(idx: number): void;
insertMany(idx: number, items: T[]): void;
insert(idx: number, item: T): void;
move(fromIdx: number, toIdx: number): void;
update(idx: number, item: T, params?: any): void;
get array(): Readonly<T[]>;
at(idx: number): T | undefined;
get length(): number;
[Symbol.iterator](): IterableIterator<T>;
}
export type ListComparator<T> = (a: T, b: T) => number;
export class SortedMapList<T> extends BaseObservableList<T> {
constructor(sourceMap: BaseObservableMap<any, T>, comparator: ListComparator<T>);
onAdd(key: any, value: T): void;
onRemove(key: any, value: T): void;
onUpdate(key: any, value: T, params: any): void;
onReset(): void;
get(index: number): T;
get length(): number;
[Symbol.iterator](): IterableIterator<T>;
}
export enum LoadStatus {
NotLoading = "NotLoading",
Login = "Login",
LoginFailed = "LoginFailed",
QueryAccount = "QueryAccount", // check for dehydrated device after login
AccountSetup = "AccountSetup", // asked to restore from dehydrated device if present, call sc.accountSetup.finish() to progress to the next stage
Loading = "Loading",
SessionSetup = "SessionSetup", // upload e2ee keys, ...
Migrating = "Migrating", // not used atm, but would fit here
FirstSync = "FirstSync",
Error = "Error",
Ready = "Ready",
}
export interface ISessionInfo {
id: string;
deviceId: string;
userId: string;
homeserver: string;
/**
* @deprecated Use homeserver instead
*/
homeServer: string;
accessToken: string;
lastUsed: number;
}
export interface ISessionInfoStorage {
getAll(): Promise<ISessionInfo[]>;
updateLastUsed(id: string, timestamp: number): Promise<void>;
get(id: string): Promise<ISessionInfo | undefined>;
add(sessionInfo: ISessionInfo): Promise<void>;
delete(sessionId: string): Promise<void>;
}
export class Segment {
type: string;
value: any;
}
export type NavigationAllowsChildHandler = (parent: Segment, child: Segment) => boolean;
export class Navigation {
constructor(allowsChild: NavigationAllowsChildHandler);
}
export interface IBlobHandle {
nativeBlob: any;
url: string;
size: number;
mimeType: string;
readAsBuffer(): BufferSource;
dispose(): void;
}
export class Platform {
sessionInfoStorage: ISessionInfoStorage;
devicePixelRatio: number;
logger: ILogger;
mediaDevices: MediaDevices;
config: {
defaultHomeServer: string;
[key: string]: any;
};
constructor(options: { container: HTMLElement; assetPaths: any; config: any; options?: any; cryptoExtras?: any });
setNavigation(navigation: Navigation): void;
openFile(mimeType: string): Promise<
| {
name: string;
blob: IBlobHandle;
}
| undefined
>;
dispose(): void;
}
export class MediaRepository {
mxcUrlThumbnail(url: string, width: number, height: number, method: "crop" | "scale"): string | null;
}
export enum RoomVisibility {
DirectMessage,
Private,
Public,
}
export enum RoomType {
World,
}
export class RoomBeingCreated extends EventEmitter<any> {
public readonly id: string;
public readonly mediaRepository: MediaRepository;
public readonly platform: Platform;
get avatarColorId(): string;
get avatarUrl(): string | undefined;
get avatarBlobUrl(): string | undefined;
get roomId(): string | undefined;
get name(): string;
get isBeingCreated(): boolean;
get error(): Error | undefined;
cancel(): void;
}
export enum RoomStatus {
None = 1 << 0,
BeingCreated = 1 << 1,
Invited = 1 << 2,
Joined = 1 << 3,
Replaced = 1 << 4,
Archived = 1 << 5,
}
interface ICreateRoom {
type?: RoomType;
visibility: RoomVisibility;
name?: string;
topic?: string;
isEncrypted?: boolean;
isFederationDisabled?: boolean;
alias?: string;
avatar?: {
name: string;
blob: IBlobHandle;
info: {
w?: number;
h?: number;
mimetype: string;
size: number;
};
};
powerLevelContentOverride?: any;
initialState?: any[];
}
export class Session {
userId: string;
_sessionInfo: ISessionInfo;
_hsApi: HomeServerApi;
mediaRepository: MediaRepository;
rooms: ObservableMap<string, Room>;
roomsBeingCreated: ObservableMap<string, RoomBeingCreated>;
callHandler: CallHandler;
createRoom(options: ICreateRoom): RoomBeingCreated;
joinRoom(roomIdOrAlias: string, log?: ILogger): Promise<string>;
observeRoomStatus(roomId: string): Promise<RetainedObservableValue<RoomStatus>>;
}
export class LocalMedia {
readonly userMedia?: Stream | undefined;
readonly screenShare?: Stream | undefined;
readonly dataChannelOptions?: RTCDataChannelInit | undefined;
constructor(
userMedia?: Stream | undefined,
screenShare?: Stream | undefined,
dataChannelOptions?: RTCDataChannelInit | undefined
);
withUserMedia(stream: Stream): LocalMedia;
withScreenShare(stream: Stream): LocalMedia;
withDataChannel(options: RTCDataChannelInit): LocalMedia;
clone(): LocalMedia;
dispose(): void;
}
enum SyncStatus {
InitialSync = "InitialSync",
CatchupSync = "CatchupSync",
Syncing = "Syncing",
Stopped = "Stopped",
}
export class Sync {
constructor(options: { hsApi: any; session: Session; storage: any; logger: any });
get status(): ObservableValue<SyncStatus>;
get error(): any;
start(): void;
stop(): void;
}
class ObservedEvent<T> extends BaseObservableValue<T> {
constructor(eventMap: ObservedEventMap, entry: T, id: string);
update(entry: T): void;
get(): T;
}
export class ObservedEventMap {
constructor(notifyEmpty: () => void);
observe(eventId: string, eventEntry: any): ObservedEvent<any>;
updateEvents(eventEntries: any[]): void;
}
export class Timeline {}
export class RoomMember {}
export class MemberList {}
export interface PowerLevelOptions {
powerLevelEvent: any;
createEvent: any;
ownUserId: any;
membership: any;
}
export class PowerLevels {
canRedactFromSender(userId: string): boolean;
canSendType(eventType: string): boolean;
get canRedact(): boolean;
getUserLevel(userId: string): number;
}
export abstract class RoomKey {
isForSession(roomId: string, senderKey: string, sessionId: string): boolean;
abstract get roomId(): string;
abstract get senderKey(): string;
abstract get sessionId(): string;
abstract get claimedEd25519Key(): string;
abstract get serializationKey(): string;
abstract get serializationType(): string;
abstract get eventIds(): string[] | undefined;
abstract loadInto(session: any, pickleKey: string): void;
get isBetter(): boolean | undefined;
set isBetter(value: boolean | undefined);
}
export class AttachmentUpload {
constructor({ filename, blob, platform }: { filename: string; blob: IBlobHandle; platform: Platform });
get size(): number;
get sentBytes(): number;
abort(): void;
get localPreview(): Blob;
encrypt(): Promise<void>;
upload(hsApi: HomeServerApi, progressCallback: () => void, log?: any): Promise<void>;
applyToContent(urlPath: string, content: {}): void;
dispose(): void;
}
export interface RoomOptions {
roomId: string;
storage: any;
hsApi: any;
mediaRepository: MediaRepository;
emitCollectionChange: any;
user: any;
createRoomEncryption: any;
getSyncToken: any;
platform: Platform;
}
export type RoomId = string;
export class BaseRoom extends EventEmitter<any> {
constructor(roomOptions: RoomOptions);
getStateEvent(type: string, key?: string): any;
notifyRoomKey(roomKey: RoomKey, eventIds: string[], log?: any): Promise<void>;
load(summary: any, txn: any, log: any): Promise<void>;
observeMember(userId: string): Promise<RetainedObservableValue<RoomMember> | null>;
loadMemberList(log?: any): Promise<MemberList>;
fillGap(fragmentEntry: any, amount: number, log?: any): Promise<void>;
get name(): string | null;
get id(): RoomId;
get avatarUrl(): string | null;
get avatarColorId(): string;
get type(): string | undefined;
get lastMessageTimestamp(): number;
get isLowPriority(): boolean;
get isEncrypted(): boolean;
get isJoined(): boolean;
get isLeft(): boolean;
get canonicalAlias(): string;
get joinedMemberCount(): number;
get mediaRepository(): MediaRepository;
get membership(): any;
get isDirectMessage(): boolean;
isDirectMessageForUserId(userId: string): boolean;
observePowerLevels(): Promise<RetainedObservableValue<PowerLevels>>;
enableKeyBackup(keyBackup: boolean): void;
openTimeline(log?: any): Promise<Timeline>;
observeEvent<T = any>(eventId: string): ObservedEvent<T>;
dispose(): void;
}
export class Room extends BaseRoom {
_timeline: any;
constructor(roomOptions: RoomOptions);
sendEvent(eventType: string, content: any, attachments?: any, log?: any): Promise<void>;
sendRedaction(eventIdOrTxnId: string, reason: string, log?: any): Promise<void>;
ensureMessageKeyIsShared(log?: any): Promise<any>;
get avatarColorId(): string;
get isUnread(): boolean;
get notificationCount(): number;
get highlightCount(): number;
get isTrackingMembers(): boolean;
clearUnread(log?: any): Promise<void>;
leave(log?: any): Promise<void>;
createAttachment(blob: Blob, filename: string): AttachmentUpload;
dispose(): void;
}
export class Client {
sessionId: string;
session?: Session;
sync: Sync;
loadStatus: ObservableValue<LoadStatus>;
constructor(platform: Platform);
startWithExistingSession(sessionId: string): Promise<void>;
queryLogin(homeserver: string): any;
startWithLogin(loginMethod: any, options?: { inspectAccountSetup: boolean }): Promise<void>;
startLogout(sessionId: string): Promise<void>;
dispose(): void;
}
export interface IDisposable {
dispose(): void;
}
export type Disposable = IDisposable | (() => void);
export class Disposables {
track<D extends Disposable>(disposable: D): D;
untrack(disposable: Disposable): undefined;
dispose(): void;
get isDisposed(): boolean;
disposeTracked(value: Disposable | undefined): undefined;
}
type Handler<T> = (value?: T) => void;
export class EventEmitter<T> {
emit<K extends keyof T>(name: K, value?: T[K]): void;
disposableOn<K extends keyof T>(name: K, callback: Handler<T[K]>): () => void;
on<K extends keyof T>(name: K, callback: Handler<T[K]>): void;
off<K extends keyof T>(name: K, callback: Handler<T[K]>): void;
onFirstSubscriptionAdded<K extends keyof T>(name: K): void;
onLastSubscriptionRemoved<K extends keyof T>(name: K): void;
}
class Timeout {
constructor(ms: number);
elapsed(): Promise<void>;
abort(): void;
dispose(): void;
}
class Interval {
constructor(ms: number, callback: () => void);
dispose(): void;
}
class TimeMeasure {
constructor();
measure(): number;
}
export class Clock {
createMeasure(): TimeMeasure;
createTimeout(ms: number): Timeout;
createInterval(callback: () => void, ms: number): Interval;
now(): number;
}
export class URLRouter {
constructor(options: any);
attach(): void;
dispose(): void;
pushUrl(url: string): void;
tryRestoreLastUrl(): boolean;
urlForSegments(segments: string): string;
urlForSegment(type: string, value: string): string;
urlUntilSegment(type: string): string;
urlForPath(path: string): string;
openRoomActionUrl(roomId: string): string;
createSSOCallbackURL(): string;
normalizeUrl(): void;
}
export type ViewModelOptions = {
platform: Platform;
logger: ILogger;
urlCreator: URLRouter;
navigation: Navigation;
emitChange?: (params: any) => void;
};
export class ViewModel<O extends ViewModelOptions = ViewModelOptions> extends EventEmitter<{ change: never }> {
constructor(options: O);
childOptions<T extends Object>(explicitOptions: T): T & ViewModelOptions;
get options(): O;
getOption<N extends keyof O>(name: N): O[N];
observeNavigation(type: string, onChange: (value: string | true | undefined, type: string) => void): void;
track<D extends Disposable>(disposable: D): D;
untrack(disposable: Disposable): undefined;
dispose(): void;
get isDisposed(): boolean;
disposeTracked(disposable: Disposable | undefined): undefined;
i18n(parts: TemplateStringsArray, ...expr: any[]): string;
updateOptions(options: O): void;
emitChange(changedProps: any): void;
get platform(): Platform;
get clock(): Clock;
get logger(): ILogger;
get urlCreator(): URLRouter;
get navigation(): Navigation;
}
export interface IRoomViewModel {
room: Room;
_room: Room;
isEncrypted: boolean;
_createTile(entry: any): SimpleTile | undefined;
_sendMessage(message: any, replyVM: any): Promise<boolean>;
_pickAndSendPicture(): void;
_pickAndSendFile(): void;
_pickAndSendVideo(): void;
startReply(entry: any): void;
}
export interface SimpleTileOptions extends ViewModelOptions {
timeline: Timeline;
roomVM: IRoomViewModel;
}
export class SimpleTile extends ViewModel {
constructor(entry: any, options: SimpleTileOptions);
get shape(): string | null;
get isContinuation(): boolean;
get hasDateSeparator(): boolean;
get id(): string;
get eventId(): string;
get isPending(): boolean;
get isUnsent(): boolean;
get canAbortSending(): boolean;
abortSending(): void;
setUpdateEmit(emitUpdate: any): void;
get upperEntry(): any;
get lowerEntry(): any;
compare(tile: SimpleTile): number;
compareEntry(entry: any): number;
updateEntry(entry: any, param: any): any;
removeEntry(entry: any): boolean;
tryIncludeEntry(): boolean;
updatePreviousSibling(prev: SimpleTile): void;
updateNextSibling(next: SimpleTile): void;
notifyVisible(): void;
dispose(): void;
get displayName(): string;
get sender(): string;
}
export class GapTile extends SimpleTile {
constructor(entry: any, options: SimpleTileOptions);
fill(): boolean;
notifyVisible(): void;
get isAtTop(): boolean;
updatePreviousSibling(prev: any): void;
updateNextSibling(): void;
updateEntry(entry: any, params: any): any;
get shape(): "gap";
get isLoading(): boolean;
get error(): string | null;
}
export class RoomMemberTile extends SimpleTile {
constructor(entry: any, options: SimpleTileOptions);
get shape(): "announcement";
get announcement(): string;
}
export class BaseMessageTile extends SimpleTile {
constructor(entry: any, options: SimpleTileOptions);
notifyVisible(): void;
get permalink(): string;
get senderProfileLink(): string;
get displayName(): string;
get sender(): string;
get memberPanelLink(): string;
get avatarColorNumber(): number;
avatarUrl(size: number): string | null;
get avatarLetter(): string;
get avatarTitle(): string;
get date(): string | null;
get time(): string | null;
get isOwn(): boolean;
get isContinuation(): boolean;
get isUnverified(): boolean;
get isReply(): boolean;
updatePreviousSibling(prev: any): void;
updateEntry(entry: any, param: any): any;
startReply(): void;
reply(msgtype: string, body: string, log: any): any;
redact(reason: string, log: any): any;
get canRedact(): boolean;
get reactions(): null | any;
get canReact(): boolean;
react(key: string, log: any): any;
redactReaction(key: string, log: any): any;
toggleReaction(key: string, log: any): any;
get replyTile(): null | any;
}
class BaseTextTile extends BaseMessageTile {
constructor(entry: any, options: SimpleTileOptions);
get shape(): "message" | "message-status";
get body(): null | string;
}
export class TextTile extends BaseTextTile {
constructor(entry: any, options: SimpleTileOptions);
_getPlainBody(): string;
}
export class EncryptedEventTile extends BaseTextTile {
constructor(entry: any, params: SimpleTileOptions);
updateEntry(entry: any, param: any): any;
get shape(): "message-status";
}
export class BaseMediaTile extends BaseMessageTile {
constructor(entry: any, options: SimpleTileOptions);
get isUploading(): boolean;
get uploadPercentage(): number | any;
get sendStatus(): string;
get thumbnailUrl(): string;
notifyVisible(): void;
get width(): number;
get height(): number;
get mimeType(): string | undefined;
get label(): any;
get error(): string | null;
setViewError(err: string): void;
}
export class ImageTile extends BaseMediaTile {
constructor(entry: any, options: SimpleTileOptions);
get lightboxUrl(): string;
get shape(): "image";
}
export interface TilesCollectionOptions extends SimpleTileOptions {
tileClassForEntry(entry: any): { new (entry: any, tileOptions: SimpleTileOptions): SimpleTile };
}
export class TilesCollection extends BaseObservableList<SimpleTile> {
constructor(entries: BaseObservableList<any>, tileOptions: TilesCollectionOptions);
onAdd(index: number, entry: any): void;
onUpdate(index: number, entry: any, params: any): void;
onRemove(index: number, entry: any): void;
onMove(fromIdx: number, toIdx: number, value: any): void;
get length(): number;
[Symbol.iterator](): IterableIterator<SimpleTile>;
getFirst(): SimpleTile;
getTileIndex(searchTile: SimpleTile): number;
sliceIterator(start: number, end: number): IterableIterator<SimpleTile>;
}
export type TileOptions = SimpleTileOptions & {
session: Session;
tileClassForEntry: TileClassForEntryFn;
};
export type TileConstructor = new (entry: TimelineEntry, options: TileOptions) => SimpleTile;
export type TimelineEntry = any;
export type TileClassForEntryFn = (entry: TimelineEntry) => TileConstructor | undefined;
export const tileClassForEntry: TileClassForEntryFn;
export interface TimelineViewModelOptions extends ViewModelOptions {
timeline: Timeline;
tileOptions: TileOptions;
}
export class TimelineViewModel extends ViewModel {
constructor(options: TimelineViewModelOptions);
setVisibleTileRange(startTile: any, endTile: any): void;
get tiles(): TilesCollection;
get showJumpDown(): boolean;
}
export class ComposerViewModel extends ViewModel {
constructor(roomVM: IRoomViewModel);
setReplyingTo(entry: any): void;
clearReplyingTo(): void;
get replyViewModel(): SimpleTile;
get isEncrypted(): boolean;
sendMessage(message: string): Promise<boolean>;
sendPicture(): void;
sendFile(): void;
sendVideo(): void;
get canSend(): boolean;
setInput(text: string): Promise<void>;
get kind(): string;
}
export interface IObservableValue {
on?(event: "change", handler: (props?: string[]) => void): void;
off?(event: "change", handler: (props?: string[]) => void): void;
}
export interface IMountArgs {
parentProvidesUpdates?: boolean;
}
export type ViewNode = Element | Comment;
export interface IView {
mount(args?: IMountArgs): ViewNode;
root(): ViewNode | undefined;
unmount(): void;
update(...args: any[]): void;
}
export abstract class BaseUpdateView<T extends IObservableValue> implements IView {
protected _value: T;
protected _boundUpdateFromValue: ((props?: string[]) => void) | null;
abstract mount(args?: IMountArgs): ViewNode;
abstract root(): ViewNode | undefined;
abstract update(...args: any[]): void;
constructor(value: T);
subscribeOnMount(options?: IMountArgs): void;
unmount(): void;
get value(): T;
}
export interface TileView extends IView {
readonly value: SimpleTile;
onClick(event: UIEvent): void;
}
export type TileViewConstructor<T extends SimpleTile = SimpleTile> = new (
tile: T,
viewClassForTile?: ViewClassForEntryFn,
renderFlags?: { reply?: boolean; interactive?: boolean }
) => TileView;
export type ViewClassForEntryFn<T extends SimpleTile = SimpleTile> = (tile: T) => TileViewConstructor<T>;
export abstract class TemplateView<T extends IObservableValue> extends BaseUpdateView<T> {
abstract render(t: Builder<T>, value: T): ViewNode;
mount(options?: IMountArgs): ViewNode;
unmount(): void;
root(): ViewNode | undefined;
update(value: T, props?: string[]): void;
addSubView(view: IView): void;
removeSubView(view: IView): void;
updateSubViews(value: IObservableValue, props: string[]): void;
}
export class TemplateBuilder<T extends IObservableValue> {
constructor(templateView: TemplateView<T>);
close(): void;
el(name: string, attributes?: Attributes<T> | Child | Child[], children?: Child | Child[]): ViewNode;
elNS(ns: string, name: string, attributes?: Attributes<T> | Child | Child[], children?: Child | Child[]): ViewNode;
view(view: IView, mountOptions?: IMountArgs): ViewNode;
mapView<R>(mapFn: (value: T) => R, viewCreator: (mapped: R) => IView | null): ViewNode;
map<R>(mapFn: (value: T) => R, renderFn: (mapped: R, t: Builder<T>, vm: T) => ViewNode): ViewNode;
ifView(predicate: (value: T) => boolean, viewCreator: (value: T) => IView): ViewNode;
if(predicate: (value: T) => boolean, renderFn: (t: Builder<T>, vm: T) => ViewNode): ViewNode;
mapSideEffect<R>(mapFn: (value: T) => R, sideEffect: (newV: R, oldV: R | undefined) => void): void;
}
export const HTML_NS = "http://www.w3.org/1999/xhtml";
export const SVG_NS = "http://www.w3.org/2000/svg";
export type ClassNames<T> = { [className: string]: boolean | ((value: T) => boolean) };
export type Child = string | Text | ViewNode;
export type RenderFn<T> = (t: Builder<T>, vm: T) => ViewNode;
type EventHandler = (event: Event) => void;
type AttributeStaticValue = string | boolean;
type AttributeBinding<T> = (value: T) => AttributeStaticValue;
export type AttrValue<T> = AttributeStaticValue | AttributeBinding<T> | EventHandler | ClassNames<T>;
export type Attributes<T> = { [attribute: string]: AttrValue<T> };
type ElementFn<T> = (attributes?: Attributes<T> | Child | Child[], children?: Child | Child[]) => Element;
export type Builder<T> = TemplateBuilder<T> & { [tagName: string]: ElementFn<T> };
export class TimelineView extends TemplateView<TimelineViewModel> {
constructor(vm: TimelineViewModel, viewClassForTile: ViewClassForEntryFn);
render(t: Builder<TimelineViewModel>, vm: TimelineViewModel): Element;
unmount(): void;
}
export function viewClassForTile(vm: SimpleTile): TileViewConstructor;
export class GapView extends TemplateView<GapTile> implements TileView {
constructor(vm: GapTile);
render(t: Builder<GapTile>, value: GapTile): ViewNode;
onClick(): void;
}
export enum LogLevel {
All = 1,
Debug = 2,
Detail = 3,
Info = 4,
Warn = 5,
Error = 6,
Fatal = 7,
Off = 8,
}
export class LogFilter {
private _min?;
private _parentFilter?;
constructor(parentFilter?: LogFilter);
filter(item: ILogItem, children: ISerializedItem[] | null): boolean;
minLevel(logLevel: LogLevel): LogFilter;
}
export interface ISerializedItem {
s: number;
d?: number;
v: LogItemValues;
l: LogLevel;
e?: {
stack?: string;
name: string;
message: string;
};
f?: boolean;
c?: Array<ISerializedItem>;
}
export interface ILogItem {
logLevel: LogLevel;
error?: Error;
readonly logger: ILogger;
readonly level: typeof LogLevel;
readonly end?: number;
readonly start?: number;
readonly values: LogItemValues;
wrap<T>(
labelOrValues: LabelOrValues,
callback: LogCallback<T>,
logLevel?: LogLevel,
filterCreator?: FilterCreator
): T;
log(labelOrValues: LabelOrValues, logLevel?: LogLevel): ILogItem;
set(key: string | object, value: unknown): ILogItem;
runDetached(
labelOrValues: LabelOrValues,
callback: LogCallback<unknown>,
logLevel?: LogLevel,
filterCreator?: FilterCreator
): ILogItem;
wrapDetached(
labelOrValues: LabelOrValues,
callback: LogCallback<unknown>,
logLevel?: LogLevel,
filterCreator?: FilterCreator
): void;
refDetached(logItem: ILogItem, logLevel?: LogLevel): void;
ensureRefId(): void;
catch(err: Error): Error;
serialize(filter: LogFilter, parentStartTime: number | undefined, forced: boolean): ISerializedItem | undefined;
finish(): void;
forceFinish(): void;
child(labelOrValues: LabelOrValues, logLevel?: LogLevel, filterCreator?: FilterCreator): ILogItem;
}
export interface ILogger {
log(labelOrValues: LabelOrValues, logLevel?: LogLevel): void;
child(labelOrValues: LabelOrValues, logLevel?: LogLevel, filterCreator?: FilterCreator): ILogItem;
wrapOrRun<T>(
item: ILogItem | undefined,
labelOrValues: LabelOrValues,
callback: LogCallback<T>,
logLevel?: LogLevel,
filterCreator?: FilterCreator
): T;
runDetached<T>(
labelOrValues: LabelOrValues,
callback: LogCallback<T>,
logLevel?: LogLevel,
filterCreator?: FilterCreator
): ILogItem;
run<T>(
labelOrValues: LabelOrValues,
callback: LogCallback<T>,
logLevel?: LogLevel,
filterCreator?: FilterCreator
): T;
export(): Promise<ILogExport | undefined>;
get level(): typeof LogLevel;
}
type BlobHandle = any;
export interface ILogExport {
get count(): number;
removeFromStore(): Promise<void>;
asBlob(): BlobHandle;
}
export type LogItemValues = {
l?: string;
t?: string;
id?: unknown;
status?: string | number;
refId?: number;
ref?: number;
[key: string]: any;
};
export type LabelOrValues = string | LogItemValues;
export type FilterCreator = (filter: LogFilter, item: ILogItem) => LogFilter;
export type LogCallback<T> = (item: ILogItem) => T;
export type EncodedBody = {
mimeType: string;
body: BlobHandle | string;
};
export function encodeQueryParams(queryParams?: object): string;
export function encodeBody(body: BlobHandle | object): EncodedBody;
export class RequestResult {
constructor(promise: Promise<{ status: number; body: any }>, controller: AbortController);
abort(): void;
response(): Promise<{ status: number; body: any }>;
}
export interface IRequestOptions {
uploadProgress?: (loadedBytes: number) => void;
timeout?: number;
body?: EncodedBody;
headers?: Map<string, string | number>;
cache?: boolean;
method?: string;
format?: string;
}
export type RequestFunction = (url: string, options: IRequestOptions) => RequestResult;
export interface IBlobHandle {
nativeBlob: any;
url: string;
size: number;
mimeType: string;
readAsBuffer(): BufferSource;
dispose(): any;
}
export type File = {
readonly name: string;
readonly blob: IBlobHandle;
};
export interface Timeout {
elapsed(): Promise<void>;
abort(): void;
dispose(): void;
}
export type TimeoutCreator = (timeout: number) => Timeout;
export interface MediaDevices {
enumerate(): Promise<MediaDeviceInfo[]>;
getMediaTracks(audio: true | MediaDeviceInfo, video: boolean | MediaDeviceInfo): Promise<Stream>;
getScreenShareTrack(): Promise<Stream | undefined>;
}
export interface Stream extends MediaStream {
readonly audioTrack: AudioTrack | undefined;
readonly videoTrack: Track | undefined;
readonly id: string;
clone(): Stream;
}
export enum TrackKind {
Video = "video",
Audio = "audio",
}
export interface Track {
readonly kind: TrackKind;
readonly label: string;
readonly id: string;
readonly settings: MediaTrackSettings;
stop(): void;
}
export interface AudioTrack extends Track {
get isSpeaking(): boolean;
}
export interface WebRTC {
createPeerConnection(
handler: PeerConnectionHandler,
forceTURN: boolean,
turnServers: RTCIceServer[],
iceCandidatePoolSize: number
): PeerConnection;
}
export interface StreamSender {
get stream(): Stream;
get audioSender(): TrackSender | undefined;
get videoSender(): TrackSender | undefined;
}
export interface StreamReceiver {
get stream(): Stream;
get audioReceiver(): TrackReceiver | undefined;
get videoReceiver(): TrackReceiver | undefined;
}
export interface TrackReceiver {
get track(): Track;
get enabled(): boolean;
enable(enabled: boolean): any;
}
export interface TrackSender extends TrackReceiver {
/** replaces the track if possible without renegotiation. Can throw. */
replaceTrack(track: Track | undefined): Promise<void>;
/** make any needed adjustments to the sender or transceiver settings
* depending on the purpose, after adding the track to the connection */
prepareForPurpose(purpose: SDPStreamMetadataPurpose): void;
}
export interface PeerConnectionHandler {
onIceConnectionStateChange(state: RTCIceConnectionState): any;
onLocalIceCandidate(candidate: RTCIceCandidate): any;
onIceGatheringStateChange(state: RTCIceGatheringState): any;
onRemoteStreamRemoved(stream: Stream): any;
onRemoteTracksAdded(receiver: TrackReceiver): any;
onRemoteDataChannel(dataChannel: any | undefined): any;
onNegotiationNeeded(): any;
}
export interface PeerConnection {
get iceGatheringState(): RTCIceGatheringState;
get signalingState(): RTCSignalingState;
get localDescription(): RTCSessionDescription | undefined;
get localStreams(): ReadonlyMap<string, StreamSender>;
get remoteStreams(): ReadonlyMap<string, StreamReceiver>;
createOffer(): Promise<RTCSessionDescriptionInit>;
createAnswer(): Promise<RTCSessionDescriptionInit>;
setLocalDescription(description?: RTCSessionDescriptionInit): Promise<void>;
setRemoteDescription(description: RTCSessionDescriptionInit): Promise<void>;
addIceCandidate(candidate: RTCIceCandidate): Promise<void>;
addTrack(track: Track): TrackSender | undefined;
removeTrack(track: TrackSender): void;
createDataChannel(options: RTCDataChannelInit): any;
dispose(): void;
close(): void;
}
export type PeerCallOptions = {
webRTC: WebRTC;
forceTURN: boolean;
turnServers: RTCIceServer[];
createTimeout: TimeoutCreator;
emitUpdate: (peerCall: PeerCall, params: any) => void;
sendSignallingMessage: (message: SignallingMessage<MCallBase>, log: ILogItem) => Promise<void>;
};
export class RemoteMedia {
userMedia?: Stream | undefined;
screenShare?: Stream | undefined;
constructor(userMedia?: Stream | undefined, screenShare?: Stream | undefined);
}
/**
* Does WebRTC signalling for a single PeerConnection, and deals with WebRTC wrappers from platform
* */
/** Implements a call between two peers with the signalling state keeping, while still delegating the signalling message sending. Used by GroupCall.*/
export class PeerCall implements IDisposable {
private callId;
private readonly options;
private readonly logItem;
private readonly peerConnection;
private _state;
private direction;
private localMedia?;
private seq;
private candidateSendQueue;
private remoteCandidateBuffer?;
private remoteSDPStreamMetadata?;
private responsePromiseChain?;
private opponentPartyId?;
private hangupParty;
private disposables;
private statePromiseMap;
private makingOffer;
private ignoreOffer;
private sentEndOfCandidates;
private iceDisconnectedTimeout?;
private _dataChannel?;
private _hangupReason?;
private _remoteMedia;
constructor(callId: string, options: PeerCallOptions, logItem: ILogItem);
get dataChannel(): any | undefined;
get state(): CallState;
get hangupReason(): CallErrorCode | undefined;
get remoteMedia(): Readonly<RemoteMedia>;
call(localMedia: LocalMedia): Promise<void>;
answer(localMedia: LocalMedia): Promise<void>;
setMedia(localMedia: LocalMedia, logItem?: ILogItem): Promise<void>;
/** group calls would handle reject at the group call level, not at the peer call level */
reject(): Promise<void>;
hangup(errorCode: CallErrorCode): Promise<void>;
private _hangup;
handleIncomingSignallingMessage<B extends MCallBase>(
message: SignallingMessage<B>,
partyId: PartyId
): Promise<void>;
private sendHangupWithCallId;
private handleNegotiation;
private handleInviteGlare;
private handleHangupReceived;
private handleFirstInvite;
private handleInvite;
private handleAnswer;
private handleIceGatheringState;
private handleLocalIceCandidate;
private handleRemoteIceCandidates;
private sendAnswer;
private queueCandidate;
private sendCandidateQueue;
private updateRemoteSDPStreamMetadata;
private addBufferedIceCandidates;
private addIceCandidates;
private onIceConnectionStateChange;
private setState;
private waitForState;
private terminate;
private getSDPMetadata;
private updateRemoteMedia;
private delay;
private sendSignallingMessage;
dispose(): void;
close(reason: CallErrorCode | undefined, log: ILogItem): void;
}
type PartyId = string | null;
export enum CallParty {
Local = "local",
Remote = "remote",
}
export enum CallState {
Fledgling = "fledgling",
CreateOffer = "create_offer",
InviteSent = "invite_sent",
CreateAnswer = "create_answer",
Connecting = "connecting",
Connected = "connected",
Ringing = "ringing",
Ended = "ended",
}
export enum CallDirection {
Inbound = "inbound",
Outbound = "outbound",
}
export class CallError extends Error {
code: string;
constructor(code: CallErrorCode, msg: string, err: Error);
}
export enum EventType {
GroupCall = "org.matrix.msc3401.call",
GroupCallMember = "org.matrix.msc3401.call.member",
Invite = "m.call.invite",
Candidates = "m.call.candidates",
Answer = "m.call.answer",
Hangup = "m.call.hangup",
Reject = "m.call.reject",
SelectAnswer = "m.call.select_answer",
Negotiate = "m.call.negotiate",
SDPStreamMetadataChanged = "m.call.sdp_stream_metadata_changed",
SDPStreamMetadataChangedPrefix = "org.matrix.call.sdp_stream_metadata_changed",
Replaces = "m.call.replaces",
AssertedIdentity = "m.call.asserted_identity",
AssertedIdentityPrefix = "org.matrix.call.asserted_identity",
}
export const SDPStreamMetadataKey = "org.matrix.msc3077.sdp_stream_metadata";
export interface CallDeviceMembership {
device_id: string;
session_id: string;
}
export interface CallMembership {
["m.call_id"]: string;
["m.devices"]: CallDeviceMembership[];
}
export interface CallMemberContent {
["m.calls"]: CallMembership[];
}
export interface SessionDescription {
sdp?: string;
type: RTCSdpType;
}
export enum SDPStreamMetadataPurpose {
Usermedia = "m.usermedia",
Screenshare = "m.screenshare",
}
export interface SDPStreamMetadataObject {
purpose: SDPStreamMetadataPurpose;
audio_muted: boolean;
video_muted: boolean;
}
export interface SDPStreamMetadata {
[key: string]: SDPStreamMetadataObject;
}
export interface CallCapabilities {
"m.call.transferee": boolean;
"m.call.dtmf": boolean;
}
export interface CallReplacesTarget {
id: string;
display_name: string;
avatar_url: string;
}
export type MCallBase = {
call_id: string;
version: string | number;
seq: number;
};
export type MGroupCallBase = MCallBase & {
conf_id: string;
device_id: string;
sender_session_id: string;
dest_session_id: string;
party_id: string;
};
export type MCallAnswer<Base extends MCallBase> = Base & {
answer: SessionDescription;
capabilities?: CallCapabilities;
[SDPStreamMetadataKey]: SDPStreamMetadata;
};
export type MCallSelectAnswer<Base extends MCallBase> = Base & {
selected_party_id: string;
};
export type MCallInvite<Base extends MCallBase> = Base & {
offer: SessionDescription;
lifetime: number;
[SDPStreamMetadataKey]: SDPStreamMetadata;
};
export type MCallSDPStreamMetadataChanged<Base extends MCallBase> = Base & {
[SDPStreamMetadataKey]: SDPStreamMetadata;
};
export type MCallReplacesEvent<Base extends MCallBase> = Base & {
replacement_id: string;
target_user: CallReplacesTarget;
create_call: string;
await_call: string;
target_room: string;
};
export type MCAllAssertedIdentity<Base extends MCallBase> = Base & {
asserted_identity: {
id: string;
display_name: string;
avatar_url: string;
};
};
export type MCallCandidates<Base extends MCallBase> = Base & {
candidates: RTCIceCandidate[];
};
export type MCallHangupReject<Base extends MCallBase> = Base & {
reason?: CallErrorCode;
};
export enum CallErrorCode {
/** The user chose to end the call */
UserHangup = "user_hangup",
/** An error code when the local client failed to create an offer. */
LocalOfferFailed = "local_offer_failed",
/**
* An error code when there is no local mic/camera to use. This may be because
* the hardware isn't plugged in, or the user has explicitly denied access.
*/
NoUserMedia = "no_user_media",
/**
* Error code used when a call event failed to send
* because unknown devices were present in the room
*/
UnknownDevices = "unknown_devices",
/**
* Error code used when we fail to send the invite
* for some reason other than there being unknown devices
*/
SendInvite = "send_invite",
/**
* An answer could not be created
*/
CreateAnswer = "create_answer",
/**
* Error code used when we fail to send the answer
* for some reason other than there being unknown devices
*/
SendAnswer = "send_answer",
/**
* The session description from the other side could not be set
*/
SetRemoteDescription = "set_remote_description",
/**
* The session description from this side could not be set
*/
SetLocalDescription = "set_local_description",
/**
* A different device answered the call
*/
AnsweredElsewhere = "answered_elsewhere",
/**
* No media connection could be established to the other party
*/
IceFailed = "ice_failed",
/**
* The invite timed out whilst waiting for an answer
*/
InviteTimeout = "invite_timeout",
/**
* The call was replaced by another call
*/
Replaced = "replaced",
/**
* Signalling for the call could not be sent (other than the initial invite)
*/
SignallingFailed = "signalling_timeout",
/**
* The remote party is busy
*/
UserBusy = "user_busy",
/**
* We transferred the call off to somewhere else
*/
Transfered = "transferred",
/**
* A call from the same user was found with a new session id
*/
NewSession = "new_session",
}
export type SignallingMessage<Base extends MCallBase> =
| {
type: EventType.Invite;
content: MCallInvite<Base>;
}
| {
type: EventType.Answer;
content: MCallAnswer<Base>;
}
| {
type: EventType.SDPStreamMetadataChanged | EventType.SDPStreamMetadataChangedPrefix;
content: MCallSDPStreamMetadataChanged<Base>;
}
| {
type: EventType.Candidates;
content: MCallCandidates<Base>;
}
| {
type: EventType.Hangup | EventType.Reject;
content: MCallHangupReject<Base>;
};
export enum CallIntent {
Ring = "m.ring",
Prompt = "m.prompt",
Room = "m.room",
}
export type MemberOptions = Omit<PeerCallOptions, "emitUpdate" | "sendSignallingMessage"> & {
confId: string;
ownUserId: string;
ownDeviceId: string;
sessionId: string;
hsApi: HomeServerApi;
encryptDeviceMessage: (
userId: string,
message: SignallingMessage<MGroupCallBase>,
log: ILogItem
) => Promise<EncryptedMessage>;
emitUpdate: (participant: Member, params?: any) => void;
};
export class Member {
readonly member: RoomMember;
private callDeviceMembership;
private readonly options;
private readonly logItem;
private peerCall?;
private localMedia?;
private retryCount;
constructor(
member: RoomMember,
callDeviceMembership: CallDeviceMembership,
options: MemberOptions,
logItem: ILogItem
);
get remoteMedia(): RemoteMedia | undefined;
get isConnected(): boolean;
get userId(): string;
get deviceId(): string;
get deviceIndex(): number;
get eventTimestamp(): number;
get dataChannel(): any | undefined;
/** @internal */
connect(localMedia: LocalMedia): void;
/** @internal */
disconnect(hangup: boolean): void;
/** @internal */
updateCallInfo(callDeviceMembership: CallDeviceMembership): void;
/** @internal */
emitUpdate: (peerCall: PeerCall, params: any) => void;
/** @internal */
sendSignallingMessage: (message: SignallingMessage<MCallBase>, log: ILogItem) => Promise<void>;
/** @internal */
handleDeviceMessage(message: SignallingMessage<MGroupCallBase>, deviceId: string, syncLog: ILogItem): void;
private _createPeerCall;
}
export enum GroupCallState {
Fledgling = "fledgling",
Creating = "creating",
Created = "created",
Joining = "joining",
Joined = "joined",
}
export type GroupCallOptions = Omit<MemberOptions, "emitUpdate" | "confId" | "encryptDeviceMessage"> & {
emitUpdate: (call: GroupCall, params?: any) => void;
encryptDeviceMessage: (
roomId: string,
userId: string,
message: SignallingMessage<MGroupCallBase>,
log: ILogItem
) => Promise<EncryptedMessage>;
storage: Storage;
};
export class GroupCall extends EventEmitter<{
change: never;
}> {
readonly id: string;
private callContent;
readonly roomId: string;
private readonly options;
private readonly logItem;
private readonly _members;
private _localMedia?;
private _memberOptions;
private _state;
constructor(
id: string,
newCall: boolean,
callContent: Record<string, any>,
roomId: string,
options: GroupCallOptions,
logItem: ILogItem
);
get localMedia(): LocalMedia | undefined;
get members(): BaseObservableMap<string, Member>;
get isTerminated(): boolean;
get isRinging(): boolean;
get name(): string;
get intent(): CallIntent;
get deviceIndex(): number | undefined;
get eventTimestamp(): number | undefined;
join(localMedia: LocalMedia): Promise<void>;
get hasJoined(): boolean;
leave(): Promise<void>;
terminate(): Promise<void>;
/** @internal */
create(localMedia: LocalMedia): Promise<void>;
/** @internal */
updateCallEvent(callContent: Record<string, any>, syncLog: ILogItem): void;
/** @internal */
updateMembership(userId: string, callMembership: CallMembership, syncLog: ILogItem): void;
/** @internal */
removeMembership(userId: string, syncLog: ILogItem): void;
private getDeviceIdsForUserId;
private isMember;
private removeOwnDevice;
/** @internal */
private removeMemberDevice;
/** @internal */
handleDeviceMessage(
message: SignallingMessage<MGroupCallBase>,
userId: string,
deviceId: string,
syncLog: ILogItem
): void;
/** @internal */
dispose(): void;
private _createJoinPayload;
private _leaveCallMemberContent;
protected emitChange(): void;
}
export type CallHandlerOptions = Omit<GroupCallOptions, "emitUpdate" | "createTimeout"> & {
logger: ILogger;
clock: Clock;
};
type MemberChange = any;
type StateEvent = any;
export class CallHandler {
private readonly options;
private readonly _calls;
private memberToCallIds;
private groupCallOptions;
private sessionId;
constructor(options: CallHandlerOptions);
loadCalls(intent?: CallIntent): Promise<void>;
loadCallsForRoom(intent: CallIntent, roomId: string): Promise<void>;
private _getLoadTxn;
private _loadCallEntries;
createCall(roomId: string, callType: string, name: string, intent?: CallIntent): Promise<GroupCall>;
get calls(): BaseObservableMap<string, GroupCall>;
/** @internal */
handleRoomState(room: Room, events: StateEvent[], txn: Transaction, log: ILogItem): void;
/** @internal */
updateRoomMembers(room: Room, memberChanges: Map<string, MemberChange>): void;
/** @internal */
handlesDeviceMessageEventType(eventType: string): boolean;
/** @internal */
handleDeviceMessage(
message: SignallingMessage<MGroupCallBase>,
userId: string,
deviceId: string,
log: ILogItem
): void;
private handleCallEvent;
private handleCallMemberEvent;
}
export interface MediaDevices {
// filter out audiooutput
enumerate(): Promise<MediaDeviceInfo[]>;
// to assign to a video element, we downcast to WrappedTrack and use the stream property.
getMediaTracks(audio: true | MediaDeviceInfo, video: boolean | MediaDeviceInfo): Promise<Stream>;
getScreenShareTrack(): Promise<Stream | undefined>;
}
type HomeServerApiOptions = {
homeserver: string;
accessToken: string;
request: RequestFunction;
reconnector: Reconnector;
};
type BaseRequestOptions = {
log?: ILogItem;
allowedStatusCodes?: number[];
uploadProgress?: (loadedBytes: number) => void;
timeout?: number;
prefix?: string;
};
export class HomeServerApi {
private readonly _homeserver;
private readonly _accessToken;
private readonly _requestFn;
private readonly _reconnector;
constructor({ homeserver, accessToken, request, reconnector }: HomeServerApiOptions);
private _url;
private _baseRequest;
private _unauthedRequest;
private _authedRequest;
private _post;
private _put;
private _get;
sync(since: string, filter: string, timeout: number, options?: BaseRequestOptions): IHomeServerRequest;
context(roomId: string, eventId: string, limit: number, filter: string): IHomeServerRequest;
messages(roomId: string, params: Record<string, any>, options?: BaseRequestOptions): IHomeServerRequest;
members(roomId: string, params: Record<string, any>, options?: BaseRequestOptions): IHomeServerRequest;
send(
roomId: string,
eventType: string,
txnId: string,
content: Record<string, any>,
options?: BaseRequestOptions
): IHomeServerRequest;
redact(
roomId: string,
eventId: string,
txnId: string,
content: Record<string, any>,
options?: BaseRequestOptions
): IHomeServerRequest;
receipt(roomId: string, receiptType: string, eventId: string, options?: BaseRequestOptions): IHomeServerRequest;
state(roomId: string, eventType: string, stateKey: string, options?: BaseRequestOptions): IHomeServerRequest;
sendState(
roomId: string,
eventType: string,
stateKey: string,
content: Record<string, any>,
options?: BaseRequestOptions
): IHomeServerRequest;
getLoginFlows(): IHomeServerRequest;
register(
username: string | null,
password: string,
initialDeviceDisplayName: string,
auth?: Record<string, any>,
inhibitLogin?: boolean,
options?: BaseRequestOptions
): IHomeServerRequest;
passwordLogin(
username: string,
password: string,
initialDeviceDisplayName: string,
options?: BaseRequestOptions
): IHomeServerRequest;
tokenLogin(
loginToken: string,
txnId: string,
initialDeviceDisplayName: string,
options?: BaseRequestOptions
): IHomeServerRequest;
createFilter(userId: string, filter: Record<string, any>, options?: BaseRequestOptions): IHomeServerRequest;
versions(options?: BaseRequestOptions): IHomeServerRequest;
uploadKeys(
dehydratedDeviceId: string,
payload: Record<string, any>,
options?: BaseRequestOptions
): IHomeServerRequest;
queryKeys(queryRequest: Record<string, any>, options?: BaseRequestOptions): IHomeServerRequest;
claimKeys(payload: Record<string, any>, options?: BaseRequestOptions): IHomeServerRequest;
sendToDevice(
type: string,
payload: Record<string, any>,
txnId: string,
options?: BaseRequestOptions
): IHomeServerRequest;
roomKeysVersion(version?: string, options?: BaseRequestOptions): IHomeServerRequest;
roomKeyForRoomAndSession(
version: string,
roomId: string,
sessionId: string,
options?: BaseRequestOptions
): IHomeServerRequest;
uploadRoomKeysToBackup(
version: string,
payload: Record<string, any>,
options?: BaseRequestOptions
): IHomeServerRequest;
uploadAttachment(blob: Blob, filename: string, options?: BaseRequestOptions): IHomeServerRequest;
setPusher(pusher: Record<string, any>, options?: BaseRequestOptions): IHomeServerRequest;
getPushers(options?: BaseRequestOptions): IHomeServerRequest;
join(roomId: string, options?: BaseRequestOptions): IHomeServerRequest;
joinIdOrAlias(roomIdOrAlias: string, options?: BaseRequestOptions): IHomeServerRequest;
leave(roomId: string, options?: BaseRequestOptions): IHomeServerRequest;
forget(roomId: string, options?: BaseRequestOptions): IHomeServerRequest;
logout(options?: BaseRequestOptions): IHomeServerRequest;
getDehydratedDevice(options?: BaseRequestOptions): IHomeServerRequest;
createDehydratedDevice(payload: Record<string, any>, options?: BaseRequestOptions): IHomeServerRequest;
claimDehydratedDevice(deviceId: string, options?: BaseRequestOptions): IHomeServerRequest;
profile(userId: string, options?: BaseRequestOptions): IHomeServerRequest;
createRoom(payload: Record<string, any>, options?: BaseRequestOptions): IHomeServerRequest;
setAccountData(
ownUserId: string,
type: string,
content: Record<string, any>,
options?: BaseRequestOptions
): IHomeServerRequest;
}
export interface IHomeServerRequest {
abort(): void;
response(): Promise<any>;
responseCode(): Promise<number>;
}
type HomeServerRequestOptions = {
log?: ILogItem;
allowedStatusCodes?: number[];
};
export class HomeServerRequest implements IHomeServerRequest {
private readonly _log?;
private _sourceRequest?;
private readonly _promise;
constructor(method: string, url: string, sourceRequest: RequestResult, options?: HomeServerRequestOptions);
abort(): void;
response(): Promise<any>;
responseCode(): Promise<number>;
}
enum ConnectionStatus {
"Waiting" = 0,
"Reconnecting" = 1,
"Online" = 2,
}
type Ctor = {
retryDelay: ExponentialRetryDelay;
createMeasure: () => TimeMeasure;
onlineStatus: any;
};
export type Attachment = {
body: string;
info: AttachmentInfo;
msgtype: string;
url?: string;
file?: EncryptedFile;
filename?: string;
};
export type EncryptedFile = {
key: JsonWebKey;
iv: string;
hashes: {
sha256: string;
};
url: string;
v: string;
mimetype?: string;
};
type AttachmentInfo = {
h?: number;
w?: number;
mimetype: string;
size: number;
duration?: number;
thumbnail_url?: string;
thumbnail_file?: EncryptedFile;
thumbnail_info?: ThumbnailInfo;
};
type ThumbnailInfo = {
h: number;
w: number;
mimetype: string;
size: number;
};
export type VersionResponse = {
versions: string[];
unstable_features?: Record<string, boolean>;
};
export class Reconnector {
private readonly _retryDelay;
private readonly _createTimeMeasure;
private readonly _onlineStatus;
private readonly _state;
private _isReconnecting;
private _versionsResponse?;
private _stateSince;
constructor({ retryDelay, createMeasure, onlineStatus }: Ctor);
get lastVersionsResponse(): VersionResponse | undefined;
get connectionStatus(): ObservableValue<ConnectionStatus>;
get retryIn(): number;
onRequestFailed(hsApi: HomeServerApi): Promise<void>;
tryNow(): void;
private _setState;
private _reconnectLoop;
}
export class ExponentialRetryDelay {
private readonly _start;
private _current;
private readonly _createTimeout;
private readonly _max;
private _timeout?;
constructor(createTimeout: (ms: number) => Timeout);
waitForRetry(): Promise<void>;
abort(): void;
reset(): void;
get nextValue(): number;
}
export type IDBKey = IDBValidKey | IDBKeyRange;
export class Transaction {
private _txn;
private _allowedStoreNames;
private _stores;
private _storage;
private _writeErrors;
constructor(txn: IDBTransaction, allowedStoreNames: StoreNames[], storage: Storage);
get idbFactory(): IDBFactory;
get IDBKeyRange(): typeof IDBKeyRange;
get databaseName(): string;
get logger(): ILogger;
_idbStore(name: StoreNames): Store<any>;
_store<T>(name: StoreNames, mapStore: (idbStore: Store<any>) => T): T;
get session(): SessionStore;
get roomSummary(): RoomSummaryStore;
get archivedRoomSummary(): RoomSummaryStore;
get invites(): InviteStore;
get timelineFragments(): any;
get timelineEvents(): any;
get timelineRelations(): any;
get roomState(): any;
get roomMembers(): RoomMemberStore;
get pendingEvents(): any;
get userIdentities(): any;
get deviceIdentities(): any;
get olmSessions(): any;
get inboundGroupSessions(): any;
get outboundGroupSessions(): any;
get groupSessionDecryptions(): any;
get operations(): any;
get accountData(): any;
get calls(): CallStore;
complete(log?: ILogItem): Promise<void>;
getCause(error: Error): Error;
abort(log?: ILogItem): void;
addWriteError(
error: StorageError,
refItem: ILogItem | undefined,
operationName: string,
keys: IDBKey[] | undefined
): void;
private _logWriteErrors;
}
export enum StoreNames {
session = "session",
roomState = "roomState",
roomSummary = "roomSummary",
archivedRoomSummary = "archivedRoomSummary",
invites = "invites",
roomMembers = "roomMembers",
timelineEvents = "timelineEvents",
timelineRelations = "timelineRelations",
timelineFragments = "timelineFragments",
pendingEvents = "pendingEvents",
userIdentities = "userIdentities",
deviceIdentities = "deviceIdentities",
olmSessions = "olmSessions",
inboundGroupSessions = "inboundGroupSessions",
outboundGroupSessions = "outboundGroupSessions",
groupSessionDecryptions = "groupSessionDecryptions",
operations = "operations",
accountData = "accountData",
calls = "calls",
}
export const STORE_NAMES: Readonly<StoreNames[]>;
export class StorageError extends Error {
errcode?: string;
cause?: Error;
constructor(message: string, cause?: Error);
get name(): string;
}
export const KeyLimits: {
readonly minStorageKey: number;
readonly middleStorageKey: number;
readonly maxStorageKey: number;
};
export interface CallEntry {
intent: string;
roomId: string;
callId: string;
timestamp: number;
}
type CallStorageEntry = {
key: string;
timestamp: number;
};
export class CallStore {
private _callStore;
constructor(idbStore: Store<CallStorageEntry>);
getByIntent(intent: string): Promise<CallEntry[]>;
getByIntentAndRoom(intent: string, roomId: string): Promise<CallEntry[]>;
add(entry: CallEntry): void;
remove(intent: string, roomId: string, callId: string): void;
}
export class QueryTargetWrapper<T> {
private _qt;
constructor(qt: IDBIndex | IDBObjectStore);
get keyPath(): string | string[];
get _qtStore(): IDBObjectStore;
supports(methodName: string): boolean;
openKeyCursor(range?: IDBQuery, direction?: IDBCursorDirection | undefined): IDBRequest<IDBCursor | null>;
openCursor(range?: IDBQuery, direction?: IDBCursorDirection | undefined): IDBRequest<IDBCursorWithValue | null>;
put(item: T, key?: IDBValidKey | undefined): IDBRequest<IDBValidKey>;
add(item: T, key?: IDBValidKey | undefined): IDBRequest<IDBValidKey>;
get(key: IDBValidKey | IDBKeyRange): IDBRequest<T | undefined>;
getKey(key: IDBValidKey | IDBKeyRange): IDBRequest<IDBValidKey | undefined>;
delete(key: IDBValidKey | IDBKeyRange): IDBRequest<undefined>;
count(keyRange?: IDBKeyRange): IDBRequest<number>;
index(name: string): IDBIndex;
get indexNames(): string[];
}
export class Store<T> extends QueryTarget<T> {
constructor(idbStore: IDBObjectStore, transaction: ITransaction);
get _idbStore(): QueryTargetWrapper<T>;
index(indexName: string): QueryTarget<T>;
put(value: T, log?: ILogItem): void;
add(value: T, log?: ILogItem): void;
tryAdd(value: T, log: ILogItem): Promise<boolean>;
delete(keyOrKeyRange: IDBValidKey | IDBKeyRange, log?: ILogItem): void;
private _prepareErrorLog;
private _getKeys;
private _readKeyPath;
}
export interface ITransaction {
idbFactory: IDBFactory;
IDBKeyRange: typeof IDBKeyRange;
databaseName: string;
addWriteError(
error: StorageError,
refItem: ILogItem | undefined,
operationName: string,
keys: IDBKey[] | undefined
): any;
}
type Reducer<A, B> = (acc: B, val: A) => B;
export type IDBQuery = IDBValidKey | IDBKeyRange | undefined | null;
interface QueryTargetInterface<T> {
openCursor(range?: IDBQuery, direction?: IDBCursorDirection | undefined): IDBRequest<IDBCursorWithValue | null>;
openKeyCursor(range?: IDBQuery, direction?: IDBCursorDirection | undefined): IDBRequest<IDBCursor | null>;
supports(method: string): boolean;
keyPath: string | string[];
count(keyRange?: IDBKeyRange): IDBRequest<number>;
get(key: IDBValidKey | IDBKeyRange): IDBRequest<T | undefined>;
getKey(key: IDBValidKey | IDBKeyRange): IDBRequest<IDBValidKey | undefined>;
}
export class QueryTarget<T> {
protected _target: QueryTargetInterface<T>;
protected _transaction: ITransaction;
constructor(target: QueryTargetInterface<T>, transaction: ITransaction);
get idbFactory(): IDBFactory;
get IDBKeyRange(): typeof IDBKeyRange;
get databaseName(): string;
_openCursor(range?: IDBQuery, direction?: IDBCursorDirection): IDBRequest<IDBCursorWithValue | null>;
supports(methodName: string): boolean;
count(keyRange?: IDBKeyRange): Promise<number>;
get(key: IDBValidKey | IDBKeyRange): Promise<T | undefined>;
getKey(key: IDBValidKey | IDBKeyRange): Promise<IDBValidKey | undefined>;
reduce<B>(range: IDBQuery, reducer: Reducer<T, B>, initialValue: B): Promise<boolean>;
reduceReverse<B>(range: IDBQuery, reducer: Reducer<T, B>, initialValue: B): Promise<boolean>;
selectLimit(range: IDBQuery, amount: number): Promise<T[]>;
selectLimitReverse(range: IDBQuery, amount: number): Promise<T[]>;
selectWhile(range: IDBQuery, predicate: (v: T) => boolean): Promise<T[]>;
selectWhileReverse(range: IDBQuery, predicate: (v: T) => boolean): Promise<T[]>;
selectAll(range?: IDBQuery, direction?: IDBCursorDirection): Promise<T[]>;
selectFirst(range: IDBQuery): Promise<T | undefined>;
selectLast(range: IDBQuery): Promise<T | undefined>;
find(range: IDBQuery, predicate: (v: T) => boolean): Promise<T | undefined>;
findReverse(range: IDBQuery, predicate: (v: T) => boolean): Promise<T | undefined>;
findMaxKey(range: IDBQuery): Promise<IDBValidKey | undefined>;
iterateValues(
range: IDBQuery,
callback: (val: T, key: IDBValidKey, cur: IDBCursorWithValue) => boolean
): Promise<void>;
iterateKeys(range: IDBQuery, callback: (key: IDBValidKey, cur: IDBCursor) => boolean): Promise<void>;
/**
* Checks if a given set of keys exist.
* If the callback returns true, the search is halted and callback won't be called again.
*/
findExistingKeys(
keys: IDBValidKey[],
backwards: boolean,
callback: (key: IDBValidKey, pk: IDBValidKey) => boolean
): Promise<void>;
_reduce<B>(
range: IDBQuery,
reducer: (reduced: B, value: T) => B,
initialValue: B,
direction: IDBCursorDirection
): Promise<boolean>;
_selectLimit(range: IDBQuery, amount: number, direction: IDBCursorDirection): Promise<T[]>;
_selectUntil(range: IDBQuery, predicate: (vs: T[], v: T) => boolean, direction: IDBCursorDirection): Promise<T[]>;
_selectWhile(range: IDBQuery, predicate: (v: T) => boolean, direction: IDBCursorDirection): Promise<T[]>;
iterateWhile(range: IDBQuery, predicate: (v: T) => boolean): Promise<void>;
_find(range: IDBQuery, predicate: (v: T) => boolean, direction: IDBCursorDirection): Promise<T | undefined>;
}
export interface SessionEntry {
key: string;
value: any;
}
export class SessionStore {
private _sessionStore;
private _localStorage;
constructor(sessionStore: Store<SessionEntry>, localStorage: IDOMStorage);
private get _localStorageKeyPrefix();
get(key: string): Promise<any>;
_writeKeyToLocalStorage(key: string, value: any): void;
writeE2EEIdentityToLocalStorage(): void;
tryRestoreE2EEIdentityFromLocalStorage(log: ILogItem): Promise<boolean>;
set(key: string, value: any): void;
add(key: string, value: any): void;
remove(key: string): void;
}
export interface IDOMStorage {
getItem(key: string): string | null;
setItem(key: string, value: string): void;
removeItem(key: string): void;
key(n: number): string | null;
readonly length: number;
}
type SummaryData = any;
export class RoomSummaryStore {
private _summaryStore;
constructor(summaryStore: Store<SummaryData>);
getAll(): Promise<SummaryData[]>;
set(summary: SummaryData): void;
get(roomId: string): Promise<SummaryData | null>;
has(roomId: string): Promise<boolean>;
remove(roomId: string): void;
}
type ClaimedOTKResponse = {
[userId: string]: {
[deviceId: string]: {
[algorithmAndOtk: string]: {
key: string;
signatures: {
[userId: string]: {
[algorithmAndDevice: string]: string;
};
};
};
};
};
};
type Account = any;
export class Encryption {
private readonly account;
private readonly pickleKey;
private readonly olm;
private readonly storage;
private readonly now;
private readonly ownUserId;
private readonly olmUtil;
private readonly senderKeyLock;
constructor(
account: Account,
pickleKey: string,
olm: typeof Olm,
storage: Storage,
now: () => number,
ownUserId: string,
olmUtil: Olm.Utility,
senderKeyLock: any
);
encrypt(
type: string,
content: Record<string, any>,
devices: DeviceIdentity[],
hsApi: HomeServerApi,
log: ILogItem
): Promise<EncryptedMessage[]>;
_encryptForMaxDevices(
type: string,
content: Record<string, any>,
devices: DeviceIdentity[],
hsApi: HomeServerApi,
log: ILogItem
): Promise<EncryptedMessage[]>;
_findExistingSessions(devices: DeviceIdentity[]): Promise<{
devicesWithoutSession: DeviceIdentity[];
existingEncryptionTargets: EncryptionTarget[];
}>;
_encryptForDevice(type: string, content: Record<string, any>, target: EncryptionTarget): OlmEncryptedMessageContent;
_buildPlainTextMessageForDevice(type: string, content: Record<string, any>, device: DeviceIdentity): OlmPayload;
_createNewSessions(
devicesWithoutSession: DeviceIdentity[],
hsApi: HomeServerApi,
timestamp: number,
log: ILogItem
): Promise<EncryptionTarget[]>;
_claimOneTimeKeys(
hsApi: HomeServerApi,
deviceIdentities: DeviceIdentity[],
log: ILogItem
): Promise<EncryptionTarget[]>;
_verifyAndCreateOTKTargets(
userKeyMap: ClaimedOTKResponse,
devicesByUser: Map<string, Map<string, DeviceIdentity>>,
log: ILogItem
): EncryptionTarget[];
_loadSessions(encryptionTargets: EncryptionTarget[]): Promise<void>;
_storeSessions(encryptionTargets: EncryptionTarget[], timestamp: number): Promise<void>;
}
class EncryptionTarget {
readonly device: DeviceIdentity;
readonly oneTimeKey: string | null;
readonly sessionId: string | null;
session: Olm.Session | null;
constructor(device: DeviceIdentity, oneTimeKey: string | null, sessionId: string | null);
static fromOTK(device: DeviceIdentity, oneTimeKey: string): EncryptionTarget;
static fromSessionId(device: DeviceIdentity, sessionId: string): EncryptionTarget;
dispose(): void;
}
export class EncryptedMessage {
readonly content: OlmEncryptedMessageContent;
readonly device: DeviceIdentity;
constructor(content: OlmEncryptedMessageContent, device: DeviceIdentity);
}
export interface DeviceIdentity {
userId: string;
deviceId: string;
ed25519Key: string;
curve25519Key: string;
algorithms: string[];
displayName: string;
key: string;
}
export class DeviceIdentityStore {
private _store;
constructor(store: Store<DeviceIdentity>);
getAllForUserId(userId: string): Promise<DeviceIdentity[]>;
getAllDeviceIds(userId: string): Promise<string[]>;
get(userId: string, deviceId: string): Promise<DeviceIdentity | undefined>;
set(deviceIdentity: DeviceIdentity): void;
getByCurve25519Key(curve25519Key: string): Promise<DeviceIdentity | undefined>;
remove(userId: string, deviceId: string): void;
removeAllForUser(userId: string): void;
}
export const enum OlmPayloadType {
PreKey = 0,
Normal = 1,
}
export type OlmMessage = {
type?: OlmPayloadType;
body?: string;
};
export type OlmEncryptedMessageContent = {
algorithm?: "m.olm.v1.curve25519-aes-sha2";
sender_key?: string;
ciphertext?: {
[deviceCurve25519Key: string]: OlmMessage;
};
};
export type OlmEncryptedEvent = {
type?: "m.room.encrypted";
content?: OlmEncryptedMessageContent;
sender?: string;
};
export type OlmPayload = {
type?: string;
content?: Record<string, any>;
sender?: string;
recipient?: string;
recipient_keys?: {
ed25519?: string;
};
keys?: {
ed25519?: string;
};
};
export interface InviteData {
roomId: string;
isEncrypted: boolean;
isDirectMessage: boolean;
name?: string;
avatarUrl?: string;
avatarColorId: number;
canonicalAlias?: string;
timestamp: number;
joinRule: string;
inviter?: MemberData;
}
export class InviteStore {
private _inviteStore;
constructor(inviteStore: Store<InviteData>);
getAll(): Promise<InviteData[]>;
set(invite: InviteData): void;
remove(roomId: string): void;
}
export interface MemberData {
roomId: string;
userId: string;
avatarUrl: string;
displayName: string;
membership: "join" | "leave" | "invite" | "ban";
}
type MemberStorageEntry = MemberData & {
key: string;
};
export class RoomMemberStore {
private _roomMembersStore;
constructor(roomMembersStore: Store<MemberStorageEntry>);
get(roomId: string, userId: string): Promise<MemberStorageEntry | undefined>;
set(member: MemberData): void;
getAll(roomId: string): Promise<MemberData[]>;
getAllUserIds(roomId: string): Promise<string[]>;
removeAllForRoom(roomId: string): void;
}
} | the_stack |
module RongIMLib {
export class RCUploadLib {
public static _instance: RCUploadLib;
private store: any = {};
private listener: any = {};
private uploadType: string = "";
private conversationType: number;
private targetId: string;
constructor(imgOpts: any, fileOpts: any) {
var head: any = document.getElementsByTagName('head')[0], me = this;
var plScript: any = document.createElement('script');
plScript.src = 'http://cdn.ronghub.com/plupload.min.js';
plScript.onload = plScript.onreadystatechange = function() {
imgOpts && imgOpts.domain && imgOpts.browse_button && (me.store["imgOpts"] = imgOpts) && me.createOptions(imgOpts, "IMAGE");
fileOpts && fileOpts.domain && fileOpts.browse_button && (me.store["fileOpts"] = fileOpts) && me.createOptions(fileOpts, "FILE");
};
head.appendChild(plScript);
}
static init(imgOpts: any, fileOpts: any): void {
RCUploadLib._instance = new RCUploadLib(imgOpts, fileOpts);
}
static getInstance(): RCUploadLib {
return RCUploadLib._instance;
}
// 必须重写,否则将没有文件 URL
static getFileUrl(info: any): string {
return "";
}
// 将 response 传入 callback 如:callback(response.responseText);
static uploadAjax(base64: string, callback: Function) {
}
//自定义压缩图片过程,方法最后一行必须调用 callback ,并把压缩好的 base64 传入 callback
static imageCompressToBase64(file: any, callback: any) {
RCUploadLib.getInstance().getThumbnail(file, 60000, function(obj: any, data: any) {
var reg = new RegExp('^data:image/[^;]+;base64,');
var dataFinal = data.replace(reg, '');
callback(dataFinal);
});
}
setListeners(listener: any): void {
this.listener = listener;
}
createOptions(opts: any, type: string): void {
opts['max_file_size'] || (opts['max_file_size'] = '100mb');
opts['chunk_size'] || (opts['chunk_size'] = '10mb');
opts['useUserDefine'] || (opts['useUserDefine'] = false);
switch (type) {
case 'IMAGE':
opts['filters'] = {
mime_types: [{ title: "Image files", extensions: "jpg,gif,png" }],
prevent_duplicates: true
};
opts['multipart'] = true;
opts['unique_names'] = true;
opts['uploadType'] = 'IMAGE';
break;
case 'FILE':
opts['filters'] = {
mime_types: [],
prevent_duplicates: true
};
opts['multipart'] = true;
opts['unique_names'] = true;
opts['uploadType'] = 'FILE';
break;
}
this.uploadFactory(opts);
}
start(conversationType: ConversationType, targetId: string): void {
this.conversationType = conversationType;
this.targetId = targetId;
this.store[this.uploadType].start();
}
cancel(fileId: string): void {
this.store[this.uploadType].removeFile(fileId);
}
cancelAll(callback: any): void {
var up = this.store[this.uploadType], files = up.files;
for (let i = 0, len = files.length; i < len; i++) {
up.removeFile(files[i]);
}
callback();
}
reload(image: string, file: string): void {
var me = this;
image && me.store["IMAGE"] && me.store['IMAGE'].destroy();
me.store["imgOpts"] && image == 'IMAGE' && me.createOptions(me.store["imgOpts"], 'IMAGE');
file && me.store['FILE'] && me.store['FILE'].destroy();
me.store['fileOpts'] && file == 'FILE' && me.createOptions(me.store['fileOpts'], 'FILE');
}
postImage(base64: string, file: any, conversationType: ConversationType, targetId: string, callback: any): void {
var me = this;
RCUploadLib.uploadAjax(base64, function(ret: any) {
var opt = { uploadType: 'IMAGE', info: ret, isBase64Data: true };
me.createMessage(opt, file, function(msg: MessageContent) {
RongIMClient.getInstance().sendMessage(conversationType, targetId, msg, <SendMessageCallback>{
onSuccess: function(message: Message) {
callback(ret, message);
},
onError: function(error: ErrorCode, message: Message) {
callback(ret, message, error);
}
});
});
});
}
uploadFactory(opts: any): void {
var me = this;
me.store[opts.uploadType] = new plupload.Uploader({
browse_button: opts.browse_button,
url: opts.domain,
container: opts.container,
max_file_size: opts.max_file_size,
// flash_swf_url: 'path/of/plupload/Moxie.swf',
max_retries: 0,
runtimes: opts.runtimes,
dragdrop: opts.dragdrop,
unique_names: true,
filters: opts.filters,
drop_element: opts.drop_element,
chunk_size: opts.chunk_size,
auto_start: false,
uploadType: opts.uploadType,
useUserDefine:opts.useUserDefine,
userData:opts.userData,
userDataKey:opts.userDataKey,
userDataArrs:[],
init: {
'FilesAdded': function(up: any, files: any) {
var opts: any = up.getOption(), name: string = "";
me.uploadType = opts.uploadType;
plupload.each(files, function(file: any) {
file.uploadType = me.uploadType;
me.listener.onFileAdded(file);
});
},
'BeforeUpload': function(up: any, file: any) {
var name: string = "";
file.oldName = file.name;
if (file.name.lastIndexOf('.') > -1) {
name = file.id + file.name.substr(file.name.lastIndexOf('.'));
}
else {
name = file.id;
}
file.name = name;
file.uploadType = me.uploadType;
me.listener.onBeforeUpload(file);
},
'UploadProgress': function(up: any, file: any) {
file.uploadType = me.uploadType;
me.listener.onUploadProgress(file);
},
'FileUploaded': function(up: any, file: any, info: any) {
var option: any = up.getOption();
if (file.name.lastIndexOf('.') > -1) {
var index = file.target_name.lastIndexOf('.')
opts.fileName = file.target_name.substr(0, index) + '.' + file.target_name.substr(index + 1).toLocaleLowerCase();
} else {
opts.fileName = file.id;
}
file.uploadType = me.uploadType;
opts['info'] = info;
me.createMessage(opts, file, function(msg: MessageContent) {
RongIMClient.getInstance().sendMessage(me.conversationType, me.targetId, msg, <SendMessageCallback>{
onSuccess: function(ret: Message) {
me.listener.onFileUploaded(file, ret);
},
onError: function(error: ErrorCode, ret: Message) {
me.listener.onFileUploaded(file, ret, error);
}
});
});
},
'Error': function(up: any, err: any, errTip: any) {
me.listener.onError(up, err, errTip);
},
'UploadComplete': function() {
me.listener.onUploadComplete();
},
'Key': function(up: any, file: any) {
}
}
});
me.store[opts.uploadType].init();
}
createMessage(opts: any, file: any, callback: Function): void {
var msg: MessageContent = null;
switch (opts.uploadType) {
case 'IMAGE':
if (opts.isBase64Data) {
RCUploadLib.imageCompressToBase64(file, function(content: string) {
msg = new RongIMLib.ImageMessage({ content: content, imageUri: RCUploadLib.getFileUrl(opts.info) });
callback(msg);
});
} else {
RCUploadLib.imageCompressToBase64(file.getNative(), function(content: string) {
msg = new RongIMLib.ImageMessage({ content: content, imageUri: RCUploadLib.getFileUrl(opts.info) });
callback(msg);
});
}
break;
case 'FILE':
var type: string = (opts.fileName && opts.fileName.split('.')[1]) || "";
var url = RCUploadLib.getFileUrl(opts.info);
url.indexOf('?') > -1 ? url += "&attname=" + encodeURIComponent(file.oldName) : url += "?attname=" + encodeURIComponent(file.oldName);
msg = new RongIMLib.FileMessage({ name: file.oldName, size: file.size, type: type, fileUrl: url });
callback(msg);
break;
}
}
private getThumbnail(obj: any, area: number, callback: any) {
var canvas = document.createElement("canvas"),
context = canvas.getContext('2d'), me = this;
var img = new Image();
img.onload = function() {
var target_w: number;
var target_h: number;
var imgarea = img.width * img.height;
var _y = 0, _x = 0, maxWidth = 240, maxHeight = 240;
if (imgarea > area) {
var scale = Math.sqrt(imgarea / area);
scale = Math.ceil(scale * 100) / 100;
target_w = img.width / scale;
target_h = img.height / scale;
} else {
target_w = img.width;
target_h = img.height;
}
canvas.width = target_w;
canvas.height = target_h;
context.drawImage(img, 0, 0, target_w, target_h);
try {
if (canvas.width > maxWidth || canvas.height > maxHeight) {
if (target_w > maxWidth) {
_x = (target_w - maxWidth) / 2;
target_w = maxWidth;
}
if (target_h > maxHeight) {
_y = (target_h - maxHeight) / 2;
target_h = maxHeight;
}
var imgData = context.getImageData(_x, _y, target_w, target_h);
context.createImageData(target_w, target_h);
canvas.width = target_w;
canvas.height = target_h;
context.putImageData(imgData, 0, 0);
}
var _canvas = canvas.toDataURL("image/jpeg", 0.5);
callback(obj, _canvas);
} catch (e) {
callback(obj, null);
}
}
img.src = me.getFullPath(obj);
}
private getFullPath(file: File): any {
window.URL = window.URL || window.webkitURL;
if (window.URL && window.URL.createObjectURL) {
return window.URL.createObjectURL(file)
} else {
return null;
}
}
}
} | the_stack |
import * as cfxers from './cfxers';
import * as ethLikeCompiled from './CFX_compiled';
import {
debug,
envDefault,
memoizeThunk,
replaceableThunk,
truthyEnv,
} from './shared_impl';
import type { Env } from './shim'; // =>
import { process, window } from './shim';
import waitPort from './waitPort';
import cfxsdk from 'js-conflux-sdk';
import Timeout from 'await-timeout';
import { canonicalizeConnectorMode, ConnectorMode } from './ConnectorMode';
import buffer from 'buffer';
const { Buffer } = buffer;
const { Conflux } = cfxsdk;
type NetworkAccount = cfxers.IWallet; // XXX or other things
type Provider = cfxers.providers.Provider;
function notYetSupported(label: string): any {
throw Error(`${label} not yet supported on CFX`);
}
function throwError(msg: string): any {
throw Error(msg);
}
const DEFAULT_CFX_NODE_URI = 'http://localhost:12537';
const DEFAULT_CFX_NETWORK_ID = '999';
export function isIsolatedNetwork(): boolean {
return truthyEnv(getProviderEnv().REACH_ISOLATED_NETWORK);
}
export function isWindowProvider(): boolean {
return !!window.conflux;
}
export function canGetDefaultAccount(): boolean {
// XXX be pickier
return true;
}
export async function _getDefaultNetworkAccount(): Promise<NetworkAccount> {
const cp = await getConfluxPortal();
const addr = (await cp.enable())[0];
const w = new cfxers.BrowserWallet(cp, addr);
if (w.provider) {
return w;
} else {
return w.connect(await getProvider());
}
}
// from /scripts/devnet-cfx/default.toml
const mining_key = '0x091ca0785ec2bd9a5eca245fdc83baddd570644f3e0489b41e515f0e5c33f3d9';
const defaultFaucetWallet = new cfxers.Wallet(mining_key);
export const _getDefaultFaucetNetworkAccount = memoizeThunk(async (): Promise<NetworkAccount> => {
if (!defaultFaucetWallet.provider) {
const provider = await getProvider();
// Async things can cause this state to change...
if (!defaultFaucetWallet.provider) defaultFaucetWallet.connect(provider);
}
return defaultFaucetWallet;
});
function toHexAddr(cfxAddr: string) {
return '0x' + Buffer.from(
// @ts-ignore
cfxsdk.address.decodeCfxAddress(cfxAddr).hexAddress
).toString('hex').toLowerCase();
}
async function _fundOnCfxTestNet(to: any, amt: any) {
// XXX TestNet faucet only gives out 100 CFX at a time
// Should we throw an error if amt !== 100 CFX?
void(amt)
const method = '_fundOnCfxTestNet';
to = to.getAddress ? await to.getAddress() : to;
debug({method, to});
const toHex = toHexAddr(to);
debug({method, message: 'requesting from testnet faucet', toHex});
const res = await window.fetch(`http://test-faucet.confluxnetwork.org:18088/dev/ask?address=${toHex}`);
const resJson = await res.json();
debug({method, message: 'got response from testnet faucet', resJson});
}
export async function canFundFromFaucet() {
debug('canFundFromFaucet');
const netId = ethLikeCompiled.getNetworkId();
return netId == 0x1 || netId == 999;
}
export async function _specialFundFromFaucet() {
debug(`_specialFundFromFaucet`);
if (ethLikeCompiled.getNetworkId() == 0x1) {
return _fundOnCfxTestNet;
} else {
return null;
}
}
async function waitCaughtUp(provider: Provider, env: ProviderEnv): Promise<void> {
if ('CFX_NODE_URI' in env && env.CFX_NODE_URI && truthyEnv(env.REACH_DO_WAIT_PORT)) {
await waitPort(env.CFX_NODE_URI);
}
if (isIsolatedNetwork()) {
// XXX this doesn't work with setFaucet; requires the default faucet to be used
// But we can't call getFaucet() or _getDefaultFaucetNetworkAccount() here because
// those (if left to defaults) call getProvider which calls this fn (waitCaughtUp).
// TODO: disentangle
if (!defaultFaucetWallet.provider) defaultFaucetWallet.connect(provider);
const maxTries = 20;
const waitMs = 1000;
let err: Error|null = null;
for (let tries = 0; tries < maxTries; tries++) {
if (err) {
debug(`waitCaughtUp: waiting some more`, {waitMs, tries, maxTries, err});
await Timeout.set(waitMs); // wait 1s between tries
}
try {
const faddr = defaultFaucetWallet.getAddress();
const fbal = await defaultFaucetWallet.provider?.conflux.getBalance(faddr);
debug(`Faucet bal`, fbal);
// @ts-ignore
if (fbal == 0) {
const failMsg = `Faucet balance is 0 (${faddr})`;
debug(failMsg);
throw Error(failMsg);
}
const w = cfxers.Wallet.createRandom().connect(provider);
const txn = {to: w.getAddress(), value: '1'};
debug(`sending dummy txn`, txn);
const t = await defaultFaucetWallet.sendTransaction(txn);
await t.wait();
return;
} catch (e:any) {
// TODO: only loop again if we detect that it's the "not caught up yet" error
// err: RPCError: Request rejected due to still in the catch up mode.
// { code: -32077 }
err = e;
}
}
if (err) throw err;
}
}
const [getProvider, _setProvider] = replaceableThunk<Promise<Provider>|Provider>(async (): Promise<Provider> => {
const fullEnv = getProviderEnv();
const provider = await waitProviderFromEnv(fullEnv);
// XXX disentangle the places where we waitProvider vs waitCaughtUp
// XXX is there a better place to wait for this
// such that toying with things at the repl doesn't hang if no connection is available?
await waitCaughtUp(provider, fullEnv);
return provider;
});
export function setProvider(provider: Provider|Promise<Provider>): void {
_setProvider(provider);
if (!_providerEnv) {
// this circumstance is weird and maybe we should handle it better
// process.env isn't available in browser so we try to avoid relying on it here.
setProviderEnv({
REACH_CONNECTOR_MODE: 'CFX-unspecified',
REACH_ISOLATED_NETWORK: 'no',
});
}
};
export type WhichNetExternal
= 'tethys'
| 'TestNet' // XXX name?
| 'BlockNumber' // XXX not permanent
// TODO: more providers 'by name'
export type ProviderName
= WhichNetExternal
| 'MainNet'
| 'TestNet'
| 'LocalHost'
| 'window'
export interface ProviderByWindow {
REACH_CONNECTOR_MODE: string
REACH_ISOLATED_NETWORK: string // preferably: 'yes' | 'no'
}
type ProviderByURI = {
CFX_NODE_URI: string
CFX_NETWORK_ID: string // XXX just query the URI for its net id?
REACH_CONNECTOR_MODE: string
REACH_DO_WAIT_PORT: string // preferably: 'yes' | 'no'
REACH_ISOLATED_NETWORK: string // preferably: 'yes' | 'no'
}
export type ProviderEnv = ProviderByURI | ProviderByWindow
function connectorModeIsolatedNetwork(cm: string): 'yes' | 'no' {
switch (cm) {
case 'CFX-devnet': return 'yes';
default: return 'no';
}
}
function guessConnectorMode(env: Env): ConnectorMode|undefined {
if ('CFX_NODE_URI' in env && env.CFX_NODE_URI) {
// take a guess if CFX_NODE_URI is set
return env.CFX_NODE_URI.toLowerCase().includes('localhost') ? 'CFX-devnet' : 'CFX-live';
} else {
// abstain from guessing
return undefined;
}
}
// XXX less copy/paste from ETH_impl
function envDefaultsCFX(env: Env): ProviderEnv {
const { CFX_NODE_URI, CFX_NETWORK_ID } = env;
const cm = envDefault(env.REACH_CONNECTOR_MODE, guessConnectorMode(env));
const REACH_CONNECTOR_MODE = envDefault(cm, canonicalizeConnectorMode(env.REACH_CONNECTOR_MODE || 'CFX'));
const isolatedDefault
= connectorModeIsolatedNetwork(REACH_CONNECTOR_MODE);
const REACH_ISOLATED_NETWORK = envDefault(env.REACH_ISOLATED_NETWORK, isolatedDefault);
if (truthyEnv(CFX_NODE_URI)) {
const REACH_DO_WAIT_PORT = envDefault(env.REACH_DO_WAIT_PORT, 'yes');
const cni = envDefault(CFX_NETWORK_ID, localhostProviderEnv.CFX_NETWORK_ID);
return { CFX_NODE_URI, CFX_NETWORK_ID: cni, REACH_CONNECTOR_MODE, REACH_DO_WAIT_PORT, REACH_ISOLATED_NETWORK };
} else {
if (window.conflux) {
return localhostProviderEnv;
// XXX instead of this ^ support using window.conflux as provider
// return notYetSupported(`window.conflux`);
// return windowProviderEnv(REACH_ISOLATED_NETWORK);
} else {
return localhostProviderEnv;
}
}
}
// Avoid using _providerEnv directly; use get/set
// We don't use replaceableThunk because slightly more nuanced inspection needs to be possible.
let _providerEnv: ProviderEnv|undefined;
function getProviderEnv(): ProviderEnv {
if (!_providerEnv) {
// We only fall back on process.env if there no setProviderEnv occurrs
const env = envDefaultsCFX(process.env);
_providerEnv = env;
}
return _providerEnv;
}
function setProviderEnv(env: ProviderEnv): void {
if (_providerEnv) {
throw Error(`setProviderEnv called after it was already set`);
}
_providerEnv = env;
if ('CFX_NETWORK_ID' in env) {
try {
const networkId = parseInt(env.CFX_NETWORK_ID);
ethLikeCompiled.setNetworkId(networkId);
} catch (_) {
throw Error(`Invalid CFX_NETWORK_ID='${env.CFX_NETWORK_ID}'`);
}
}
}
// XXX less copy/pasta from ETH_impl
async function waitProviderFromEnv(env: ProviderEnv): Promise<Provider> {
if ('CFX_NODE_URI' in env && env.CFX_NODE_URI) {
const {CFX_NODE_URI, CFX_NETWORK_ID, REACH_DO_WAIT_PORT} = env;
return (async () => {
if (truthyEnv(REACH_DO_WAIT_PORT)) await waitPort(CFX_NODE_URI);
// await doHealthcheck(CFX_NODE_URI);
// XXX ^ do health check?
const networkId = CFX_NETWORK_ID ? parseInt(CFX_NETWORK_ID) : undefined;
debug(`waitProviderFromEnv`, `new Conflux`, {url: CFX_NODE_URI, networkId});
const provider = new cfxers.providers.Provider(new Conflux({
url: CFX_NODE_URI,
networkId,
// Uncomment if you want CFX logs on every API call
// logger: console,
}));
// XXX: make some sort of configurable polling interval?
// provider.pollingInterval = 500; // ms
return provider;
})();
} else {
const {conflux} = window;
if (conflux) {
return (async () => {
return notYetSupported(`using window.conflux as provider.`);
// TODO
// const provider = new ethers.providers.Web3Provider(ethereum);
// // The proper way to ask MetaMask to enable itself is eth_requestAccounts
// // https://eips.ethereum.org/EIPS/eip-1102
// await provider.send('eth_requestAccounts', []);
// return provider;
})();
} else {
throw Error(`window.conflux is not defined`);
}
}
}
function setProviderByEnv(env: any): void {
const fullEnv = envDefaultsCFX(env);
setProviderEnv(fullEnv);
setProvider(waitProviderFromEnv(fullEnv));
}
function setProviderByName(providerName: ProviderName): void {
const env = providerEnvByName(providerName)
setProviderByEnv(env);
}
const localhostProviderEnv: ProviderByURI = {
CFX_NODE_URI: DEFAULT_CFX_NODE_URI,
CFX_NETWORK_ID: DEFAULT_CFX_NETWORK_ID,
REACH_CONNECTOR_MODE: 'CFX-devnet', // browser?
REACH_DO_WAIT_PORT: 'yes',
REACH_ISOLATED_NETWORK: 'yes',
}
function providerEnvByName(providerName: ProviderName): ProviderEnv {
switch (providerName) {
case 'LocalHost': return localhostProviderEnv;
case 'window': return notYetSupported(`providerEnvByName('window')`);
case 'MainNet': return providerEnvByName('tethys');
case 'TestNet': return cfxProviderEnv('TestNet');
case 'tethys': return cfxProviderEnv('tethys');
case 'BlockNumber': return cfxProviderEnv('BlockNumber'); // XXX temporary
default: throw Error(`Unrecognized provider name: ${providerName}`);
}
}
function cfxProviderEnv(network: WhichNetExternal): ProviderByURI {
const [CFX_NODE_URI, CFX_NETWORK_ID] =
network == 'BlockNumber' ? ['http://52.53.235.44:12537', '1'] // 0x1
: network == 'TestNet' ? ['https://portal-test.confluxrpc.com', '1'] // 0x1
: network == 'tethys' ? ['https://portal-main.confluxrpc.com', '1029'] // 0x405
: throwError(`network name not recognized: '${network}'`);
return {
CFX_NODE_URI,
CFX_NETWORK_ID,
REACH_DO_WAIT_PORT: 'yes',
REACH_CONNECTOR_MODE: 'CFX-live',
REACH_ISOLATED_NETWORK: 'no',
}
}
async function getConfluxPortal(): Promise<cfxers.CP> {
const maxTries = 10;
for (let tries = 1; tries <= maxTries; tries++) {
if (window.conflux) return window.conflux;
await Timeout.set(100);
}
throw Error(`Couldn't find window.conflux`);
}
const setWalletFallback = (wf:() => any) => {
if ( ! window.conflux ) { window.conflux = wf(); }
};
const walletFallback = (opts:any) => () => {
void(opts);
throw new Error(`There is no wallet fallback for Conflux`);
};
export { ethLikeCompiled };
export { cfxers as ethers };
export const providerLib = {
getProvider,
setProvider,
setProviderByName,
setProviderByEnv,
providerEnvByName,
setWalletFallback,
walletFallback,
}
export const _warnTxNoBlockNumber = false; // XXX ?
export const standardUnit = 'CFX';
export const atomicUnit = 'Drip';
// This can probably be 999, but Dan is superstitious,
// and wants to avoid off-by-ones by a larger margin
export const validQueryWindow = 990; | the_stack |
import areShallowEqual from 'are-shallow-equal';
import {useCallback, useDebugValue, useEffect, useMemo, useRef, useState} from 'react';
import ChangesCounters from '../changes_counters';
import {EMPTY_ARRAY, COMPARATOR_FALSE, SELECTOR_IDENTITY} from '../consts';
import Errors from '../errors';
import onChange from '../on_change';
import Utils from '../utils';
import {Primitive} from '../types';
/* USE STORE */
function useStore<S1 extends object, S2 extends object, S3 extends object, S4 extends object, S5 extends object, S6 extends object, S7 extends object, S8 extends object, S9 extends object> ( stores: [S1, S2, S3, S4, S5, S6, S7, S8, S9] ): [S1, S2, S3, S4, S5, S6, S7, S8, S9];
function useStore<S1 extends object, S2 extends object, S3 extends object, S4 extends object, S5 extends object, S6 extends object, S7 extends object, S8 extends object> ( stores: [S1, S2, S3, S4, S5, S6, S7, S8] ): [S1, S2, S3, S4, S5, S6, S7, S8];
function useStore<S1 extends object, S2 extends object, S3 extends object, S4 extends object, S5 extends object, S6 extends object, S7 extends object> ( stores: [S1, S2, S3, S4, S5, S6, S7] ): [S1, S2, S3, S4, S5, S6, S7];
function useStore<S1 extends object, S2 extends object, S3 extends object, S4 extends object, S5 extends object, S6 extends object> ( stores: [S1, S2, S3, S4, S5, S6] ): [S1, S2, S3, S4, S5, S6];
function useStore<S1 extends object, S2 extends object, S3 extends object, S4 extends object, S5 extends object> ( stores: [S1, S2, S3, S4, S5] ): [S1, S2, S3, S4, S5];
function useStore<S1 extends object, S2 extends object, S3 extends object, S4 extends object> ( stores: [S1, S2, S3, S4] ): [S1, S2, S3, S4];
function useStore<S1 extends object, S2 extends object, S3 extends object> ( stores: [S1, S2, S3] ): [S1, S2, S3];
function useStore<S1 extends object, S2 extends object> ( stores: [S1, S2] ): [S1, S2];
function useStore<S1 extends object> ( store: S1 ): S1;
function useStore<S1 extends object, S2 extends object, S3 extends object, S4 extends object, S5 extends object, S6 extends object, S7 extends object, S8 extends object, S9 extends object, R> ( stores: [S1, S2, S3, S4, S5, S6, S7, S8, S9], selector: ( ...stores: [S1, S2, S3, S4, S5, S6, S7, S8, S9] ) => R, dependencies?: any[] ): R;
function useStore<S1 extends object, S2 extends object, S3 extends object, S4 extends object, S5 extends object, S6 extends object, S7 extends object, S8 extends object, R> ( stores: [S1, S2, S3, S4, S5, S6, S7, S8], selector: ( ...stores: [S1, S2, S3, S4, S5, S6, S7, S8] ) => R, dependencies?: any[] ): R;
function useStore<S1 extends object, S2 extends object, S3 extends object, S4 extends object, S5 extends object, S6 extends object, S7 extends object, R> ( stores: [S1, S2, S3, S4, S5, S6, S7], selector: ( ...stores: [S1, S2, S3, S4, S5, S6, S7] ) => R, dependencies?: any[] ): R;
function useStore<S1 extends object, S2 extends object, S3 extends object, S4 extends object, S5 extends object, S6 extends object, R> ( stores: [S1, S2, S3, S4, S5, S6], selector: ( ...stores: [S1, S2, S3, S4, S5, S6] ) => R, dependencies?: any[] ): R;
function useStore<S1 extends object, S2 extends object, S3 extends object, S4 extends object, S5 extends object, R> ( stores: [S1, S2, S3, S4, S5], selector: ( ...stores: [S1, S2, S3, S4, S5] ) => R, dependencies?: any[] ): R;
function useStore<S1 extends object, S2 extends object, S3 extends object, S4 extends object, R> ( stores: [S1, S2, S3, S4], selector: ( ...stores: [S1, S2, S3, S4] ) => R, dependencies?: any[] ): R;
function useStore<S1 extends object, S2 extends object, S3 extends object, R> ( stores: [S1, S2, S3], selector: ( ...stores: [S1, S2, S3] ) => R, dependencies?: any[] ): R;
function useStore<S1 extends object, S2 extends object, R> ( stores: [S1, S2], selector: ( ...stores: [S1, S2] ) => R, dependencies?: any[] ): R;
function useStore<S1 extends object, R> ( store: S1, selector: ( store: S1 ) => R, dependencies?: any[] ): R;
function useStore<S1 extends object, S2 extends object, S3 extends object, S4 extends object, S5 extends object, S6 extends object, S7 extends object, S8 extends object, S9 extends object, R> ( stores: [S1, S2, S3, S4, S5, S6, S7, S8, S9], selector: ( ...stores: [S1, S2, S3, S4, S5, S6, S7, S8, S9] ) => R, comparator: ( dataPrev: Exclude<R, Primitive>, dataNext: Exclude<R, Primitive> ) => boolean, dependencies?: any[] ): R;
function useStore<S1 extends object, S2 extends object, S3 extends object, S4 extends object, S5 extends object, S6 extends object, S7 extends object, S8 extends object, R> ( stores: [S1, S2, S3, S4, S5, S6, S7, S8], selector: ( ...stores: [S1, S2, S3, S4, S5, S6, S7, S8] ) => R, comparator: ( dataPrev: Exclude<R, Primitive>, dataNext: Exclude<R, Primitive> ) => boolean, dependencies?: any[] ): R;
function useStore<S1 extends object, S2 extends object, S3 extends object, S4 extends object, S5 extends object, S6 extends object, S7 extends object, R> ( stores: [S1, S2, S3, S4, S5, S6, S7], selector: ( ...stores: [S1, S2, S3, S4, S5, S6, S7] ) => R, comparator: ( dataPrev: Exclude<R, Primitive>, dataNext: Exclude<R, Primitive> ) => boolean, dependencies?: any[] ): R;
function useStore<S1 extends object, S2 extends object, S3 extends object, S4 extends object, S5 extends object, S6 extends object, R> ( stores: [S1, S2, S3, S4, S5, S6], selector: ( ...stores: [S1, S2, S3, S4, S5, S6] ) => R, comparator: ( dataPrev: Exclude<R, Primitive>, dataNext: Exclude<R, Primitive> ) => boolean, dependencies?: any[] ): R;
function useStore<S1 extends object, S2 extends object, S3 extends object, S4 extends object, S5 extends object, R> ( stores: [S1, S2, S3, S4, S5], selector: ( ...stores: [S1, S2, S3, S4, S5] ) => R, comparator: ( dataPrev: Exclude<R, Primitive>, dataNext: Exclude<R, Primitive> ) => boolean, dependencies?: any[] ): R;
function useStore<S1 extends object, S2 extends object, S3 extends object, S4 extends object, R> ( stores: [S1, S2, S3, S4], selector: ( ...stores: [S1, S2, S3, S4] ) => R, comparator: ( dataPrev: Exclude<R, Primitive>, dataNext: Exclude<R, Primitive> ) => boolean, dependencies?: any[] ): R;
function useStore<S1 extends object, S2 extends object, S3 extends object, R> ( stores: [S1, S2, S3], selector: ( ...stores: [S1, S2, S3] ) => R, comparator: ( dataPrev: Exclude<R, Primitive>, dataNext: Exclude<R, Primitive> ) => boolean, dependencies?: any[] ): R;
function useStore<S1 extends object, S2 extends object, R> ( stores: [S1, S2], selector: ( ...stores: [S1, S2] ) => R, comparator: ( dataPrev: Exclude<R, Primitive>, dataNext: Exclude<R, Primitive> ) => boolean, dependencies?: any[] ): R;
function useStore<S1 extends object, R> ( store: S1, selector: ( store: S1 ) => R, comparator: ( dataPrev: Exclude<R, Primitive>, dataNext: Exclude<R, Primitive> ) => boolean, dependencies?: any[] ): R;
function useStore<Store extends object, R> ( store: Store | Store[], selector: (( store: Store ) => R) | (( ...stores: Store[] ) => R) = SELECTOR_IDENTITY, comparator?: (( dataPrev: Exclude<R, Primitive>, dataNext: Exclude<R, Primitive> ) => boolean) | any[], dependencies?: any[] ): Store | Store[] | R {
if ( !dependencies && !comparator ) return useStore ( store, selector, COMPARATOR_FALSE, EMPTY_ARRAY );
if ( !dependencies ) {
if ( typeof comparator === 'function' ) return useStore ( store, selector, comparator, EMPTY_ARRAY );
return useStore ( store, selector, COMPARATOR_FALSE, comparator );
}
const stores = Utils.isStores ( store ) ? store : [store];
if ( !stores.length ) throw Errors.storesEmpty ();
const mountedRef = useRef ( false ),
storesRef = useRef<Store[] | undefined> (),
storesMemo = ( storesRef.current && areShallowEqual ( storesRef.current, stores ) ) ? storesRef.current : stores,
selectorMemo = useCallback ( selector, dependencies ),
selectorRef = useRef ( selectorMemo ), // Storing a ref so we won't have to resubscribe if the selector changes
comparatorMemo = useCallback ( comparator as any, dependencies ), //TSC
comparatorRef = useRef ( comparatorMemo ), // Storing a ref so we won't have to resubscribe if the comparator changes
changesCountersRendering = useMemo ( () => ChangesCounters.getMultiple ( storesMemo ), [storesMemo] ), // Storing the number of changes at rendering time, in order to understand if changes happened before now and commit time
valueRef = useRef<R> ( undefined as any ), // Using a ref in order not to trigger *any* unnecessary re-renders //TSC
setUpdateId = useState<symbol> ()[1], // Dummy state used for triggering updates
forceUpdate = useCallback ( () => setUpdateId ( Symbol () ), [] );
if ( storesRef.current !== storesMemo || selectorRef.current !== selectorMemo || comparatorRef.current !== comparatorMemo ) {
storesRef.current = storesMemo;
selectorRef.current = selectorMemo;
comparatorRef.current = comparatorMemo;
const value = selectorMemo.apply ( undefined, storesMemo );
if ( !Object.is ( value, valueRef.current ) ) {
valueRef.current = value;
}
}
useDebugValue ( valueRef.current );
useEffect ( () => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
};
}, [] );
useEffect ( () => {
/* COUNTERS */ // Checking if something changed while we weren't subscribed yet, updating
const changesCounterMounting = ChangesCounters.getMultiple ( storesMemo );
if ( !Utils.isEqual ( changesCountersRendering, changesCounterMounting ) ) {
const value = selectorRef.current.apply ( undefined, storesMemo );
if ( !Object.is ( value, valueRef.current ) ) {
valueRef.current = value;
forceUpdate ();
}
}
/* SUBSCRIPTION */
return onChange ( storesMemo, ( ...stores ) => selectorRef.current.apply ( undefined, stores ), ( dataPrev, dataNext ) => comparatorRef.current.call ( undefined, dataPrev, dataNext ), ( ...values ) => {
if ( !mountedRef.current ) return;
const value = values.length > 1 ? values : values[0];
valueRef.current = value;
forceUpdate ();
});
}, [storesMemo, changesCountersRendering] );
return valueRef.current;
}
/* EXPORT */
export default useStore; | the_stack |
import * as Emscripten from "./emscripten";
// emcc -s MODULARIZE=0
// declare const Module: Module; export default Module;
// emcc -s MODULARIZE=1
export default function Module(Module?: Partial<Module>): Module;
export interface mallinfo {
arena: number;
ordblks: number;
smblks: number;
hblks: number;
hblkhd: number;
usmblks: number;
fsmblks: number;
uordblks: number;
fordblks: number;
keepcost: number;
}
export type ImAccess<T> = (value?: T) => T;
export type ImScalar<T> = [ T ];
export type ImTuple2<T> = [ T, T ];
export type ImTuple3<T> = [ T, T, T ];
export type ImTuple4<T> = [ T, T, T, T ];
// Enums/Flags (declared as int for compatibility with old C++, to allow using as flags and to not pollute the top of this file)
// - Tip: Use your programming IDE navigation facilities on the names in the _central column_ below to find the actual flags/enum lists!
// In Visual Studio IDE: CTRL+comma ("Edit.NavigateTo") can follow symbols in comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot.
// With Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols in comments.
type ImGuiCol = number; // -> enum ImGuiCol_ // Enum: A color identifier for styling
type ImGuiCond = number; // -> enum ImGuiCond_ // Enum: A condition for many Set*() functions
type ImGuiDataType = number; // -> enum ImGuiDataType_ // Enum: A primary data type
type ImGuiDir = number; // -> enum ImGuiDir_ // Enum: A cardinal direction
type ImGuiKey = number; // -> enum ImGuiKey_ // Enum: A key identifier (ImGui-side enum)
type ImGuiNavInput = number; // -> enum ImGuiNavInput_ // Enum: An input identifier for navigation
type ImGuiMouseButton = number; // -> enum ImGuiMouseButton_ // Enum: A mouse button identifier (0=left, 1=right, 2=middle)
type ImGuiMouseCursor = number; // -> enum ImGuiMouseCursor_ // Enum: A mouse cursor identifier
type ImGuiSortDirection = number; // -> enum ImGuiSortDirection_ // Enum: A sorting direction (ascending or descending)
type ImGuiStyleVar = number; // -> enum ImGuiStyleVar_ // Enum: A variable identifier for styling
type ImGuiTableBgTarget = number; // -> enum ImGuiTableBgTarget_ // Enum: A color target for TableSetBgColor()
type ImDrawCornerFlags = number; // -> enum ImDrawCornerFlags_ // Flags: for ImDrawList::AddRect(), AddRectFilled() etc.
type ImDrawListFlags = number; // -> enum ImDrawListFlags_ // Flags: for ImDrawList
type ImFontAtlasFlags = number; // -> enum ImFontAtlasFlags_ // Flags: for ImFontAtlas build
type ImGuiBackendFlags = number; // -> enum ImGuiBackendFlags_ // Flags: for io.BackendFlags
type ImGuiButtonFlags = number; // -> enum ImGuiButtonFlags_ // Flags: for InvisibleButton()
type ImGuiColorEditFlags = number; // -> enum ImGuiColorEditFlags_ // Flags: for ColorEdit4(), ColorPicker4() etc.
type ImGuiConfigFlags = number; // -> enum ImGuiConfigFlags_ // Flags: for io.ConfigFlags
type ImGuiComboFlags = number; // -> enum ImGuiComboFlags_ // Flags: for BeginCombo()
type ImGuiDragDropFlags = number; // -> enum ImGuiDragDropFlags_ // Flags: for BeginDragDropSource(), AcceptDragDropPayload()
type ImGuiFocusedFlags = number; // -> enum ImGuiFocusedFlags_ // Flags: for IsWindowFocused()
type ImGuiHoveredFlags = number; // -> enum ImGuiHoveredFlags_ // Flags: for IsItemHovered(), IsWindowHovered() etc.
type ImGuiInputTextFlags = number; // -> enum ImGuiInputTextFlags_ // Flags: for InputText(), InputTextMultiline()
type ImGuiKeyModFlags = number; // -> enum ImGuiKeyModFlags_ // Flags: for io.KeyMods (Ctrl/Shift/Alt/Super)
type ImGuiPopupFlags = number; // -> enum ImGuiPopupFlags_ // Flags: for OpenPopup*(), BeginPopupContext*(), IsPopupOpen()
type ImGuiSelectableFlags = number; // -> enum ImGuiSelectableFlags_ // Flags: for Selectable()
type ImGuiSliderFlags = number; // -> enum ImGuiSliderFlags_ // Flags: for DragFloat(), DragInt(), SliderFloat(), SliderInt() etc.
type ImGuiTabBarFlags = number; // -> enum ImGuiTabBarFlags_ // Flags: for BeginTabBar()
type ImGuiTabItemFlags = number; // -> enum ImGuiTabItemFlags_ // Flags: for BeginTabItem()
type ImGuiTableFlags = number; // -> enum ImGuiTableFlags_ // Flags: For BeginTable()
type ImGuiTableColumnFlags = number; // -> enum ImGuiTableColumnFlags_// Flags: For TableSetupColumn()
type ImGuiTableRowFlags = number; // -> enum ImGuiTableRowFlags_ // Flags: For TableNextRow()
type ImGuiTreeNodeFlags = number; // -> enum ImGuiTreeNodeFlags_ // Flags: for TreeNode(), TreeNodeEx(), CollapsingHeader()
type ImGuiWindowFlags = number; // -> enum ImGuiWindowFlags_ // Flags: for Begin(), BeginChild()
// Other types
// #ifndef ImTextureID // ImTextureID [configurable type: override in imconfig.h with '#define ImTextureID xxx']
// typedef void* ImTextureID; // User data for rendering backend to identify a texture. This is whatever to you want it to be! read the FAQ about ImTextureID for details.
// #endif
export type ImTextureID = number;
// typedef unsigned int ImGuiID; // A unique ID used by widgets, typically hashed from a stack of string.
export type ImGuiID = number;
// typedef int (*ImGuiInputTextCallback)(ImGuiInputTextCallbackData* data); // Callback function for ImGui::InputText()
export type ImGuiInputTextCallback = (data: reference_ImGuiInputTextCallbackData) => number;
// typedef void (*ImGuiSizeCallback)(ImGuiSizeCallbackData* data); // Callback function for ImGui::SetNextWindowSizeConstraints()
export type ImGuiSizeCallback = (data: reference_ImGuiSizeCallbackData) => void;
// Character types
// (we generally use UTF-8 encoded string in the API. This is storage specifically for a decoded character used for keyboard input and display)
// typedef unsigned short ImWchar16; // A single decoded U16 character/code point. We encode them as multi bytes UTF-8 when used in strings.
export type ImWchar16 = number;
// typedef unsigned int ImWchar32; // A single decoded U32 character/code point. We encode them as multi bytes UTF-8 when used in strings.
export type ImWchar32 = number;
// #ifdef IMGUI_USE_WCHAR32 // ImWchar [configurable type: override in imconfig.h with '#define IMGUI_USE_WCHAR32' to support Unicode planes 1-16]
// typedef ImWchar32 ImWchar;
// #else
// typedef ImWchar16 ImWchar;
// #endif
export type ImWchar = number;
// Basic scalar data types
// typedef signed char ImS8; // 8-bit signed integer
// typedef unsigned char ImU8; // 8-bit unsigned integer
// typedef signed short ImS16; // 16-bit signed integer
export type ImS16 = number;
// typedef unsigned short ImU16; // 16-bit unsigned integer
// typedef signed int ImS32; // 32-bit signed integer == int
// typedef unsigned int ImU32; // 32-bit unsigned integer (often used to store packed colors)
export type ImU32 = number;
// #if defined(_MSC_VER) && !defined(__clang__)
// typedef signed __int64 ImS64; // 64-bit signed integer (pre and post C++11 with Visual Studio)
// typedef unsigned __int64 ImU64; // 64-bit unsigned integer (pre and post C++11 with Visual Studio)
// #elif (defined(__clang__) || defined(__GNUC__)) && (__cplusplus < 201100)
// #include <stdint.h>
// typedef int64_t ImS64; // 64-bit signed integer (pre C++11)
// typedef uint64_t ImU64; // 64-bit unsigned integer (pre C++11)
// #else
// typedef signed long long ImS64; // 64-bit signed integer (post C++11)
// typedef unsigned long long ImU64; // 64-bit unsigned integer (post C++11)
// #endif
export class WrapImGuiContext extends Emscripten.EmscriptenClass {}
export interface interface_ImVec2 {
x: number;
y: number;
Set(x: number, y: number): this;
Copy(other: Readonly<interface_ImVec2>): this;
Equals(other: Readonly<interface_ImVec2>): boolean;
}
export interface reference_ImVec2 extends Emscripten.EmscriptenClassReference, interface_ImVec2 {}
export interface interface_ImVec4 {
x: number;
y: number;
z: number;
w: number;
Set(x: number, y: number, z: number, w: number): this;
Copy(other: Readonly<interface_ImVec4>): this;
Equals(other: Readonly<interface_ImVec4>): boolean;
}
export interface reference_ImVec4 extends Emscripten.EmscriptenClassReference, interface_ImVec4 {}
// Shared state of InputText(), passed to callback when a ImGuiInputTextFlags_Callback* flag is used and the corresponding callback is triggered.
export interface reference_ImGuiInputTextCallbackData extends Emscripten.EmscriptenClassReference {
// ImGuiInputTextFlags EventFlag; // One of ImGuiInputTextFlags_Callback* // Read-only
EventFlag: ImGuiInputTextFlags;
// ImGuiInputTextFlags Flags; // What user passed to InputText() // Read-only
Flags: ImGuiInputTextFlags;
// void* UserData; // What user passed to InputText() // Read-only
UserData: any;
// CharFilter event:
// ImWchar EventChar; // Character input // Read-write (replace character or set to zero)
EventChar: ImWchar;
// Completion,History,Always events:
// If you modify the buffer contents make sure you update 'BufTextLen' and set 'BufDirty' to true.
// ImGuiKey EventKey; // Key pressed (Up/Down/TAB) // Read-only
EventKey: ImGuiKey;
// char* Buf; // Current text buffer // Read-write (pointed data only, can't replace the actual pointer)
Buf: string;
// int BufTextLen; // Current text length in bytes // Read-write
BufTextLen: number;
// int BufSize; // Maximum text length in bytes // Read-only
BufSize: number;
// bool BufDirty; // Set if you modify Buf/BufTextLen!! // Write
BufDirty: boolean;
// int CursorPos; // // Read-write
CursorPos: number;
// int SelectionStart; // // Read-write (== to SelectionEnd when no selection)
SelectionStart: number;
// int SelectionEnd; // // Read-write
SelectionEnd: number;
// NB: Helper functions for text manipulation. Calling those function loses selection.
// IMGUI_API void DeleteChars(int pos, int bytes_count);
DeleteChars(pos: number, bytes_count: number): void;
// IMGUI_API void InsertChars(int pos, const char* text, const char* text_end = NULL);
InsertChars(pos: number, text: string): void;
// void SelectAll() { SelectionStart = 0; SelectionEnd = BufTextLen; }
SelectAll(): void;
// void ClearSelection() { SelectionStart = SelectionEnd = BufTextLen; }
ClearSelection(): void;
// bool HasSelection() const { return SelectionStart != SelectionEnd; }
HasSelection(): boolean;
}
// Resizing callback data to apply custom constraint. As enabled by SetNextWindowSizeConstraints(). Callback is called during the next Begin().
// NB: For basic min/max size constraint on each axis you don't need to use the callback! The SetNextWindowSizeConstraints() parameters are enough.
export interface reference_ImGuiSizeCallbackData extends Emscripten.EmscriptenClassReference
{
// void* UserData; // Read-only. What user passed to SetNextWindowSizeConstraints()
// UserData: any;
// ImVec2 Pos; // Read-only. Window position, for reference.
Pos: Readonly<reference_ImVec2>;
// ImVec2 CurrentSize; // Read-only. Current window size.
CurrentSize: Readonly<reference_ImVec2>;
// ImVec2 DesiredSize; // Read-write. Desired size, based on user's mouse position. Write to this field to restrain resizing.
DesiredSize: reference_ImVec2;
}
export class ImGuiListClipper extends Emscripten.EmscriptenClass {
public DisplayStart: number;
public DisplayEnd: number;
public ItemsCount: number;
public StepNo: number;
public ItemsFrozen: number;
public ItemsHeight: number;
public StartPosY: number;
// items_count: Use -1 to ignore (you can call Begin later). Use INT_MAX if you don't know how many items you have (in which case the cursor won't be advanced in the final step).
// items_height: Use -1.0f to be calculated automatically on first step. Otherwise pass in the distance between your items, typically GetTextLineHeightWithSpacing() or GetFrameHeightWithSpacing().
// If you don't specify an items_height, you NEED to call Step(). If you specify items_height you may call the old Begin()/End() api directly, but prefer calling Step().
// ImGuiListClipper(int items_count = -1, float items_height = -1.0f) { Begin(items_count, items_height); } // NB: Begin() initialize every fields (as we allow user to call Begin/End multiple times on a same instance if they want).
// ~ImGuiListClipper() { IM_ASSERT(ItemsCount == -1); } // Assert if user forgot to call End() or Step() until false.
// IMGUI_API void Begin(int items_count, float items_height = -1.0f); // Automatically called by constructor if you passed 'items_count' or by Step() in Step 1.
public Begin(items_count: number, items_height: number): void;
// IMGUI_API void End(); // Automatically called on the last call of Step() that returns false.
public End(): void;
// IMGUI_API bool Step(); // Call until it returns false. The DisplayStart/DisplayEnd fields will be set and you can process/draw those items.
public Step(): boolean;
}
export interface reference_ImGuiTableColumnSortSpecs extends Emscripten.EmscriptenClassReference {
// ImGuiID ColumnUserID; // User id of the column (if specified by a TableSetupColumn() call)
ColumnUserID: number;
// ImS16 ColumnIndex; // Index of the column
ColumnIndex: number;
// ImS16 SortOrder; // Index within parent ImGuiTableSortSpecs (always stored in order starting from 0, tables sorted on a single criteria will always have a 0 here)
SortOrder: number;
// ImGuiSortDirection SortDirection : 8; // ImGuiSortDirection_Ascending or ImGuiSortDirection_Descending (you can use this or SortSign, whichever is more convenient for your sort function)
SortDirection: number; // TODO: use an enum?
}
export interface reference_ImGuiTableSortSpecs extends Emscripten.EmscriptenClassReference {
//const ImGuiTableColumnSortSpecs* Specs; // Pointer to sort spec array.
//Specs: readonly reference_ImGuiTableColumnSortSpecs[];
GetSpec(idx: number) : reference_ImGuiTableColumnSortSpecs;
//int SpecsCount; // Sort spec count. Most often 1. May be > 1 when ImGuiTableFlags_SortMulti is enabled. May be == 0 when ImGuiTableFlags_SortTristate is enabled.
SpecsCount: number; // TODO: make readonly?
//bool SpecsDirty; // Set to true when specs have changed since last time! Use this to sort again, then clear the flag.
SpecsDirty: boolean;
//ImGuiTableSortSpecs() { memset(this, 0, sizeof(*this)); }
}
// You may modify the ImGui::GetStyle() main instance during initialization and before NewFrame().
// During the frame, prefer using ImGui::PushStyleVar(ImGuiStyleVar_XXXX)/PopStyleVar() to alter the main style values, and ImGui::PushStyleColor(ImGuiCol_XXX)/PopStyleColor() for colors.
export interface interface_ImGuiStyle {
// float Alpha; // Global alpha applies to everything in Dear ImGui.
// ImVec2 WindowPadding; // Padding within a window.
// float WindowRounding; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
// float WindowBorderSize; // Thickness of border around windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).
// ImVec2 WindowMinSize; // Minimum window size. This is a global setting. If you want to constraint individual windows, use SetNextWindowSizeConstraints().
// ImVec2 WindowTitleAlign; // Alignment for title bar text. Defaults to (0.0f,0.5f) for left-aligned,vertically centered.
// ImGuiDir WindowMenuButtonPosition; // Side of the collapsing/docking button in the title bar (None/Left/Right). Defaults to ImGuiDir_Left.
// float ChildRounding; // Radius of child window corners rounding. Set to 0.0f to have rectangular windows.
// float ChildBorderSize; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).
// float PopupRounding; // Radius of popup window corners rounding. (Note that tooltip windows use WindowRounding)
// float PopupBorderSize; // Thickness of border around popup/tooltip windows. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).
// ImVec2 FramePadding; // Padding within a framed rectangle (used by most widgets).
// float FrameRounding; // Radius of frame corners rounding. Set to 0.0f to have rectangular frame (used by most widgets).
// float FrameBorderSize; // Thickness of border around frames. Generally set to 0.0f or 1.0f. (Other values are not well tested and more CPU/GPU costly).
// ImVec2 ItemSpacing; // Horizontal and vertical spacing between widgets/lines.
// ImVec2 ItemInnerSpacing; // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label).
// ImVec2 CellPadding; // Padding within a table cell
// ImVec2 TouchExtraPadding; // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
// float IndentSpacing; // Horizontal indentation when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
// float ColumnsMinSpacing; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
// float ScrollbarSize; // Width of the vertical scrollbar, Height of the horizontal scrollbar.
// float ScrollbarRounding; // Radius of grab corners for scrollbar.
// float GrabMinSize; // Minimum width/height of a grab box for slider/scrollbar.
// float GrabRounding; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
// float LogSliderDeadzone; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
// float TabRounding; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
// float TabBorderSize; // Thickness of border around tabs.
// float TabMinWidthForCloseButton; // Minimum width for close button to appears on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
// ImGuiDir ColorButtonPosition; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
// ImVec2 ButtonTextAlign; // Alignment of button text when button is larger than text. Defaults to (0.5f, 0.5f) (centered).
// ImVec2 SelectableTextAlign; // Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
// ImVec2 DisplayWindowPadding; // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
// ImVec2 DisplaySafeAreaPadding; // If you cannot see the edges of your screen (e.g. on a TV) increase the safe area padding. Apply to popups/tooltips as well regular windows. NB: Prefer configuring your TV sets correctly!
// float MouseCursorScale; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
// bool AntiAliasedLines; // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList).
// bool AntiAliasedLinesUseTex; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering. Latched at the beginning of the frame (copied to ImDrawList).
// bool AntiAliasedFill; // Enable anti-aliased edges around filled shapes (rounded rectangles, circles, etc.). Disable if you are really tight on CPU/GPU. Latched at the beginning of the frame (copied to ImDrawList).
// float CurveTessellationTol; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
// float CircleSegmentMaxError; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
// ImVec4 Colors[ImGuiCol_COUNT];
Alpha: number;
readonly WindowPadding: interface_ImVec2;
WindowRounding: number;
WindowBorderSize: number;
readonly WindowMinSize: interface_ImVec2;
readonly WindowTitleAlign: interface_ImVec2;
WindowMenuButtonPosition: ImGuiDir;
ChildRounding: number;
ChildBorderSize: number;
PopupRounding: number;
PopupBorderSize: number;
readonly FramePadding: interface_ImVec2;
FrameRounding: number;
FrameBorderSize: number;
readonly ItemSpacing: interface_ImVec2;
readonly ItemInnerSpacing: interface_ImVec2;
readonly TouchExtraPadding: interface_ImVec2;
readonly CellPadding: interface_ImVec2;
IndentSpacing: number;
ColumnsMinSpacing: number;
ScrollbarSize: number;
ScrollbarRounding: number;
GrabMinSize: number;
GrabRounding: number;
LogSliderDeadzone: number;
TabRounding: number;
TabBorderSize: number;
TabMinWidthForCloseButton: number;
ColorButtonPosition: number;
readonly ButtonTextAlign: interface_ImVec2;
readonly SelectableTextAlign: interface_ImVec2;
readonly DisplayWindowPadding: interface_ImVec2;
readonly DisplaySafeAreaPadding: interface_ImVec2;
MouseCursorScale: number;
AntiAliasedLines: boolean;
AntiAliasedLinesUseTex: boolean;
AntiAliasedFill: boolean;
CurveTessellationTol: number;
CircleSegmentMaxError: number;
_getAt_Colors(idx: number): interface_ImVec4;
_setAt_Colors(idx: number, value: Readonly<interface_ImVec4>): boolean;
// IMGUI_API ImGuiStyle();
// IMGUI_API void ScaleAllSizes(float scale_factor);
ScaleAllSizes(scale_factor: number): void;
}
export class ImGuiStyle extends Emscripten.EmscriptenClass implements interface_ImGuiStyle {
Alpha: number;
readonly WindowPadding: reference_ImVec2;
WindowRounding: number;
WindowBorderSize: number;
readonly WindowMinSize: reference_ImVec2;
readonly WindowTitleAlign: reference_ImVec2;
WindowMenuButtonPosition: ImGuiDir;
ChildRounding: number;
ChildBorderSize: number;
PopupRounding: number;
PopupBorderSize: number;
readonly FramePadding: reference_ImVec2;
FrameRounding: number;
FrameBorderSize: number;
readonly ItemSpacing: reference_ImVec2;
readonly ItemInnerSpacing: reference_ImVec2;
readonly TouchExtraPadding: reference_ImVec2;
readonly CellPadding: reference_ImVec2;
IndentSpacing: number;
ColumnsMinSpacing: number;
ScrollbarSize: number;
ScrollbarRounding: number;
GrabMinSize: number;
GrabRounding: number;
LogSliderDeadzone: number;
TabRounding: number;
TabBorderSize: number;
TabMinWidthForCloseButton: number;
ColorButtonPosition: ImGuiDir;
readonly ButtonTextAlign: reference_ImVec2;
readonly SelectableTextAlign: reference_ImVec2;
readonly DisplayWindowPadding: reference_ImVec2;
readonly DisplaySafeAreaPadding: reference_ImVec2;
MouseCursorScale: number;
AntiAliasedLines: boolean;
AntiAliasedLinesUseTex: boolean;
AntiAliasedFill: boolean;
CurveTessellationTol: number;
CircleSegmentMaxError: number;
_getAt_Colors(idx: number): reference_ImVec4;
_setAt_Colors(idx: number, value: Readonly<interface_ImVec4>): boolean;
public ScaleAllSizes(scale_factor: number): void;
}
export interface reference_DragDropPayload extends Emscripten.EmscriptenClassReference {
}
export type ImDrawCallback = (parent_list: Readonly<reference_ImDrawList>, cmd: Readonly<reference_ImDrawCmd>) => void;
export interface reference_ImDrawCmd extends Emscripten.EmscriptenClassReference {
// unsigned int ElemCount; // Number of indices (multiple of 3) to be rendered as triangles. Vertices are stored in the callee ImDrawList's vtx_buffer[] array, indices in idx_buffer[].
readonly ElemCount: number;
// ImVec4 ClipRect; // Clipping rectangle (x1, y1, x2, y2)
readonly ClipRect: Readonly<reference_ImVec4>;
// ImTextureID TextureId; // User-provided texture ID. Set by user in ImfontAtlas::SetTexID() for fonts or passed to Image*() functions. Ignore if never using images or multiple fonts atlas.
readonly TextureId: ImTextureID;
// unsigned int VtxOffset; // Start offset in vertex buffer. Pre-1.71 or without ImGuiBackendFlags_RendererHasVtxOffset: always 0. With ImGuiBackendFlags_RendererHasVtxOffset: may be >0 to support meshes larger than 64K vertices with 16-bits indices.
readonly VtxOffset: number;
// unsigned int IdxOffset; // Start offset in index buffer. Always equal to sum of ElemCount drawn so far.
readonly IdxOffset: number;
// ImDrawCallback UserCallback; // If != NULL, call the function instead of rendering the vertices. clip_rect and texture_id will be set normally.
// void* UserCallbackData; // The draw callback code can access this.
// ImDrawCmd() { ElemCount = 0; ClipRect.x = ClipRect.y = ClipRect.z = ClipRect.w = 0.0f; TextureId = NULL; UserCallback = NULL; UserCallbackData = NULL; }
// readonly ClipRect: Readonly<ImVec4>;
}
export interface reference_ImDrawListSharedData extends Emscripten.EmscriptenClassReference {}
export interface reference_ImDrawList extends Emscripten.EmscriptenClassReference {
IterateDrawCmds(callback: (draw_cmd: reference_ImDrawCmd, ElemStart: number) => void): void;
// This is what you have to render
// ImVector<ImDrawCmd> CmdBuffer; // Draw commands. Typically 1 command = 1 GPU draw call, unless the command is a callback.
// ImVector<ImDrawIdx> IdxBuffer; // Index buffer. Each command consume ImDrawCmd::ElemCount of those
readonly IdxBuffer: Uint8Array;
// ImVector<ImDrawVert> VtxBuffer; // Vertex buffer.
readonly VtxBuffer: Uint8Array;
// [Internal, used while building lists]
// ImDrawListFlags Flags; // Flags, you may poke into these to adjust anti-aliasing settings per-primitive.
Flags: ImDrawListFlags;
// const ImDrawListSharedData* _Data; // Pointer to shared draw data (you can use ImGui::GetDrawListSharedData() to get the one from current ImGui context)
// const char* _OwnerName; // Pointer to owner window's name for debugging
// unsigned int _VtxCurrentIdx; // [Internal] == VtxBuffer.Size
// ImDrawVert* _VtxWritePtr; // [Internal] point within VtxBuffer.Data after each add command (to avoid using the ImVector<> operators too much)
// ImDrawIdx* _IdxWritePtr; // [Internal] point within IdxBuffer.Data after each add command (to avoid using the ImVector<> operators too much)
// ImVector<ImVec4> _ClipRectStack; // [Internal]
// ImVector<ImTextureID> _TextureIdStack; // [Internal]
// ImVector<ImVec2> _Path; // [Internal] current path building
// int _ChannelsCurrent; // [Internal] current channel number (0)
// int _ChannelsCount; // [Internal] number of active channels (1+)
// ImVector<ImDrawChannel> _Channels; // [Internal] draw channels for columns API (not resized down so _ChannelsCount may be smaller than _Channels.Size)
// If you want to create ImDrawList instances, pass them ImGui::GetDrawListSharedData() or create and use your own ImDrawListSharedData (so you can use ImDrawList without ImGui)
// ImDrawList(const ImDrawListSharedData* shared_data) { _Data = shared_data; _OwnerName = NULL; Clear(); }
// ~ImDrawList() { ClearFreeMemory(); }
// IMGUI_API void PushClipRect(ImVec2 clip_rect_min, ImVec2 clip_rect_max, bool intersect_with_current_clip_rect = false); // Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling)
PushClipRect(clip_rect_min: Readonly<interface_ImVec2>, clip_rect_max: Readonly<interface_ImVec2>, intersect_with_current_clip_rect: boolean): void;
// IMGUI_API void PushClipRectFullScreen();
PushClipRectFullScreen(): void;
// IMGUI_API void PopClipRect();
PopClipRect(): void;
// IMGUI_API void PushTextureID(const ImTextureID& texture_id);
PushTextureID(texture_id: ImTextureID): void;
// IMGUI_API void PopTextureID();
PopTextureID(): void;
// inline ImVec2 GetClipRectMin() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.x, cr.y); }
GetClipRectMin(out: interface_ImVec2): typeof out;
// inline ImVec2 GetClipRectMax() const { const ImVec4& cr = _ClipRectStack.back(); return ImVec2(cr.z, cr.w); }
GetClipRectMax(out: interface_ImVec2): typeof out;
// Primitives
// IMGUI_API void AddLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness = 1.0f);
AddLine(a: Readonly<interface_ImVec2>, b: Readonly<interface_ImVec2>, col: ImU32, thickness: number): void;
// IMGUI_API void AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners_flags = ImDrawCornerFlags_All, float thickness = 1.0f); // a: upper-left, b: lower-right, rounding_corners_flags: 4-bits corresponding to which corner to round
AddRect(a: Readonly<interface_ImVec2>, b: Readonly<interface_ImVec2>, col: ImU32, rounding: number, rounding_corners_flags: ImDrawCornerFlags, thickness: number): void;
// IMGUI_API void AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding = 0.0f, int rounding_corners_flags = ImDrawCornerFlags_All); // a: upper-left, b: lower-right
AddRectFilled(a: Readonly<interface_ImVec2>, b: Readonly<interface_ImVec2>, col: ImU32, rounding: number, rounding_corners_flags: ImDrawCornerFlags): void;
// IMGUI_API void AddRectFilledMultiColor(const ImVec2& a, const ImVec2& b, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left);
AddRectFilledMultiColor(a: Readonly<interface_ImVec2>, b: Readonly<interface_ImVec2>, col_upr_left: ImU32, col_upr_right: ImU32, col_bot_right: ImU32, col_bot_left: ImU32): void;
// IMGUI_API void AddQuad(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col, float thickness = 1.0f);
AddQuad(a: Readonly<interface_ImVec2>, b: Readonly<interface_ImVec2>, c: Readonly<interface_ImVec2>, d: Readonly<interface_ImVec2>, col: ImU32, thickness: number): void;
// IMGUI_API void AddQuadFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col);
AddQuadFilled(a: Readonly<interface_ImVec2>, b: Readonly<interface_ImVec2>, c: Readonly<interface_ImVec2>, d: Readonly<interface_ImVec2>, col: ImU32): void;
// IMGUI_API void AddTriangle(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col, float thickness = 1.0f);
AddTriangle(a: Readonly<interface_ImVec2>, b: Readonly<interface_ImVec2>, c: Readonly<interface_ImVec2>, col: ImU32, thickness: number): void;
// IMGUI_API void AddTriangleFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col);
AddTriangleFilled(a: Readonly<interface_ImVec2>, b: Readonly<interface_ImVec2>, c: Readonly<interface_ImVec2>, col: ImU32): void;
// IMGUI_API void AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12, float thickness = 1.0f);
AddCircle(centre: Readonly<interface_ImVec2>, radius: number, col: ImU32, num_segments: number, thickness: number): void;
// IMGUI_API void AddCircleFilled(const ImVec2& centre, float radius, ImU32 col, int num_segments = 12);
AddCircleFilled(centre: Readonly<interface_ImVec2>, radius: number, col: ImU32, num_segments: number): void;
// IMGUI_API void AddNgon(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness = 1.0f);
AddNgon(centre: Readonly<interface_ImVec2>, radius: number, col: ImU32, num_segments: number, thickness: number): void;
// IMGUI_API void AddNgonFilled(const ImVec2& center, float radius, ImU32 col, int num_segments);
AddNgonFilled(centre: Readonly<interface_ImVec2>, radius: number, col: ImU32, num_segments: number): void;
// IMGUI_API void AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL);
AddText_A(pos: Readonly<interface_ImVec2>, col: ImU32, text_begin: string): void;
// IMGUI_API void AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end = NULL, float wrap_width = 0.0f, const ImVec4* cpu_fine_clip_rect = NULL);
AddText_B(font: reference_ImFont, font_size: number, pos: Readonly<interface_ImVec2>, col: ImU32, text_begin: string, wrap_width: number, cpu_fine_clip_rect: Readonly<interface_ImVec4> | null): void;
// IMGUI_API void AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a = ImVec2(0,0), const ImVec2& uv_b = ImVec2(1,1), ImU32 col = 0xFFFFFFFF);
AddImage(user_texture_id: ImTextureID, a: Readonly<interface_ImVec2>, b: Readonly<interface_ImVec2>, uv_a: Readonly<interface_ImVec2>, uv_b: Readonly<interface_ImVec2>, col: ImU32): void;
// IMGUI_API void AddImageQuad(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a = ImVec2(0,0), const ImVec2& uv_b = ImVec2(1,0), const ImVec2& uv_c = ImVec2(1,1), const ImVec2& uv_d = ImVec2(0,1), ImU32 col = 0xFFFFFFFF);
AddImageQuad(user_texture_id: ImTextureID, a: Readonly<interface_ImVec2>, b: Readonly<interface_ImVec2>, c: Readonly<interface_ImVec2>, d: Readonly<interface_ImVec2>, uv_a: Readonly<interface_ImVec2>, uv_b: Readonly<interface_ImVec2>, uv_c: Readonly<interface_ImVec2>, uv_d: Readonly<interface_ImVec2>, col: ImU32): void;
// IMGUI_API void AddImageRounded(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col, float rounding, int rounding_corners = ImDrawCornerFlags_All);
AddImageRounded(user_texture_id: ImTextureID, a: Readonly<interface_ImVec2>, b: Readonly<interface_ImVec2>, uv_a: Readonly<interface_ImVec2>, uv_b: Readonly<interface_ImVec2>, col: ImU32, rounding: number, rounding_corners: ImDrawCornerFlags): void;
// IMGUI_API void AddPolyline(const ImVec2* points, const int num_points, ImU32 col, bool closed, float thickness);
AddPolyline(points: Readonly<interface_ImVec2>[], num_points: number, col: ImU32, closed: boolean, thickness: number): void;
// IMGUI_API void AddConvexPolyFilled(const ImVec2* points, const int num_points, ImU32 col);
AddConvexPolyFilled(points: Readonly<interface_ImVec2>[], num_points: number, col: ImU32): void;
// IMGUI_API void AddBezierCubic(const ImVec2& pos0, const ImVec2& cp0, const ImVec2& cp1, const ImVec2& pos1, ImU32 col, float thickness, int num_segments = 0);
AddBezierCubic(pos0: Readonly<interface_ImVec2>, cp0: Readonly<interface_ImVec2>, cp1: Readonly<interface_ImVec2>, pos1: Readonly<interface_ImVec2>, col: ImU32, thickness: number, num_segments: number): void;
AddBezierQuadratic(pos0: Readonly<interface_ImVec2>, cp0: Readonly<interface_ImVec2>, cp1: Readonly<interface_ImVec2>, col: ImU32, thickness: number, num_segments: number): void;
// Stateful path API, add points then finish with PathFill() or PathStroke()
// inline void PathClear() { _Path.resize(0); }
PathClear(): void;
// inline void PathLineTo(const ImVec2& pos) { _Path.push_back(pos); }
PathLineTo(pos: Readonly<interface_ImVec2>): void;
// inline void PathLineToMergeDuplicate(const ImVec2& pos) { if (_Path.Size == 0 || memcmp(&_Path[_Path.Size-1], &pos, 8) != 0) _Path.push_back(pos); }
PathLineToMergeDuplicate(pos: Readonly<interface_ImVec2>): void;
// inline void PathFillConvex(ImU32 col) { AddConvexPolyFilled(_Path.Data, _Path.Size, col); PathClear(); }
PathFillConvex(col: ImU32): void;
// inline void PathStroke(ImU32 col, bool closed, float thickness = 1.0f) { AddPolyline(_Path.Data, _Path.Size, col, closed, thickness); PathClear(); }
PathStroke(col: ImU32, closed: boolean, thickness: number): void;
// IMGUI_API void PathArcTo(const ImVec2& centre, float radius, float a_min, float a_max, int num_segments = 10);
PathArcTo(centre: Readonly<interface_ImVec2>, radius: number, a_min: number, a_max: number, num_segments: number): void;
// IMGUI_API void PathArcToFast(const ImVec2& centre, float radius, int a_min_of_12, int a_max_of_12); // Use precomputed angles for a 12 steps circle
PathArcToFast(centre: Readonly<interface_ImVec2>, radius: number, a_min_of_12: number, a_max_of_12: number): void;
// IMGUI_API void PathBezierCurveTo(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, int num_segments = 0);
PathBezierCubicCurveTo(p1: Readonly<interface_ImVec2>, p2: Readonly<interface_ImVec2>, p3: Readonly<interface_ImVec2>, num_segments: number): void;
PathBezierQuadraticCurveTo(p2: Readonly<interface_ImVec2>, p3: Readonly<interface_ImVec2>, num_segments: number): void;
// IMGUI_API void PathRect(const ImVec2& rect_min, const ImVec2& rect_max, float rounding = 0.0f, int rounding_corners_flags = ImDrawCornerFlags_All);
PathRect(rect_min: Readonly<interface_ImVec2>, rect_max: Readonly<interface_ImVec2>, rounding: number, rounding_corners_flags: ImDrawCornerFlags): void;
// Channels
// - Use to simulate layers. By switching channels to can render out-of-order (e.g. submit foreground primitives before background primitives)
// - Use to minimize draw calls (e.g. if going back-and-forth between multiple non-overlapping clipping rectangles, prefer to append into separate channels then merge at the end)
// IMGUI_API void ChannelsSplit(int channels_count);
ChannelsSplit(channels_count: number): void;
// IMGUI_API void ChannelsMerge();
ChannelsMerge(): void;
// IMGUI_API void ChannelsSetCurrent(int channel_index);
ChannelsSetCurrent(channel_index: number): void;
// Advanced
// IMGUI_API void AddCallback(ImDrawCallback callback, void* callback_data); // Your rendering function must check for 'UserCallback' in ImDrawCmd and call the function instead of rendering triangles.
AddCallback(callback: ImDrawCallback, callback_data: any): void;
// IMGUI_API void AddDrawCmd(); // This is useful if you need to forcefully create a new draw call (to allow for dependent rendering / blending). Otherwise primitives are merged into the same draw-call as much as possible
AddDrawCmd(): void;
// Internal helpers
// NB: all primitives needs to be reserved via PrimReserve() beforehand!
// IMGUI_API void Clear();
Clear(): void;
// IMGUI_API void ClearFreeMemory();
ClearFreeMemory(): void;
// IMGUI_API void PrimReserve(int idx_count, int vtx_count);
PrimReserve(idx_count: number, vtx_count: number): void;
PrimUnreserve(idx_count: number, vtx_count: number): void;
// IMGUI_API void PrimRect(const ImVec2& a, const ImVec2& b, ImU32 col); // Axis aligned rectangle (composed of two triangles)
PrimRect(a: Readonly<interface_ImVec2>, b: Readonly<interface_ImVec2>, col: ImU32): void;
// IMGUI_API void PrimRectUV(const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, ImU32 col);
PrimRectUV(a: Readonly<interface_ImVec2>, b: Readonly<interface_ImVec2>, uv_a: Readonly<interface_ImVec2>, uv_b: Readonly<interface_ImVec2>, col: ImU32): void;
// IMGUI_API void PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col);
PrimQuadUV(a: Readonly<interface_ImVec2>, b: Readonly<interface_ImVec2>, c: Readonly<interface_ImVec2>, d: Readonly<interface_ImVec2>, uv_a: Readonly<interface_ImVec2>, uv_b: Readonly<interface_ImVec2>, uv_c: Readonly<interface_ImVec2>, uv_d: Readonly<interface_ImVec2>, col: ImU32): void;
// inline void PrimWriteVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col){ _VtxWritePtr->pos = pos; _VtxWritePtr->uv = uv; _VtxWritePtr->col = col; _VtxWritePtr++; _VtxCurrentIdx++; }
PrimWriteVtx(pos: Readonly<interface_ImVec2>, us: Readonly<interface_ImVec2>, col: ImU32): void;
// inline void PrimWriteIdx(ImDrawIdx idx) { *_IdxWritePtr = idx; _IdxWritePtr++; }
PrimWriteIdx(idx: number): void;
// inline void PrimVtx(const ImVec2& pos, const ImVec2& uv, ImU32 col) { PrimWriteIdx((ImDrawIdx)_VtxCurrentIdx); PrimWriteVtx(pos, uv, col); }
PrimVtx(pos: Readonly<interface_ImVec2>, uv: Readonly<interface_ImVec2>, col: ImU32): void;
// IMGUI_API void UpdateClipRect();
UpdateClipRect(): void;
// IMGUI_API void UpdateTextureID();
UpdateTextureID(): void;
}
export interface reference_ImDrawData extends Emscripten.EmscriptenClassReference {
IterateDrawLists(callback: (draw_list: reference_ImDrawList) => void): void;
// bool Valid; // Only valid after Render() is called and before the next NewFrame() is called.
readonly Valid: boolean;
// ImDrawList** CmdLists;
// int CmdListsCount;
readonly CmdListsCount: number;
// int TotalVtxCount; // For convenience, sum of all cmd_lists vtx_buffer.Size
readonly TotalVtxCount: number;
// int TotalIdxCount; // For convenience, sum of all cmd_lists idx_buffer.Size
readonly TotalIdxCount: number;
// ImVec2 DisplayPos; // Upper-left position of the viewport to render (== upper-left of the orthogonal projection matrix to use)
readonly DisplayPos: Readonly<reference_ImVec2>;
// ImVec2 DisplaySize; // Size of the viewport to render (== io.DisplaySize for the main viewport) (DisplayPos + DisplaySize == lower-right of the orthogonal projection matrix to use)
readonly DisplaySize: Readonly<reference_ImVec2>;
// ImVec2 FramebufferScale; // Amount of pixels for each unit of DisplaySize. Based on io.DisplayFramebufferScale. Generally (1,1) on normal display, (2,2) on OSX with Retina display.
readonly FramebufferScale: Readonly<reference_ImVec2>;
// Functions
// ImDrawData() { Clear(); }
// void Clear() { Valid = false; CmdLists = NULL; CmdListsCount = TotalVtxCount = TotalIdxCount = 0; } // Draw lists are owned by the ImGuiContext and only pointed to here.
// IMGUI_API void DeIndexAllBuffers(); // For backward compatibility or convenience: convert all buffers from indexed to de-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering!
DeIndexAllBuffers(): void;
// IMGUI_API void ScaleClipRects(const ImVec2& fb_scale); // Helper to scale the ClipRect field of each ImDrawCmd. Use if your final output buffer is at a different scale than ImGui expects, or if there is a difference between your window resolution and framebuffer resolution.
ScaleClipRects(fb_scale: Readonly<interface_ImVec2>): void;
}
export interface reference_ImFont extends Emscripten.EmscriptenClassReference {
// Members: Hot ~62/78 bytes
// float FontSize; // <user set> // Height of characters, set during loading (don't change after loading)
FontSize: number;
// float Scale; // = 1.f // Base font scale, multiplied by the per-window font scale which you can adjust with SetFontScale()
Scale: number;
// ImVec2 DisplayOffset; // = (0.f,1.f) // Offset font rendering by xx pixels
readonly DisplayOffset: reference_ImVec2;
// ImVector<ImFontGlyph> Glyphs; // // All glyphs.
IterateGlyphs(callback: (cfg: reference_ImFontGlyph) => void): void;
// ImVector<float> IndexAdvanceX; // // Sparse. Glyphs->AdvanceX in a directly indexable way (more cache-friendly, for CalcTextSize functions which are often bottleneck in large UI).
// IndexAdvanceX: any;
// ImVector<unsigned short> IndexLookup; // // Sparse. Index glyphs by Unicode code-point.
// IndexLookup: any;
// const ImFontGlyph* FallbackGlyph; // == FindGlyph(FontFallbackChar)
// FallbackGlyph: any;
FallbackGlyph: Readonly<reference_ImFontGlyph> | null;
// float FallbackAdvanceX; // == FallbackGlyph->AdvanceX
FallbackAdvanceX: number;
// ImWchar FallbackChar; // = '?' // Replacement glyph if one isn't found. Only set via SetFallbackChar()
FallbackChar: number;
EllipsisChar: number;
// Members: Cold ~18/26 bytes
// short ConfigDataCount; // ~ 1 // Number of ImFontConfig involved in creating this font. Bigger than 1 when merging multiple font sources into one ImFont.
ConfigDataCount: number;
// ImFontConfig* ConfigData; // // Pointer within ContainerAtlas->ConfigData
// ConfigData: any;
IterateConfigData(callback: (cfg: interface_ImFontConfig) => void): void;
// ImFontAtlas* ContainerAtlas; // // What we has been loaded into
// ContainerAtlas: any;
// float Ascent, Descent; // // Ascent: distance from top to bottom of e.g. 'A' [0..FontSize]
Ascent: number;
Descent: number;
// int MetricsTotalSurface;// // Total surface in pixels to get an idea of the font rasterization/texture cost (not exact, we approximate the cost of padding between glyphs)
MetricsTotalSurface: number;
// Methods
// IMGUI_API ImFont();
// IMGUI_API ~ImFont();
// IMGUI_API void ClearOutputData();
ClearOutputData(): void;
// IMGUI_API void BuildLookupTable();
BuildLookupTable(): void;
// IMGUI_API const ImFontGlyph*FindGlyph(ImWchar c) const;
FindGlyph(c: number): Readonly<reference_ImFontGlyph> | null;
// IMGUI_API const ImFontGlyph*FindGlyphNoFallback(ImWchar c) const;
FindGlyphNoFallback(c: number): Readonly<reference_ImFontGlyph> | null;
// IMGUI_API void SetFallbackChar(ImWchar c);
SetFallbackChar(c: number): void;
// float GetCharAdvance(ImWchar c) const { return ((int)c < IndexAdvanceX.Size) ? IndexAdvanceX[(int)c] : FallbackAdvanceX; }
GetCharAdvance(c: number): number;
// bool IsLoaded() const { return ContainerAtlas != NULL; }
IsLoaded(): boolean;
// const char* GetDebugName() const { return ConfigData ? ConfigData->Name : "<unknown>"; }
GetDebugName(): string;
// 'max_width' stops rendering after a certain width (could be turned into a 2d size). FLT_MAX to disable.
// 'wrap_width' enable automatic word-wrapping across multiple lines to fit into given width. 0.0f to disable.
// IMGUI_API ImVec2 CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end = NULL, const char** remaining = NULL) const; // utf8
CalcTextSizeA(size: number, max_width: number, wrap_width: number, text_begin: string, remaining: ImScalar<number> | null, out: interface_ImVec2): interface_ImVec2;
// IMGUI_API const char* CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const;
CalcWordWrapPositionA(scale: number, text: string, wrap_width: number): number;
// IMGUI_API void RenderChar(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, unsigned short c) const;
RenderChar(draw_list: reference_ImDrawList, size: number, pos: Readonly<interface_ImVec2>, col: ImU32, c: ImWchar): void;
// IMGUI_API void RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width = 0.0f, bool cpu_fine_clip = false) const;
// [Internal]
// IMGUI_API void GrowIndex(int new_size);
// IMGUI_API void AddGlyph(ImWchar c, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x);
// IMGUI_API void AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst = true); // Makes 'dst' character/glyph points to 'src' character/glyph. Currently needs to be called AFTER fonts have been built.
// #ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
// typedef ImFontGlyph Glyph; // OBSOLETE 1.52+
// #endif
}
export interface interface_ImFontConfig {
// void* FontData; // // TTF/OTF data
// int FontDataSize; // // TTF/OTF data size
FontData: DataView | null;
// bool FontDataOwnedByAtlas; // true // TTF/OTF data ownership taken by the container ImFontAtlas (will delete memory itself).
FontDataOwnedByAtlas: boolean;
// int FontNo; // 0 // Index of font within TTF/OTF file
FontNo: number;
// float SizePixels; // // Size in pixels for rasterizer.
SizePixels: number;
// int OversampleH, OversampleV; // 3, 1 // Rasterize at higher quality for sub-pixel positioning. We don't use sub-pixel positions on the Y axis.
OversampleH: number;
OversampleV: number;
// bool PixelSnapH; // false // Align every glyph to pixel boundary. Useful e.g. if you are merging a non-pixel aligned font with the default font. If enabled, you can set OversampleH/V to 1.
PixelSnapH: boolean;
// ImVec2 GlyphExtraSpacing; // 0, 0 // Extra spacing (in pixels) between glyphs. Only X axis is supported for now.
readonly GlyphExtraSpacing: interface_ImVec2;
// ImVec2 GlyphOffset; // 0, 0 // Offset all glyphs from this font input.
readonly GlyphOffset: interface_ImVec2;
// const ImWchar* GlyphRanges; // NULL // Pointer to a user-provided list of Unicode range (2 value per range, values are inclusive, zero-terminated list). THE ARRAY DATA NEEDS TO PERSIST AS LONG AS THE FONT IS ALIVE.
GlyphRanges: number | null;
// float GlyphMinAdvanceX; // 0 // Minimum AdvanceX for glyphs, set Min to align font icons, set both Min/Max to enforce mono-space font
GlyphMinAdvanceX: number;
// float GlyphMaxAdvanceX; // FLT_MAX // Maximum AdvanceX for glyphs
GlyphMaxAdvanceX: number;
// bool MergeMode; // false // Merge into previous ImFont, so you can combine multiple inputs font into one ImFont (e.g. ASCII font + icons + Japanese glyphs). You may want to use GlyphOffset.y when merge font of different heights.
MergeMode: boolean;
// unsigned int RasterizerFlags; // 0x00 // Settings for custom font rasterizer (e.g. ImGuiFreeType). Leave as zero if you aren't using one.
RasterizerFlags: number;
// float RasterizerMultiply; // 1.0f // Brighten (>1.0f) or darken (<1.0f) font output. Brightening small fonts may be a good workaround to make them more readable.
RasterizerMultiply: number;
// [Internal]
// char Name[32]; // Name (strictly to ease debugging)
Name: string;
// ImFont* DstFont;
DstFont: reference_ImFont | null;
// IMGUI_API ImFontConfig();
}
export interface reference_ImFontConfig extends Emscripten.EmscriptenClassReference, interface_ImFontConfig {}
export interface interface_ImFontGlyph {
// ImWchar Codepoint; // 0x0000..0xFFFF
Codepoint: number;
Visible: boolean;
// float AdvanceX; // Distance to next character (= data from font + ImFontConfig::GlyphExtraSpacing.x baked in)
AdvanceX: number;
// float X0, Y0, X1, Y1; // Glyph corners
X0: number;
Y0: number;
X1: number;
Y1: number;
// float U0, V0, U1, V1; // Texture coordinates
U0: number;
V0: number;
U1: number;
V1: number;
}
export interface reference_ImFontGlyph extends Emscripten.EmscriptenClassReference, interface_ImFontGlyph {}
export interface reference_ImFontAtlas extends Emscripten.EmscriptenClassReference {
// IMGUI_API ImFontAtlas();
// IMGUI_API ~ImFontAtlas();
// IMGUI_API ImFont* AddFont(const ImFontConfig* font_cfg);
// IMGUI_API ImFont* AddFontDefault(const ImFontConfig* font_cfg = NULL);
AddFontDefault(font_cfg: interface_ImFontConfig | null): reference_ImFont;
// IMGUI_API ImFont* AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL);
// IMGUI_API ImFont* AddFontFromMemoryTTF(void* font_data, int font_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // Note: Transfer ownership of 'ttf_data' to ImFontAtlas! Will be deleted after Build(). Set font_cfg->FontDataOwnedByAtlas to false to keep ownership.
AddFontFromMemoryTTF(data: Uint8Array, size_pixels: number, font_cfg: interface_ImFontConfig | null, glyph_ranges: number | null): reference_ImFont;
// IMGUI_API ImFont* AddFontFromMemoryCompressedTTF(const void* compressed_font_data, int compressed_font_size, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data' still owned by caller. Compress with binary_to_compressed_c.cpp.
// IMGUI_API ImFont* AddFontFromMemoryCompressedBase85TTF(const char* compressed_font_data_base85, float size_pixels, const ImFontConfig* font_cfg = NULL, const ImWchar* glyph_ranges = NULL); // 'compressed_font_data_base85' still owned by caller. Compress with binary_to_compressed_c.cpp with -base85 parameter.
// IMGUI_API void ClearTexData(); // Clear the CPU-side texture data. Saves RAM once the texture has been copied to graphics memory.
ClearTexData(): void;
// IMGUI_API void ClearInputData(); // Clear the input TTF data (inc sizes, glyph ranges)
ClearInputData(): void;
// IMGUI_API void ClearFonts(); // Clear the ImGui-side font data (glyphs storage, UV coordinates)
ClearFonts(): void;
// IMGUI_API void Clear(); // Clear all
Clear(): void;
// Build atlas, retrieve pixel data.
// User is in charge of copying the pixels into graphics memory (e.g. create a texture with your engine). Then store your texture handle with SetTexID().
// RGBA32 format is provided for convenience and compatibility, but note that unless you use CustomRect to draw color data, the RGB pixels emitted from Fonts will all be white (~75% of waste).
// Pitch = Width * BytesPerPixels
// IMGUI_API bool Build(); // Build pixels data. This is called automatically for you by the GetTexData*** functions.
Build(): boolean;
// IMGUI_API bool IsBuilt() { return Fonts.Size > 0 && (TexPixelsAlpha8 != NULL || TexPixelsRGBA32 != NULL); }
IsBuilt(): boolean;
// IMGUI_API void GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 1 byte per-pixel
GetTexDataAsAlpha8(): { pixels: Uint8ClampedArray, width: number, height: number, bytes_per_pixel: number };
// IMGUI_API void GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel = NULL); // 4 bytes-per-pixel
GetTexDataAsRGBA32(): { pixels: Uint8ClampedArray, width: number, height: number, bytes_per_pixel: number };
// void SetTexID(ImTextureID id) { TexID = id; }
// //-------------------------------------------
// Glyph Ranges
// //-------------------------------------------
// Helpers to retrieve list of common Unicode ranges (2 value per range, values are inclusive, zero-terminated list)
// NB: Make sure that your string are UTF-8 and NOT in your local code page. In C++11, you can create UTF-8 string literal using the u8"Hello world" syntax. See FAQ for details.
// IMGUI_API const ImWchar* GetGlyphRangesDefault(); // Basic Latin, Extended Latin
GetGlyphRangesDefault(): number;
// IMGUI_API const ImWchar* GetGlyphRangesKorean(); // Default + Korean characters
GetGlyphRangesKorean(): number;
// IMGUI_API const ImWchar* GetGlyphRangesJapanese(); // Default + Hiragana, Katakana, Half-Width, Selection of 1946 Ideographs
GetGlyphRangesJapanese(): number;
// IMGUI_API const ImWchar* GetGlyphRangesChineseFull(); // Default + Half-Width + Japanese Hiragana/Katakana + full set of about 21000 CJK Unified Ideographs
GetGlyphRangesChineseFull(): number;
// IMGUI_API const ImWchar* GetGlyphRangesChineseSimplifiedCommon();// Default + Half-Width + Japanese Hiragana/Katakana + set of 2500 CJK Unified Ideographs for common simplified Chinese
GetGlyphRangesChineseSimplifiedCommon(): number;
// IMGUI_API const ImWchar* GetGlyphRangesCyrillic(); // Default + about 400 Cyrillic characters
GetGlyphRangesCyrillic(): number;
// IMGUI_API const ImWchar* GetGlyphRangesThai(); // Default + Thai characters
GetGlyphRangesThai(): number;
// IMGUI_API const ImWchar* GetGlyphRangesVietnamese(); // Default + Vietnamese characters
GetGlyphRangesVietnamese(): number;
// Helpers to build glyph ranges from text data. Feed your application strings/characters to it then call BuildRanges().
// struct GlyphRangesBuilder
// {
// ImVector<unsigned char> UsedChars; // Store 1-bit per Unicode code point (0=unused, 1=used)
// GlyphRangesBuilder() { UsedChars.resize(0x10000 / 8); memset(UsedChars.Data, 0, 0x10000 / 8); }
// bool GetBit(int n) { return (UsedChars[n >> 3] & (1 << (n & 7))) != 0; }
// void SetBit(int n) { UsedChars[n >> 3] |= 1 << (n & 7); } // Set bit 'c' in the array
// void AddChar(ImWchar c) { SetBit(c); } // Add character
// IMGUI_API void AddText(const char* text, const char* text_end = NULL); // Add string (each character of the UTF-8 string are added)
// IMGUI_API void AddRanges(const ImWchar* ranges); // Add ranges, e.g. builder.AddRanges(ImFontAtlas::GetGlyphRangesDefault) to force add all of ASCII/Latin+Ext
// IMGUI_API void BuildRanges(ImVector<ImWchar>* out_ranges); // Output new ranges
// };
// //-------------------------------------------
// Custom Rectangles/Glyphs API
// //-------------------------------------------
// You can request arbitrary rectangles to be packed into the atlas, for your own purposes. After calling Build(), you can query the rectangle position and render your pixels.
// You can also request your rectangles to be mapped as font glyph (given a font + Unicode point), so you can render e.g. custom colorful icons and use them as regular glyphs.
// struct CustomRect
// {
// unsigned int ID; // Input // User ID. Use <0x10000 to map into a font glyph, >=0x10000 for other/internal/custom texture data.
// unsigned short Width, Height; // Input // Desired rectangle dimension
// unsigned short X, Y; // Output // Packed position in Atlas
// float GlyphAdvanceX; // Input // For custom font glyphs only (ID<0x10000): glyph xadvance
// ImVec2 GlyphOffset; // Input // For custom font glyphs only (ID<0x10000): glyph display offset
// ImFont* Font; // Input // For custom font glyphs only (ID<0x10000): target font
// CustomRect() { ID = 0xFFFFFFFF; Width = Height = 0; X = Y = 0xFFFF; GlyphAdvanceX = 0.0f; GlyphOffset = ImVec2(0,0); Font = NULL; }
// bool IsPacked() const { return X != 0xFFFF; }
// };
// IMGUI_API int AddCustomRectRegular(unsigned int id, int width, int height); // Id needs to be >= 0x10000. Id >= 0x80000000 are reserved for ImGui and ImDrawList
// IMGUI_API int AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset = ImVec2(0,0)); // Id needs to be < 0x10000 to register a rectangle to map into a specific font.
// const CustomRect* GetCustomRectByIndex(int index) const { if (index < 0) return NULL; return &CustomRects[index]; }
// Internals
// IMGUI_API void CalcCustomRectUV(const CustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max);
// IMGUI_API bool GetMouseCursorTexData(ImGuiMouseCursor cursor, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2]);
// //-------------------------------------------
// Members
// //-------------------------------------------
// bool Locked; // Marked as Locked by ImGui::NewFrame() so attempt to modify the atlas will assert.
Locked: boolean;
// ImFontAtlasFlags Flags; // Build flags (see ImFontAtlasFlags_)
Flags: ImFontAtlasFlags;
// ImTextureID TexID; // User data to refer to the texture once it has been uploaded to user's graphic systems. It is passed back to you during rendering via the ImDrawCmd structure.
TexID: ImTextureID;
// int TexDesiredWidth; // Texture width desired by user before Build(). Must be a power-of-two. If have many glyphs your graphics API have texture size restrictions you may want to increase texture width to decrease height.
TexDesiredWidth: number;
// int TexGlyphPadding; // Padding between glyphs within texture in pixels. Defaults to 1.
TexGlyphPadding: number;
// [Internal]
// NB: Access texture data via GetTexData*() calls! Which will setup a default font for you.
// unsigned char* TexPixelsAlpha8; // 1 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight
// unsigned int* TexPixelsRGBA32; // 4 component per pixel, each component is unsigned 8-bit. Total size = TexWidth * TexHeight * 4
// int TexWidth; // Texture width calculated during Build().
readonly TexWidth: number;
// int TexHeight; // Texture height calculated during Build().
readonly TexHeight: number;
// ImVec2 TexUvScale; // = (1.0f/TexWidth, 1.0f/TexHeight)
readonly TexUvScale: Readonly<reference_ImVec2>;
// ImVec2 TexUvWhitePixel; // Texture coordinates to a white pixel
readonly TexUvWhitePixel: Readonly<reference_ImVec2>;
// ImVector<ImFont*> Fonts; // Hold all the fonts returned by AddFont*. Fonts[0] is the default font upon calling ImGui::NewFrame(), use ImGui::PushFont()/PopFont() to change the current font.
IterateFonts(callback: (font: reference_ImFont) => void): void;
// ImVector<CustomRect> CustomRects; // Rectangles for packing custom texture data into the atlas.
// ImVector<ImFontConfig> ConfigData; // Internal data
// int CustomRectIds[1]; // Identifiers of custom texture rectangle used by ImFontAtlas/ImDrawList
}
export interface reference_ImGuiIO extends Emscripten.EmscriptenClassReference {
//------------------------------------------------------------------
// Settings (fill once) // Default value:
//------------------------------------------------------------------
// ImGuiConfigFlags ConfigFlags; // = 0 // See ImGuiConfigFlags_. Gamepad/keyboard navigation options.
ConfigFlags: ImGuiConfigFlags;
// ImGuiBackendFlags BackendFlags; // = 0 // Set ImGuiBackendFlags_ enum. Set by imgui_impl_xxx files or custom back-end.
BackendFlags: ImGuiBackendFlags;
// ImVec2 DisplayS0ize; // <unset> // Display size, in pixels. For clamping windows positions.
readonly DisplaySize: reference_ImVec2;
// float DeltaTime; // = 1.0f/60.0f // Time elapsed since last frame, in seconds.
DeltaTime: number;
// float IniSavingRate; // = 5.0f // Maximum time between saving positions/sizes to .ini file, in seconds.
IniSavingRate: number;
// const char* IniFilename; // = "imgui.ini" // Path to .ini file. NULL to disable .ini saving.
IniFilename: string;
// const char* LogFilename; // = "imgui_log.txt" // Path to .log file (default parameter to ImGui::LogToFile when no file is specified).
LogFilename: string;
// float MouseDoubleClickTime; // = 0.30f // Time for a double-click, in seconds.
MouseDoubleClickTime: number;
// float MouseDoubleClickMaxDist; // = 6.0f // Distance threshold to stay in to validate a double-click, in pixels.
MouseDoubleClickMaxDist: number;
// float MouseDragThreshold; // = 6.0f // Distance threshold before considering we are dragging.
MouseDragThreshold: number;
// int KeyMap[ImGuiKey_COUNT]; // <unset> // Map of indices into the KeysDown[512] entries array which represent your "native" keyboard state.
_getAt_KeyMap(index: ImGuiKey): number;
_setAt_KeyMap(index: ImGuiKey, value: number): boolean;
// float KeyRepeatDelay; // = 0.250f // When holding a key/button, time before it starts repeating, in seconds (for buttons in Repeat mode, etc.).
KeyRepeatDelay: number;
// float KeyRepeatRate; // = 0.050f // When holding a key/button, rate at which it repeats, in seconds.
KeyRepeatRate: number;
// void* UserData; // = NULL // Store your own data for retrieval by callbacks.
UserData: any;
// ImFontAtlas* Fonts; // <auto> // Load and assemble one or more fonts into a single tightly packed texture. Output to Fonts array.
readonly Fonts: reference_ImFontAtlas;
// float FontGlobalScale; // = 1.0f // Global scale all fonts
FontGlobalScale: number;
// bool FontAllowUserScaling; // = false // Allow user scaling text of individual window with CTRL+Wheel.
FontAllowUserScaling: boolean;
// ImFont* FontDefault; // = NULL // Font to use on NewFrame(). Use NULL to uses Fonts->Fonts[0].
FontDefault: reference_ImFont | null;
// ImVec2 DisplayFramebufferScale; // = (1.0f,1.0f) // For retina display or other situations where window coordinates are different from framebuffer coordinates. User storage only, presently not used by ImGui.
readonly DisplayFramebufferScale: reference_ImVec2;
// Advanced/subtle behaviors
// bool MouseDrawCursor; // Request ImGui to draw a mouse cursor for you (if you are on a platform without a mouse cursor).
MouseDrawCursor: boolean;
// bool OptMacOSXBehaviors; // = defined(__APPLE__) // OS X style: Text editing cursor movement using Alt instead of Ctrl, Shortcuts using Cmd/Super instead of Ctrl, Line/Text Start and End using Cmd+Arrows instead of Home/End, Double click selects by word instead of selecting whole text, Multi-selection in lists uses Cmd/Super instead of Ctrl
ConfigMacOSXBehaviors: boolean;
// bool ConfigInputTextCursorBlink; // = true // Enable blinking cursor, for users who consider it annoying.
ConfigInputTextCursorBlink: boolean;
ConfigDragClickToInputText: boolean;
// bool ConfigWindowsResizeFromEdges; // = false // [BETA] Enable resizing of windows from their edges and from the lower-left corner. This requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback. (This used to be the ImGuiWindowFlags_ResizeFromAnySide flag)
ConfigWindowsResizeFromEdges: boolean;
// bool ConfigWindowsMoveFromTitleBarOnly;// = false // [BETA] Set to true to only allow moving windows when clicked+dragged from the title bar. Windows without a title bar are not affected.
ConfigWindowsMoveFromTitleBarOnly: boolean;
ConfigMemoryCompactTimer: number;
//------------------------------------------------------------------
// Settings (User Functions)
//------------------------------------------------------------------
// Optional: Platform/Renderer back-end name (informational only! will be displayed in About Window) + User data for back-end/wrappers to store their own stuff.
// const char* BackendPlatformName; // = NULL
BackendPlatformName: string | null;
// const char* BackendRendererName; // = NULL
BackendRendererName: string | null;
// void* BackendPlatformUserData; // = NULL
BackendPlatformUserData: string | null;
// void* BackendRendererUserData; // = NULL
BackendRendererUserData: string | null;
// void* BackendLanguageUserData; // = NULL
BackendLanguageUserData: string | null;
// Optional: access OS clipboard
// (default to use native Win32 clipboard on Windows, otherwise uses a private clipboard. Override to access OS clipboard on other architectures)
// const char* (*GetClipboardTextFn)(void* user_data);
GetClipboardTextFn: ((user_data: any) => string) | null;
// void (*SetClipboardTextFn)(void* user_data, const char* text);
SetClipboardTextFn: ((user_data: any, text: string) => void) | null;
// void* ClipboardUserData;
ClipboardUserData: any;
// Optional: notify OS Input Method Editor of the screen position of your cursor for text input position (e.g. when using Japanese/Chinese IME in Windows)
// (default to use native imm32 api on Windows)
// void (*ImeSetInputScreenPosFn)(int x, int y);
// void* ImeWindowHandle; // (Windows) Set this to your HWND to get automatic IME cursor positioning.
//------------------------------------------------------------------
// Input - Fill before calling NewFrame()
//------------------------------------------------------------------
// ImVec2 MousePos; // Mouse position, in pixels. Set to ImVec2(-FLT_MAX,-FLT_MAX) if mouse is unavailable (on another screen, etc.)
readonly MousePos: reference_ImVec2;
// bool MouseDown[5]; // Mouse buttons: left, right, middle + extras. ImGui itself mostly only uses left button (BeginPopupContext** are using right button). Others buttons allows us to track if the mouse is being used by your application + available to user as a convenience via IsMouse** API.
_getAt_MouseDown(index: number): boolean;
_setAt_MouseDown(index: number, value: boolean): boolean;
// float MouseWheel; // Mouse wheel: 1 unit scrolls about 5 lines text.
MouseWheel: number;
// float MouseWheelH; // Mouse wheel (Horizontal). Most users don't have a mouse with an horizontal wheel, may not be filled by all back ends.
MouseWheelH: number;
// bool KeyCtrl; // Keyboard modifier pressed: Control
KeyCtrl: boolean;
// bool KeyShift; // Keyboard modifier pressed: Shift
KeyShift: boolean;
// bool KeyAlt; // Keyboard modifier pressed: Alt
KeyAlt: boolean;
// bool KeySuper; // Keyboard modifier pressed: Cmd/Super/Windows
KeySuper: boolean;
// bool KeysDown[512]; // Keyboard keys that are pressed (ideally left in the "native" order your engine has access to keyboard keys, so you can use your own defines/enums for keys).
_getAt_KeysDown(index: number): boolean;
_setAt_KeysDown(index: number, value: boolean): boolean;
// float NavInputs[ImGuiNavInput_COUNT]; // Gamepad inputs (keyboard keys will be auto-mapped and be written here by ImGui::NewFrame)
_getAt_NavInputs(index: number): number;
_setAt_NavInputs(index: number, value: number): boolean;
// Functions
// IMGUI_API void AddInputCharacter(ImWchar c); // Add new character into InputCharacters[]
AddInputCharacter(c: number): void;
// IMGUI_API void AddInputCharacterUTF16(ImWchar16 c); // Queue new character input from an UTF-16 character, it can be a surrogate
AddInputCharacterUTF16(c: ImWchar16): void;
// IMGUI_API void AddInputCharactersUTF8(const char* utf8_chars); // Add new characters into InputCharacters[] from an UTF-8 string
AddInputCharactersUTF8(utf8_chars: string): void;
// inline void ClearInputCharacters() { InputCharacters[0] = 0; } // Clear the text input buffer manually
ClearInputCharacters(): void;
//------------------------------------------------------------------
// Output - Retrieve after calling NewFrame()
//------------------------------------------------------------------
// bool WantCaptureMouse; // When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. This is set by ImGui when it wants to use your mouse (e.g. unclicked mouse is hovering a window, or a widget is active).
WantCaptureMouse: boolean;
// bool WantCaptureKeyboard; // When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. This is set by ImGui when it wants to use your keyboard inputs.
WantCaptureKeyboard: boolean;
// bool WantTextInput; // Mobile/console: when io.WantTextInput is true, you may display an on-screen keyboard. This is set by ImGui when it wants textual keyboard input to happen (e.g. when a InputText widget is active).
WantTextInput: boolean;
// bool WantSetMousePos; // MousePos has been altered, back-end should reposition mouse on next frame. Set only when ImGuiConfigFlags_MoveMouse flag is enabled in io.ConfigFlags.
WantSetMousePos: boolean;
// bool WantSaveIniSettings; // When manual .ini load/save is active (io.IniFilename == NULL), this will be set to notify your application that you can call SaveIniSettingsToMemory() and save yourself. IMPORTANT: You need to clear io.WantSaveIniSettings yourself.
WantSaveIniSettings: boolean;
// bool NavActive; // Directional navigation is currently allowed (will handle ImGuiKey_NavXXX events) = a window is focused and it doesn't use the ImGuiWindowFlags_NoNavInputs flag.
NavActive: boolean;
// bool NavVisible; // Directional navigation is visible and allowed (will handle ImGuiKey_NavXXX events).
NavVisible: boolean;
// float Framerate; // Application framerate estimation, in frame per second. Solely for convenience. Rolling average estimation based on IO.DeltaTime over 120 frames
Framerate: number;
// int MetricsRenderVertices; // Vertices output during last call to Render()
MetricsRenderVertices: number;
// int MetricsRenderIndices; // Indices output during last call to Render() = number of triangles * 3
MetricsRenderIndices: number;
// int MetricsRenderWindows; // Number of visible windows
MetricsRenderWindows: number;
// int MetricsActiveWindows; // Number of visible root windows (exclude child windows)
MetricsActiveWindows: number;
// int MetricsActiveAllocations; // Number of active allocations, updated by MemAlloc/MemFree based on current context. May be off if you have multiple imgui contexts.
MetricsActiveAllocations: number;
// ImVec2 MouseDelta; // Mouse delta. Note that this is zero if either current or previous position are invalid (-FLT_MAX,-FLT_MAX), so a disappearing/reappearing mouse won't have a huge delta.
readonly MouseDelta: Readonly<reference_ImVec2>;
//------------------------------------------------------------------
// [Internal] ImGui will maintain those fields. Forward compatibility not guaranteed!
//------------------------------------------------------------------
// ImVec2 MousePosPrev; // Previous mouse position temporary storage (nb: not for public use, set to MousePos in NewFrame())
// ImVec2 MouseClickedPos[5]; // Position at time of clicking
_getAt_MouseClickedPos(index: number): Readonly<reference_ImVec2>;
// float MouseClickedTime[5]; // Time of last click (used to figure out double-click)
// bool MouseClicked[5]; // Mouse button went from !Down to Down
// bool MouseDoubleClicked[5]; // Has mouse button been double-clicked?
// bool MouseReleased[5]; // Mouse button went from Down to !Down
// bool MouseDownOwned[5]; // Track if button was clicked inside a window. We don't request mouse capture from the application if click started outside ImGui bounds.
// bool MouseDownWasDoubleClick[5]; // Track if button down was a double-click
// float MouseDownDuration[5]; // Duration the mouse button has been down (0.0f == just clicked)
_getAt_MouseDownDuration(index: number): number;
// float MouseDownDurationPrev[5]; // Previous time the mouse button has been down
// ImVec2 MouseDragMaxDistanceAbs[5]; // Maximum distance, absolute, on each axis, of how much mouse has traveled from the clicking point
// float MouseDragMaxDistanceSqr[5]; // Squared maximum distance of how much mouse has traveled from the clicking point
// float KeysDownDuration[512]; // Duration the keyboard key has been down (0.0f == just pressed)
_getAt_KeysDownDuration(index: number): number;
// float KeysDownDurationPrev[512]; // Previous duration the key has been down
// float NavInputsDownDuration[ImGuiNavInput_COUNT];
_getAt_NavInputsDownDuration(index: number): number;
// float NavInputsDownDurationPrev[ImGuiNavInput_COUNT];
// IMGUI_API ImGuiIO();
}
export interface Module extends Emscripten.EmscriptenModule {
mallinfo(): mallinfo;
IMGUI_VERSION: string;
IMGUI_CHECKVERSION(): boolean;
ImGuiIOSize: number;
ImGuiStyleSize: number;
ImVec2Size: number;
ImVec4Size: number;
ImDrawVertSize: number;
ImDrawIdxSize: number;
ImDrawVertPosOffset: number;
ImDrawVertUVOffset: number;
ImDrawVertColOffset: number;
ImGuiListClipper: { new(): ImGuiListClipper; };
ImGuiStyle: { new(): ImGuiStyle; };
// Context creation and access
// Each context create its own ImFontAtlas by default. You may instance one yourself and pass it to CreateContext() to share a font atlas between imgui contexts.
// None of those functions is reliant on the current context.
// IMGUI_API ImGuiContext* CreateContext(ImFontAtlas* shared_font_atlas = NULL);
// IMGUI_API void DestroyContext(ImGuiContext* ctx = NULL); // NULL = destroy current context
// IMGUI_API ImGuiContext* GetCurrentContext();
// IMGUI_API void SetCurrentContext(ImGuiContext* ctx);
CreateContext(shared_font_atlas: reference_ImFontAtlas | null): WrapImGuiContext;
DestroyContext(ctx: WrapImGuiContext | null): void;
GetCurrentContext(): WrapImGuiContext | null;
SetCurrentContext(ctx: WrapImGuiContext | null): void;
// Main
// IMGUI_API ImGuiIO& GetIO(); // access the IO structure (mouse/keyboard/gamepad inputs, time, various configuration options/flags)
// IMGUI_API ImGuiStyle& GetStyle(); // access the Style structure (colors, sizes). Always use PushStyleCol(), PushStyleVar() to modify style mid-frame!
// IMGUI_API void NewFrame(); // start a new Dear ImGui frame, you can submit any command from this point until Render()/EndFrame().
// IMGUI_API void EndFrame(); // ends the Dear ImGui frame. automatically called by Render(). If you don't need to render data (skipping rendering) you may call EndFrame() without Render()... but you'll have wasted CPU already! If you don't need to render, better to not create any windows and not call NewFrame() at all!
// IMGUI_API void Render(); // ends the Dear ImGui frame, finalize the draw data. You can then get call GetDrawData().
// IMGUI_API ImDrawData* GetDrawData(); // valid after Render() and until the next call to NewFrame(). this is what you have to render.
GetIO(): reference_ImGuiIO;
GetStyle(): ImGuiStyle;
NewFrame(): void;
EndFrame(): void;
Render(): void;
GetDrawData(): reference_ImDrawData | null;
// Demo, Debug, Information
// IMGUI_API void ShowDemoWindow(bool* p_open = NULL); // create Demo window. demonstrate most ImGui features. call this to learn about the library! try to make it always available in your application!
// IMGUI_API void ShowMetricsWindow(bool* p_open = NULL); // create Metrics/Debugger window. display Dear ImGui internals: windows, draw commands, various internal state, etc.
// IMGUI_API void ShowAboutWindow(bool* p_open = NULL); // create About window. display Dear ImGui version, credits and build/system information.
// IMGUI_API void ShowStyleEditor(ImGuiStyle* ref = NULL); // add style editor block (not a window). you can pass in a reference ImGuiStyle structure to compare to, revert to and save to (else it uses the default style)
// IMGUI_API bool ShowStyleSelector(const char* label); // add style selector block (not a window), essentially a combo listing the default styles.
// IMGUI_API void ShowFontSelector(const char* label); // add font selector block (not a window), essentially a combo listing the loaded fonts.
// IMGUI_API void ShowUserGuide(); // add basic help/info block (not a window): how to manipulate ImGui as a end-user (mouse/keyboard controls).
// IMGUI_API const char* GetVersion(); // get the compiled version string e.g. "1.80 WIP" (essentially the value for IMGUI_VERSION from the compiled version of imgui.cpp)
ShowDemoWindow(p_open: ImScalar<boolean> | null): void;
ShowMetricsWindow(p_open: ImScalar<boolean> | null): void;
ShowAboutWindow(p_open: ImScalar<boolean> | null): void;
ShowStyleEditor(ref: ImGuiStyle | null): void;
ShowStyleSelector(label: string): boolean;
ShowFontSelector(label: string): void;
ShowUserGuide(): void;
GetVersion(): string;
// Styles
// IMGUI_API void StyleColorsDark(ImGuiStyle* dst = NULL); // new, recommended style (default)
// IMGUI_API void StyleColorsLight(ImGuiStyle* dst = NULL); // best used with borders and a custom, thicker font
// IMGUI_API void StyleColorsClassic(ImGuiStyle* dst = NULL); // classic imgui style
StyleColorsDark(dst: ImGuiStyle | null): void;
StyleColorsLight(dst: ImGuiStyle | null): void;
StyleColorsClassic(dst: ImGuiStyle | null): void;
// Windows
// - Begin() = push window to the stack and start appending to it. End() = pop window from the stack.
// - Passing 'bool* p_open != NULL' shows a window-closing widget in the upper-right corner of the window,
// which clicking will set the boolean to false when clicked.
// - You may append multiple times to the same window during the same frame by calling Begin()/End() pairs multiple times.
// Some information such as 'flags' or 'p_open' will only be considered by the first call to Begin().
// - Begin() return false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting
// anything to the window. Always call a matching End() for each Begin() call, regardless of its return value!
// [Important: due to legacy reason, this is inconsistent with most other functions such as BeginMenu/EndMenu,
// BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding BeginXXX function
// returned true. Begin and BeginChild are the only odd ones out. Will be fixed in a future update.]
// - Note that the bottom of window stack always contains a window called "Debug".
// IMGUI_API bool Begin(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0);
// IMGUI_API void End();
Begin(name: string, p_open: ImScalar<boolean> | null , flags: ImGuiWindowFlags): boolean;
End(): void;
// Child Windows
// - Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window. Child windows can embed their own child.
// - For each independent axis of 'size': ==0.0f: use remaining host window size / >0.0f: fixed size / <0.0f: use remaining window size minus abs(size) / Each axis can use a different mode, e.g. ImVec2(0,400).
// - BeginChild() returns false to indicate the window is collapsed or fully clipped, so you may early out and omit submitting anything to the window.
// Always call a matching EndChild() for each BeginChild() call, regardless of its return value.
// [Important: due to legacy reason, this is inconsistent with most other functions such as BeginMenu/EndMenu,
// BeginPopup/EndPopup, etc. where the EndXXX call should only be called if the corresponding BeginXXX function
// returned true. Begin and BeginChild are the only odd ones out. Will be fixed in a future update.]
// IMGUI_API bool BeginChild(const char* str_id, const ImVec2& size = ImVec2(0, 0), bool border = false, ImGuiWindowFlags flags = 0);
// IMGUI_API bool BeginChild(ImGuiID id, const ImVec2& size = ImVec2(0, 0), bool border = false, ImGuiWindowFlags flags = 0);
// IMGUI_API void EndChild();
BeginChild(id: string | ImGuiID, size: Readonly<interface_ImVec2>, border: boolean, flags: ImGuiWindowFlags): boolean;
EndChild(): void;
// Windows Utilities
// - 'current window' = the window we are appending into while inside a Begin()/End() block. 'next window' = next window we will Begin() into.
// IMGUI_API bool IsWindowAppearing();
// IMGUI_API bool IsWindowCollapsed();
// IMGUI_API bool IsWindowFocused(ImGuiFocusedFlags flags=0); // is current window focused? or its root/child, depending on flags. see flags for options.
// IMGUI_API bool IsWindowHovered(ImGuiHoveredFlags flags=0); // is current window hovered (and typically: not blocked by a popup/modal)? see flags for options. NB: If you are trying to check whether your mouse should be dispatched to imgui or to your app, you should use the 'io.WantCaptureMouse' boolean for that! Please read the FAQ!
// IMGUI_API ImDrawList* GetWindowDrawList(); // get draw list associated to the current window, to append your own drawing primitives
// IMGUI_API ImVec2 GetWindowPos(); // get current window position in screen space (useful if you want to do your own drawing via the DrawList API)
// IMGUI_API ImVec2 GetWindowSize(); // get current window size
// IMGUI_API float GetWindowWidth(); // get current window width (shortcut for GetWindowSize().x)
// IMGUI_API float GetWindowHeight(); // get current window height (shortcut for GetWindowSize().y)
IsWindowAppearing(): boolean;
IsWindowCollapsed(): boolean;
IsWindowFocused(flags: ImGuiFocusedFlags): boolean;
IsWindowHovered(flags: ImGuiHoveredFlags): boolean;
GetWindowDrawList(): reference_ImDrawList;
GetWindowPos(out: interface_ImVec2): typeof out;
GetWindowSize(out: interface_ImVec2): typeof out;
GetWindowWidth(): number;
GetWindowHeight(): number;
// Prefer using SetNextXXX functions (before Begin) rather that SetXXX functions (after Begin).
// IMGUI_API void SetNextWindowPos(const ImVec2& pos, ImGuiCond cond = 0, const ImVec2& pivot = ImVec2(0, 0)); // set next window position. call before Begin(). use pivot=(0.5f,0.5f) to center on given point, etc.
// IMGUI_API void SetNextWindowSize(const ImVec2& size, ImGuiCond cond = 0); // set next window size. set axis to 0.0f to force an auto-fit on this axis. call before Begin()
// IMGUI_API void SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback = NULL, void* custom_callback_data = NULL); // set next window size limits. use -1,-1 on either X/Y axis to preserve the current size. Sizes will be rounded down. Use callback to apply non-trivial programmatic constraints.
// IMGUI_API void SetNextWindowContentSize(const ImVec2& size); // set next window content size (~ scrollable client area, which enforce the range of scrollbars). Not including window decorations (title bar, menu bar, etc.) nor WindowPadding. set an axis to 0.0f to leave it automatic. call before Begin()
// IMGUI_API void SetNextWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // set next window collapsed state. call before Begin()
// IMGUI_API void SetNextWindowFocus(); // set next window to be focused / top-most. call before Begin()
// IMGUI_API void SetNextWindowBgAlpha(float alpha); // set next window background color alpha. helper to easily override the Alpha component of ImGuiCol_WindowBg/ChildBg/PopupBg. you may also use ImGuiWindowFlags_NoBackground.
// IMGUI_API void SetWindowPos(const ImVec2& pos, ImGuiCond cond = 0); // (not recommended) set current window position - call within Begin()/End(). prefer using SetNextWindowPos(), as this may incur tearing and side-effects.
// IMGUI_API void SetWindowSize(const ImVec2& size, ImGuiCond cond = 0); // (not recommended) set current window size - call within Begin()/End(). set to ImVec2(0, 0) to force an auto-fit. prefer using SetNextWindowSize(), as this may incur tearing and minor side-effects.
// IMGUI_API void SetWindowCollapsed(bool collapsed, ImGuiCond cond = 0); // (not recommended) set current window collapsed state. prefer using SetNextWindowCollapsed().
// IMGUI_API void SetWindowFocus(); // (not recommended) set current window to be focused / top-most. prefer using SetNextWindowFocus().
// IMGUI_API void SetWindowFontScale(float scale); // set font scale. Adjust IO.FontGlobalScale if you want to scale all windows. This is an old API! For correct scaling, prefer to reload font + rebuild ImFontAtlas + call style.ScaleAllSizes().
// IMGUI_API void SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond = 0); // set named window position.
// IMGUI_API void SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond = 0); // set named window size. set axis to 0.0f to force an auto-fit on this axis.
// IMGUI_API void SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond = 0); // set named window collapsed state
// IMGUI_API void SetWindowFocus(const char* name); // set named window to be focused / top-most. use NULL to remove focus.
SetNextWindowPos(pos: Readonly<interface_ImVec2>, cond: ImGuiCond, pivot: Readonly<interface_ImVec2>): void;
SetNextWindowSize(size: Readonly<interface_ImVec2>, cond: ImGuiCond): void;
SetNextWindowSizeConstraints(size_min: Readonly<interface_ImVec2>, size_max: Readonly<interface_ImVec2>, custom_callback: ImGuiSizeCallback | null, data: any): void;
SetNextWindowContentSize(size: Readonly<interface_ImVec2>): void;
SetNextWindowCollapsed(collapsed: boolean, cond: ImGuiCond): void;
SetNextWindowFocus(): void;
SetNextWindowBgAlpha(alpha: number): void;
SetWindowPos(pos: Readonly<interface_ImVec2>, cond: ImGuiCond): void;
SetWindowSize(size: Readonly<interface_ImVec2>, cond: ImGuiCond): void;
SetWindowCollapsed(collapsed: boolean, cond: ImGuiCond): void;
SetWindowFocus(): void;
SetWindowFontScale(scale: number): void;
SetWindowNamePos(name: string, pos: Readonly<interface_ImVec2>, cond: ImGuiCond): void;
SetWindowNameSize(name: string, size: Readonly<interface_ImVec2>, cond: ImGuiCond): void;
SetWindowNameCollapsed(name: string, collapsed: boolean, cond: ImGuiCond): void;
SetWindowNameFocus(name: string): void;
// Content region
// - Retrieve available space from a given point. GetContentRegionAvail() is frequently useful.
// - Those functions are bound to be redesigned (they are confusing, incomplete and the Min/Max return values are in local window coordinates which increases confusion)
// IMGUI_API ImVec2 GetContentRegionAvail(); // == GetContentRegionMax() - GetCursorPos()
// IMGUI_API ImVec2 GetContentRegionMax(); // current content boundaries (typically window boundaries including scrolling, or current column boundaries), in windows coordinates
// IMGUI_API ImVec2 GetWindowContentRegionMin(); // content boundaries min (roughly (0,0)-Scroll), in window coordinates
// IMGUI_API ImVec2 GetWindowContentRegionMax(); // content boundaries max (roughly (0,0)+Size-Scroll) where Size can be override with SetNextWindowContentSize(), in window coordinates
// IMGUI_API float GetWindowContentRegionWidth(); //
GetContentRegionAvail(out: interface_ImVec2): typeof out;
GetContentRegionMax(out: interface_ImVec2): typeof out;
GetWindowContentRegionMin(out: interface_ImVec2): typeof out;
GetWindowContentRegionMax(out: interface_ImVec2): typeof out;
GetWindowContentRegionWidth(): number;
// Windows Scrolling
// IMGUI_API float GetScrollX(); // get scrolling amount [0 .. GetScrollMaxX()]
// IMGUI_API float GetScrollY(); // get scrolling amount [0 .. GetScrollMaxY()]
// IMGUI_API void SetScrollX(float scroll_x); // set scrolling amount [0 .. GetScrollMaxX()]
// IMGUI_API void SetScrollY(float scroll_y); // set scrolling amount [0 .. GetScrollMaxY()]
// IMGUI_API float GetScrollMaxX(); // get maximum scrolling amount ~~ ContentSize.x - WindowSize.x - DecorationsSize.x
// IMGUI_API float GetScrollMaxY(); // get maximum scrolling amount ~~ ContentSize.y - WindowSize.y - DecorationsSize.y
// IMGUI_API void SetScrollHereX(float center_x_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_x_ratio=0.0: left, 0.5: center, 1.0: right. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead.
// IMGUI_API void SetScrollHereY(float center_y_ratio = 0.5f); // adjust scrolling amount to make current cursor position visible. center_y_ratio=0.0: top, 0.5: center, 1.0: bottom. When using to make a "default/current item" visible, consider using SetItemDefaultFocus() instead.
// IMGUI_API void SetScrollFromPosX(float local_x, float center_x_ratio = 0.5f); // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position.
// IMGUI_API void SetScrollFromPosY(float local_y, float center_y_ratio = 0.5f); // adjust scrolling amount to make given position visible. Generally GetCursorStartPos() + offset to compute a valid position.
GetScrollX(): number;
GetScrollY(): number;
SetScrollX(scroll_x: number): void;
SetScrollY(scroll_y: number): void;
GetScrollMaxX(): number;
GetScrollMaxY(): number;
SetScrollHereX(center_x_ratio: number): void;
SetScrollHereY(center_y_ratio: number): void;
SetScrollFromPosX(pos_x: number, center_x_ratio: number): void;
SetScrollFromPosY(pos_y: number, center_y_ratio: number): void;
// Parameters stacks (shared)
// IMGUI_API void PushFont(ImFont* font); // use NULL as a shortcut to push default font
// IMGUI_API void PopFont();
// IMGUI_API void PushStyleColor(ImGuiCol idx, ImU32 col); // modify a style color. always use this if you modify the style after NewFrame().
// IMGUI_API void PushStyleColor(ImGuiCol idx, const ImVec4& col);
// IMGUI_API void PopStyleColor(int count = 1);
// IMGUI_API void PushStyleVar(ImGuiStyleVar idx, float val); // modify a style float variable. always use this if you modify the style after NewFrame().
// IMGUI_API void PushStyleVar(ImGuiStyleVar idx, const ImVec2& val); // modify a style ImVec2 variable. always use this if you modify the style after NewFrame().
// IMGUI_API void PopStyleVar(int count = 1);
// IMGUI_API void PushAllowKeyboardFocus(bool allow_keyboard_focus); // allow focusing using TAB/Shift-TAB, enabled by default but you can disable it for certain widgets
// IMGUI_API void PopAllowKeyboardFocus();
// IMGUI_API void PushButtonRepeat(bool repeat); // in 'repeat' mode, Button*() functions return repeated true in a typematic manner (using io.KeyRepeatDelay/io.KeyRepeatRate setting). Note that you can call IsItemActive() after any Button() to tell if the button is held in the current frame.
// IMGUI_API void PopButtonRepeat();
PushFont(font: reference_ImFont | null): void;
PopFont(): void;
PushStyleColor(idx: ImGuiCol, col: ImU32 | Readonly<interface_ImVec4>): void;
PopStyleColor(count: number): void;
PushStyleVar(idx: ImGuiStyleVar, val: number | Readonly<interface_ImVec2>): void;
PopStyleVar(count: number): void;
PushAllowKeyboardFocus(allow_keyboard_focus: boolean): void;
PopAllowKeyboardFocus(): void;
PushButtonRepeat(repeat: boolean): void;
PopButtonRepeat(): void;
// Parameters stacks (current window)
// IMGUI_API void PushItemWidth(float item_width); // push width of items for common large "item+label" widgets. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -FLT_MIN always align width to the right side). 0.0f = default to ~2/3 of windows width,
// IMGUI_API void PopItemWidth();
// IMGUI_API void SetNextItemWidth(float item_width); // set width of the _next_ common large "item+label" widget. >0.0f: width in pixels, <0.0f align xx pixels to the right of window (so -FLT_MIN always align width to the right side)
// IMGUI_API float CalcItemWidth(); // width of item given pushed settings and current cursor position. NOT necessarily the width of last item unlike most 'Item' functions.
// IMGUI_API void PushTextWrapPos(float wrap_local_pos_x = 0.0f); // push word-wrapping position for Text*() commands. < 0.0f: no wrapping; 0.0f: wrap to end of window (or column); > 0.0f: wrap at 'wrap_pos_x' position in window local space
// IMGUI_API void PopTextWrapPos();
PushItemWidth(item_width: number): void;
PopItemWidth(): void;
SetNextItemWidth(item_width: number): void;
CalcItemWidth(): number;
PushTextWrapPos(wrap_pos_x: number): void;
PopTextWrapPos(): void;
// Style read access
// IMGUI_API ImFont* GetFont(); // get current font
// IMGUI_API float GetFontSize(); // get current font size (= height in pixels) of current font with current scale applied
// IMGUI_API ImVec2 GetFontTexUvWhitePixel(); // get UV coordinate for a while pixel, useful to draw custom shapes via the ImDrawList API
// IMGUI_API ImU32 GetColorU32(ImGuiCol idx, float alpha_mul = 1.0f); // retrieve given style color with style alpha applied and optional extra alpha multiplier, packed as a 32-bit value suitable for ImDrawList
// IMGUI_API ImU32 GetColorU32(const ImVec4& col); // retrieve given color with style alpha applied, packed as a 32-bit value suitable for ImDrawList
// IMGUI_API ImU32 GetColorU32(ImU32 col); // retrieve given color with style alpha applied, packed as a 32-bit value suitable for ImDrawList
// IMGUI_API const ImVec4& GetStyleColorVec4(ImGuiCol idx); // retrieve style color as stored in ImGuiStyle structure. use to feed back into PushStyleColor(), otherwise use GetColorU32() to get style color with style alpha baked in.
GetFont(): reference_ImFont;
GetFontSize(): number;
GetFontTexUvWhitePixel(out: interface_ImVec2): typeof out;
GetColorU32_A(idx: ImGuiCol, alpha_mul: number): ImU32;
GetColorU32_B(col: Readonly<interface_ImVec4>): ImU32;
GetColorU32_C(col: ImU32): ImU32;
GetStyleColorVec4(idx: ImGuiCol): Readonly<reference_ImVec4>;
// Cursor / Layout
// - By "cursor" we mean the current output position.
// - The typical widget behavior is to output themselves at the current cursor position, then move the cursor one line down.
// - You can call SameLine() between widgets to undo the last carriage return and output at the right of the preceding widget.
// - Attention! We currently have inconsistencies between window-local and absolute positions we will aim to fix with future API:
// Window-local coordinates: SameLine(), GetCursorPos(), SetCursorPos(), GetCursorStartPos(), GetContentRegionMax(), GetWindowContentRegion*(), PushTextWrapPos()
// Absolute coordinate: GetCursorScreenPos(), SetCursorScreenPos(), all ImDrawList:: functions.
// IMGUI_API void Separator(); // separator, generally horizontal. inside a menu bar or in horizontal layout mode, this becomes a vertical separator.
// IMGUI_API void SameLine(float offset_from_start_x=0.0f, float spacing=-1.0f); // call between widgets or groups to layout them horizontally. X position given in window coordinates.
// IMGUI_API void NewLine(); // undo a SameLine() or force a new line when in an horizontal-layout context.
// IMGUI_API void Spacing(); // add vertical spacing.
// IMGUI_API void Dummy(const ImVec2& size); // add a dummy item of given size. unlike InvisibleButton(), Dummy() won't take the mouse click or be navigable into.
// IMGUI_API void Indent(float indent_w = 0.0f); // move content position toward the right, by indent_w, or style.IndentSpacing if indent_w <= 0
// IMGUI_API void Unindent(float indent_w = 0.0f); // move content position back to the left, by indent_w, or style.IndentSpacing if indent_w <= 0
// IMGUI_API void BeginGroup(); // lock horizontal starting position
// IMGUI_API void EndGroup(); // unlock horizontal starting position + capture the whole group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
// IMGUI_API ImVec2 GetCursorPos(); // cursor position in window coordinates (relative to window position)
// IMGUI_API float GetCursorPosX(); // (some functions are using window-relative coordinates, such as: GetCursorPos, GetCursorStartPos, GetContentRegionMax, GetWindowContentRegion* etc.
// IMGUI_API float GetCursorPosY(); // other functions such as GetCursorScreenPos or everything in ImDrawList::
// IMGUI_API void SetCursorPos(const ImVec2& local_pos); // are using the main, absolute coordinate system.
// IMGUI_API void SetCursorPosX(float local_x); // GetWindowPos() + GetCursorPos() == GetCursorScreenPos() etc.)
// IMGUI_API void SetCursorPosY(float local_y); //
// IMGUI_API ImVec2 GetCursorStartPos(); // initial cursor position in window coordinates
// IMGUI_API ImVec2 GetCursorScreenPos(); // cursor position in absolute screen coordinates [0..io.DisplaySize] (useful to work with ImDrawList API)
// IMGUI_API void SetCursorScreenPos(const ImVec2& pos); // cursor position in absolute screen coordinates [0..io.DisplaySize]
// IMGUI_API void AlignTextToFramePadding(); // vertically align upcoming text baseline to FramePadding.y so that it will align properly to regularly framed items (call if you have text on a line before a framed item)
// IMGUI_API float GetTextLineHeight(); // ~ FontSize
// IMGUI_API float GetTextLineHeightWithSpacing(); // ~ FontSize + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of text)
// IMGUI_API float GetFrameHeight(); // ~ FontSize + style.FramePadding.y * 2
// IMGUI_API float GetFrameHeightWithSpacing(); // ~ FontSize + style.FramePadding.y * 2 + style.ItemSpacing.y (distance in pixels between 2 consecutive lines of framed widgets)
Separator(): void;
SameLine(pos_x: number, spacing_w: number): void;
NewLine(): void;
Spacing(): void;
Dummy(size: Readonly<interface_ImVec2>): void;
Indent(indent_w: number): void;
Unindent(indent_w: number): void;
BeginGroup(): void;
EndGroup(): void;
GetCursorPos(out: interface_ImVec2): typeof out;
GetCursorPosX(): number;
GetCursorPosY(): number;
SetCursorPos(local_pos: Readonly<interface_ImVec2>): void;
SetCursorPosX(x: number): void;
SetCursorPosY(y: number): void;
GetCursorStartPos(out: interface_ImVec2): typeof out;
GetCursorScreenPos(out: interface_ImVec2): typeof out;
SetCursorScreenPos(pos: interface_ImVec2): void;
AlignTextToFramePadding(): void;
GetTextLineHeight(): number;
GetTextLineHeightWithSpacing(): number;
GetFrameHeight(): number;
GetFrameHeightWithSpacing(): number;
// ID stack/scopes
// - Read the FAQ for more details about how ID are handled in dear imgui. If you are creating widgets in a loop you most
// likely want to push a unique identifier (e.g. object pointer, loop index) to uniquely differentiate them.
// - The resulting ID are hashes of the entire stack.
// - You can also use the "Label##foobar" syntax within widget label to distinguish them from each others.
// - In this header file we use the "label"/"name" terminology to denote a string that will be displayed and used as an ID,
// whereas "str_id" denote a string that is only used as an ID and not normally displayed.
// IMGUI_API void PushID(const char* str_id); // push string into the ID stack (will hash string).
// IMGUI_API void PushID(const char* str_id_begin, const char* str_id_end); // push string into the ID stack (will hash string).
// IMGUI_API void PushID(const void* ptr_id); // push pointer into the ID stack (will hash pointer).
// IMGUI_API void PushID(int int_id); // push integer into the ID stack (will hash integer).
// IMGUI_API void PopID(); // pop from the ID stack.
// IMGUI_API ImGuiID GetID(const char* str_id); // calculate unique ID (hash of whole ID stack + given parameter). e.g. if you want to query into ImGuiStorage yourself
// IMGUI_API ImGuiID GetID(const char* str_id_begin, const char* str_id_end);
// IMGUI_API ImGuiID GetID(const void* ptr_id);
PushID(id: string | number): void;
PopID(): void;
GetID(id: string | number): ImGuiID;
// Widgets: Text
// IMGUI_API void TextUnformatted(const char* text, const char* text_end = NULL); // raw text without formatting. Roughly equivalent to Text("%s", text) but: A) doesn't require null terminated string if 'text_end' is specified, B) it's faster, no memory copy is done, no buffer size limits, recommended for long chunks of text.
// IMGUI_API void Text(const char* fmt, ...) IM_FMTARGS(1); // formatted text
// IMGUI_API void TextV(const char* fmt, va_list args) IM_FMTLIST(1);
// IMGUI_API void TextColored(const ImVec4& col, const char* fmt, ...) IM_FMTARGS(2); // shortcut for PushStyleColor(ImGuiCol_Text, col); Text(fmt, ...); PopStyleColor();
// IMGUI_API void TextColoredV(const ImVec4& col, const char* fmt, va_list args) IM_FMTLIST(2);
// IMGUI_API void TextDisabled(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]); Text(fmt, ...); PopStyleColor();
// IMGUI_API void TextDisabledV(const char* fmt, va_list args) IM_FMTLIST(1);
// IMGUI_API void TextWrapped(const char* fmt, ...) IM_FMTARGS(1); // shortcut for PushTextWrapPos(0.0f); Text(fmt, ...); PopTextWrapPos();. Note that this won't work on an auto-resizing window if there's no other widgets to extend the window width, yoy may need to set a size using SetNextWindowSize().
// IMGUI_API void TextWrappedV(const char* fmt, va_list args) IM_FMTLIST(1);
// IMGUI_API void LabelText(const char* label, const char* fmt, ...) IM_FMTARGS(2); // display text+label aligned the same way as value+label widgets
// IMGUI_API void LabelTextV(const char* label, const char* fmt, va_list args) IM_FMTLIST(2);
// IMGUI_API void BulletText(const char* fmt, ...) IM_FMTARGS(1); // shortcut for Bullet()+Text()
// IMGUI_API void BulletTextV(const char* fmt, va_list args) IM_FMTLIST(1);
TextUnformatted(text: string): void;
Text(fmt: string): void;
TextColored(col: Readonly<interface_ImVec4>, fmt: string): void;
TextDisabled(fmt: string): void;
TextWrapped(fmt: string): void;
LabelText(label: string, fmt: string): void;
BulletText(fmt: string): void;
// Widgets: Main
// - Most widgets return true when the value has been changed or when pressed/selected
// - You may also use one of the many IsItemXXX functions (e.g. IsItemActive, IsItemHovered, etc.) to query widget state.
// IMGUI_API bool Button(const char* label, const ImVec2& size = ImVec2(0, 0)); // button
// IMGUI_API bool SmallButton(const char* label); // button with FramePadding=(0,0) to easily embed within text
// IMGUI_API bool InvisibleButton(const char* str_id, const ImVec2& size, ImGuiButtonFlags flags = 0); // flexible button behavior without the visuals, frequently useful to build custom behaviors using the public api (along with IsItemActive, IsItemHovered, etc.)
// IMGUI_API bool ArrowButton(const char* str_id, ImGuiDir dir); // square button with an arrow shape
// IMGUI_API void Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1,1), const ImVec4& tint_col = ImVec4(1,1,1,1), const ImVec4& border_col = ImVec4(0,0,0,0));
// IMGUI_API bool ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0 = ImVec2(0, 0), const ImVec2& uv1 = ImVec2(1,1), int frame_padding = -1, const ImVec4& bg_col = ImVec4(0,0,0,0), const ImVec4& tint_col = ImVec4(1,1,1,1)); // <0 frame_padding uses default frame padding settings. 0 for no padding
// IMGUI_API bool Checkbox(const char* label, bool* v);
// IMGUI_API bool CheckboxFlags(const char* label, int* flags, int flags_value);
// IMGUI_API bool CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value);
// IMGUI_API bool RadioButton(const char* label, bool active); // use with e.g. if (RadioButton("one", my_value==1)) { my_value = 1; }
// IMGUI_API bool RadioButton(const char* label, int* v, int v_button); // shortcut to handle the above pattern when value is an integer
// IMGUI_API void ProgressBar(float fraction, const ImVec2& size_arg = ImVec2(-FLT_MIN, 0), const char* overlay = NULL);
// IMGUI_API void Bullet(); // draw a small circle + keep the cursor on the same line. advance cursor x position by GetTreeNodeToLabelSpacing(), same distance that TreeNode() uses
Button(label: string, size: Readonly<interface_ImVec2>): boolean;
SmallButton(label: string): boolean;
InvisibleButton(str_id: string, size: Readonly<interface_ImVec2>, flags: ImGuiButtonFlags): boolean;
ArrowButton(label: string, dir: ImGuiDir): boolean;
Image(user_texture_id: any, size: Readonly<interface_ImVec2>, uv0: Readonly<interface_ImVec2>, uv1: Readonly<interface_ImVec2>, tint_col: Readonly<interface_ImVec4>, border_col: Readonly<interface_ImVec4>): void;
ImageButton(user_texture_id: any, size: Readonly<interface_ImVec2>, uv0: Readonly<interface_ImVec2>, uv1: Readonly<interface_ImVec2>, frame_padding: number, bg_col: Readonly<interface_ImVec4>, tint_col: Readonly<interface_ImVec4>): boolean;
Checkbox(label: string, v: ImScalar<boolean>): boolean;
CheckboxFlags(label: string, flags: ImScalar<number> | null, flags_value: number): boolean;
RadioButton_A(label: string, active: boolean): boolean;
RadioButton_B(label: string, v: ImScalar<number>, v_button: number): boolean;
ProgressBar(fraction: number, size_arg: Readonly<interface_ImVec2>, overlay: string | null): void;
Bullet(): void;
// Widgets: Combo Box
// - The BeginCombo()/EndCombo() api allows you to manage your contents and selection state however you want it, by creating e.g. Selectable() items.
// - The old Combo() api are helpers over BeginCombo()/EndCombo() which are kept available for convenience purpose.
// IMGUI_API bool BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags = 0);
// IMGUI_API void EndCombo(); // only call EndCombo() if BeginCombo() returns true!
// IMGUI_API bool Combo(const char* label, int* current_item, const char* const items[], int items_count, int popup_max_height_in_items = -1);
// IMGUI_API bool Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int popup_max_height_in_items = -1); // Separate items with \0 within a string, end item-list with \0\0. e.g. "One\0Two\0Three\0"
// IMGUI_API bool Combo(const char* label, int* current_item, bool(*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int popup_max_height_in_items = -1);
BeginCombo(label: string, preview_value: string | null, flags: ImGuiComboFlags): boolean;
EndCombo(): void;
Combo<T>(label: string, current_item: ImScalar<number>, items_getter: (data: T, idx: number, out_text: [string]) => boolean, data: T, items_count: number, popup_max_height_in_items: number): boolean;
// Widgets: Drag Sliders
// - CTRL+Click on any drag box to turn them into an input box. Manually input values aren't clamped and can go off-bounds.
// - For all the Float2/Float3/Float4/Int2/Int3/Int4 versions of every functions, note that a 'float v[X]' function argument is the same as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible. You can pass address of your first element out of a contiguous set, e.g. &myvector.x
// - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc.
// - Format string may also be set to NULL or use the default format ("%f" or "%d").
// - Speed are per-pixel of mouse movement (v_speed=0.2f: mouse needs to move by 5 pixels to increase value by 1). For gamepad/keyboard navigation, minimum speed is Max(v_speed, minimum_step_at_given_precision).
// - Use v_min < v_max to clamp edits to given limits. Note that CTRL+Click manual input can override those limits.
// - Use v_max = FLT_MAX / INT_MAX etc to avoid clamping to a maximum, same with v_min = -FLT_MAX / INT_MIN to avoid clamping to a minimum.
// - We use the same sets of flags for DragXXX() and SliderXXX() functions as the features are the same and it makes it easier to swap them.
// - Legacy: Pre-1.78 there are DragXXX() function signatures that takes a final `float power=1.0f' argument instead of the `ImGuiSliderFlags flags=0' argument.
// If you get a warning converting a float to ImGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361
// IMGUI_API bool DragFloat(const char* label, float* v, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0); // If v_min >= v_max we have no bound
// IMGUI_API bool DragFloat2(const char* label, float v[2], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0);
// IMGUI_API bool DragFloat3(const char* label, float v[3], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0);
// IMGUI_API bool DragFloat4(const char* label, float v[4], float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", ImGuiSliderFlags flags = 0);
// IMGUI_API bool DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed = 1.0f, float v_min = 0.0f, float v_max = 0.0f, const char* format = "%.3f", const char* format_max = NULL, ImGuiSliderFlags flags = 0);
// IMGUI_API bool DragInt(const char* label, int* v, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0); // If v_min >= v_max we have no bound
// IMGUI_API bool DragInt2(const char* label, int v[2], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0);
// IMGUI_API bool DragInt3(const char* label, int v[3], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0);
// IMGUI_API bool DragInt4(const char* label, int v[4], float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", ImGuiSliderFlags flags = 0);
// IMGUI_API bool DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed = 1.0f, int v_min = 0, int v_max = 0, const char* format = "%d", const char* format_max = NULL, ImGuiSliderFlags flags = 0);
// IMGUI_API bool DragScalar(const char* label, ImGuiDataType data_type, void* p_data, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiSliderFlags flags = 0);
// IMGUI_API bool DragScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, float v_speed, const void* p_min = NULL, const void* p_max = NULL, const char* format = NULL, ImGuiSliderFlags flags = 0);
DragFloat(label: string, v: ImScalar<number> | ImTuple2<number> | ImTuple3<number> | ImTuple4<number>, v_speed: number, v_min: number, v_max: number, format: string | null, flags: ImGuiSliderFlags): boolean;
DragFloat2(label: string, v: ImTuple2<number> | ImTuple3<number> | ImTuple4<number>, v_speed: number, v_min: number, v_max: number, format: string, flags: ImGuiSliderFlags): boolean;
DragFloat3(label: string, v: ImTuple3<number> | ImTuple4<number>, v_speed: number, v_min: number, v_max: number, format: string, flags: ImGuiSliderFlags): boolean;
DragFloat4(label: string, v: ImTuple4<number>, v_speed: number, v_min: number, v_max: number, format: string, flags: ImGuiSliderFlags): boolean;
DragFloatRange2(label: string, v_current_min: ImScalar<number>, v_current_max: ImScalar<number>, v_speed: number, v_min: number, v_max: number, format: string, format_max: string | null, flags: ImGuiSliderFlags): boolean;
DragInt(label: string, v: ImScalar<number> | ImTuple2<number> | ImTuple3<number> | ImTuple4<number>, v_speed: number, v_min: number, v_max: number, format: string, flags: ImGuiSliderFlags): boolean;
DragInt2(label: string, v: ImTuple2<number> | ImTuple3<number> | ImTuple4<number>, v_speed: number, v_min: number, v_max: number, format: string, flags: ImGuiSliderFlags): boolean;
DragInt3(label: string, v: ImTuple3<number> | ImTuple4<number>, v_speed: number, v_min: number, v_max: number, format: string, flags: ImGuiSliderFlags): boolean;
DragInt4(label: string, v: ImTuple4<number>, v_speed: number, v_min: number, v_max: number, format: string, flags: ImGuiSliderFlags): boolean;
DragIntRange2(label: string, v_current_min: ImScalar<number>, v_current_max: ImScalar<number>, v_speed: number, v_min: number, v_max: number, format: string, format_max: string | null, flags: ImGuiSliderFlags): boolean;
DragScalar(label: string, data_type: ImGuiDataType, v: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array, v_speed: number, v_min: number | null, v_max: number | null, format: string | null, flags: ImGuiSliderFlags): boolean;
// Widgets: Regular Sliders
// - CTRL+Click on any slider to turn them into an input box. Manually input values aren't clamped and can go off-bounds.
// - Adjust format string to decorate the value with a prefix, a suffix, or adapt the editing and display precision e.g. "%.3f" -> 1.234; "%5.2f secs" -> 01.23 secs; "Biscuit: %.0f" -> Biscuit: 1; etc.
// - Format string may also be set to NULL or use the default format ("%f" or "%d").
// - Legacy: Pre-1.78 there are SliderXXX() function signatures that takes a final `float power=1.0f' argument instead of the `ImGuiSliderFlags flags=0' argument.
// If you get a warning converting a float to ImGuiSliderFlags, read https://github.com/ocornut/imgui/issues/3361
// IMGUI_API bool SliderFloat(const char* label, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0); // adjust format to decorate the value with a prefix or a suffix for in-slider labels or unit display.
// IMGUI_API bool SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0);
// IMGUI_API bool SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0);
// IMGUI_API bool SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0);
// IMGUI_API bool SliderAngle(const char* label, float* v_rad, float v_degrees_min = -360.0f, float v_degrees_max = +360.0f, const char* format = "%.0f deg", ImGuiSliderFlags flags = 0);
// IMGUI_API bool SliderInt(const char* label, int* v, int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0);
// IMGUI_API bool SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0);
// IMGUI_API bool SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0);
// IMGUI_API bool SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0);
// IMGUI_API bool SliderScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0);
// IMGUI_API bool SliderScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0);
// IMGUI_API bool VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* format = "%.3f", ImGuiSliderFlags flags = 0);
// IMGUI_API bool VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* format = "%d", ImGuiSliderFlags flags = 0);
// IMGUI_API bool VSliderScalar(const char* label, const ImVec2& size, ImGuiDataType data_type, void* p_data, const void* p_min, const void* p_max, const char* format = NULL, ImGuiSliderFlags flags = 0);
SliderFloat(label: string, v: ImScalar<number> | ImTuple2<number> | ImTuple3<number> | ImTuple4<number>, v_min: number, v_max: number, format: string, flags: ImGuiSliderFlags): boolean;
SliderFloat2(label: string, v: ImTuple2<number> | ImTuple3<number> | ImTuple4<number>, v_min: number, v_max: number, format: string, flags: ImGuiSliderFlags): boolean;
SliderFloat3(label: string, v: ImTuple3<number> | ImTuple4<number>, v_min: number, v_max: number, format: string, flags: ImGuiSliderFlags): boolean;
SliderFloat4(label: string, v: ImTuple4<number>, v_min: number, v_max: number, format: string, flags: ImGuiSliderFlags): boolean;
SliderAngle(label: string, v_rad: ImScalar<number> | ImTuple2<number> | ImTuple3<number> | ImTuple4<number>, v_degrees_min: number, v_degrees_max: number, format: string, flags: ImGuiSliderFlags): boolean;
SliderInt(label: string, v: ImScalar<number> | ImTuple2<number> | ImTuple3<number> | ImTuple4<number>, v_min: number, v_max: number, format: string, flags: ImGuiSliderFlags): boolean;
SliderInt2(label: string, v: ImTuple2<number> | ImTuple3<number> | ImTuple4<number>, v_min: number, v_max: number, format: string, flags: ImGuiSliderFlags): boolean;
SliderInt3(label: string, v: ImTuple3<number> | ImTuple4<number>, v_min: number, v_max: number, format: string, flags: ImGuiSliderFlags): boolean;
SliderInt4(label: string, v: ImTuple4<number>, v_min: number, v_max: number, format: string, flags: ImGuiSliderFlags): boolean;
SliderScalar(label: string, data_type: ImGuiDataType, v: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array, v_min: number | null, v_max: number | null, format: string | null, flags: ImGuiSliderFlags): boolean;
VSliderFloat(label: string, size: Readonly<interface_ImVec2>, v: ImScalar<number> | ImTuple2<number> | ImTuple3<number> | ImTuple4<number>, v_min: number, v_max: number, format: string, flags: ImGuiSliderFlags): boolean;
VSliderInt(label: string, size: Readonly<interface_ImVec2>, v: ImScalar<number> | ImTuple2<number> | ImTuple3<number> | ImTuple4<number>, v_min: number, v_max: number, format: string, flags: ImGuiSliderFlags): boolean;
VSliderScalar(label: string, size: Readonly<interface_ImVec2>, data_type: ImGuiDataType, v: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array, v_min: number | null, v_max: number | null, format: string | null, flags: ImGuiSliderFlags): boolean;
// Widgets: Input with Keyboard
// - If you want to use InputText() with std::string or any custom dynamic string type, see misc/cpp/imgui_stdlib.h and comments in imgui_demo.cpp.
// - Most of the ImGuiInputTextFlags flags are only useful for InputText() and not for InputFloatX, InputIntX, InputDouble etc.
// IMGUI_API bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);
// IMGUI_API bool InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);
// IMGUI_API bool InputTextWithHint(const char* label, const char* hint, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = NULL, void* user_data = NULL);
// IMGUI_API bool InputFloat(const char* label, float* v, float step = 0.0f, float step_fast = 0.0f, const char* format = "%.3f", ImGuiInputTextFlags flags = 0);
// IMGUI_API bool InputFloat2(const char* label, float v[2], const char* format = "%.3f", ImGuiInputTextFlags flags = 0);
// IMGUI_API bool InputFloat3(const char* label, float v[3], const char* format = "%.3f", ImGuiInputTextFlags flags = 0);
// IMGUI_API bool InputFloat4(const char* label, float v[4], const char* format = "%.3f", ImGuiInputTextFlags flags = 0);
// IMGUI_API bool InputInt(const char* label, int* v, int step = 1, int step_fast = 100, ImGuiInputTextFlags flags = 0);
// IMGUI_API bool InputInt2(const char* label, int v[2], ImGuiInputTextFlags flags = 0);
// IMGUI_API bool InputInt3(const char* label, int v[3], ImGuiInputTextFlags flags = 0);
// IMGUI_API bool InputInt4(const char* label, int v[4], ImGuiInputTextFlags flags = 0);
// IMGUI_API bool InputDouble(const char* label, double* v, double step = 0.0, double step_fast = 0.0, const char* format = "%.6f", ImGuiInputTextFlags flags = 0);
// IMGUI_API bool InputScalar(const char* label, ImGuiDataType data_type, void* p_data, const void* p_step = NULL, const void* p_step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags flags = 0);
// IMGUI_API bool InputScalarN(const char* label, ImGuiDataType data_type, void* p_data, int components, const void* p_step = NULL, const void* p_step_fast = NULL, const char* format = NULL, ImGuiInputTextFlags flags = 0);
InputText(label: string, buf: [ string ], buf_size: number, flags: ImGuiInputTextFlags, callback: ImGuiInputTextCallback | null, user_data: any): boolean;
InputTextMultiline(label: string, buf: [ string ], buf_size: number, size: Readonly<interface_ImVec2>, flags: ImGuiInputTextFlags, callback: ImGuiInputTextCallback | null, user_data: any): boolean;
InputTextWithHint(label: string, hint: string, buf: [ string ], buf_size: number, flags: ImGuiInputTextFlags, callback: ImGuiInputTextCallback | null, user_data: any): boolean;
InputFloat(label: string, v: ImScalar<number> | ImTuple2<number> | ImTuple3<number> | ImTuple4<number>, step: number, step_fast: number, format: string, flags: ImGuiInputTextFlags): boolean;
InputFloat2(label: string, v: ImTuple2<number> | ImTuple3<number> | ImTuple4<number>, format: string, flags: ImGuiInputTextFlags): boolean;
InputFloat3(label: string, v: ImTuple3<number> | ImTuple4<number>, format: string, flags: ImGuiInputTextFlags): boolean;
InputFloat4(label: string, v: ImTuple4<number>, format: string, flags: ImGuiInputTextFlags): boolean;
InputInt(label: string, v: ImScalar<number> | ImTuple2<number> | ImTuple3<number> | ImTuple4<number>, step: number, step_fast: number, flags: ImGuiInputTextFlags): boolean;
InputInt2(label: string, v: ImTuple2<number> | ImTuple3<number> | ImTuple4<number>, flags: ImGuiInputTextFlags): boolean;
InputInt3(label: string, v: ImTuple3<number> | ImTuple4<number>, flags: ImGuiInputTextFlags): boolean;
InputInt4(label: string, v: ImTuple4<number>, flags: ImGuiInputTextFlags): boolean;
InputDouble(label: string, v: ImScalar<number> | ImTuple2<number> | ImTuple3<number> | ImTuple4<number>, step: number, step_fast: number, format: string, flags: ImGuiInputTextFlags): boolean;
InputScalar(label: string, data_type: ImGuiDataType, v: Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array, step: number | null, step_fast: number | null, format: string | null, flags: ImGuiInputTextFlags): boolean;
// Widgets: Color Editor/Picker (tip: the ColorEdit* functions have a little color square that can be left-clicked to open a picker, and right-clicked to open an option menu.)
// - Note that in C++ a 'float v[X]' function argument is the _same_ as 'float* v', the array syntax is just a way to document the number of elements that are expected to be accessible.
// - You can pass the address of a first float element out of a contiguous structure, e.g. &myvector.x
// IMGUI_API bool ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags = 0);
// IMGUI_API bool ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0);
// IMGUI_API bool ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags = 0);
// IMGUI_API bool ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags = 0, const float* ref_col = NULL);
// IMGUI_API bool ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0)); // display a color square/button, hover for details, return true when pressed.
// IMGUI_API void SetColorEditOptions(ImGuiColorEditFlags flags); // initialize current options (generally on application startup) if you want to select a default format, picker type, etc. User will be able to change many settings, unless you pass the _NoOptions flag to your calls.
ColorEdit3(label: string, col: ImTuple3<number> | ImTuple4<number>, flags: ImGuiColorEditFlags): boolean;
ColorEdit4(label: string, col: ImTuple4<number>, flags: ImGuiColorEditFlags): boolean;
ColorPicker3(label: string, col: ImTuple3<number> | ImTuple4<number>, flags: ImGuiColorEditFlags): boolean;
ColorPicker4(label: string, col: ImTuple4<number>, flags: ImGuiColorEditFlags, ref_col: ImTuple4<number> | null): boolean;
ColorButton(desc_id: string, col: Readonly<interface_ImVec4>, flags: ImGuiColorEditFlags, size: Readonly<interface_ImVec2>): boolean;
SetColorEditOptions(flags: ImGuiColorEditFlags): void;
// Widgets: Trees
// - TreeNode functions return true when the node is open, in which case you need to also call TreePop() when you are finished displaying the tree node contents.
// IMGUI_API bool TreeNode(const char* label);
// IMGUI_API bool TreeNode(const char* str_id, const char* fmt, ...) IM_FMTARGS(2); // helper variation to easily decorelate the id from the displayed string. Read the FAQ about why and how to use ID. to align arbitrary text at the same level as a TreeNode() you can use Bullet().
// IMGUI_API bool TreeNode(const void* ptr_id, const char* fmt, ...) IM_FMTARGS(2); // "
// IMGUI_API bool TreeNodeV(const char* str_id, const char* fmt, va_list args) IM_FMTLIST(2);
// IMGUI_API bool TreeNodeV(const void* ptr_id, const char* fmt, va_list args) IM_FMTLIST(2);
// IMGUI_API bool TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags = 0);
// IMGUI_API bool TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3);
// IMGUI_API bool TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...) IM_FMTARGS(3);
// IMGUI_API bool TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3);
// IMGUI_API bool TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args) IM_FMTLIST(3);
// IMGUI_API void TreePush(const char* str_id); // ~ Indent()+PushId(). Already called by TreeNode() when returning true, but you can call TreePush/TreePop yourself if desired.
// IMGUI_API void TreePush(const void* ptr_id = NULL); // "
// IMGUI_API void TreePop(); // ~ Unindent()+PopId()
// IMGUI_API float GetTreeNodeToLabelSpacing(); // horizontal distance preceding label when using TreeNode*() or Bullet() == (g.FontSize + style.FramePadding.x*2) for a regular unframed TreeNode
// IMGUI_API bool CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags = 0); // if returning 'true' the header is open. doesn't indent nor push on ID stack. user doesn't have to call TreePop().
// IMGUI_API bool CollapsingHeader(const char* label, bool* p_visible, ImGuiTreeNodeFlags flags = 0); // when 'p_visible != NULL': if '*p_visible==true' display an additional small close button on upper right of the header which will set the bool to false when clicked, if '*p_visible==false' don't display the header.
// IMGUI_API void SetNextItemOpen(bool is_open, ImGuiCond cond = 0); // set next TreeNode/CollapsingHeader open state.
TreeNode_A(label: string): boolean;
TreeNode_B(str_id: string, fmt: string): boolean;
TreeNode_C(ptr_id: number, fmt: string): boolean;
TreeNodeEx_A(label: string, flags: ImGuiTreeNodeFlags): boolean;
TreeNodeEx_B(str_id: string, flags: ImGuiTreeNodeFlags, fmt: string): boolean;
TreeNodeEx_C(ptr_id: number, flags: ImGuiTreeNodeFlags, fmt: string): boolean;
TreePush_A(str_id: string): void;
TreePush_B(ptr_id: number): void;
TreePop(): void;
GetTreeNodeToLabelSpacing(): number;
CollapsingHeader_A(label: string, flags: ImGuiTreeNodeFlags): boolean;
CollapsingHeader_B(label: string, p_open: ImScalar<boolean> | null, flags: ImGuiTreeNodeFlags): boolean;
SetNextItemOpen(is_open: boolean, cond: ImGuiCond): void;
// Widgets: Selectables
// - A selectable highlights when hovered, and can display another color when selected.
// - Neighbors selectable extend their highlight bounds in order to leave no gap between them. This is so a series of selected Selectable appear contiguous.
// IMGUI_API bool Selectable(const char* label, bool selected = false, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0, 0)); // "bool selected" carry the selection state (read-only). Selectable() is clicked is returns true so you can modify your selection state. size.x==0.0: use remaining width, size.x>0.0: specify width. size.y==0.0: use label height, size.y>0.0: specify height
// IMGUI_API bool Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags = 0, const ImVec2& size = ImVec2(0, 0)); // "bool* p_selected" point to the selection state (read-write), as a convenient helper.
Selectable_A(label: string, selected: boolean, flags: ImGuiSelectableFlags, size: interface_ImVec2): boolean;
Selectable_B(label: string, p_selected: ImScalar<boolean>, flags: ImGuiSelectableFlags, size: interface_ImVec2): boolean;
// Widgets: List Boxes
// - FIXME: To be consistent with all the newer API, ListBoxHeader/ListBoxFooter should in reality be called BeginListBox/EndListBox. Will rename them.
// IMGUI_API bool ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items = -1);
// IMGUI_API bool ListBox(const char* label, int* current_item, bool (*items_getter)(void* data, int idx, const char** out_text), void* data, int items_count, int height_in_items = -1);
// IMGUI_API bool ListBoxHeader(const char* label, const ImVec2& size = ImVec2(0, 0)); // use if you want to reimplement ListBox() will custom data or interactions. if the function return true, you can output elements then call ListBoxFooter() afterwards.
// IMGUI_API bool ListBoxHeader(const char* label, int items_count, int height_in_items = -1); // "
// IMGUI_API void ListBoxFooter(); // terminate the scrolling region. only call ListBoxFooter() if ListBoxHeader() returned true!
ListBox_A(label: string, current_item: ImScalar<number>, items: string[], items_count: number, height_in_items: number): boolean;
ListBox_B<T>(label: string, current_item: ImScalar<number>, items_getter: (data: T, idx: number, out_text: [string]) => boolean, data: T, items_count: number, height_in_items: number): boolean;
ListBoxHeader_A(label: string, size: Readonly<interface_ImVec2>): boolean;
ListBoxHeader_B(label: string, items_count: number, height_in_items: number): boolean;
ListBoxFooter(): void;
// Widgets: Data Plotting
// IMGUI_API void PlotLines(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0), int stride = sizeof(float));
// IMGUI_API void PlotLines(const char* label, float(*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0));
// IMGUI_API void PlotHistogram(const char* label, const float* values, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0), int stride = sizeof(float));
// IMGUI_API void PlotHistogram(const char* label, float(*values_getter)(void* data, int idx), void* data, int values_count, int values_offset = 0, const char* overlay_text = NULL, float scale_min = FLT_MAX, float scale_max = FLT_MAX, ImVec2 graph_size = ImVec2(0, 0));
PlotLines<T>(label: string, values_getter: (data: T, idx: number) => number, data: T, values_count: number, value_offset: number, overlay_text: string | null, scale_min: number, scale_max: number, graph_size: Readonly<interface_ImVec2>): void;
PlotHistogram<T>(label: string, values_getter: (data: T, idx: number) => number, data: T, values_count: number, value_offset: number, overlay_text: string | null, scale_min: number, scale_max: number, graph_size: Readonly<interface_ImVec2>): void;
// Widgets: Value() Helpers.
// - Those are merely shortcut to calling Text() with a format string. Output single value in "name: value" format (tip: freely declare more in your code to handle your types. you can add functions to the ImGui namespace)
// IMGUI_API void Value(const char* prefix, bool b);
// IMGUI_API void Value(const char* prefix, int v);
// IMGUI_API void Value(const char* prefix, unsigned int v);
// IMGUI_API void Value(const char* prefix, float v, const char* float_format = NULL);
Value_A(prefix: string, b: boolean): void;
Value_B(prefix: string, v: number): void;
Value_C(prefix: string, v: number): void;
Value_D(prefix: string, v: number, float_format: string | null): void;
// Widgets: Menus
// - Use BeginMenuBar() on a window ImGuiWindowFlags_MenuBar to append to its menu bar.
// - Use BeginMainMenuBar() to create a menu bar at the top of the screen and append to it.
// - Use BeginMenu() to create a menu. You can call BeginMenu() multiple time with the same identifier to append more items to it.
// IMGUI_API bool BeginMenuBar(); // append to menu-bar of current window (requires ImGuiWindowFlags_MenuBar flag set on parent window).
// IMGUI_API void EndMenuBar(); // only call EndMenuBar() if BeginMenuBar() returns true!
// IMGUI_API bool BeginMainMenuBar(); // create and append to a full screen menu-bar.
// IMGUI_API void EndMainMenuBar(); // only call EndMainMenuBar() if BeginMainMenuBar() returns true!
// IMGUI_API bool BeginMenu(const char* label, bool enabled = true); // create a sub-menu entry. only call EndMenu() if this returns true!
// IMGUI_API void EndMenu(); // only call EndMenu() if BeginMenu() returns true!
// IMGUI_API bool MenuItem(const char* label, const char* shortcut = NULL, bool selected = false, bool enabled = true); // return true when activated. shortcuts are displayed for convenience but not processed by ImGui at the moment
// IMGUI_API bool MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled = true); // return true when activated + toggle (*p_selected) if p_selected != NULL
BeginMenuBar(): boolean;
EndMenuBar(): void;
BeginMainMenuBar(): boolean;
EndMainMenuBar(): void;
BeginMenu(label: string, enabled: boolean): boolean;
EndMenu(): void;
MenuItem_A(label: string, shortcut: string | null, selected: boolean, enabled: boolean): boolean;
MenuItem_B(label: string, shortcut: string | null, p_selected: ImScalar<boolean>, enabled: boolean): boolean;
// Tooltips
// - Tooltip are windows following the mouse. They do not take focus away.
// IMGUI_API void BeginTooltip(); // begin/append a tooltip window. to create full-featured tooltip (with any kind of items).
// IMGUI_API void EndTooltip();
// IMGUI_API void SetTooltip(const char* fmt, ...) IM_FMTARGS(1); // set a text-only tooltip, typically use with ImGui::IsItemHovered(). override any previous call to SetTooltip().
// IMGUI_API void SetTooltipV(const char* fmt, va_list args) IM_FMTLIST(1);
BeginTooltip(): void;
EndTooltip(): void;
SetTooltip(fmt: string): void;
// Popups, Modals
// - They block normal mouse hovering detection (and therefore most mouse interactions) behind them.
// - If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE.
// - Their visibility state (~bool) is held internally instead of being held by the programmer as we are used to with regular Begin*() calls.
// - The 3 properties above are related: we need to retain popup visibility state in the library because popups may be closed as any time.
// - You can bypass the hovering restriction by using ImGuiHoveredFlags_AllowWhenBlockedByPopup when calling IsItemHovered() or IsWindowHovered().
// - IMPORTANT: Popup identifiers are relative to the current ID stack, so OpenPopup and BeginPopup generally needs to be at the same level of the stack.
// This is sometimes leading to confusing mistakes. May rework this in the future.
// Popups: begin/end functions
// - BeginPopup(): query popup state, if open start appending into the window. Call EndPopup() afterwards. ImGuiWindowFlags are forwarded to the window.
// - BeginPopupModal(): block every interactions behind the window, cannot be closed by user, add a dimming background, has a title bar.
// IMGUI_API bool BeginPopup(const char* str_id, ImGuiWindowFlags flags = 0); // return true if the popup is open, and you can start outputting to it.
// IMGUI_API bool BeginPopupModal(const char* name, bool* p_open = NULL, ImGuiWindowFlags flags = 0); // return true if the modal is open, and you can start outputting to it.
// IMGUI_API void EndPopup(); // only call EndPopup() if BeginPopupXXX() returns true!
BeginPopup(str_id: string, flags: ImGuiWindowFlags): boolean;
BeginPopupModal(name: string, p_open: ImScalar<boolean> | null, flags: ImGuiWindowFlags): boolean;
EndPopup(): void;
// Popups: open/close functions
// - OpenPopup(): set popup state to open. ImGuiPopupFlags are available for opening options.
// - If not modal: they can be closed by clicking anywhere outside them, or by pressing ESCAPE.
// - CloseCurrentPopup(): use inside the BeginPopup()/EndPopup() scope to close manually.
// - CloseCurrentPopup() is called by default by Selectable()/MenuItem() when activated (FIXME: need some options).
// - Use ImGuiPopupFlags_NoOpenOverExistingPopup to avoid opening a popup if there's already one at the same level. This is equivalent to e.g. testing for !IsAnyPopupOpen() prior to OpenPopup().
// IMGUI_API void OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags = 0); // call to mark popup as open (don't call every frame!).
// IMGUI_API void OpenPopupOnItemClick(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // helper to open popup when clicked on last item. return true when just opened. (note: actually triggers on the mouse _released_ event to be consistent with popup behaviors)
// IMGUI_API void CloseCurrentPopup(); // manually close the popup we have begin-ed into.
OpenPopup(str_id: string, popup_flags: ImGuiPopupFlags): void;
OpenPopupOnItemClick(str_id: string | null, popup_flags: ImGuiPopupFlags): void;
CloseCurrentPopup(): void;
// Popups: open+begin combined functions helpers
// - Helpers to do OpenPopup+BeginPopup where the Open action is triggered by e.g. hovering an item and right-clicking.
// - They are convenient to easily create context menus, hence the name.
// - IMPORTANT: Notice that BeginPopupContextXXX takes ImGuiPopupFlags just like OpenPopup() and unlike BeginPopup(). For full consistency, we may add ImGuiWindowFlags to the BeginPopupContextXXX functions in the future.
// - IMPORTANT: we exceptionally default their flags to 1 (== ImGuiPopupFlags_MouseButtonRight) for backward compatibility with older API taking 'int mouse_button = 1' parameter, so if you add other flags remember to re-add the ImGuiPopupFlags_MouseButtonRight.
// IMGUI_API bool BeginPopupContextItem(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // open+begin popup when clicked on last item. if you can pass a NULL str_id only if the previous item had an id. If you want to use that on a non-interactive item such as Text() you need to pass in an explicit ID here. read comments in .cpp!
// IMGUI_API bool BeginPopupContextWindow(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1);// open+begin popup when clicked on current window.
// IMGUI_API bool BeginPopupContextVoid(const char* str_id = NULL, ImGuiPopupFlags popup_flags = 1); // open+begin popup when clicked in void (where there are no windows).
BeginPopupContextItem(str_id: string | null, popup_flags: ImGuiPopupFlags): boolean;
BeginPopupContextWindow(str_id: string | null, popup_flags: ImGuiPopupFlags): boolean;
BeginPopupContextVoid(str_id: string | null, popup_flags: ImGuiPopupFlags): boolean;
// Popups: test function
// - IsPopupOpen(): return true if the popup is open at the current BeginPopup() level of the popup stack.
// - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId: return true if any popup is open at the current BeginPopup() level of the popup stack.
// - IsPopupOpen() with ImGuiPopupFlags_AnyPopupId + ImGuiPopupFlags_AnyPopupLevel: return true if any popup is open.
// IMGUI_API bool IsPopupOpen(const char* str_id, ImGuiPopupFlags flags = 0); // return true if the popup is open.
IsPopupOpen(str_id: string, flags: ImGuiPopupFlags): boolean;
// Tables
// [BETA API] API may evolve slightly! If you use this, please update to the next version when it comes out!
// - Full-featured replacement for old Columns API.
// - See Demo->Tables for demo code.
// - See top of imgui_tables.cpp for general commentary.
// - See ImGuiTableFlags_ and ImGuiTableColumnFlags_ enums for a description of available flags.
// The typical call flow is:
// - 1. Call BeginTable().
// - 2. Optionally call TableSetupColumn() to submit column name/flags/defaults.
// - 3. Optionally call TableSetupScrollFreeze() to request scroll freezing of columns/rows.
// - 4. Optionally call TableHeadersRow() to submit a header row. Names are pulled from TableSetupColumn() data.
// - 5. Populate contents:
// - In most situations you can use TableNextRow() + TableSetColumnIndex(N) to start appending into a column.
// - If you are using tables as a sort of grid, where every columns is holding the same type of contents,
// you may prefer using TableNextColumn() instead of TableNextRow() + TableSetColumnIndex().
// TableNextColumn() will automatically wrap-around into the next row if needed.
// - IMPORTANT: Comparatively to the old Columns() API, we need to call TableNextColumn() for the first column!
// - Summary of possible call flow:
// --------------------------------------------------------------------------------------------------------
// TableNextRow() -> TableSetColumnIndex(0) -> Text("Hello 0") -> TableSetColumnIndex(1) -> Text("Hello 1") // OK
// TableNextRow() -> TableNextColumn() -> Text("Hello 0") -> TableNextColumn() -> Text("Hello 1") // OK
// TableNextColumn() -> Text("Hello 0") -> TableNextColumn() -> Text("Hello 1") // OK: TableNextColumn() automatically gets to next row!
// TableNextRow() -> Text("Hello 0") // Not OK! Missing TableSetColumnIndex() or TableNextColumn()! Text will not appear!
// --------------------------------------------------------------------------------------------------------
// - 5. Call EndTable()
// IMGUI_API bool BeginTable(const char* str_id, int column, ImGuiTableFlags flags = 0, const ImVec2& outer_size = ImVec2(0.0f, 0.0f), float inner_width = 0.0f);
// IMGUI_API void EndTable(); // only call EndTable() if BeginTable() returns true!
// IMGUI_API void TableNextRow(ImGuiTableRowFlags row_flags = 0, float min_row_height = 0.0f); // append into the first cell of a new row.
// IMGUI_API bool TableNextColumn(); // append into the next column (or first column of next row if currently in last column). Return true when column is visible.
// IMGUI_API bool TableSetColumnIndex(int column_n); // append into the specified column. Return true when column is visible.
BeginTable(str_id: string, column: number, flags: ImGuiTableFlags, outer_size: interface_ImVec2, inner_width: number): boolean;
EndTable(): void;
TableNextRow(row_flags: ImGuiTableRowFlags, min_row_height: number): void;
TableNextColumn(): boolean
TableSetColumnIndex(column_n: number): boolean;
// Tables: Headers & Columns declaration
// - Use TableSetupColumn() to specify label, resizing policy, default width/weight, id, various other flags etc.
// - Use TableHeadersRow() to create a header row and automatically submit a TableHeader() for each column.
// Headers are required to perform: reordering, sorting, and opening the context menu.
// The context menu can also be made available in columns body using ImGuiTableFlags_ContextMenuInBody.
// - You may manually submit headers using TableNextRow() + TableHeader() calls, but this is only useful in
// some advanced use cases (e.g. adding custom widgets in header row).
// - Use TableSetupScrollFreeze() to lock columns/rows so they stay visible when scrolled.
// IMGUI_API void TableSetupColumn(const char* label, ImGuiTableColumnFlags flags = 0, float init_width_or_weight = 0.0f, ImU32 user_id = 0);
// IMGUI_API void TableSetupScrollFreeze(int cols, int rows); // lock columns/rows so they stay visible when scrolled.
// IMGUI_API void TableHeadersRow(); // submit all headers cells based on data provided to TableSetupColumn() + submit context menu
// IMGUI_API void TableHeader(const char* label); // submit one header cell manually (rarely used)
TableSetupColumn(label: string, flags: ImGuiTableColumnFlags, init_width_or_weight: number, user_id: ImU32): void;
TableSetupScrollFreeze(cols: number, rows: number): void;
TableHeadersRow(): void;
TableHeader(label: string): void;
// Tables: Sorting
// - Call TableGetSortSpecs() to retrieve latest sort specs for the table. NULL when not sorting.
// - When 'SpecsDirty == true' you should sort your data. It will be true when sorting specs have changed
// since last call, or the first time. Make sure to set 'SpecsDirty = false' after sorting, else you may
// wastefully sort your data every frame!
// - Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable().
// IMGUI_API ImGuiTableSortSpecs* TableGetSortSpecs(); // get latest sort specs for the table (NULL if not sorting).
TableGetSortSpecs(): reference_ImGuiTableSortSpecs | null;
// Tables: Miscellaneous functions
// - Functions args 'int column_n' treat the default value of -1 as the same as passing the current column index.
// IMGUI_API int TableGetColumnCount(); // return number of columns (value passed to BeginTable)
// IMGUI_API int TableGetColumnIndex(); // return current column index.
// IMGUI_API int TableGetRowIndex(); // return current row index.
// IMGUI_API const char* TableGetColumnName(int column_n = -1); // return "" if column didn't have a name declared by TableSetupColumn(). Pass -1 to use current column.
// IMGUI_API ImGuiTableColumnFlags TableGetColumnFlags(int column_n = -1); // return column flags so you can query their Enabled/Visible/Sorted/Hovered status flags. Pass -1 to use current column.
// IMGUI_API void TableSetBgColor(ImGuiTableBgTarget target, ImU32 color, int column_n = -1); // change the color of a cell, row, or column. See ImGuiTableBgTarget_ flags for details.
TableGetColumnCount(): number;
TableGetColumnIndex(): number;
TableGetRowIndex(): number;
TableGetColumnName(column_n: number): string;
TableGetColumnFlags(column_n: number): ImGuiTableColumnFlags;
TableSetBgColor(target: ImGuiTableBgTarget, color: ImU32, column_n: number): void;
// Legacy Columns API (2020: prefer using Tables!)
// - You can also use SameLine(pos_x) to mimic simplified columns.
// IMGUI_API void Columns(int count = 1, const char* id = NULL, bool border = true);
// IMGUI_API void NextColumn(); // next column, defaults to current row or next row if the current row is finished
// IMGUI_API int GetColumnIndex(); // get current column index
// IMGUI_API float GetColumnWidth(int column_index = -1); // get column width (in pixels). pass -1 to use current column
// IMGUI_API void SetColumnWidth(int column_index, float width); // set column width (in pixels). pass -1 to use current column
// IMGUI_API float GetColumnOffset(int column_index = -1); // get position of column line (in pixels, from the left side of the contents region). pass -1 to use current column, otherwise 0..GetColumnsCount() inclusive. column 0 is typically 0.0f
// IMGUI_API void SetColumnOffset(int column_index, float offset_x); // set position of column line (in pixels, from the left side of the contents region). pass -1 to use current column
// IMGUI_API int GetColumnsCount();
Columns(count: number, id: string | null, border: boolean): void;
NextColumn(): void;
GetColumnIndex(): number;
GetColumnWidth(column_index: number): number;
SetColumnWidth(column_index: number, width: number): void;
GetColumnOffset(column_index: number): number;
SetColumnOffset(column_index: number, offset_x: number): void;
GetColumnsCount(): number;
// Tab Bars, Tabs
// IMGUI_API bool BeginTabBar(const char* str_id, ImGuiTabBarFlags flags = 0); // create and append into a TabBar
// IMGUI_API void EndTabBar(); // only call EndTabBar() if BeginTabBar() returns true!
// IMGUI_API bool BeginTabItem(const char* label, bool* p_open = NULL, ImGuiTabItemFlags flags = 0); // create a Tab. Returns true if the Tab is selected.
// IMGUI_API void EndTabItem(); // only call EndTabItem() if BeginTabItem() returns true!
// IMGUI_API bool TabItemButton(const char* label, ImGuiTabItemFlags flags = 0); // create a Tab behaving like a button. return true when clicked. cannot be selected in the tab bar.
// IMGUI_API void SetTabItemClosed(const char* tab_or_docked_window_label); // notify TabBar or Docking system of a closed tab/window ahead (useful to reduce visual flicker on reorderable tab bars). For tab-bar: call after BeginTabBar() and before Tab submissions. Otherwise call with a window name.
BeginTabBar(str_id: string, flags: ImGuiTabBarFlags): boolean;
EndTabBar(): void;
BeginTabItem(label: string, p_open: ImScalar<boolean> | null, flags: ImGuiTabBarFlags): boolean;
EndTabItem(): void;
TabItemButton(label: string, flags: ImGuiTabItemFlags): boolean;
SetTabItemClosed(tab_or_docked_window_label: string): void;
// Logging/Capture
// - All text output from the interface can be captured into tty/file/clipboard. By default, tree nodes are automatically opened during logging.
// IMGUI_API void LogToTTY(int auto_open_depth = -1); // start logging to tty (stdout)
// IMGUI_API void LogToFile(int auto_open_depth = -1, const char* filename = NULL); // start logging to file
// IMGUI_API void LogToClipboard(int auto_open_depth = -1); // start logging to OS clipboard
// IMGUI_API void LogFinish(); // stop logging (close file, etc.)
// IMGUI_API void LogButtons(); // helper to display buttons for logging to tty/file/clipboard
// IMGUI_API void LogText(const char* fmt, ...) IM_FMTARGS(1); // pass text data straight to log (without being displayed)
LogToTTY(max_depth: number): void;
LogToFile(max_depth: number, filename: string | null): void;
LogToClipboard(max_depth: number): void;
LogFinish(): void;
LogButtons(): void;
LogText(fmt: string): void;
// Drag and Drop
// - If you stop calling BeginDragDropSource() the payload is preserved however it won't have a preview tooltip (we currently display a fallback "..." tooltip as replacement)
// IMGUI_API bool BeginDragDropSource(ImGuiDragDropFlags flags = 0); // call when the current item is active. If this return true, you can call SetDragDropPayload() + EndDragDropSource()
// IMGUI_API bool SetDragDropPayload(const char* type, const void* data, size_t sz, ImGuiCond cond = 0); // type is a user defined string of maximum 32 characters. Strings starting with '_' are reserved for dear imgui internal types. Data is copied and held by imgui.
// IMGUI_API void EndDragDropSource(); // only call EndDragDropSource() if BeginDragDropSource() returns true!
// IMGUI_API bool BeginDragDropTarget(); // call after submitting an item that may receive a payload. If this returns true, you can call AcceptDragDropPayload() + EndDragDropTarget()
// IMGUI_API const ImGuiPayload* AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags = 0); // accept contents of a given type. If ImGuiDragDropFlags_AcceptBeforeDelivery is set you can peek into the payload before the mouse button is released.
// IMGUI_API void EndDragDropTarget(); // only call EndDragDropTarget() if BeginDragDropTarget() returns true!
// IMGUI_API const ImGuiPayload* GetDragDropPayload(); // peek directly into the current payload from anywhere. may return NULL. use ImGuiPayload::IsDataType() to test for the payload type.
BeginDragDropSource(flags: ImGuiDragDropFlags): boolean;
SetDragDropPayload(type: string, data: any, size: number, cond: ImGuiCond): boolean;
EndDragDropSource(): void;
BeginDragDropTarget(): boolean;
AcceptDragDropPayload(type: string, flags: ImGuiDragDropFlags): boolean; // reference_DragDropPayload | null; // TODO
EndDragDropTarget(): void;
GetDragDropPayload(): null; // reference_DragDropPayload | null; // TODO
// Clipping
// - Mouse hovering is affected by ImGui::PushClipRect() calls, unlike direct calls to ImDrawList::PushClipRect() which are render only.
// IMGUI_API void PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect);
// IMGUI_API void PopClipRect();
PushClipRect(clip_rect_min: Readonly<interface_ImVec2>, clip_rect_max: Readonly<interface_ImVec2>, intersect_with_current_clip_rect: boolean): void;
PopClipRect(): void;
// Focus, Activation
// - Prefer using "SetItemDefaultFocus()" over "if (IsWindowAppearing()) SetScrollHereY()" when applicable to signify "this is the default item"
// IMGUI_API void SetItemDefaultFocus(); // make last item the default focused item of a window.
// IMGUI_API void SetKeyboardFocusHere(int offset = 0); // focus keyboard on the next widget. Use positive 'offset' to access sub components of a multiple component widget. Use -1 to access previous widget.
SetItemDefaultFocus(): void;
SetKeyboardFocusHere(offset: number): void;
// Item/Widgets Utilities
// - Most of the functions are referring to the last/previous item we submitted.
// - See Demo Window under "Widgets->Querying Status" for an interactive visualization of most of those functions.
// IMGUI_API bool IsItemHovered(ImGuiHoveredFlags flags = 0); // is the last item hovered? (and usable, aka not blocked by a popup, etc.). See ImGuiHoveredFlags for more options.
// IMGUI_API bool IsItemActive(); // is the last item active? (e.g. button being held, text field being edited. This will continuously return true while holding mouse button on an item. Items that don't interact will always return false)
// IMGUI_API bool IsItemFocused(); // is the last item focused for keyboard/gamepad navigation?
// IMGUI_API bool IsItemClicked(ImGuiMouseButton mouse_button = 0); // is the last item clicked? (e.g. button/node just clicked on) == IsMouseClicked(mouse_button) && IsItemHovered()
// IMGUI_API bool IsItemVisible(); // is the last item visible? (items may be out of sight because of clipping/scrolling)
// IMGUI_API bool IsItemEdited(); // did the last item modify its underlying value this frame? or was pressed? This is generally the same as the "bool" return value of many widgets.
// IMGUI_API bool IsItemActivated(); // was the last item just made active (item was previously inactive).
// IMGUI_API bool IsItemDeactivated(); // was the last item just made inactive (item was previously active). Useful for Undo/Redo patterns with widgets that requires continuous editing.
// IMGUI_API bool IsItemDeactivatedAfterEdit(); // was the last item just made inactive and made a value change when it was active? (e.g. Slider/Drag moved). Useful for Undo/Redo patterns with widgets that requires continuous editing. Note that you may get false positives (some widgets such as Combo()/ListBox()/Selectable() will return true even when clicking an already selected item).
// IMGUI_API bool IsItemToggledOpen(); // was the last item open state toggled? set by TreeNode().
// IMGUI_API bool IsAnyItemHovered(); // is any item hovered?
// IMGUI_API bool IsAnyItemActive(); // is any item active?
// IMGUI_API bool IsAnyItemFocused(); // is any item focused?
// IMGUI_API ImVec2 GetItemRectMin(); // get upper-left bounding rectangle of the last item (screen space)
// IMGUI_API ImVec2 GetItemRectMax(); // get lower-right bounding rectangle of the last item (screen space)
// IMGUI_API ImVec2 GetItemRectSize(); // get size of last item
// IMGUI_API void SetItemAllowOverlap(); // allow last item to be overlapped by a subsequent item. sometimes useful with invisible buttons, selectables, etc. to catch unused area.
IsItemHovered(flags: ImGuiHoveredFlags): boolean;
IsItemActive(): boolean;
IsItemFocused(): boolean;
IsItemClicked(mouse_button: ImGuiMouseButton): boolean;
IsItemVisible(): boolean;
IsItemEdited(): boolean;
IsItemActivated(): boolean;
IsItemDeactivated(): boolean;
IsItemDeactivatedAfterEdit(): boolean;
IsItemToggledOpen(): boolean;
IsAnyItemHovered(): boolean;
IsAnyItemActive(): boolean;
IsAnyItemFocused(): boolean;
GetItemRectMin(out: interface_ImVec2): typeof out;
GetItemRectMax(out: interface_ImVec2): typeof out;
GetItemRectSize(out: interface_ImVec2): typeof out;
SetItemAllowOverlap(): void;
// Miscellaneous Utilities
// IMGUI_API bool IsRectVisible(const ImVec2& size); // test if rectangle (of given size, starting from cursor position) is visible / not clipped.
// IMGUI_API bool IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max); // test if rectangle (in screen space) is visible / not clipped. to perform coarse clipping on user's side.
// IMGUI_API double GetTime(); // get global imgui time. incremented by io.DeltaTime every frame.
// IMGUI_API int GetFrameCount(); // get global imgui frame count. incremented by 1 every frame.
// IMGUI_API ImDrawList* GetBackgroundDrawList(); // this draw list will be the first rendering one. Useful to quickly draw shapes/text behind dear imgui contents.
// IMGUI_API ImDrawList* GetForegroundDrawList(); // this draw list will be the last rendered one. Useful to quickly draw shapes/text over dear imgui contents.
// IMGUI_API ImDrawListSharedData* GetDrawListSharedData(); // you may use this when creating your own ImDrawList instances.
// IMGUI_API const char* GetStyleColorName(ImGuiCol idx); // get a string corresponding to the enum value (for display, saving, etc.).
// IMGUI_API void SetStateStorage(ImGuiStorage* storage); // replace current window storage with our own (if you want to manipulate it yourself, typically clear subsection of it)
// IMGUI_API ImGuiStorage* GetStateStorage();
// IMGUI_API void CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end); // calculate coarse clipping for large list of evenly sized items. Prefer using the ImGuiListClipper higher-level helper if you can.
// IMGUI_API bool BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags flags = 0); // helper to create a child window / scrolling region that looks like a normal widget frame
// IMGUI_API void EndChildFrame(); // always call EndChildFrame() regardless of BeginChildFrame() return values (which indicates a collapsed/clipped window)
IsRectVisible_A(size: Readonly<interface_ImVec2>): boolean;
IsRectVisible_B(rect_min: Readonly<interface_ImVec2>, rect_max: Readonly<interface_ImVec2>): boolean;
GetTime(): number;
GetFrameCount(): number;
GetBackgroundDrawList(): reference_ImDrawList;
GetForegroundDrawList(): reference_ImDrawList;
GetDrawListSharedData(): reference_ImDrawListSharedData;
// function SetStateStorage(tree: ImGuiStorage | null): void;
// function GetStateStorage(): ImGuiStorage | null;
GetStyleColorName(idx: ImGuiCol): string;
CalcListClipping(items_count: number, items_height: number, out_items_display_start: ImScalar<number>, out_items_display_end: ImScalar<number>): void;
BeginChildFrame(id: ImGuiID, size: Readonly<interface_ImVec2>, flags: ImGuiWindowFlags): boolean;
EndChildFrame(): void;
// Text Utilities
// IMGUI_API ImVec2 CalcTextSize(const char* text, const char* text_end = NULL, bool hide_text_after_double_hash = false, float wrap_width = -1.0f);
CalcTextSize(text: string, hide_text_after_double_hash: boolean, wrap_width: number, out: interface_ImVec2): typeof out;
// Color Utilities
// IMGUI_API ImVec4 ColorConvertU32ToFloat4(ImU32 in);
// IMGUI_API ImU32 ColorConvertFloat4ToU32(const ImVec4& in);
// IMGUI_API void ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v);
// IMGUI_API void ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b);
ColorConvertU32ToFloat4(in_: ImU32, out: interface_ImVec4): typeof out;
ColorConvertFloat4ToU32(in_: Readonly<interface_ImVec4>): ImU32;
ColorConvertRGBtoHSV(r: number, g: number, b: number, out_h: ImScalar<number>, out_s: ImScalar<number>, out_v: ImScalar<number>): void;
ColorConvertHSVtoRGB(h: number, s: number, v: number, out_r: ImScalar<number>, out_g: ImScalar<number>, out_b: ImScalar<number>): void;
// Inputs Utilities: Keyboard
// - For 'int user_key_index' you can use your own indices/enums according to how your backend/engine stored them in io.KeysDown[].
// - We don't know the meaning of those value. You can use GetKeyIndex() to map a ImGuiKey_ value into the user index.
// IMGUI_API int GetKeyIndex(ImGuiKey imgui_key); // map ImGuiKey_* values into user's key index. == io.KeyMap[key]
// IMGUI_API bool IsKeyDown(int user_key_index); // is key being held. == io.KeysDown[user_key_index].
// IMGUI_API bool IsKeyPressed(int user_key_index, bool repeat = true); // was key pressed (went from !Down to Down)? if repeat=true, uses io.KeyRepeatDelay / KeyRepeatRate
// IMGUI_API bool IsKeyReleased(int user_key_index); // was key released (went from Down to !Down)?
// IMGUI_API int GetKeyPressedAmount(int key_index, float repeat_delay, float rate); // uses provided repeat rate/delay. return a count, most often 0 or 1 but might be >1 if RepeatRate is small enough that DeltaTime > RepeatRate
// IMGUI_API void CaptureKeyboardFromApp(bool want_capture_keyboard_value = true); // attention: misleading name! manually override io.WantCaptureKeyboard flag next frame (said flag is entirely left for your application to handle). e.g. force capture keyboard when your widget is being hovered. This is equivalent to setting "io.WantCaptureKeyboard = want_capture_keyboard_value"; after the next NewFrame() call.
GetKeyIndex(imgui_key: ImGuiKey): number;
IsKeyDown(user_key_index: number): boolean;
IsKeyPressed(user_key_index: number, repeat: boolean): boolean;
IsKeyReleased(user_key_index: number): boolean;
GetKeyPressedAmount(key_index: number, repeat_delay: number, rate: number): number;
CaptureKeyboardFromApp(capture: boolean): void;
// Inputs Utilities: Mouse
// - To refer to a mouse button, you may use named enums in your code e.g. ImGuiMouseButton_Left, ImGuiMouseButton_Right.
// - You can also use regular integer: it is forever guaranteed that 0=Left, 1=Right, 2=Middle.
// - Dragging operations are only reported after mouse has moved a certain distance away from the initial clicking position (see 'lock_threshold' and 'io.MouseDraggingThreshold')
// IMGUI_API bool IsMouseDown(ImGuiMouseButton button); // is mouse button held?
// IMGUI_API bool IsMouseClicked(ImGuiMouseButton button, bool repeat = false); // did mouse button clicked? (went from !Down to Down)
// IMGUI_API bool IsMouseReleased(ImGuiMouseButton button); // did mouse button released? (went from Down to !Down)
// IMGUI_API bool IsMouseDoubleClicked(ImGuiMouseButton button); // did mouse button double-clicked? (note that a double-click will also report IsMouseClicked() == true)
// IMGUI_API bool IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip = true);// is mouse hovering given bounding rect (in screen space). clipped by current clipping settings, but disregarding of other consideration of focus/window ordering/popup-block.
// IMGUI_API bool IsMousePosValid(const ImVec2* mouse_pos = NULL); // by convention we use (-FLT_MAX,-FLT_MAX) to denote that there is no mouse available
// IMGUI_API bool IsAnyMouseDown(); // is any mouse button held?
// IMGUI_API ImVec2 GetMousePos(); // shortcut to ImGui::GetIO().MousePos provided by user, to be consistent with other calls
// IMGUI_API ImVec2 GetMousePosOnOpeningCurrentPopup(); // retrieve mouse position at the time of opening popup we have BeginPopup() into (helper to avoid user backing that value themselves)
// IMGUI_API bool IsMouseDragging(ImGuiMouseButton button, float lock_threshold = -1.0f); // is mouse dragging? (if lock_threshold < -1.0f, uses io.MouseDraggingThreshold)
// IMGUI_API ImVec2 GetMouseDragDelta(ImGuiMouseButton button = 0, float lock_threshold = -1.0f); // return the delta from the initial clicking position while the mouse button is pressed or was just released. This is locked and return 0.0f until the mouse moves past a distance threshold at least once (if lock_threshold < -1.0f, uses io.MouseDraggingThreshold)
// IMGUI_API void ResetMouseDragDelta(ImGuiMouseButton button = 0); //
// IMGUI_API ImGuiMouseCursor GetMouseCursor(); // get desired cursor type, reset in ImGui::NewFrame(), this is updated during the frame. valid before Render(). If you use software rendering by setting io.MouseDrawCursor ImGui will render those for you
// IMGUI_API void SetMouseCursor(ImGuiMouseCursor cursor_type); // set desired cursor type
// IMGUI_API void CaptureMouseFromApp(bool want_capture_mouse_value = true); // attention: misleading name! manually override io.WantCaptureMouse flag next frame (said flag is entirely left for your application to handle). This is equivalent to setting "io.WantCaptureMouse = want_capture_mouse_value;" after the next NewFrame() call.
IsMouseDown(button: ImGuiMouseButton): boolean;
IsMouseClicked(button: ImGuiMouseButton, repeat: boolean): boolean;
IsMouseReleased(button: ImGuiMouseButton): boolean;
IsMouseDoubleClicked(button: ImGuiMouseButton): boolean;
IsMouseHoveringRect(r_min: Readonly<interface_ImVec2>, r_max: Readonly<interface_ImVec2>, clip: boolean): boolean;
IsMousePosValid(mouse_pos: Readonly<interface_ImVec2> | null): boolean;
IsAnyMouseDown(): boolean;
GetMousePos(out: interface_ImVec2): typeof out;
GetMousePosOnOpeningCurrentPopup(out: interface_ImVec2): typeof out;
IsMouseDragging(button: ImGuiMouseButton, lock_threshold: number): boolean;
GetMouseDragDelta(button: ImGuiMouseButton, lock_threshold: number, out: interface_ImVec2): typeof out;
ResetMouseDragDelta(button: ImGuiMouseButton): void;
GetMouseCursor(): ImGuiMouseCursor;
SetMouseCursor(type: ImGuiMouseCursor): void;
CaptureMouseFromApp(capture: boolean): void;
// Clipboard Utilities
// - Also see the LogToClipboard() function to capture GUI into clipboard, or easily output text data to the clipboard.
// IMGUI_API const char* GetClipboardText();
// IMGUI_API void SetClipboardText(const char* text);
GetClipboardText(): string;
SetClipboardText(text: string): void;
// Settings/.Ini Utilities
// - The disk functions are automatically called if io.IniFilename != NULL (default is "imgui.ini").
// - Set io.IniFilename to NULL to load/save manually. Read io.WantSaveIniSettings description about handling .ini saving manually.
// IMGUI_API void LoadIniSettingsFromDisk(const char* ini_filename); // call after CreateContext() and before the first call to NewFrame(). NewFrame() automatically calls LoadIniSettingsFromDisk(io.IniFilename).
// IMGUI_API void LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size=0); // call after CreateContext() and before the first call to NewFrame() to provide .ini data from your own data source.
// IMGUI_API void SaveIniSettingsToDisk(const char* ini_filename); // this is automatically called (if io.IniFilename is not empty) a few seconds after any modification that should be reflected in the .ini file (and also by DestroyContext).
// IMGUI_API const char* SaveIniSettingsToMemory(size_t* out_ini_size = NULL); // return a zero-terminated string with the .ini data which you can save by your own mean. call when io.WantSaveIniSettings is set, then save data by your own mean and clear io.WantSaveIniSettings.
LoadIniSettingsFromMemory(ini_data: string/*, ini_size: number*/): void;
SaveIniSettingsToMemory(/*out_ini_size: ImScalar<number> | null*/): string;
// Debug Utilities
// IMGUI_API bool DebugCheckVersionAndDataLayout(const char* version_str, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_drawvert, size_t sz_drawidx); // This is called by IMGUI_CHECKVERSION() macro.
DebugCheckVersionAndDataLayout(version_str: string, sz_io: number, sz_style: number, sz_vec2: number, sz_vec4: number, sz_draw_vert: number, sz_draw_idx: number): boolean;
// Memory Allocators
// - All those functions are not reliant on the current context.
// - If you reload the contents of imgui.cpp at runtime, you may need to call SetCurrentContext() + SetAllocatorFunctions() again because we use global storage for those.
// IMGUI_API void SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data = NULL);
// IMGUI_API void* MemAlloc(size_t size);
// IMGUI_API void MemFree(void* ptr);
SetAllocatorFunctions(alloc_func: (sz: number, user_data: any) => number, free_func: (ptr: number, user_data: any) => void, user_data: any): void;
MemAlloc(sz: number): any;
MemFree(ptr: any): void;
} | the_stack |
import nodeFetch from "node-fetch"
import * as FormData from "form-data"
import { AbortController, abortableFetch } from "abortcontroller-polyfill/dist/cjs-ponyfill"
import * as fs from "fs"
import { URLSearchParams } from "url"
import * as path from "path"
import wretch from "../../src"
import { mix } from "../../src/mix"
import { performance, PerformanceObserver } from "perf_hooks"
performance["clearResourceTimings"] = () => {}
const _PORT = 9876
const _URL = `http://localhost:${_PORT}`
const allRoutes = (obj, type, action, opts?, body?) => Promise.all([
obj.get(opts)[type](_ => _).then(action),
obj.put(body, opts)[type](action),
obj.patch(body, opts)[type](action),
obj.post(body, opts)[type](action),
obj.delete(opts)[type](action),
])
const fetchPolyfill = (timeout = null) =>
function (url, opts) {
performance.mark(url + " - begin")
const { fetch } = abortableFetch(nodeFetch) as any
return fetch(url, opts).then(res => {
performance.mark(url + " - end")
const measure = () => performance.measure(res.url, url + " - begin", url + " - end")
if(timeout)
setTimeout(measure, timeout)
else
measure()
return res
})
}
const duckImagePath = path.resolve(__dirname, "..", "assets", "duck.jpg")
const duckImage = fs.readFileSync(duckImagePath)
describe("Wretch", function () {
it("should set and use non global polyfills", async function () {
global["FormData"] = null
global["URLSearchParams"] = null
expect(() => wretch("...").query({ a: 1, b: 2 })).toThrow("URLSearchParams is not defined")
expect(() => wretch("...").formData({ a: 1, b: 2 })).toThrow("FormData is not defined")
expect(() => wretch("...").get()).toThrow("fetch is not defined")
wretch().polyfills({
fetch: fetchPolyfill(),
FormData,
URLSearchParams
})
await wretch(`${_URL}/text`).get().perfs(_ => fail("should never be called")).res()
wretch(null, null).polyfills({
fetch: fetchPolyfill(),
FormData,
URLSearchParams,
performance,
PerformanceObserver,
AbortController
})
})
it("should perform crud requests and parse a text response", async function () {
const init = wretch(`${_URL}/text`)
const test = _ => expect(_).toBe("A text string")
await allRoutes(init, "text", test)
await allRoutes(init, "text", test, {}, {})
})
it("should perform crud requests and parse a json response", async function () {
const test = _ => expect(_).toEqual({ a: "json", object: "which", is: "stringified" })
const init = wretch(`${_URL}/json`)
await allRoutes(init, "json", test)
await allRoutes(init, "json", test, {}, {})
})
it("should perform crud requests and parse a blob response", async function () {
const test = _ => expect(_.size).toBe(duckImage.length)
const init = wretch(`${_URL}/blob`)
await allRoutes(init, "blob", test)
await allRoutes(init, "blob", test, {}, {})
})
it("should not stringify a blob when the content-type is not json", async function () {
expect((
await wretch(`${_URL}/blob/roundTrip`, {
// using 'xxx-' prefix because otherwise node-fetch sends an empty body
headers: { "content-type": "application/xxx-octet-stream" }
})
.post(duckImage)
.res(res => res["buffer"]() as Buffer))
.compare(duckImage)
).toBe(0)
// Headers are set in the options argument of the http method
expect((
await wretch(`${_URL}/blob/roundTrip`)
.post(duckImage, {
headers: { "content-type":"application/xxx-octet-stream" }
})
.res(res => res["buffer"]() as Buffer)
).compare(duckImage)
).toBe(0)
})
it("should perform crud requests and parse an arrayBuffer response", async function () {
const test = arrayBuffer => {
const buffer = Buffer.alloc(arrayBuffer.byteLength)
const view = new Uint8Array(arrayBuffer)
for (let i = 0; i < buffer.length; ++i) {
buffer[i] = view[i]
}
expect(buffer.equals(Buffer.from([ 0x00, 0x01, 0x02, 0x03 ]))).toBe(true)
}
const init = wretch(`${_URL}/arrayBuffer`)
await allRoutes(init, "arrayBuffer", test)
await allRoutes(init, "arrayBuffer", test, {})
})
it("should perform a plain text round trip", async function () {
const text = "hello, server !"
const roundTrip = await wretch(`${_URL}/text/roundTrip`).content("text/plain").body(text).post().text()
expect(roundTrip).toBe(text)
// Using shorthand
const roundTrip2 = await wretch(`${_URL}/text/roundTrip`).content("text/plain").post(text).text()
expect(roundTrip2).toBe(text)
})
it("should perform a json round trip", async function () {
const jsonObject = { a: 1, b: 2, c: 3 }
const roundTrip = await wretch(`${_URL}/json/roundTrip`).json(jsonObject).post().json()
expect(roundTrip).toEqual(jsonObject)
// Using shorthand
const roundTrip2 = await wretch(`${_URL}/json/roundTrip`).post(jsonObject).json()
expect(roundTrip2).toEqual(jsonObject)
// Ensure that calling .json with the shorthand works
const roundTrip3 = await wretch(`${_URL}/json/roundTrip`).json({}).post(jsonObject).json()
expect(roundTrip3).toEqual(jsonObject)
// Ensure that it preserves any content type set previously
try {
await wretch(`${_URL}/json/roundTrip`).content("bad/content").post(jsonObject).json()
fail("should have thrown")
} catch(e) {}
// Ensure that the charset is preserved.
const headerWithCharset = "application/json; charset=utf-16"
expect(wretch().content(headerWithCharset).json({})._options.headers['Content-Type']).toBe(headerWithCharset)
})
it("should perform an url encoded form data round trip", async function () {
const reference = "a=1&b=2&%20c=%203&d=%7B%22a%22%3A1%7D&e=1%20&e=2"
const jsonObject = { "a": 1, "b": 2, " c": " 3", "d": { a: 1 }, "e": ["1 ", 2] }
let roundTrip = await wretch(`${_URL}/urlencoded/roundTrip`).formUrl(reference).post().text()
expect(roundTrip).toBe(reference)
roundTrip = await wretch(`${_URL}/urlencoded/roundTrip`).formUrl(jsonObject).post().text()
expect(roundTrip).toEqual(reference)
})
it("should send a FormData object", async function () {
// Test with a nested object with an excluded field.
let form : any = {
hello: "world",
duck: "Muscovy",
duckImage: fs.createReadStream(duckImagePath),
duckProperties: {
beak: {
color: "yellow"
},
nbOfLegs: 2,
nullProp: null
}
}
let decoded = await wretch(`${_URL}/formData/decode`)
.formData(form, ["duckImage"])
.post()
.json()
expect(decoded).toMatchObject({
hello: "world",
duck: "Muscovy",
duckImage: {
data: duckImage,
type: "Buffer"
},
"duckProperties[beak][color]": "yellow",
"duckProperties[nbOfLegs]": "2"
})
// Test with full nesting.
form = {
hello: "world",
nested: {
property: 1
}
}
decoded = await wretch(`${_URL}/formData/decode`)
.formData(form, true)
.post()
.json()
expect(decoded).toMatchObject({
hello: "world"
})
// Test without nesting.
form = {
hello: "world",
// Unfortunately, form-data has issues casting objects to strings.
// This means that we cannot test this properly for now…
// See: https://github.com/form-data/form-data/pull/362
// nested: {
// property: 1
// }
}
decoded = await wretch(`${_URL}/formData/decode`)
.formData(form)
.post()
.json()
expect(decoded).toMatchObject({
hello: "world"
})
// Test for arrays.
const f = { arr: [ 1, 2, 3 ]}
const d = await wretch(`${_URL}/formData/decode`).formData(f).post().json()
expect(d).toEqual({
// browser FormData output:
// "arr[]": [1, 2, 3]
// form-data package has an implementation which differs from the browser standard.
"arr[]": "3"
})
})
it("should perform OPTIONS and HEAD requests", async function () {
const optsRes = await wretch(_URL + "/options").opts().res()
const optsRes2 = await wretch(_URL + "/options").opts({}).res()
expect(optsRes.headers.get("Allow")).toBe("OPTIONS")
expect(optsRes2.headers.get("Allow")).toBe("OPTIONS")
const headRes = await wretch(_URL + "/json").head().res()
const headRes2 = await wretch(_URL + "/json").head({}).res()
expect(headRes.headers.get("content-type")).toBe("application/json")
expect(headRes2.headers.get("content-type")).toBe("application/json")
})
it("should preserve existing headers when undefined or null is passed to .headers()", async function () {
const headers = { "X-HELLO": "WORLD", "X-Y": "Z" }
let req = wretch().headers({ "X-HELLO": "WORLD" })
req = req.headers({ "X-Y": "Z" })
expect(req._options.headers).toEqual(headers)
req = req.headers(null)
expect(req._options.headers).toEqual(headers)
req = req.headers(undefined)
expect(req._options.headers).toEqual(headers)
})
it("should catch common error codes", async function () {
const w = wretch(_URL + "/")
let check = 0
await w.url("400").get().badRequest(_ => {
expect(_.message).toBe("error code : 400")
check++
}).text(_ => expect(_).toBeNull())
await w.url("401").get().unauthorized(_ => {
expect(_.message).toBe("error code : 401")
check++
}).text(_ => expect(_).toBeNull())
await w.url("403").get().forbidden(_ => {
expect(_.message).toBe("error code : 403")
check++
}).text(_ => expect(_).toBeNull())
await w.url("404").get().notFound(_ => {
expect(_.message).toBe("error code : 404")
check++
}).text(_ => expect(_).toBeNull())
await w.url("408").get().timeout(_ => {
expect(_.message).toBe("error code : 408")
check++
}).text(_ => expect(_).toBeNull())
await w.url("500").get().internalError(_ => {
expect(_.message).toBe("error code : 500")
check++
}).text(_ => expect(_).toBeNull())
expect(check).toBe(6)
})
it("should catch other error codes", async function () {
let check = 0
await wretch(`${_URL}/444`)
.get()
.notFound(_ => check++)
.error(444, _ => check++)
.unauthorized(_ => check++)
.fetchError(_ => check++)
.res(_ => expect(_).toBe(undefined))
expect(check).toBe(1)
wretch().polyfills({
fetch: () => Promise.reject("Error")
})
check = 0
await wretch(`${_URL}/444`)
.get()
.notFound(_ => check++)
.error(444, _ => check++)
.unauthorized(_ => check++)
.fetchError(_ => check--)
.res(_ => expect(_).toBe(undefined))
expect(check).toBe(-1)
})
it("should set and catch errors with global catchers", async function () {
wretch().polyfills({
fetch: fetchPolyfill()
})
let check = 0
const w = wretch(_URL)
.catcher(404, err => check++)
.catcher(500, err => check++)
.catcher(400, err => check++)
.catcher(401, err => check--)
.catcher("FetchError", err => check++)
// +1 : 1
await w.url("/text").get().res(_ => check++)
// +0 : 1
await w.url("/text").get().json(_ => check--)
// +1 : 2
await w.url("/400").get().res(_ => check--)
// +1 : 3
await w.url("/401").get().unauthorized(_ => check++).res(_ => check--)
// +1 : 4
await w.url("/404").get().res(_ => check--)
// +1 : 5
await w.url("/408").get().timeout(_ => check++).res(_ => check--)
// +1 : 6
await w.url("/418").get().res(_ => check--).catch(_ => "muted")
// +1: 7
await w.url("/500").get().res(_ => check--)
expect(check).toBe(7)
})
it("should capture the original request with resolvers/catchers", async function () {
let check = 0
const redirectedNotFound = await wretch(`${_URL}/404`)
.get()
.notFound((error, req) => {
check++
return req.url(`${_URL}/text`, true).get().text()
}).text()
expect(redirectedNotFound).toBe("A text string")
const withNotFoundCatcher = wretch(`${_URL}/401`)
.catcher(401, (err, req) => {
check++
return req.url(`${_URL}/text`, true).get().text()
})
const withNotFoundRedirect = wretch(`${_URL}/404`)
.resolve(resolver => resolver.notFound((err, req) => {
check++
return req.url(`${_URL}/text`, true).get().text()
}))
expect(await withNotFoundCatcher.get().text()).toBe("A text string")
expect(await withNotFoundRedirect.get().text()).toBe("A text string")
expect(check).toBe(3)
})
it("should set default fetch options", async function () {
let rejected = await new Promise(res => wretch(`${_URL}/customHeaders`).get().badRequest(_ => {
res(true)
}).res(result => res(!result)))
expect(rejected).toBeTruthy()
wretch().defaults({
headers: { "X-Custom-Header": "Anything" }
})
rejected = await new Promise(res => wretch(`${_URL}/customHeaders`).get().badRequest(_ => {
res(true)
}).res(result => res(!result)))
expect(rejected).toBeTruthy()
wretch().defaults({
headers: { "X-Custom-Header-2": "Anything" }
}, true)
rejected = await new Promise(res => wretch(`${_URL}/customHeaders`).get().badRequest(_ => {
res(true)
}).res(result => res(!result)))
wretch().defaults("not an object" as any, true)
expect(rejected).toBeTruthy()
const accepted = await new Promise(res => wretch(`${_URL}/customHeaders`)
.options({ headers: { "X-Custom-Header-3" : "Anything" }}, false)
.options({ headers: { "X-Custom-Header-4" : "Anything" }})
.get()
.badRequest(_ => { res(false) })
.res(result => res(!!result)))
expect(accepted).toBeTruthy()
})
it("should allow url, query parameters & options modifications and return a fresh new Wretcher object containing the change", async function () {
const obj1 = wretch("...")
const obj2 = obj1.url(_URL, true)
expect(obj1["_url"]).toBe("...")
expect(obj2["_url"]).toBe(_URL)
const obj3 = obj1.options({ headers: { "X-test": "test" }})
expect(obj3["_options"]).toEqual({ headers: { "X-test": "test" }})
expect(obj1["_options"]).toEqual({})
const obj4 = obj2.query({a: "1!", b: "2"})
expect(obj4["_url"]).toBe(`${_URL}?a=1%21&b=2`)
expect(obj2["_url"]).toBe(_URL)
const obj5 = obj4.query({c: 6, d: [7, 8]})
expect(obj4["_url"]).toBe(`${_URL}?a=1%21&b=2`)
expect(obj5["_url"]).toBe(`${_URL}?a=1%21&b=2&c=6&d=7&d=8`)
const obj6 = obj5.query("Literal[]=Query&String", true)
expect(obj5["_url"]).toBe(`${_URL}?a=1%21&b=2&c=6&d=7&d=8`)
expect(obj6["_url"]).toBe(`${_URL}?Literal[]=Query&String`)
const obj7 = obj5.query("Literal[]=Query&String").url("/test")
expect(obj5["_url"]).toBe(`${_URL}?a=1%21&b=2&c=6&d=7&d=8`)
expect(obj7["_url"]).toBe(`${_URL}/test?a=1%21&b=2&c=6&d=7&d=8&Literal[]=Query&String`)
})
it("should set the Accept header", async function () {
expect(await wretch(`${_URL}/accept`).get().text()).toBe("text")
expect(await wretch(`${_URL}/accept`).accept("application/json").get().json()).toEqual({ json: "ok" })
})
it("should set the Authorization header", async function () {
try { await wretch(_URL + "/basicauth")
.get()
.res(_ => fail("Authenticated route should not respond without credentials."))
} catch(e) {
expect(e.status).toBe(401)
}
const res = await wretch(_URL + "/basicauth")
.auth("Basic d3JldGNoOnJvY2tz")
.get()
.text()
expect(res).toBe("ok")
})
it("should change the parsing used in the default error handler", async function () {
await wretch(`${_URL}/json500`)
.get()
.internalError(error => { expect(error.text).toEqual(`{"error":500,"message":"ok"}`) })
.res(_ => fail("I should never be called because an error was thrown"))
.then(_ => expect(_).toBe(undefined))
wretch().errorType("json")
await wretch(`${_URL}/json500`)
.get()
.internalError(error => { expect(error.json).toEqual({ error: 500, message: "ok" }) })
.res(_ => fail("I should never be called because an error was thrown"))
.then(_ => expect(_).toBe(undefined))
// Change back
wretch().errorType("text")
})
it("should retrieve performance timings associated with a fetch request", function (done) {
wretch().polyfills({
fetch: fetchPolyfill(1)
})
// Test empty perfs()
wretch(`${_URL}/text`).get().perfs().res(_ => expect(_.ok).toBeTruthy()).then(_ => {
// Racing condition : observer triggered before response
wretch(`${_URL}/bla`).get().perfs(timings => {
expect(timings.name).toBe(`${_URL}/bla`)
expect(typeof timings.startTime).toBe("number")
// Racing condition : response triggered before observer
wretch().polyfills({
fetch: fetchPolyfill(1000)
})
wretch(`${_URL}/fakeurl`).get().perfs(timings => {
expect(timings.name).toBe(`${_URL}/fakeurl`)
expect(typeof timings.startTime).toBe("number")
wretch().polyfills({
fetch: fetchPolyfill(1)
})
done()
}).res().catch(() => "ignore")
}).res().catch(_ => "ignore")
})
// Test multiple requests concurrency and proper timings dispatching
for(let i = 0; i < 5; i++) {
wretch(`${_URL}/fake/${i}`).get().perfs(timings => {
expect(timings.name).toBe(`${_URL}/fake/${i}`)
}).res().catch(() => "ignore")
}
})
it("should abort a request", function (done) {
let count = 0
const handleError = error => {
expect(error.name).toBe("AbortError")
count++
}
const controller = new AbortController()
wretch(`${_URL}/longResult`)
.signal(controller)
.get()
.res()
.catch(handleError)
controller.abort()
const [c, w] = wretch(`${_URL}/longResult`).get().controller()
w.res().catch(handleError)
c.abort()
wretch(`${_URL}/longResult`)
.get()
.setTimeout(100)
.onAbort(handleError)
.res()
const [c2, w2] = wretch(`${_URL}/longResult`).get().controller()
w2.setTimeout(100, c2).onAbort(handleError).res()
setTimeout(() => {
expect(count).toBe(4)
done()
}, 1000)
})
it("should program resolvers", async function () {
let check = 0
const w = wretch()
.url(_URL)
.resolve(resolver => resolver
.unauthorized(_ => check--))
.resolve(resolver => resolver
.unauthorized(_ => check++), true)
.resolve(resolver => resolver
.perfs(_ => check++)
.json(_ => { check++; return _ }))
const result = await w.url("/json").get()
await new Promise(res => setTimeout(res, 100))
expect(result).toEqual({ a: "json", object: "which", is: "stringified" })
expect(check).toBe(2)
await w.url("/401").get()
await new Promise(res => setTimeout(res, 100))
expect(check).toBe(4)
})
it("should use middlewares", async function () {
const shortCircuit = () => next => (url, opts) => Promise.resolve({
ok: true,
text: () => Promise.resolve(opts.method + "@" + url)
} as any)
const setGetMethod = () => next => (url, opts) => {
return next(url, {...opts, method: "GET"})
}
const setPostMethod = () => next => (url, opts) => {
return next(url, {...opts, method: "POST"})
}
const w = wretch().middlewares([
shortCircuit()
])
expect(await w.url(_URL).head().text()).toBe(`HEAD@${_URL}`)
const w2 = w.middlewares([
setGetMethod(),
shortCircuit()
], true)
expect(await w2.url(_URL).head().text()).toBe(`GET@${_URL}`)
const w3 = w.middlewares([
setGetMethod(),
setPostMethod(),
shortCircuit()
], true)
expect(await w3.url(_URL).head().text()).toBe(`POST@${_URL}`)
})
it("should chain actions that will be performed just before the request is sent", async function () {
const w = wretch(_URL + "/basicauth")
.defer((w, url, opts) => {
expect(opts.method).toBe("GET")
expect(opts.q).toBe("a")
expect(url).toBe(_URL + "/basicauth")
return w.auth("toto")
})
.defer((w, url, { token }) => w.auth(token), true)
const result = await w
.options({ token: "Basic d3JldGNoOnJvY2tz" })
.get({ q: "a" })
.text()
expect(result).toBe("ok")
})
it("should replay a request with the same method", async function () {
const result = await wretch(_URL + "/basicauth")
.get()
.unauthorized((_, request) => {
return request
.auth("Basic d3JldGNoOnJvY2tz")
.replay()
.text()
})
.text()
expect(result).toBe("ok")
})
it("should handle falsey json", async function () {
expect(await wretch(`${_URL}/json/null`).get().json()).toEqual(null)
expect(await wretch(`${_URL}/json/null`).get().json(_ => true)).toEqual(true)
expect(await wretch(`${_URL}/json/null`).get().json(_ => false)).toEqual(false)
})
it("should not append an extra character (&/?) when trying to append or replace empty query params", function() {
const w = wretch(_URL)
expect(w.query("")._url).toBe(_URL)
expect(w.query("", true)._url).toBe(_URL)
expect(w.query("a=1").query("", true)._url).toBe(_URL)
expect(w.query({})._url).toBe(_URL)
expect(w.query({}, true)._url).toBe(_URL)
expect(w.query({a: 1}).query({}, true)._url).toBe(_URL)
})
})
describe("Mix", function () {
it("should mix two objects", function () {
const obj1 = { a: 1, b: 2, c: [ 3, 4 ] }
const obj2proto = { z: 1 }
const obj2 = Object.create(obj2proto)
Object.assign(obj2, { a: 0, d: 5, e: [6], c: [ 5, 6 ] })
expect(mix(obj1, obj2, false)).toEqual({ a: 0, b: 2, c: [ 5, 6 ], d: 5, e: [6] })
expect(mix(obj1, obj2, true)).toEqual({ a: 0, b: 2, c: [ 3, 4, 5, 6 ], d: 5, e: [6] })
})
}) | the_stack |
import { cloneDeep } from "lodash";
import sinon from "sinon";
import { pureMerge } from "coral-common/utils";
import { GQLResolver } from "coral-framework/schema";
import {
act,
createResolversStub,
CreateTestRendererParams,
findParentWithType,
replaceHistoryLocation,
toJSON,
wait,
waitForElement,
within,
} from "coral-framework/testHelpers";
import create from "../create";
import { settingsWithEmptyAuth, users } from "../fixtures";
beforeEach(async () => {
replaceHistoryLocation("http://localhost/admin/configure/auth");
});
const viewer = users.admins[0];
async function createTestRenderer(
params: CreateTestRendererParams<GQLResolver> = {}
) {
const { testRenderer, context } = create({
...params,
resolvers: pureMerge(
createResolversStub<GQLResolver>({
Query: {
settings: () => settingsWithEmptyAuth,
viewer: () => viewer,
},
}),
params.resolvers
),
initLocalState: (localRecord, source, environment) => {
if (params.initLocalState) {
params.initLocalState(localRecord, source, environment);
}
},
});
const configureContainer = await waitForElement(() =>
within(testRenderer.root).getByTestID("configure-container")
);
const authContainer = await waitForElement(() =>
within(configureContainer).getByTestID("configure-authContainer")
);
return { context, testRenderer, configureContainer, authContainer };
}
it("renders configure auth", async () => {
const { configureContainer } = await createTestRenderer();
expect(within(configureContainer).toJSON()).toMatchSnapshot();
});
it("rotate sso key", async () => {
const { testRenderer } = await createTestRenderer({
resolvers: createResolversStub<GQLResolver>({
Mutation: {
rotateSSOSigningSecret: () => {
return {
settings: pureMerge<typeof settingsWithEmptyAuth>(
settingsWithEmptyAuth,
{
auth: {
integrations: {
sso: {
enabled: true,
signingSecrets: [
{
kid: "kid-01",
secret: "secret",
createdAt: "2015-01-01T00:00:00.000Z",
lastUsedAt: "2016-01-01T01:45:00.000Z",
rotatedAt: "2016-01-01T01:45:00.000Z",
inactiveAt: "2016-01-01T01:45:00.000Z",
},
{
kid: "kid-02",
secret: "new-secret",
createdAt: "2019-01-01T01:45:00.000Z",
},
],
},
},
},
}
),
};
},
},
}),
});
const container = within(testRenderer.root).getByTestID("configure-auth-sso");
act(() => {
within(container).getByLabelText("Enabled").props.onChange({});
});
act(() => {
within(container)
.getByText("Rotate", { selector: "button" })
.props.onClick();
});
const rotateNow = await waitForElement(() => {
return within(container).getByText("Now", { selector: "button" });
});
act(() => {
rotateNow.props.onClick();
});
await wait(() => {
// Check that we have two SSO Keys that match
// our expected key IDs
const keyIDs = within(container).getAllByTestID("SSO-Key-ID");
const hasOldKey = keyIDs.some((k) => k.props.value === "kid-01");
const hasNewKey = keyIDs.some((k) => k.props.value === "kid-02");
expect(hasNewKey).toBe(true);
expect(hasOldKey).toBe(true);
const statuses = within(container).getAllByTestID("SSO-Key-Status");
expect(statuses.length).toBe(2);
const firstStatus: any = toJSON(statuses[0]);
const firstStatusIsActive = firstStatus.children.some(
(s: string) => s === "Active"
);
expect(firstStatusIsActive).toBe(true);
const secondStatus: any = toJSON(statuses[1]);
const secondStatusIsActive = secondStatus.children.some(
(s: string) => s === "Active"
);
expect(secondStatusIsActive).toBe(false);
});
});
it("prevents admin lock out", async () => {
const { testRenderer } = await createTestRenderer();
const container = within(testRenderer.root).getByTestID(
"configure-auth-local"
);
// Let's disable local auth.
act(() => {
within(container).getByLabelText("Enabled").props.onChange(false);
});
// Send form
await act(async () =>
findParentWithType(container, "form")!.props.onSubmit()
);
await waitForElement(() =>
within(testRenderer.root).getByText(
"Please enable at least one authentication integration",
{
exact: false,
}
)
);
});
it("prevents stream lock out", async () => {
let settingsRecord = cloneDeep(settingsWithEmptyAuth);
const { testRenderer } = await createTestRenderer({
resolvers: createResolversStub<GQLResolver>({
Mutation: {
updateSettings: ({ variables }) => {
expectAndFail(variables.settings.auth!.integrations!.local).toEqual({
enabled: true,
allowRegistration: true,
targetFilter: {
admin: true,
stream: false,
},
});
settingsRecord = pureMerge(settingsRecord, variables.settings);
return {
settings: settingsRecord,
};
},
},
}),
});
const origConfirm = window.confirm;
const stubContinue = sinon.stub().returns(true);
const stubCancel = sinon.stub().returns(false);
const container = within(testRenderer.root).getByTestID(
"configure-auth-local"
);
const streamTarget = within(container).getByLabelText("Comment Stream");
const form = findParentWithType(container, "form")!;
const saveChanges = within(testRenderer.root).getByText("Save Changes", {
selector: "button",
});
try {
window.confirm = stubCancel;
// Let's disable stream target in local auth.
act(() => streamTarget.props.onChange(false));
// Send form
await act(async () => await form.props.onSubmit());
// Submit button should not be disabled because we canceled the submit.
await wait(() => expect(saveChanges.props.disabled).toBe(false));
await wait(() => {
expect(stubCancel.calledOnce).toBe(true);
});
window.confirm = stubContinue;
// Send form
await act(async () => await form.props.onSubmit());
expect(stubContinue.calledOnce).toBe(true);
} finally {
window.confirm = origConfirm;
}
});
it("change settings", async () => {
const { testRenderer } = await createTestRenderer({
resolvers: createResolversStub<GQLResolver>({
Query: {
discoverOIDCConfiguration: ({ variables }) => {
expectAndFail(variables).toEqual({ issuer: "http://issuer.com" });
return {
issuer: "http://issuer.com",
tokenURL: "http://issuer.com/tokenURL",
jwksURI: "http://issuer.com/jwksURI",
authorizationURL: "http://issuer.com/authorizationURL",
};
},
},
Mutation: {
updateSettings: ({ variables, callCount }) => {
switch (callCount) {
case 0:
expectAndFail(
variables.settings.auth!.integrations!.facebook
).toEqual({
enabled: true,
allowRegistration: true,
targetFilter: {
admin: true,
stream: true,
},
clientID: "myClientID",
clientSecret: "myClientSecret",
});
return {
settings: pureMerge(settingsWithEmptyAuth, variables.settings),
};
default:
expectAndFail(
variables.settings.auth!.integrations!.oidc
).toEqual({
enabled: true,
allowRegistration: false,
targetFilter: {
admin: true,
stream: true,
},
name: "name",
clientID: "clientID",
clientSecret: "clientSecret",
issuer: "http://issuer.com",
jwksURI: "http://issuer.com/jwksURI",
authorizationURL: "http://issuer.com/authorizationURL",
tokenURL: "http://issuer.com/tokenURL",
});
return {
settings: pureMerge(settingsWithEmptyAuth, variables.settings),
};
}
},
},
}),
});
const facebookContainer = within(testRenderer.root).getByTestID(
"configure-auth-facebook-container"
);
const facebookEnabled = within(facebookContainer).getByLabelText("Enabled");
const oidcContainer = within(testRenderer.root).getByTestID(
"configure-auth-oidc-container"
);
const oidcEnabled = within(oidcContainer).getByLabelText("Enabled");
const form = findParentWithType(facebookContainer, "form")!;
const saveChanges = within(testRenderer.root).getByText("Save Changes", {
selector: "button",
});
// Let's change some facebook settings.
act(() => facebookEnabled.props.onChange({}));
act(() =>
within(facebookContainer)
.getByLabelText("Client ID", { exact: false })
.props.onChange("myClientID")
);
act(() =>
within(facebookContainer)
.getByLabelText("Client secret", { exact: false })
.props.onChange("myClientSecret")
);
// Send form
act(() => {
form.props.onSubmit();
});
// Submit button should be disabled.
expect(saveChanges.props.disabled).toBe(true);
// Disable other fields while submitting
// We are only testing for one here right now..
expect(facebookEnabled.props.disabled).toBe(true);
await act(async () => {
// When submitting finished, the fields become enabled again.
await wait(() => expect(facebookEnabled.props.disabled).toBe(false));
});
// Now let's enable oidc
act(() => oidcEnabled.props.onChange({}));
expect(() =>
within(oidcContainer).getAllByText("This field is required", {
exact: false,
})
).toThrow();
// Try to submit form, this will give validation error messages.
act(() => {
form.props.onSubmit();
});
within(oidcContainer).getAllByText("This field is required", {
exact: false,
});
// Fill form
act(() =>
within(oidcContainer)
.getByLabelText("Provider name", { exact: false })
.props.onChange("name")
);
act(() =>
within(oidcContainer)
.getByLabelText("Client ID", { exact: false })
.props.onChange("clientID")
);
act(() =>
within(oidcContainer)
.getByLabelText("Client secret", { exact: false })
.props.onChange("clientSecret")
);
act(() =>
within(oidcContainer)
.getByLabelText("Issuer", { exact: false })
.props.onChange("http://issuer.com")
);
// Discover the rest.
await act(
async () =>
await within(oidcContainer)
.getByText("Discover", { selector: "button" })
.props.onClick()
);
// Try to submit again, this should work now.
act(() => {
form.props.onSubmit();
});
// Submit button should be disabled.
expect(saveChanges.props.disabled).toBe(true);
// Disable other fields while submitting
// We are only testing for one here right now..
expect(oidcEnabled.props.disabled).toBe(true);
await act(async () => {
// When submitting finished, the fields become enabled again.
await wait(() => expect(oidcEnabled.props.disabled).toBe(false));
});
}); | the_stack |
import { newKit } from '@celo/contractkit'
import { extend, range } from 'lodash'
import { getHooks, sleep } from 'src/e2e-tests/utils'
import { privateKeyToPublicKey } from 'src/lib/generate_utils'
import { GethInstanceConfig } from 'src/lib/interfaces/geth-instance-config'
import { GethRunConfig } from 'src/lib/interfaces/geth-run-config'
import Web3 from 'web3'
import { Admin } from 'web3-eth-admin'
import yargs from 'yargs'
const Account: any = require('eth-lib/lib/account')
export const command = 'local-testnet'
export const describe = `Command to run a local testnet of geth instances.
Running this command will create a number of geth nodes, connect them together to form a network,
and run smart contract migrations to initialize the core protocols. When this is complete, it will
open a NodeJS console with some preloaded objects to facilitate interactions with the test network.
Exiting this console will kill all running geth instances and exit.
Examples:
* local-testnet
* local-testnet --local-geth ~/code/celo-blockchain
* local-testnet --validators 5 --proxies 3 --bootnode
* local-testnet --tx-nodes 2 --light-clients 3
* local-testnet --migrate-to 19 --migration-override '{ "lockedGold": { "unlockingPeriod": 30 } }'
* local-testnet --no-migrate --genesis-override '{ "blockTime": 3, "epoch": 50 }'
Network makeup is configured the --validators, --tx-nodes, --light-clients, and --lightest-client
flags. These flags will add the corresponding nodes to the network.
A NodeJS REPL is provided to conveniently interact with the created network. A number of global
variables are defined with useful values including {
Web3 (Imported 'web3' module)
Admin (Imported 'web3-eth-admin' module)
testnet: GethRunConfig (Configuration values for the tesnet)
[nodeType][index] (e.g. validator0, txNode2): {
web3: Web3 (A web3 object connected to the node over RPC)
kit: ContractKit (A contractkit object connected to the node over RPC)
admin: Admin (An Admin object connected to the node over RPC)
config: GethInstanceConfig (Configuration values for the node)
kill(signal?: string): (Send a signal, default SIGTERM, to the node. e.g. SIGINT, SIGSTOP)
}
}
Tip: Export NODE_OPTIONS="--experimental-repl-await" in your terminal to natively use await.
When the network is created without a bootnode, all nodes will be connected as follows:
* Proxy nodes are connected to their validators, other proxies and unproxied validators.
* Unproxied validator nodes are connected to all other proxies and unproxied validators.
* Transaction nodes are connected to proxies and unproxied validators and other transaction nodes.
* Light clients are connected to all transaction nodes.
If the network is started with the --bootnode flag, a bootnode will be created and all nodes will be
connected to it, rather than each other directly.
By default, the celo-blockchain repository will be cloned to a temporary location and built from
master to produce the geth binary to run for each node. The --branch flag can be used to control
which branch is built in the cloned repository. Alternatively, a existing repository can be used
by specifying the --local-geth flag as the path to that repository root.`
interface LocalTestnetArgs {
localgeth?: string
keepdata?: boolean
branch?: string
bootnode: boolean
validators: number
proxies: number
txnodes: number
lightclients: number
lightestclients: number
migrate: boolean
migrateTo: number
instances: string
genesisOverride: string
migrationOverride: string
}
export const builder = (argv: yargs.Argv) => {
return argv
.option('local-geth', {
type: 'string',
description: 'Local path to celo-blockchain repository.',
alias: ['localGeth', 'localgeth'],
})
.option('keep-data', {
type: 'boolean',
decription: 'Keep the data directory from any previous runs.',
alias: ['keepData', 'keepdata'],
})
.option('branch', {
type: 'string',
description: 'Branch name for remote celo-blockchain repository.',
})
.option('bootnode', {
type: 'boolean',
allowNo: true,
description: 'Create a bootnode and connect all nodes to it instead of to each other.',
})
.option('validators', {
type: 'number',
description: 'Number of validator nodes to create.',
default: 1,
})
.option('proxies', {
type: 'number',
description: 'Number of proxy nodes to create; assigned to the first n validators.',
default: 0,
})
.option('tx-nodes', {
type: 'number',
description: 'Number of transaction (i.e. non-validating full nodes) nodes to create.',
default: 0,
alias: ['txnodes', 'txNodes'],
})
.option('light-clients', {
type: 'number',
description: 'Number of light sync nodes to create.',
default: 0,
alias: ['lightClients', 'lightclients'],
})
.option('lightest-clients', {
type: 'number',
description: 'Number of lightest sync nodes to create.',
default: 0,
alias: ['lightestClients', 'lightestclients'],
})
.option('migrate', {
type: 'boolean',
description: 'Whether migrations should be run.',
default: true,
allowNo: true,
})
.option('migrate-to', {
type: 'number',
description: 'Maximum migration number to run. Defaults to running all migrations.',
alias: ['migrateTo', 'migrateto'],
})
.option('instances', {
type: 'string',
description: 'Manually enter a GethInstanceConfig[] json blob to add to the config.',
default: '[]',
})
.option('genesis-override', {
type: 'string',
description: 'Genesis configuration overrides as a GenesisConfig JSON blob.',
default: '{}',
alias: ['genesisOverride', 'genesisoverride'],
})
.option('migration-override', {
type: 'string',
description: 'Migration configuration overrides as a JSON blob.',
default: '{}',
alias: ['migrationOverride', 'migrationoverride'],
})
}
async function repl(config: GethRunConfig) {
const session = require('repl').start()
const formatName = (name: string) =>
name
.split('-')
.map((token, i) => (i === 0 ? token[0] : token[0].toUpperCase()) + token.slice(1))
.join('')
extend(session.context, {
Web3,
Admin,
testnet: config,
...config.instances.reduce(
(o, instance) => ({
...o,
[formatName(instance.name)]: {
web3: new Web3(getRpcUrl(instance)),
kit: newKit(getRpcUrl(instance)),
admin: new Admin(getRpcUrl(instance)),
config: instance,
kill: (signal?: string) => {
if (!instance.pid) {
throw new Error(`no pid registered for instance ${instance.name}`)
}
process.kill(instance.pid, signal)
},
},
}),
{}
),
})
// Wait for the REPL to exit.
let exited = false
const exitHandler = () => {
exited = true
}
session.on('exit', exitHandler)
while (!exited) {
await sleep(0.1)
}
session.removeListener('exit', exitHandler)
}
function bootnodeConfigs(count: number): GethInstanceConfig[] {
return range(count).map((i) => ({
name: `bootnode-${i}`,
lightserv: false,
syncmode: 'full',
nodekey: generatePrivateKey(),
port: 0,
}))
}
function validatorConfigs(count: number, proxyCount: number = 0): GethInstanceConfig[] {
const validators: GethInstanceConfig[] = range(count).map((i) => ({
name: `validator-${i}`,
validating: true,
syncmode: 'full',
isProxied: i < proxyCount,
proxy: i < proxyCount ? `proxy-${i}` : undefined,
proxyAllowPrivateIp: i < proxyCount ? true : undefined,
port: 0,
}))
const proxies: GethInstanceConfig[] = range(proxyCount).map((i) => ({
name: `proxy-${i}`,
syncmode: 'full',
isProxy: true,
port: 0,
}))
return validators.concat(proxies)
}
function txNodeConfigs(count: number): GethInstanceConfig[] {
return range(count).map((i) => ({
name: `tx-node-${i}`,
lightserv: true,
syncmode: 'full',
port: 0,
}))
}
function lightClientConfigs(count: number): GethInstanceConfig[] {
return range(count).map((i) => ({
name: `light-client-${i}`,
syncmode: 'light',
port: 0,
}))
}
function lightestClientConfigs(count: number): GethInstanceConfig[] {
return range(count).map((i) => ({
name: `lightest-client-${i}`,
syncmode: 'lightest',
port: 0,
}))
}
// Populate network information in instance configs.
function populateConnectionInfo(configs: GethInstanceConfig[]): GethInstanceConfig[] {
// Choose ports for each instance.
for (const [i, config] of configs.entries()) {
if (!config.port) {
config.port = 30303 + 2 * i
}
if (config.isProxy && !config.proxyport) {
config.proxyport = 30503 + 2 * i
}
if (!config.rpcport && !config.wsport) {
config.rpcport = 8545 + 2 * i
config.wsport = 8546 + 2 * i
}
}
// If a bootnode is provided, populate bootnode information in other nodes.
const bootnodes = configs.filter((config) => /bootnode/.test(config.name))
if (bootnodes.length > 0) {
// Only one in-use bootnode is supported.
const bootnode = bootnodes[0]
for (const config of configs) {
if (config.name === bootnode.name || config.isProxied) {
continue
}
config.bootnodeEnode = getEnodeUrl(bootnode)
}
}
return configs
}
function getEnodeUrl(config: GethInstanceConfig) {
if (!config.nodekey) {
throw new Error('cannot get the enode url from a config without a nodekey')
}
return `enode://${privateKeyToPublicKey(config.nodekey)}@localhost:${config.port}`
}
function generatePrivateKey() {
return Account.create(Web3.utils.randomHex(32)).privateKey.replace('0x', '')
}
function getRpcUrl(config: GethInstanceConfig) {
return `${config.wsport ? 'ws' : 'http'}://localhost:${config.wsport || config.rpcport}`
}
function getAdmin(config: GethInstanceConfig) {
if (!config.wsport && !config.rpcport) {
throw new Error('connot connect to admin interface for config without port')
}
return new Admin(getRpcUrl(config))
}
async function getEnode(config: GethInstanceConfig) {
const admin = getAdmin(config)
return (await admin.getNodeInfo()).enode
}
async function connectToEnodes(config: GethInstanceConfig, enodes: string[]) {
const admin = getAdmin(config)
await Promise.all(enodes.map((enode) => admin.addPeer(enode)))
}
async function connectNodes(configs: GethInstanceConfig[]) {
// Connect tx nodes to validators and other tx nodes.
const validators = configs.filter(
(config) => (config.validating && !config.isProxied) || config.isProxy
)
const validatorEnodes = await Promise.all(validators.map(getEnode))
const txNodes = configs.filter((config) => !config.validating && config.syncmode === 'full')
const txNodeEnodes = await Promise.all(txNodes.map(getEnode))
await Promise.all(
txNodes.map((txNode) => connectToEnodes(txNode, validatorEnodes.concat(txNodeEnodes)))
)
// Connect light clients to tx nodes.
const lightClients = configs.filter((config) => ['light', 'lightest'].includes(config.syncmode))
if (lightClients.length > 0 && txNodeEnodes.length === 0) {
throw new Error('connecting light clients to the network requires at least one tx-node')
}
await Promise.all(lightClients.map((lightClient) => connectToEnodes(lightClient, txNodeEnodes)))
}
export const handler = async (argv: LocalTestnetArgs) => {
const repoPath = argv.localgeth || '/tmp/geth'
const gethConfig: GethRunConfig = {
network: 'local',
networkId: 1101,
runPath: '/tmp/e2e',
keepData: argv.keepdata,
migrate: argv.migrate,
migrateTo: argv.migrate ? argv.migrateTo : undefined,
instances: populateConnectionInfo([
...validatorConfigs(argv.validators, argv.proxies),
...txNodeConfigs(argv.txnodes),
...lightClientConfigs(argv.lightclients),
...lightestClientConfigs(argv.lightestclients),
...bootnodeConfigs(argv.bootnode ? 1 : 0),
...JSON.parse(argv.instances),
]),
repository: {
path: repoPath,
branch: argv.branch,
remote: !argv.localgeth,
},
genesisConfig: JSON.parse(argv.genesisOverride),
migrationOverrides: JSON.parse(argv.migrationOverride),
}
const hooks = getHooks(gethConfig)
await hooks.initialize()
if (!argv.bootnode) {
await connectNodes(gethConfig.instances)
}
console.info(`Local testnet is online with ${gethConfig.instances.length} nodes:`)
for (const instance of gethConfig.instances) {
console.info(
` * ${instance.name} (pid:${instance.pid}) is listening on ${getRpcUrl(instance)}`
)
}
console.info('\nPress CTRL+D to quit')
await repl(gethConfig)
await hooks.after()
process.exit(0)
} | the_stack |
import { logger } from './local-logging';
import {
getOpenShiftInfoForProject,
getOpenShiftInfoForEnvironment,
getDeployTargetConfigsForProject,
getEnvironmentByName,
getEnvironmentsForProject
} from './api';
import {
getControllerBuildData,
sendToLagoonTasks
} from './tasks';
class NoNeedToDeployBranch extends Error {
constructor(message) {
super(message);
this.name = 'NoNeedToDeployBranch';
}
}
class UnknownActiveSystem extends Error {
constructor(message) {
super(message);
this.name = 'UnknownActiveSystem';
}
}
/*
this function handles deploying a branch
*/
const deployBranch = async function(data: any) {
const {
projectId,
projectName,
branchName,
project,
deployData,
deployTarget,
} = data;
let branchesRegex = deployTarget.branches
switch (branchesRegex) {
case undefined:
case null:
logger.debug(
`projectName: ${projectName}, branchName: ${branchName}, no branches defined in active system, assuming we want all of them`
);
switch (project.activeSystemsDeploy) {
case 'lagoon_controllerBuildDeploy':
deployData.deployTarget = deployTarget
const buildDeployData = await getControllerBuildData(deployData);
const sendTasks = await sendToLagoonTasks(buildDeployData.spec.project.deployTarget+':builddeploy', buildDeployData);
return true
default:
throw new UnknownActiveSystem(
`Unknown active system '${project.activeSystemsDeploy}' for task 'deploy' in for project ${projectName}`
);
}
case 'true':
logger.debug(
`projectName: ${projectName}, branchName: ${branchName}, all branches active, therefore deploying`
);
switch (project.activeSystemsDeploy) {
case 'lagoon_controllerBuildDeploy':
deployData.deployTarget = deployTarget
const buildDeployData = await getControllerBuildData(deployData);
const sendTasks = await sendToLagoonTasks(buildDeployData.spec.project.deployTarget+':builddeploy', buildDeployData);
return true
default:
throw new UnknownActiveSystem(
`Unknown active system '${project.activeSystemsDeploy}' for task 'deploy' in for project ${projectName}`
);
}
case 'false':
logger.debug(
`projectName: ${projectName}, branchName: ${branchName}, branch deployments disabled`
);
return false
default: {
logger.debug(
`projectName: ${projectName}, branchName: ${branchName}, regex ${branchesRegex}, testing if it matches`
);
const branchRegex = new RegExp(branchesRegex);
if (branchRegex.test(branchName)) {
logger.debug(
`projectName: ${projectName}, branchName: ${branchName}, regex ${branchesRegex} matched branchname, starting deploy`
);
switch (project.activeSystemsDeploy) {
case 'lagoon_controllerBuildDeploy':
// controllers uses a different message than the other services, so we need to source it here
deployData.deployTarget = deployTarget
const buildDeployData = await getControllerBuildData(deployData);
const sendTasks = await sendToLagoonTasks(buildDeployData.spec.project.deployTarget+':builddeploy', buildDeployData);
return true
default:
throw new UnknownActiveSystem(
`Unknown active system '${project.activeSystemsDeploy}' for task 'deploy' in for project ${projectName}`
);
}
}
logger.debug(
`projectName: ${projectName}, branchName: ${branchName}, regex ${branchesRegex} did not match branchname, not deploying`
);
return false
}
}
}
/*
this function handles deploying a pullrequest
*/
const deployPullrequest = async function(data: any) {
const {
projectId,
projectName,
branchName,
project,
deployData,
pullrequestTitle,
deployTarget,
} = data;
let pullrequestRegex = deployTarget.pullrequests
switch (pullrequestRegex) {
case undefined:
case null:
logger.debug(
`projectName: ${projectName}, pullrequest: ${branchName}, no pullrequest defined in active system, assuming we want all of them`
);
switch (project.activeSystemsDeploy) {
case 'lagoon_controllerBuildDeploy':
deployData.deployTarget = deployTarget
const buildDeployData = await getControllerBuildData(deployData);
const sendTasks = await sendToLagoonTasks(buildDeployData.spec.project.deployTarget+':builddeploy', buildDeployData);
return true
default:
throw new UnknownActiveSystem(
`Unknown active system '${project.activeSystemsDeploy}' for task 'deploy' in for project ${projectName}`
);
}
case 'true':
logger.debug(
`projectName: ${projectName}, pullrequest: ${branchName}, all pullrequest active, therefore deploying`
);
switch (project.activeSystemsDeploy) {
case 'lagoon_controllerBuildDeploy':
deployData.deployTarget = deployTarget
const buildDeployData = await getControllerBuildData(deployData);
const sendTasks = await sendToLagoonTasks(buildDeployData.spec.project.deployTarget+':builddeploy', buildDeployData);
return true
default:
throw new UnknownActiveSystem(
`Unknown active system '${project.activeSystemsDeploy}' for task 'deploy' in for project ${projectName}`
);
}
case 'false':
logger.debug(
`projectName: ${projectName}, pullrequest: ${branchName}, pullrequest deployments disabled`
);
return false
default: {
logger.debug(
`projectName: ${projectName}, pullrequest: ${branchName}, regex ${pullrequestRegex}, testing if it matches PR title '${pullrequestTitle}'`
);
const branchRegex = new RegExp(pullrequestRegex);
if (branchRegex.test(pullrequestTitle)) {
logger.debug(
`projectName: ${projectName}, pullrequest: ${branchName}, regex ${pullrequestRegex} matched PR title '${pullrequestTitle}', starting deploy`
);
switch (project.activeSystemsDeploy) {
case 'lagoon_controllerBuildDeploy':
// controllers uses a different message than the other services, so we need to source it here
deployData.deployTarget = deployTarget
const buildDeployData = await getControllerBuildData(deployData);
const sendTasks = await sendToLagoonTasks(buildDeployData.spec.project.deployTarget+':builddeploy', buildDeployData);
return true
default:
throw new UnknownActiveSystem(
`Unknown active system '${project.activeSystemsDeploy}' for task 'deploy' in for project ${projectName}`
);
}
}
logger.debug(
`projectName: ${projectName}, branchName: ${branchName}, regex ${pullrequestRegex} did not match PR title, not deploying`
);
return false
}
}
}
/*
this is the primary function that handles checking the existing `openshift` configured for a deployed branch
it will check if the environment is already deployed, and if so will consume the openshift that it contains
otherwise it will check if there are deploytargetconfigs defined and use those (and only those)
if there are no deploytargetconfigs defined, then it will use what is defined in the project
*/
export const deployTargetBranches = async function(data: any) {
const {
projectId,
projectName,
branchName,
project,
deployData
} = data;
let deployTarget
// see if the environment has already been created/deployed and get the openshift and projectpattern out of it
try {
const apiEnvironment = await getEnvironmentByName(branchName, projectId, false);
let envId = apiEnvironment.environmentByName.id
const environmentOpenshift = await getOpenShiftInfoForEnvironment(envId);
deployTarget = {
openshiftProjectPattern: environmentOpenshift.environment.openshiftProjectPattern,
branches: branchName,
openshift: environmentOpenshift.environment.openshift
}
} catch (err) {
//do nothing if there is an error, likely means that the environment hasn't been deployed before
}
// check if this is an active/standby deployment
const activeStandby = await checkActiveStandbyDeployTarget(data)
if (deployTarget && activeStandby) {
if (deployTarget.openshift.id === activeStandby.environment.openshift.id) {
// if the deployed environment matches the opposite active/standby environment target
// then we allow the deployment to continue
// logger.debug(`TODO: THEY MATCH ${deployTarget.openshift.id} - ${activeStandby.environment.openshift.id}`)
} else {
// but if the deployed environment is on a different target
// we cannot allow the deployment to proceed as active/standby is not cross cluster compatable at the moment
throw new NoNeedToDeployBranch(
// @TODO: if active/standby ever supports different targets, then this error can probably be removed
`the two environments would be deployed to different targets, active/standby does not currently support this`
);
}
}
// if there is an openshift attached to the environment, then deploy deploy the environment using this deploytarget
if (deployTarget) {
data.deployTarget = deployTarget
let deploy = await deployBranch(data)
// EXISTING DEPLOY VIA ENVIRONMENT OPENSHIFT
return deploy
}
// otherwise this is probably the first time the environment is being deployed
// check if there are any deploytarget configs defined for this project
const deployTargetConfigs = await getDeployTargetConfigsForProject(projectId)
let deploy = false
if (deployTargetConfigs.targets.length > 0) {
// if there are any deploytarget configs, check through them
for (let i = 0; i < deployTargetConfigs.targets.length; i++) {
deployTarget = {
openshiftProjectPattern: deployTargetConfigs.targets[i].deployTargetProjectPattern,
branches: deployTargetConfigs.targets[i].branches,
// since deploytarget configs reference a deploytarget instead of an openshift, convert that here to be what it needs to be
openshift: deployTargetConfigs.targets[i].deployTarget
}
data.deployTarget = deployTarget
// NEW DEPLOY VIA DEPLOYTARGETCONFIG OPENSHIFT
deploy = await deployBranch(data)
if (deploy) {
// if the deploy is successful, then return
return deploy
}
}
if (deploy == false) {
throw new NoNeedToDeployBranch(
`configured regex for all deploytargets does not match branchname '${branchName}'`
);
}
} else {
// deploy the project using the projects default target
let deployTarget
try {
const projectOpenshift = await getOpenShiftInfoForProject(projectName);
deployTarget = {
openshiftProjectPattern: projectOpenshift.project.openshiftProjectPattern,
branches: projectOpenshift.project.branches,
openshift: projectOpenshift.project.openshift
}
} catch (err) {
//do nothing if there is an error, likely means that the environment hasn't been deployed before
}
data.deployTarget = deployTarget
let deploy = await deployBranch(data)
// NEW DEPLOY VIA PROJECT OPENSHIFT
return deploy
}
throw new NoNeedToDeployBranch(
`no deploy targets configured`
);
}
/*
this is the primary function that handles checking the existing `openshift` configured for a deployed branch
it will check if the environment is already deployed, and if so will consume the openshift that it contains
otherwise it will check if there are deploytargetconfigs defined and use those (and only those)
if there are no deploytargetconfigs defined, then it will use what is defined in the project
*/
export const deployTargetPullrequest = async function(data: any) {
const {
projectId,
projectName,
branchName,
project,
deployData
} = data;
let deployTarget
// see if the environment has already been created/deployed and get the openshift and projectpattern out of it
try {
const apiEnvironment = await getEnvironmentByName(branchName, projectId, false);
let envId = apiEnvironment.environmentByName.id
const environmentOpenshift = await getOpenShiftInfoForEnvironment(envId);
deployTarget = {
openshiftProjectPattern: environmentOpenshift.environment.openshiftProjectPattern,
/*
this `pullrequests: branchName,` breaks deploying an existing environment as it makes the pullrequest
attempt to do a regex check that fails. so just don't do it, the environment already exists so
just don't set pullrequests so it sends as a null value and just deploys the environment again without
testing any regex
// pullrequests: branchName,
*/
openshift: environmentOpenshift.environment.openshift
}
} catch (err) {
//do nothing if there is an error, likely means that the environment hasn't been deployed before
}
// if there is an openshift attached to the environment, then deploy deploy the environment using this deploytarget
if (deployTarget) {
data.deployTarget = deployTarget
let deploy = await deployPullrequest(data)
// EXISTING DEPLOY VIA ENVIRONMENT OPENSHIFT
return deploy
}
// otherwise this is probably the first time the environment is being deployed
// check if there are any deploytarget configs defined for this project
const deployTargetConfigs = await getDeployTargetConfigsForProject(projectId)
let deploy = false
if (deployTargetConfigs.targets.length > 0) {
// if there are any deploytarget configs, check through them
for (let i = 0; i < deployTargetConfigs.targets.length; i++) {
deployTarget = {
openshiftProjectPattern: deployTargetConfigs.targets[i].deployTargetProjectPattern,
pullrequests: deployTargetConfigs.targets[i].pullrequests,
// since deploytarget configs reference a deploytarget instead of an openshift, convert that here to be what it needs to be
openshift: deployTargetConfigs.targets[i].deployTarget
}
data.deployTarget = deployTarget
// NEW DEPLOY VIA DEPLOYTARGETCONFIG OPENSHIFT
deploy = await deployPullrequest(data)
if (deploy) {
// if the deploy is successful, then return
return deploy
}
}
if (deploy == false) {
throw new NoNeedToDeployBranch(
`configured regex for all deploytargets does not match pullrequest '${branchName}'`
);
}
} else {
// deploy the project using the projects default target
let deployTarget
try {
const projectOpenshift = await getOpenShiftInfoForProject(projectName);
deployTarget = {
openshiftProjectPattern: projectOpenshift.project.openshiftProjectPattern,
pullrequests: projectOpenshift.project.pullrequests,
openshift: projectOpenshift.project.openshift
}
} catch (err) {
//do nothing if there is an error, likely means that the environment hasn't been deployed before
}
data.deployTarget = deployTarget
let deploy = await deployPullrequest(data)
// NEW DEPLOY VIA PROJECT OPENSHIFT
return deploy
}
throw new NoNeedToDeployBranch(
`no deploy targets configured`
);
}
/*
this is the primary function that handles checking the existing `openshift` configured for a deployed promote
*/
export const deployTargetPromote = async function(data: any) {
const {
projectId,
promoteData
} = data;
let deployTarget
const projectOpenshift = await getOpenShiftInfoForProject(promoteData.projectName)
deployTarget = {
openshiftProjectPattern: projectOpenshift.project.openshiftProjectPattern,
branches: projectOpenshift.project.branches,
openshift: projectOpenshift.project.openshift
}
const deployTargetConfigs = await getDeployTargetConfigsForProject(projectId)
if (deployTargetConfigs.targets.length > 0) {
const promoteSourceEnvOpenshift = await checkPromoteEnvironment(promoteData)
if (promoteSourceEnvOpenshift) {
deployTarget = {
openshiftProjectPattern: promoteSourceEnvOpenshift.environment.openshiftProjectPattern,
branches: promoteSourceEnvOpenshift.environment.branches,
openshift: promoteSourceEnvOpenshift.environment.openshift
}
} else {
throw new NoNeedToDeployBranch(
`There is no existing environment to promote from that contains a valid deploytarget`
);
}
}
promoteData.deployTarget = deployTarget
const buildDeployData = await getControllerBuildData(promoteData);
const sendTasks = await sendToLagoonTasks(buildDeployData.spec.project.deployTarget+':builddeploy', buildDeployData);
return true
}
/*
this is the primary function that handles checking the existing `openshift` configured for an active/standby deployed environment
the main features are to check if a production or standby production environment are already deployed, and to return the data for those particular
environments
this information is used in the `deployTargetBranches` function to return an error to the user if they attempt to deploy either the production or standbyproduction
environment to different clusters than each other
*/
export const checkActiveStandbyDeployTarget = async function(data: any) {
const {
projectId,
projectName,
branchName,
project,
deployData
} = data;
let result
const environments = await getEnvironmentsForProject(projectName);
logger.info(`FOUND ${environments.project.standbyProductionEnvironment} ${branchName}`)
if (environments.project.standbyProductionEnvironment === branchName) {
// this is the standby environment being deployed
// Check to ensure the environment actually exists.
let environmentId = 0;
let foundEnvironment = false;
environments.project.environments.forEach(function(
environment,
index
) {
// check that the production environment exists
if (environment.name === environments.project.productionEnvironment) {
foundEnvironment = true;
environmentId = environment.id;
}
});
if (foundEnvironment) {
logger.info(`FOUND ${environmentId}`)
// if the production environment exists, then check which openshift it has been deployed to
result = await getOpenShiftInfoForEnvironment(environmentId);
}
}
if (environments.project.productionEnvironment === branchName) {
// this is the standby environment being deployed
// Check to ensure the environment actually exists.
let environmentId = 0;
let foundEnvironment = false;
environments.project.environments.forEach(function(
environment,
index
) {
// check that the production environment exists
if (environment.name === environments.project.standbyProductionEnvironment) {
foundEnvironment = true;
environmentId = environment.id;
}
});
if (foundEnvironment) {
logger.info(`FOUND ${environmentId}`)
// if the production environment exists, then check which openshift it has been deployed to
result = await getOpenShiftInfoForEnvironment(environmentId);
}
}
return result
}
/*
this is the primary function that handles checking the existing `openshift` configured for a promoted environment
currently promoted environments can only be promoted on the same cluster as the environment it is being promoted from
*/
export const checkPromoteEnvironment = async function(data: any) {
const {
projectId,
projectName,
branchName,
project,
promoteSourceEnvironment,
deployData
} = data;
let result
const environments = await getEnvironmentsForProject(projectName);
logger.info(`PROMOTE SOURCE ${promoteSourceEnvironment}`)
// check the sourceenvironment exists and get the openshift info for it
let environmentId = 0;
let foundEnvironment = false;
environments.project.environments.forEach(function(
environment,
index
) {
// check that the production environment exists
if (environment.name === promoteSourceEnvironment) {
foundEnvironment = true;
environmentId = environment.id;
}
});
if (foundEnvironment) {
logger.info(`FOUND ${environmentId}`)
// if the production environment exists, then check which openshift it has been deployed to
result = await getOpenShiftInfoForEnvironment(environmentId);
}
return result
} | the_stack |
import { BaseResource } from 'ms-rest-azure';
import { CloudError } from 'ms-rest-azure';
import * as moment from 'moment';
export { BaseResource } from 'ms-rest-azure';
export { CloudError } from 'ms-rest-azure';
/**
* @class
* Initializes a new instance of the JobStatisticsVertexStage class.
* @constructor
* The Data Lake Analytics job statistics vertex stage information.
*
* @member {number} [dataRead] the amount of data read, in bytes.
* @member {number} [dataReadCrossPod] the amount of data read across multiple
* pods, in bytes.
* @member {number} [dataReadIntraPod] the amount of data read in one pod, in
* bytes.
* @member {number} [dataToRead] the amount of data remaining to be read, in
* bytes.
* @member {number} [dataWritten] the amount of data written, in bytes.
* @member {number} [duplicateDiscardCount] the number of duplicates that were
* discarded.
* @member {number} [failedCount] the number of failures that occured in this
* stage.
* @member {number} [maxVertexDataRead] the maximum amount of data read in a
* single vertex, in bytes.
* @member {number} [minVertexDataRead] the minimum amount of data read in a
* single vertex, in bytes.
* @member {number} [readFailureCount] the number of read failures in this
* stage.
* @member {number} [revocationCount] the number of vertices that were revoked
* during this stage.
* @member {number} [runningCount] the number of currently running vertices in
* this stage.
* @member {number} [scheduledCount] the number of currently scheduled vertices
* in this stage
* @member {string} [stageName] the name of this stage in job execution.
* @member {number} [succeededCount] the number of vertices that succeeded in
* this stage.
* @member {number} [tempDataWritten] the amount of temporary data written, in
* bytes.
* @member {number} [totalCount] the total vertex count for this stage.
* @member {moment.duration} [totalFailedTime] the amount of time that failed
* vertices took up in this stage.
* @member {number} [totalProgress] the current progress of this stage, as a
* percentage.
* @member {moment.duration} [totalSucceededTime] the amount of time all
* successful vertices took in this stage.
*/
export interface JobStatisticsVertexStage {
readonly dataRead?: number;
readonly dataReadCrossPod?: number;
readonly dataReadIntraPod?: number;
readonly dataToRead?: number;
readonly dataWritten?: number;
readonly duplicateDiscardCount?: number;
readonly failedCount?: number;
readonly maxVertexDataRead?: number;
readonly minVertexDataRead?: number;
readonly readFailureCount?: number;
readonly revocationCount?: number;
readonly runningCount?: number;
readonly scheduledCount?: number;
readonly stageName?: string;
readonly succeededCount?: number;
readonly tempDataWritten?: number;
readonly totalCount?: number;
readonly totalFailedTime?: moment.Duration;
readonly totalProgress?: number;
readonly totalSucceededTime?: moment.Duration;
}
/**
* @class
* Initializes a new instance of the JobStatistics class.
* @constructor
* The Data Lake Analytics job execution statistics.
*
* @member {date} [lastUpdateTimeUtc] the last update time for the statistics.
* @member {date} [finalizingTimeUtc] the job finalizing start time.
* @member {array} [stages] the list of stages for the job.
*/
export interface JobStatistics {
readonly lastUpdateTimeUtc?: Date;
readonly finalizingTimeUtc?: Date;
readonly stages?: JobStatisticsVertexStage[];
}
/**
* @class
* Initializes a new instance of the JobDataPath class.
* @constructor
* A Data Lake Analytics job data path item.
*
* @member {uuid} [jobId] the id of the job this data is for.
* @member {string} [command] the command that this job data relates to.
* @member {array} [paths] the list of paths to all of the job data.
*/
export interface JobDataPath {
readonly jobId?: string;
readonly command?: string;
readonly paths?: string[];
}
/**
* @class
* Initializes a new instance of the JobStateAuditRecord class.
* @constructor
* The Data Lake Analytics job state audit records for tracking the lifecycle
* of a job.
*
* @member {string} [newState] the new state the job is in.
* @member {date} [timeStamp] the time stamp that the state change took place.
* @member {string} [requestedByUser] the user who requests the change.
* @member {string} [details] the details of the audit log.
*/
export interface JobStateAuditRecord {
readonly newState?: string;
readonly timeStamp?: Date;
readonly requestedByUser?: string;
readonly details?: string;
}
/**
* @class
* Initializes a new instance of the JobResource class.
* @constructor
* The Data Lake Analytics job resources.
*
* @member {string} [name] the name of the resource.
* @member {string} [resourcePath] the path to the resource.
* @member {string} [type] the job resource type. Possible values include:
* 'VertexResource', 'JobManagerResource', 'StatisticsResource',
* 'VertexResourceInUserFolder', 'JobManagerResourceInUserFolder',
* 'StatisticsResourceInUserFolder'
*/
export interface JobResource {
name?: string;
resourcePath?: string;
type?: string;
}
/**
* @class
* Initializes a new instance of the Diagnostics class.
* @constructor
* Error diagnostic information for failed jobs.
*
* @member {number} [columnNumber] the column where the error occured.
* @member {number} [end] the ending index of the error.
* @member {number} [lineNumber] the line number the error occured on.
* @member {string} [message] the error message.
* @member {string} [severity] the severity of the error. Possible values
* include: 'Warning', 'Error', 'Info', 'SevereWarning', 'Deprecated',
* 'UserWarning'
* @member {number} [start] the starting index of the error.
*/
export interface Diagnostics {
readonly columnNumber?: number;
readonly end?: number;
readonly lineNumber?: number;
readonly message?: string;
readonly severity?: string;
readonly start?: number;
}
/**
* @class
* Initializes a new instance of the JobProperties class.
* @constructor
* The common Data Lake Analytics job properties.
*
* @member {string} [runtimeVersion] the runtime version of the Data Lake
* Analytics engine to use for the specific type of job being run.
* @member {string} script the script to run. Please note that the maximum
* script size is 3 MB.
* @member {string} type Polymorphic Discriminator
*/
export interface JobProperties {
runtimeVersion?: string;
script: string;
type: string;
}
/**
* @class
* Initializes a new instance of the USqlJobProperties class.
* @constructor
* U-SQL job properties used when retrieving U-SQL jobs.
*
* @member {array} [resources] the list of resources that are required by the
* job
* @member {object} [statistics] the job specific statistics.
* @member {date} [statistics.lastUpdateTimeUtc] the last update time for the
* statistics.
* @member {date} [statistics.finalizingTimeUtc] the job finalizing start time.
* @member {array} [statistics.stages] the list of stages for the job.
* @member {object} [debugData] the job specific debug data locations.
* @member {uuid} [debugData.jobId] the id of the job this data is for.
* @member {string} [debugData.command] the command that this job data relates
* to.
* @member {array} [debugData.paths] the list of paths to all of the job data.
* @member {array} [diagnostics] the diagnostics for the job.
* @member {string} [algebraFilePath] the algebra file path after the job has
* completed
* @member {moment.duration} [totalCompilationTime] the total time this job
* spent compiling. This value should not be set by the user and will be
* ignored if it is.
* @member {moment.duration} [totalPauseTime] the total time this job spent
* paused. This value should not be set by the user and will be ignored if it
* is.
* @member {moment.duration} [totalQueuedTime] the total time this job spent
* queued. This value should not be set by the user and will be ignored if it
* is.
* @member {moment.duration} [totalRunningTime] the total time this job spent
* executing. This value should not be set by the user and will be ignored if
* it is.
* @member {string} [rootProcessNodeId] the ID used to identify the job manager
* coordinating job execution. This value should not be set by the user and
* will be ignored if it is.
* @member {string} [yarnApplicationId] the ID used to identify the yarn
* application executing the job. This value should not be set by the user and
* will be ignored if it is.
* @member {number} [yarnApplicationTimeStamp] the timestamp (in ticks) for the
* yarn application executing the job. This value should not be set by the user
* and will be ignored if it is.
* @member {string} [compileMode] the specific compilation mode for the job
* used during execution. If this is not specified during submission, the
* server will determine the optimal compilation mode. Possible values include:
* 'Semantic', 'Full', 'SingleBox'
*/
export interface USqlJobProperties extends JobProperties {
readonly resources?: JobResource[];
statistics?: JobStatistics;
debugData?: JobDataPath;
readonly diagnostics?: Diagnostics[];
readonly algebraFilePath?: string;
readonly totalCompilationTime?: moment.Duration;
readonly totalPauseTime?: moment.Duration;
readonly totalQueuedTime?: moment.Duration;
readonly totalRunningTime?: moment.Duration;
readonly rootProcessNodeId?: string;
readonly yarnApplicationId?: string;
readonly yarnApplicationTimeStamp?: number;
readonly compileMode?: string;
}
/**
* @class
* Initializes a new instance of the HiveJobProperties class.
* @constructor
* Hive job properties used when retrieving Hive jobs.
*
* @member {string} [logsLocation] the Hive logs location
* @member {string} [outputLocation] the location of Hive job output files
* (both execution output and results)
* @member {number} [statementCount] the number of statements that will be run
* based on the script
* @member {number} [executedStatementCount] the number of statements that have
* been run based on the script
*/
export interface HiveJobProperties extends JobProperties {
readonly logsLocation?: string;
readonly outputLocation?: string;
readonly statementCount?: number;
readonly executedStatementCount?: number;
}
/**
* @class
* Initializes a new instance of the CreateJobProperties class.
* @constructor
* The common Data Lake Analytics job properties for job submission.
*
* @member {string} [runtimeVersion] the runtime version of the Data Lake
* Analytics engine to use for the specific type of job being run.
* @member {string} script the script to run. Please note that the maximum
* script size is 3 MB.
* @member {string} type Polymorphic Discriminator
*/
export interface CreateJobProperties {
runtimeVersion?: string;
script: string;
type: string;
}
/**
* @class
* Initializes a new instance of the CreateUSqlJobProperties class.
* @constructor
* U-SQL job properties used when submitting U-SQL jobs.
*
* @member {string} [compileMode] the specific compilation mode for the job
* used during execution. If this is not specified during submission, the
* server will determine the optimal compilation mode. Possible values include:
* 'Semantic', 'Full', 'SingleBox'
*/
export interface CreateUSqlJobProperties extends CreateJobProperties {
compileMode?: string;
}
/**
* @class
* Initializes a new instance of the JobInnerError class.
* @constructor
* The Data Lake Analytics job error details.
*
* @member {number} [diagnosticCode] the diagnostic error code.
* @member {string} [severity] the severity level of the failure. Possible
* values include: 'Warning', 'Error', 'Info', 'SevereWarning', 'Deprecated',
* 'UserWarning'
* @member {string} [details] the details of the error message.
* @member {string} [component] the component that failed.
* @member {string} [errorId] the specific identifier for the type of error
* encountered in the job.
* @member {string} [helpLink] the link to MSDN or Azure help for this type of
* error, if any.
* @member {string} [internalDiagnostics] the internal diagnostic stack trace
* if the user requesting the job error details has sufficient permissions it
* will be retrieved, otherwise it will be empty.
* @member {string} [message] the user friendly error message for the failure.
* @member {string} [resolution] the recommended resolution for the failure, if
* any.
* @member {string} [source] the ultimate source of the failure (usually either
* SYSTEM or USER).
* @member {string} [description] the error message description
* @member {object} [innerError] the inner error of this specific job error
* message, if any.
*/
export interface JobInnerError {
readonly diagnosticCode?: number;
readonly severity?: string;
readonly details?: string;
readonly component?: string;
readonly errorId?: string;
readonly helpLink?: string;
readonly internalDiagnostics?: string;
readonly message?: string;
readonly resolution?: string;
readonly source?: string;
readonly description?: string;
readonly innerError?: JobInnerError;
}
/**
* @class
* Initializes a new instance of the JobErrorDetails class.
* @constructor
* The Data Lake Analytics job error details.
*
* @member {string} [description] the error message description
* @member {string} [details] the details of the error message.
* @member {number} [endOffset] the end offset in the job where the error was
* found.
* @member {string} [errorId] the specific identifier for the type of error
* encountered in the job.
* @member {string} [filePath] the path to any supplemental error files, if
* any.
* @member {string} [helpLink] the link to MSDN or Azure help for this type of
* error, if any.
* @member {string} [internalDiagnostics] the internal diagnostic stack trace
* if the user requesting the job error details has sufficient permissions it
* will be retrieved, otherwise it will be empty.
* @member {number} [lineNumber] the specific line number in the job where the
* error occured.
* @member {string} [message] the user friendly error message for the failure.
* @member {string} [resolution] the recommended resolution for the failure, if
* any.
* @member {object} [innerError] the inner error of this specific job error
* message, if any.
* @member {number} [innerError.diagnosticCode] the diagnostic error code.
* @member {string} [innerError.severity] the severity level of the failure.
* Possible values include: 'Warning', 'Error', 'Info', 'SevereWarning',
* 'Deprecated', 'UserWarning'
* @member {string} [innerError.details] the details of the error message.
* @member {string} [innerError.component] the component that failed.
* @member {string} [innerError.errorId] the specific identifier for the type
* of error encountered in the job.
* @member {string} [innerError.helpLink] the link to MSDN or Azure help for
* this type of error, if any.
* @member {string} [innerError.internalDiagnostics] the internal diagnostic
* stack trace if the user requesting the job error details has sufficient
* permissions it will be retrieved, otherwise it will be empty.
* @member {string} [innerError.message] the user friendly error message for
* the failure.
* @member {string} [innerError.resolution] the recommended resolution for the
* failure, if any.
* @member {string} [innerError.source] the ultimate source of the failure
* (usually either SYSTEM or USER).
* @member {string} [innerError.description] the error message description
* @member {object} [innerError.innerError] the inner error of this specific
* job error message, if any.
* @member {string} [severity] the severity level of the failure. Possible
* values include: 'Warning', 'Error', 'Info', 'SevereWarning', 'Deprecated',
* 'UserWarning'
* @member {string} [source] the ultimate source of the failure (usually either
* SYSTEM or USER).
* @member {number} [startOffset] the start offset in the job where the error
* was found
*/
export interface JobErrorDetails {
readonly description?: string;
readonly details?: string;
readonly endOffset?: number;
readonly errorId?: string;
readonly filePath?: string;
readonly helpLink?: string;
readonly internalDiagnostics?: string;
readonly lineNumber?: number;
readonly message?: string;
readonly resolution?: string;
readonly innerError?: JobInnerError;
readonly severity?: string;
readonly source?: string;
readonly startOffset?: number;
}
/**
* @class
* Initializes a new instance of the JobRelationshipProperties class.
* @constructor
* Job relationship information properties including pipeline information,
* correlation information, etc.
*
* @member {uuid} [pipelineId] the job relationship pipeline identifier (a
* GUID).
* @member {string} [pipelineName] the friendly name of the job relationship
* pipeline, which does not need to be unique.
* @member {string} [pipelineUri] the pipeline uri, unique, links to the
* originating service for this pipeline.
* @member {uuid} [runId] the run identifier (a GUID), unique identifier of the
* iteration of this pipeline.
* @member {uuid} recurrenceId the recurrence identifier (a GUID), unique per
* activity/script, regardless of iterations. This is something to link
* different occurrences of the same job together.
* @member {string} [recurrenceName] the recurrence name, user friendly name
* for the correlation between jobs.
*/
export interface JobRelationshipProperties {
pipelineId?: string;
pipelineName?: string;
pipelineUri?: string;
runId?: string;
recurrenceId: string;
recurrenceName?: string;
}
/**
* @class
* Initializes a new instance of the JobPipelineRunInformation class.
* @constructor
* Run info for a specific job pipeline.
*
* @member {uuid} [runId] the run identifier of an instance of pipeline
* executions (a GUID).
* @member {date} [lastSubmitTime] the time this instance was last submitted.
*/
export interface JobPipelineRunInformation {
readonly runId?: string;
readonly lastSubmitTime?: Date;
}
/**
* @class
* Initializes a new instance of the JobPipelineInformation class.
* @constructor
* Job Pipeline Information, showing the relationship of jobs and recurrences
* of those jobs in a pipeline.
*
* @member {uuid} [pipelineId] the job relationship pipeline identifier (a
* GUID).
* @member {string} [pipelineName] the friendly name of the job relationship
* pipeline, which does not need to be unique.
* @member {string} [pipelineUri] the pipeline uri, unique, links to the
* originating service for this pipeline.
* @member {number} [numJobsFailed] the number of jobs in this pipeline that
* have failed.
* @member {number} [numJobsCanceled] the number of jobs in this pipeline that
* have been canceled.
* @member {number} [numJobsSucceeded] the number of jobs in this pipeline that
* have succeeded.
* @member {number} [auHoursFailed] the number of job execution hours that
* resulted in failed jobs.
* @member {number} [auHoursCanceled] the number of job execution hours that
* resulted in canceled jobs.
* @member {number} [auHoursSucceeded] the number of job execution hours that
* resulted in successful jobs.
* @member {date} [lastSubmitTime] the last time a job in this pipeline was
* submitted.
* @member {array} [runs] the list of recurrence identifiers representing each
* run of this pipeline.
* @member {array} [recurrences] the list of recurrence identifiers
* representing each run of this pipeline.
*/
export interface JobPipelineInformation {
readonly pipelineId?: string;
readonly pipelineName?: string;
readonly pipelineUri?: string;
readonly numJobsFailed?: number;
readonly numJobsCanceled?: number;
readonly numJobsSucceeded?: number;
readonly auHoursFailed?: number;
readonly auHoursCanceled?: number;
readonly auHoursSucceeded?: number;
readonly lastSubmitTime?: Date;
readonly runs?: JobPipelineRunInformation[];
readonly recurrences?: string[];
}
/**
* @class
* Initializes a new instance of the JobRecurrenceInformation class.
* @constructor
* Recurrence job information for a specific recurrence.
*
* @member {uuid} [recurrenceId] the recurrence identifier (a GUID), unique per
* activity/script, regardless of iterations. This is something to link
* different occurrences of the same job together.
* @member {string} [recurrenceName] the recurrence name, user friendly name
* for the correlation between jobs.
* @member {number} [numJobsFailed] the number of jobs in this recurrence that
* have failed.
* @member {number} [numJobsCanceled] the number of jobs in this recurrence
* that have been canceled.
* @member {number} [numJobsSucceeded] the number of jobs in this recurrence
* that have succeeded.
* @member {number} [auHoursFailed] the number of job execution hours that
* resulted in failed jobs.
* @member {number} [auHoursCanceled] the number of job execution hours that
* resulted in canceled jobs.
* @member {number} [auHoursSucceeded] the number of job execution hours that
* resulted in successful jobs.
* @member {date} [lastSubmitTime] the last time a job in this recurrence was
* submitted.
*/
export interface JobRecurrenceInformation {
readonly recurrenceId?: string;
readonly recurrenceName?: string;
readonly numJobsFailed?: number;
readonly numJobsCanceled?: number;
readonly numJobsSucceeded?: number;
readonly auHoursFailed?: number;
readonly auHoursCanceled?: number;
readonly auHoursSucceeded?: number;
readonly lastSubmitTime?: Date;
}
/**
* @class
* Initializes a new instance of the BaseJobParameters class.
* @constructor
* Data Lake Analytics Job Parameters base class for build and submit.
*
* @member {string} type the job type of the current job (Hive or USql).
* Possible values include: 'USql', 'Hive'
* @member {object} properties the job specific properties.
* @member {string} [properties.runtimeVersion] the runtime version of the Data
* Lake Analytics engine to use for the specific type of job being run.
* @member {string} [properties.script] the script to run. Please note that the
* maximum script size is 3 MB.
* @member {string} [properties.type] Polymorphic Discriminator
*/
export interface BaseJobParameters {
type: string;
properties: CreateJobProperties;
}
/**
* @class
* Initializes a new instance of the CreateJobParameters class.
* @constructor
* The parameters used to submit a new Data Lake Analytics job.
*
* @member {string} name the friendly name of the job to submit.
* @member {number} [degreeOfParallelism] the degree of parallelism to use for
* this job. This must be greater than 0, if set to less than 0 it will default
* to 1. Default value: 1 .
* @member {number} [priority] the priority value to use for the current job.
* Lower numbers have a higher priority. By default, a job has a priority of
* 1000. This must be greater than 0.
* @member {array} [logFilePatterns] the list of log file name patterns to find
* in the logFolder. '*' is the only matching character allowed. Example
* format: jobExecution*.log or *mylog*.txt
* @member {object} [related] the recurring job relationship information
* properties.
* @member {uuid} [related.pipelineId] the job relationship pipeline identifier
* (a GUID).
* @member {string} [related.pipelineName] the friendly name of the job
* relationship pipeline, which does not need to be unique.
* @member {string} [related.pipelineUri] the pipeline uri, unique, links to
* the originating service for this pipeline.
* @member {uuid} [related.runId] the run identifier (a GUID), unique
* identifier of the iteration of this pipeline.
* @member {uuid} [related.recurrenceId] the recurrence identifier (a GUID),
* unique per activity/script, regardless of iterations. This is something to
* link different occurrences of the same job together.
* @member {string} [related.recurrenceName] the recurrence name, user friendly
* name for the correlation between jobs.
*/
export interface CreateJobParameters extends BaseJobParameters {
name: string;
degreeOfParallelism?: number;
priority?: number;
logFilePatterns?: string[];
related?: JobRelationshipProperties;
}
/**
* @class
* Initializes a new instance of the BuildJobParameters class.
* @constructor
* The parameters used to build a new Data Lake Analytics job.
*
* @member {string} [name] the friendly name of the job to build.
*/
export interface BuildJobParameters extends BaseJobParameters {
name?: string;
}
/**
* @class
* Initializes a new instance of the JobInformationBasic class.
* @constructor
* The common Data Lake Analytics job information properties.
*
* @member {uuid} [jobId] the job's unique identifier (a GUID).
* @member {string} name the friendly name of the job.
* @member {string} type the job type of the current job (Hive or USql).
* Possible values include: 'USql', 'Hive'
* @member {string} [submitter] the user or account that submitted the job.
* @member {number} [degreeOfParallelism] the degree of parallelism used for
* this job. This must be greater than 0, if set to less than 0 it will default
* to 1. Default value: 1 .
* @member {number} [priority] the priority value for the current job. Lower
* numbers have a higher priority. By default, a job has a priority of 1000.
* This must be greater than 0.
* @member {date} [submitTime] the time the job was submitted to the service.
* @member {date} [startTime] the start time of the job.
* @member {date} [endTime] the completion time of the job.
* @member {string} [state] the job state. When the job is in the Ended state,
* refer to Result and ErrorMessage for details. Possible values include:
* 'Accepted', 'Compiling', 'Ended', 'New', 'Queued', 'Running', 'Scheduling',
* 'Starting', 'Paused', 'WaitingForCapacity'
* @member {string} [result] the result of job execution or the current result
* of the running job. Possible values include: 'None', 'Succeeded',
* 'Cancelled', 'Failed'
* @member {string} [logFolder] the log folder path to use in the following
* format:
* adl://<accountName>.azuredatalakestore.net/system/jobservice/jobs/Usql/2016/03/13/17/18/5fe51957-93bc-4de0-8ddc-c5a4753b068b/logs/.
* @member {array} [logFilePatterns] the list of log file name patterns to find
* in the logFolder. '*' is the only matching character allowed. Example
* format: jobExecution*.log or *mylog*.txt
* @member {object} [related] the recurring job relationship information
* properties.
* @member {uuid} [related.pipelineId] the job relationship pipeline identifier
* (a GUID).
* @member {string} [related.pipelineName] the friendly name of the job
* relationship pipeline, which does not need to be unique.
* @member {string} [related.pipelineUri] the pipeline uri, unique, links to
* the originating service for this pipeline.
* @member {uuid} [related.runId] the run identifier (a GUID), unique
* identifier of the iteration of this pipeline.
* @member {uuid} [related.recurrenceId] the recurrence identifier (a GUID),
* unique per activity/script, regardless of iterations. This is something to
* link different occurrences of the same job together.
* @member {string} [related.recurrenceName] the recurrence name, user friendly
* name for the correlation between jobs.
*/
export interface JobInformationBasic {
readonly jobId?: string;
name: string;
type: string;
readonly submitter?: string;
degreeOfParallelism?: number;
priority?: number;
readonly submitTime?: Date;
readonly startTime?: Date;
readonly endTime?: Date;
readonly state?: string;
readonly result?: string;
readonly logFolder?: string;
logFilePatterns?: string[];
related?: JobRelationshipProperties;
}
/**
* @class
* Initializes a new instance of the JobInformation class.
* @constructor
* The extended Data Lake Analytics job information properties returned when
* retrieving a specific job.
*
* @member {array} [errorMessage] the error message details for the job, if the
* job failed.
* @member {array} [stateAuditRecords] the job state audit records, indicating
* when various operations have been performed on this job.
* @member {object} properties the job specific properties.
* @member {string} [properties.runtimeVersion] the runtime version of the Data
* Lake Analytics engine to use for the specific type of job being run.
* @member {string} [properties.script] the script to run. Please note that the
* maximum script size is 3 MB.
* @member {string} [properties.type] Polymorphic Discriminator
*/
export interface JobInformation extends JobInformationBasic {
readonly errorMessage?: JobErrorDetails[];
readonly stateAuditRecords?: JobStateAuditRecord[];
properties: JobProperties;
}
/**
* @class
* Initializes a new instance of the JobPipelineInformationListResult class.
* @constructor
* List of job pipeline information items.
*
* @member {string} [nextLink] the link (url) to the next page of results.
*/
export interface JobPipelineInformationListResult extends Array<JobPipelineInformation> {
readonly nextLink?: string;
}
/**
* @class
* Initializes a new instance of the JobRecurrenceInformationListResult class.
* @constructor
* List of job recurrence information items.
*
* @member {string} [nextLink] the link (url) to the next page of results.
*/
export interface JobRecurrenceInformationListResult extends Array<JobRecurrenceInformation> {
readonly nextLink?: string;
}
/**
* @class
* Initializes a new instance of the JobInfoListResult class.
* @constructor
* List of JobInfo items.
*
* @member {string} [nextLink] the link (url) to the next page of results.
*/
export interface JobInfoListResult extends Array<JobInformationBasic> {
readonly nextLink?: string;
} | the_stack |
import { tokenize, input, ParameterToken, Token, TokenKind, TokenStream } from './scanner'
import {
// Estree
UnaryOperator, BinaryOperator, NumberLiteral, NullLiteral, StringLiteral, BooleanLiteral,
Literal, Identifier, MemberExpression, UnaryExpression, UpdateExpression, BinaryExpression,
Property, ObjectExpression, ArrayExpression, SpreadElement, CallExpression, Expression,
// LinqBox
NumberParameter, NullParameter, StringParameter, BooleanParameter, ArrayParameter, ObjectParameter,
Parameter, FromClause, JoinIntoClause, JoinClause, WhereClause, OrderByClauseArgument, OrderByClause,
GroupIntoClause, GroupByClause, SelectClause, QueryExpression, Then, ConstClause
} from './syntax'
/** Polyfill for missing [].flat() on older versions of node. */
function flatDeep(arr: any[], d = 1): any[] {
return d > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatDeep(val, d - 1) : val), [])
: arr.slice();
}
// -----------------------------------------------------------------------
// JavaScript
// -----------------------------------------------------------------------
export const binary_operator_precedence = [
'**', '*', '/', '%', '+', '-', '<<', '>>', '>>>',
'<', '<=', '>', '>=', 'in', 'instanceof', '==',
'!=', '===', '!==', '&', '^', '|', '??', '&&', '||'
]
// --------------------------------------------------------
// TypeScript Mappings
// --------------------------------------------------------
type ParserGroup8<T0, T1, T2, T3, T4, T5, T6, T7> = [Parser<T0>, Parser<T1>, Parser<T2>, Parser<T3>, Parser<T4>, Parser<T5>, Parser<T6>, Parser<T7>]
type ParserGroup7<T0, T1, T2, T3, T4, T5, T6> = [Parser<T0>, Parser<T1>, Parser<T2>, Parser<T3>, Parser<T4>, Parser<T5>, Parser<T6>]
type ParserGroup6<T0, T1, T2, T3, T4, T5> = [Parser<T0>, Parser<T1>, Parser<T2>, Parser<T3>, Parser<T4>, Parser<T5>]
type ParserGroup5<T0, T1, T2, T3, T4> = [Parser<T0>, Parser<T1>, Parser<T2>, Parser<T3>, Parser<T4>]
type ParserGroup4<T0, T1, T2, T3> = [Parser<T0>, Parser<T1>, Parser<T2>, Parser<T3>]
type ParserGroup3<T0, T1, T2> = [Parser<T0>, Parser<T1>, Parser<T2>]
type ParserGroup2<T0, T1> = [Parser<T0>, Parser<T1>]
type ParserGroup1<T0> = [Parser<T0>]
type ParserGroup =
| ParserGroup8<any, any, any, any, any, any, any, any>
| ParserGroup7<any, any, any, any, any, any, any>
| ParserGroup6<any, any, any, any, any, any>
| ParserGroup5<any, any, any, any, any>
| ParserGroup4<any, any, any, any>
| ParserGroup3<any, any, any>
| ParserGroup2<any, any>
| ParserGroup1<any>
| any[]
type ParseGroupToUnionScalar<T> =
T extends ParserGroup8<infer U0, infer U1, infer U2, infer U3, infer U4, infer U5, infer U6, infer U7> ? U0 | U1 | U2 | U3 | U4 | U5 | U6 | U7 :
T extends ParserGroup7<infer U0, infer U1, infer U2, infer U3, infer U4, infer U5, infer U6> ? U0 | U1 | U2 | U3 | U4 | U5 | U6 :
T extends ParserGroup6<infer U0, infer U1, infer U2, infer U3, infer U4, infer U5> ? U0 | U1 | U2 | U3 | U4 | U5 :
T extends ParserGroup5<infer U0, infer U1, infer U2, infer U3, infer U4> ? U0 | U1 | U2 | U3 | U4 :
T extends ParserGroup4<infer U0, infer U1, infer U2, infer U3> ? U0 | U1 | U2 | U3 :
T extends ParserGroup3<infer U0, infer U1, infer U2> ? U0 | U1 | U2 :
T extends ParserGroup2<infer U0, infer U1> ? U0 | U1 :
T extends ParserGroup1<infer U0> ? U0 :
any
type ParseGroupToUnionArray<T extends ParserGroup> =
T extends ParserGroup8<infer U0, infer U1, infer U2, infer U3, infer U4, infer U5, infer U6, infer U7> ? Array<U0 | U1 | U2 | U3 | U4 | U5 | U6 | U7> :
T extends ParserGroup7<infer U0, infer U1, infer U2, infer U3, infer U4, infer U5, infer U6> ? Array<U0 | U1 | U2 | U3 | U4 | U5 | U6> :
T extends ParserGroup6<infer U0, infer U1, infer U2, infer U3, infer U4, infer U5> ? Array<U0 | U1 | U2 | U3 | U4 | U5> :
T extends ParserGroup5<infer U0, infer U1, infer U2, infer U3, infer U4> ? Array<U0 | U1 | U2 | U3 | U4> :
T extends ParserGroup4<infer U0, infer U1, infer U2, infer U3> ? Array<U0 | U1 | U2 | U3> :
T extends ParserGroup3<infer U0, infer U1, infer U2> ? Array<U0 | U1 | U2> :
T extends ParserGroup2<infer U0, infer U1> ? Array<U0 | U1> :
T extends ParserGroup1<infer U0> ? Array<U0> :
any[]
// --------------------------------------------------------
// Parser
// --------------------------------------------------------
export type Parser<T> = (stream: TokenStream) => [Result<T>, TokenStream]
export class Result<T> {
constructor(
private _success: boolean,
private _error: string | undefined,
private _value: T | undefined,
) { }
public success(): boolean { return this._success }
public value(): T { return this._value! }
public error(): string { return this._error! }
public static ok<T>(value: T): Result<T> {
return new Result<T>(true, undefined, value)
}
public static fail<T>(error: string = ''): Result<T> {
return new Result<T>(false, error, undefined)
}
}
// --------------------------------------------------------
// Sequence Operators
// --------------------------------------------------------
export const map = <T, U>(parser: Parser<T>, func: (result: T) => U) => (stream: TokenStream): [Result<U>, TokenStream] => {
const [result, next] = parser(stream)
if (result.success()) {
const value = func(result.value())
return [Result.ok(value), next]
}
return [Result.fail(), stream]
}
export const seq = <G extends ParserGroup>(parsers: G) => (stream: TokenStream): [Result<ParseGroupToUnionArray<G>>, TokenStream] => {
const accumulator = [] as ParseGroupToUnionScalar<G>[] as ParseGroupToUnionArray<G>
let current = stream.clone()
for (const parser of parsers) {
const [result, next] = parser(current)
if (result.success()) {
accumulator.push(result.value())
current = next
continue
}
break
}
if (accumulator.length === parsers.length) {
return [Result.ok(accumulator), current]
}
return [Result.fail(), stream]
}
export const any = <G extends ParserGroup>(parsers: G) => (stream: TokenStream): [Result<ParseGroupToUnionScalar<G>>, TokenStream] => {
let current = stream.clone()
for (const parser of parsers) {
const [result, next] = parser(current)
if (result.success()) {
return [result, next]
}
}
return [Result.fail(), stream]
}
export const zero_or_one = <T>(parser: Parser<T>) => (stream: TokenStream): [Result<T | null>, TokenStream] => {
const [result, next] = parser(stream.clone())
if (result.success()) {
return [result, next]
}
return [Result.ok(null), stream]
}
export const zero_or_more = <T>(parser: Parser<T>) => (stream: TokenStream): [Result<T[]>, TokenStream] => {
const accumulator = []
let current = stream.clone()
while (true) {
const [result, next] = parser(current)
if (result.success()) {
accumulator.push(result.value())
current = next
continue
}
break
}
return [Result.ok(accumulator), current]
}
export const one_or_more = <T>(parser: Parser<T>) => (stream: TokenStream): [Result<T[]>, TokenStream] => {
const [result, next] = zero_or_more(parser)(stream)
return (result.value().length === 0)
? [Result.fail(), stream]
: [result, next]
}
/** Parses any item in an encoded scope. */
export const enclosed = <T>(open: Parser<any>, element: Parser<T>, close: Parser<any>) => (stream: TokenStream): [Result<T>, TokenStream] => {
const select = seq([open, element, close])
return map(select, result => result[1] as T)(stream)
}
/** Parses for one or more delimited items */
export const delimited = <T>(element: Parser<T>, delimiter: Parser<any>) => (stream: TokenStream): [Result<T[]>, TokenStream] => {
const [result, next] = any([
seq([element, zero_or_more(seq([delimiter, element])), delimiter]),
seq([element, zero_or_more(seq([delimiter, element]))]),
seq([element])
])(stream)
if (result.success()) {
const captures = flatDeep(result.value(), 2) // result.value().flat(2)
if (captures.length % 2 === 0) { captures.pop() } // ,
const elements = captures.filter((_, index) => index % 2 === 0) as T[]
return [Result.ok(elements), next]
}
return [Result.fail(), stream]
}
/** Parses for zero or more items in an encoded scope. */
export const enclosed_delimited = <T>(open: Parser<any>, element: Parser<T>, close: Parser<any>, delimiter: Parser<any>) => (stream: TokenStream): [Result<T[]>, TokenStream] => {
const [result, next] = any([
seq([open, close]),
seq([open, zero_or_more(seq([element, delimiter])), close]),
seq([open, element, zero_or_more(seq([delimiter, element])), close])
])(stream)
if (result.success()) {
const captures = flatDeep(result.value(), 2) // result.value().flat(2)
captures.shift()
captures.pop()
if (captures.length % 2 === 0) { captures.pop() } // ,
const elements = captures.filter((_, index) => index % 2 === 0) as T[]
return [Result.ok(elements), next]
}
return [Result.fail(), stream]
}
// ------------------------------------------------------------
// operators
// ------------------------------------------------------------
export const select_token = (func: (token: Token) => boolean) => (stream: TokenStream): [Result<Token>, TokenStream] => {
if (stream.length > 0) {
const current = stream.clone()
const token = current.shift()!
if (func(token)) {
return [Result.ok(token), current]
}
}
return [Result.fail(), stream]
}
export const op_lbracket = select_token(token => token.kind === TokenKind.BracketLeft)
export const op_rbracket = select_token(token => token.kind === TokenKind.BracketRight)
export const op_lbrace = select_token(token => token.kind === TokenKind.BraceLeft)
export const op_rbrace = select_token(token => token.kind === TokenKind.BraceRight)
export const op_lparen = select_token(token => token.kind === TokenKind.ParenLeft)
export const op_rparen = select_token(token => token.kind === TokenKind.ParenRight)
export const op_add = select_token(token => token.kind === TokenKind.Add)
export const op_subtract = select_token(token => token.kind === TokenKind.Subtract)
export const op_multiply = select_token(token => token.kind === TokenKind.Multiply)
export const op_divide = select_token(token => token.kind === TokenKind.Divide)
export const op_modulo = select_token(token => token.kind === TokenKind.Modulo)
export const op_equal_sign = select_token(token => token.kind === TokenKind.EqualSign)
export const op_greater_than = select_token(token => token.kind === TokenKind.GreaterThan)
export const op_less_than = select_token(token => token.kind === TokenKind.LessThan)
export const op_pipe = select_token(token => token.kind === TokenKind.Pipe)
export const op_exclaimation_mark = select_token(token => token.kind === TokenKind.ExclaimationMark)
export const op_question_mark = select_token(token => token.kind === TokenKind.QuestionMark)
export const op_ampersand = select_token(token => token.kind === TokenKind.Ampersand)
export const op_tilde = select_token(token => token.kind === TokenKind.Tilde)
export const op_dot = select_token(token => token.kind === TokenKind.Dot)
export const op_comma = select_token(token => token.kind === TokenKind.Comma)
export const op_colon = select_token(token => token.kind === TokenKind.Colon)
export const op_instanceof = select_token(token => token.value === 'instanceof')
export const op_delete = select_token(token => token.value === 'delete')
export const op_typeof = select_token(token => token.value === 'typeof')
export const op_void = select_token(token => token.value === 'void')
export const op_in = select_token(token => token.value === 'in')
export const op_const = select_token(token => token.value === 'const')
export const op_let = select_token(token => token.value === 'let')
export const unary_operator = (stream: TokenStream): [Result<UnaryOperator>, TokenStream] => {
return any([
map(seq([op_subtract, op_subtract]), () => '--'),
map(seq([op_add, op_add]), () => '++'),
map(op_typeof, () => 'typeof'),
map(op_void, () => 'void'),
map(op_exclaimation_mark, () => '!'),
map(op_tilde, () => '~'),
map(op_add, () => '+'),
map(op_subtract, () => '-'),
])(stream) as [Result<UnaryOperator>, TokenStream]
}
export const binary_operator = (stream: TokenStream): [Result<BinaryOperator>, TokenStream] => {
return any([
map(seq([op_equal_sign, op_equal_sign, op_equal_sign]), () => '==='),
map(seq([op_exclaimation_mark, op_equal_sign, op_equal_sign]), () => '!=='),
map(seq([op_greater_than, op_greater_than, op_greater_than]), () => '>>>'),
map(seq([op_pipe, op_pipe]), () => '||'),
map(seq([op_ampersand, op_ampersand]), () => '&&'),
map(seq([op_question_mark, op_question_mark]), () => '??'),
map(seq([op_equal_sign, op_equal_sign]), () => '=='),
map(seq([op_exclaimation_mark, op_equal_sign]), () => '!='),
map(seq([op_greater_than, op_equal_sign]), () => '>='),
map(seq([op_less_than, op_equal_sign]), () => '<='),
map(seq([op_less_than, op_less_than]), () => '<<'),
map(seq([op_greater_than, op_greater_than]), () => '>>'),
map(seq([op_multiply, op_multiply]), () => '**'),
map(op_instanceof, () => 'instanceof'),
map(op_greater_than, () => '>'),
map(op_less_than, () => '<'),
map(op_in, () => 'in'),
map(op_ampersand, () => '&'),
map(op_pipe, () => '|'),
map(op_add, () => '+'),
map(op_subtract, () => '-'),
map(op_multiply, () => '*'),
map(op_divide, () => '/'),
map(op_modulo, () => '%'),
])(stream) as [Result<BinaryOperator>, TokenStream]
}
// ------------------------------------------------------------
// Literal
// ------------------------------------------------------------
export const literal_string = (stream: TokenStream): [Result<StringLiteral>, TokenStream] => {
const select = select_token(token => token.kind === TokenKind.String)
return map(select, token => ({ type: 'Literal', kind: 'string', raw: token.value, value: token.value.slice(1).slice(0, -1) } as StringLiteral))(stream)
}
export const literal_boolean = (stream: TokenStream): [Result<BooleanLiteral>, TokenStream] => {
const select = select_token(token => token.kind === TokenKind.Keyword && token.value === 'true' || token.value === 'false')
return map(select, token => ({ type: 'Literal', kind: 'boolean', raw: token.value, value: token.value === 'true' } as BooleanLiteral))(stream)
}
export const literal_null = (stream: TokenStream): [Result<NullLiteral>, TokenStream] => {
const select = select_token(token => token.kind === TokenKind.Keyword && token.value === 'null')
return map(select, token => ({ type: 'Literal', kind: 'null', raw: token.value, value: null } as NullLiteral))(stream)
}
export const literal_number = (stream: TokenStream): [Result<NumberLiteral>, TokenStream] => {
const select = select_token(token => token.kind === TokenKind.Number)
return map(select, token => ({ type: 'Literal', kind: 'number', raw: token.value, value: parseFloat(token.value) } as NumberLiteral))(stream)
}
export const literal = (stream: TokenStream): [Result<Literal>, TokenStream] => {
return any([literal_string, literal_boolean, literal_null, literal_number])(stream)
}
// ------------------------------------------------------------
// Parameter:
// ------------------------------------------------------------
// todo: fix parameter select
export const parameter_string = (stream: TokenStream): [Result<StringParameter>, TokenStream] => {
const select = select_token(token => token.kind === TokenKind.Parameter && typeof token.value === 'string')
return map(select as any, (token: ParameterToken) => ({ type: 'Parameter', kind: 'string', index: token.index, value: token.value }) as StringParameter)(stream)
}
export const parameter_boolean = (stream: TokenStream): [Result<BooleanParameter>, TokenStream] => {
const select = select_token(token => token.kind === TokenKind.Parameter && typeof token.value === 'boolean')
return map(select as any, (token: ParameterToken) => ({ type: 'Parameter', kind: 'boolean', index: token.index, value: token.value }) as BooleanParameter)(stream)
}
export const parameter_null = (stream: TokenStream): [Result<NullParameter>, TokenStream] => {
const select = select_token(token => token.kind === TokenKind.Parameter && token.value === null)
return map(select as any, (token: ParameterToken) => ({ type: 'Parameter', kind: 'null', index: token.index, value: token.value }) as NullParameter)(stream)
}
export const parameter_number = (stream: TokenStream): [Result<NumberParameter>, TokenStream] => {
const select = select_token(token => token.kind === TokenKind.Parameter && typeof token.value === 'number')
return map(select as any, (token: ParameterToken) => ({ type: 'Parameter', kind: 'number', index: token.index, value: token.value }) as NumberParameter)(stream)
}
export const parameter_array = (stream: TokenStream): [Result<ArrayParameter>, TokenStream] => {
const select = select_token(token => token.kind === TokenKind.Parameter && typeof token.value === 'object' && Array.isArray(token.value))
return map(select as any, (token: ParameterToken) => ({ type: 'Parameter', kind: 'array', index: token.index, value: token.value }) as ArrayParameter)(stream)
}
export const parameter_object = (stream: TokenStream): [Result<ObjectParameter>, TokenStream] => {
const select = select_token(token => token.kind === TokenKind.Parameter && typeof token.value === 'object' && !Array.isArray(token.value))
return map(select as any, (token: ParameterToken) => ({ type: 'Parameter', kind: 'object', index: token.index, value: token.value }) as ObjectParameter)(stream)
}
export const parameter = any([
parameter_string,
parameter_boolean,
parameter_null,
parameter_number,
parameter_array,
parameter_object
])
// -----------------------------------------------------------------------
// ArrayExpression
// -----------------------------------------------------------------------
export const array_expression_element_spread = (stream: TokenStream): [Result<SpreadElement>, TokenStream] => {
const spread = seq([op_dot, op_dot, op_dot])
const candidate = any([query_expression, array_expression, identifier])
const select = any([
seq([spread, op_lparen, candidate, op_rparen]),
seq([spread, candidate]),
])
return map(select, result => ({
type: 'SpreadElement',
argument: result.length === 4 ? result[2] : result[1]
} as SpreadElement))(stream)
}
export const array_expression = (stream: TokenStream): [Result<ArrayExpression>, TokenStream] => {
const candidates = any([array_expression_element_spread, expression])
const select = enclosed_delimited(op_lbracket, candidates, op_rbracket, op_comma)
return map(select, elements => ({ type: 'ArrayExpression', elements } as ArrayExpression))(stream)
}
// -----------------------------------------------------------------------
// ObjectExpression
// -----------------------------------------------------------------------
export const object_expression_property_short = (stream: TokenStream): [Result<Property>, TokenStream] => {
return map(identifier, identifer => ({ type: 'Property', key: identifer.name, value: identifer } as Property))(stream)
}
export const object_expression_property = (stream: TokenStream): [Result<Property>, TokenStream] => {
const select = seq([identifier, op_colon, expression])
return map(select, results => ({ type: 'Property', key: (results[0] as Identifier).name, value: results[2] as Expression } as Property))(stream)
}
export const object_expression_property_index = (stream: TokenStream): [Result<Property>, TokenStream] => {
const index = any([identifier, literal_number, literal_string])
const select = seq([op_lbracket, index, op_rbracket, op_colon, expression])
return map(select, result => {
const index = result[1] as Identifier | NumberLiteral | StringLiteral
const expresson = result[4] as Expression
if (index.type === 'Identifier') {
return { type: 'Property', key: index.name, value: expresson } as Property
} else if (index.type === 'Literal' && index.kind === 'number') {
return { type: 'Property', key: index.value.toString(), value: expresson } as Property
} else if (index.type === 'Literal' && index.kind === 'string') {
return { type: 'Property', key: index.value, value: expresson } as Property
}
throw Error('unreachable')
})(stream)
}
export const object_expression_property_spread = (stream: TokenStream): [Result<SpreadElement>, TokenStream] => {
const spread = seq([op_dot, op_dot, op_dot])
const candidate = any([object_expression, identifier])
const select = any([
seq([spread, op_lparen, candidate, op_rparen]),
seq([spread, candidate])
])
return map(select, result => ({ type: 'SpreadElement', argument: result.length === 4 ? result[2] : result[1] } as SpreadElement))(stream)
}
export const object_expression = (stream: TokenStream): [Result<ObjectExpression>, TokenStream] => {
const candidates = any([
object_expression_property,
object_expression_property_index,
object_expression_property_short,
object_expression_property_spread
])
const select = enclosed_delimited(op_lbrace, candidates, op_rbrace, op_comma)
return map(select, properties => ({ type: 'ObjectExpression', properties } as ObjectExpression))(stream)
}
// ------------------------------------------------------------
// Identifier
// ------------------------------------------------------------
export const identifier = (stream: TokenStream): [Result<Identifier>, TokenStream] => {
const select = select_token(token => token.kind === TokenKind.Word || token.value === 'undefined')
return map(select, token => ({ type: 'Identifier', name: token.value } as Identifier))(stream)
}
// -----------------------------------------------------------------------
// MemberExpression | CallExpression
// -----------------------------------------------------------------------
export const member_call_expression_arguments_spread = (stream: TokenStream): [Result<SpreadElement>, TokenStream] => {
const spread = seq([op_dot, op_dot, op_dot])
const candidate = any([array_expression, identifier])
const select = any([
seq([spread, op_lparen, candidate, op_rparen]),
seq([spread, candidate])
])
return map(select, result => ({ type: 'SpreadElement', argument: result.length === 4 ? result[2] : result[1] } as SpreadElement))(stream)
}
export const member_call_expression = (stream: TokenStream): [Result<CallExpression>, TokenStream] => {
const candidate = any([expression, member_call_expression_arguments_spread])
const select = enclosed_delimited(op_lparen, candidate, op_rparen, op_comma) // (a, a, a, a)
return map(select, _arguments => {
const type = 'CallExpression'
const callee = null as any as Identifier
return { type, callee, arguments: _arguments } as CallExpression
})(stream)
}
export const member_computed_member_expression = (stream: TokenStream): [Result<MemberExpression>, TokenStream] => {
const select = seq([op_lbracket, any([identifier, literal_string, literal_number]), op_rbracket])
return map(select, results => {
const type = 'MemberExpression'
const computed = true
const object = null as any as Identifier
const property = results[1] as Identifier | StringLiteral | NumberLiteral
return { type, computed, object, property } as MemberExpression
})(stream)
}
export const member_expression_identifier = (stream: TokenStream): [Result<Identifier>, TokenStream] => {
// note: member expressions are allowed to be named reserved words.
// todo: Implement a better member expression parser.
const identifier_remap = select_token(token => token.kind === TokenKind.Word || token.kind === TokenKind.Keyword || token.value === 'undefined')
const identifier = map(identifier_remap, token => ({ type: 'Identifier', name: token.value } as Identifier))
const select = seq([op_dot, identifier])
return map(select, results => results[1] as Identifier)(stream)
}
export const member_or_call_expression_entry = (stream: TokenStream): [Result<MemberExpression | CallExpression | ObjectExpression | ArrayExpression | Identifier>, TokenStream] => {
const candidate_0 = any([object_expression, array_expression, identifier]) // {} | [] | x
const candidate_1 = enclosed(op_lparen, member_or_call_expression_entry, op_rparen)// ({}) | ([]) | (x)
const candidate_2 = enclosed(op_lparen, member_or_call_expression, op_rparen) // (a()) | ([].x)
return any([candidate_0, candidate_1, candidate_2])(stream)
}
const member_or_call_expression = (stream: TokenStream): [Result<MemberExpression | CallExpression>, TokenStream] => {
const [result, next] = seq([member_or_call_expression_entry, one_or_more(any([
member_computed_member_expression,
member_call_expression,
member_expression_identifier
]))])(stream)
if (result.success()) {
const value = result.value()
const left = value[0] as MemberExpression | CallExpression | ObjectExpression | ArrayExpression | Identifier
const right = value[1] as (CallExpression | MemberExpression | Identifier)[]
//
// [0] -> computed member expression
// () -> call-expression
// .x -> identifier
//
let current = left as Identifier | MemberExpression | CallExpression
for (const next of right) {
if (next.type === 'MemberExpression') {
next.object = current
current = next
continue
}
if (next.type === 'CallExpression') {
next.callee = current
current = next
continue
}
if (next.type === 'Identifier') {
current = {
type: 'MemberExpression',
computed: false,
object: current,
property: next
} as MemberExpression
}
}
return [Result.ok(current as MemberExpression | CallExpression), next]
}
return [Result.fail(), stream]
}
// -----------------------------------------------------------------------
// UpdateExpression
// -----------------------------------------------------------------------
export const update_expression_prefix = (stream: TokenStream): [Result<UpdateExpression>, TokenStream] => {
const select = any([
seq([op_add, op_add, identifier]),
seq([op_subtract, op_subtract, identifier]),
])
return map(select, results => {
const type = 'UpdateExpression'
const token = results[0] as Token
const _argument = results[2] as Identifier
const operator = [token.value, token.value].join('')
const prefix = true
return { type, operator, argument: _argument, prefix } as UpdateExpression
})(stream)
}
export const update_expression_postfix = (stream: TokenStream): [Result<UpdateExpression>, TokenStream] => {
const select = any([
seq([identifier, op_add, op_add]),
seq([identifier, op_subtract, op_subtract]),
])
return map(select, results => {
const type = 'UpdateExpression'
const token = results[2] as Token
const _argument = results[0] as Identifier
const operator = [token.value, token.value].join('')
const prefix = false
return { type, operator, argument: _argument, prefix } as UpdateExpression
})(stream)
}
export const update_expression = (stream: TokenStream): [Result<UpdateExpression>, TokenStream] => {
return any([
update_expression_prefix,
update_expression_postfix
])(stream)
}
// -----------------------------------------------------------------------
// UnaryExpression
// -----------------------------------------------------------------------
export const unary_expression = (stream: TokenStream): [Result<UnaryExpression>, TokenStream] => {
const select = any([
seq([op_exclaimation_mark, expression]),
seq([op_add, expression]),
seq([op_tilde, expression]),
seq([op_typeof, expression]),
seq([op_void, expression]),
seq([op_delete, expression]),
])
return map(select, results => {
const type = 'UnaryExpression'
const token = results[0] as Token
const arg = results[1] as Expression
const operator = token.value
const prefix = true
return { type, operator, argument: arg, prefix } as UnaryExpression
})(stream)
}
// -----------------------------------------------------------------------
// BinaryExpression
// -----------------------------------------------------------------------
export const binary_expression_reduce_operator = (sequence: (Expression | BinaryOperator)[], operator_to_reduce: BinaryOperator): (Expression | BinaryOperator)[] => {
const reduced = [] as (Expression | BinaryOperator)[]
while (sequence.length >= 3) {
const left = sequence.shift()! as Expression
const operator = sequence.shift()! as BinaryOperator
const right = sequence.shift()! as Expression
if (operator === operator_to_reduce) {
const type = 'BinaryExpression'
const expression = { type, operator, left, right } as BinaryExpression
sequence.unshift(expression)
} else {
sequence.unshift(right)
reduced.push(left)
reduced.push(operator)
}
}
reduced.push(sequence.shift()!)
return reduced
}
export const binary_expression_oprand = (stream: TokenStream): [Result<Expression>, TokenStream] => {
return any([
any([
update_expression, unary_expression, // no binary select on outer scope.
member_or_call_expression, array_expression, object_expression,
identifier, literal, parameter
]),
enclosed(op_lparen, any([
update_expression, unary_expression, binary_expression,
member_or_call_expression, array_expression, object_expression,
identifier, literal, parameter
]), op_rparen),
])(stream)
}
export const binary_expression = (stream: TokenStream): [Result<BinaryExpression>, TokenStream] => {
const select = seq([binary_expression_oprand, one_or_more(seq([binary_operator, binary_expression_oprand]))])
return map(select, results => {
const sequence = flatDeep(results, 2) // results.flat(2) // expect minimum 3 elements
const reduced = binary_operator_precedence.reduce((items, operator) => {
return items.length === 1 ? items : binary_expression_reduce_operator(items, operator as BinaryOperator)
}, sequence)
return reduced.shift() as BinaryExpression
})(stream)
}
// -----------------------------------------------------------------------
// Expression
// -----------------------------------------------------------------------
export const expression = (stream: TokenStream): [Result<Expression>, TokenStream] => {
return any([
any([
update_expression, unary_expression, binary_expression,
member_or_call_expression, array_expression, object_expression,
identifier, literal, parameter, query_expression
]),
enclosed(op_lparen, expression, op_rparen),
])(stream)
}
// -----------------------------------------------------------------------
//
// LinqBox
//
// -----------------------------------------------------------------------
export const op_from = select_token(token => token.value === 'from')
export const op_join = select_token(token => token.value === 'join')
export const op_equals = select_token(token => token.value === 'equals')
export const op_into = select_token(token => token.value === 'into')
export const op_where = select_token(token => token.value === 'where')
export const op_orderby = select_token(token => token.value === 'orderby')
export const op_ascending = select_token(token => token.value === 'ascending')
export const op_descending = select_token(token => token.value === 'descending')
export const op_group = select_token(token => token.value === 'group')
export const op_by = select_token(token => token.value === 'by')
export const op_select = select_token(token => token.value === 'select')
export const op_on = select_token(token => token.value === 'on')
const then = (stream: TokenStream): [Result<Then>, TokenStream] => any([
from_clause,
join_into_clause,
join_clause,
const_clause,
where_clause,
orderby_clause,
group_into_clause,
groupby_clause,
select_clause
])(stream)
export const from_clause = (stream: TokenStream): [Result<FromClause>, TokenStream] => {
const iterable = any([array_expression, member_or_call_expression, identifier, parameter])
const select = seq([op_from, identifier, op_in, iterable, then])
return map(select, result => {
const type = 'FromClause'
const identifier = result[1] as Identifier
const iterable = result[3] as ArrayExpression | MemberExpression | CallExpression | Identifier | External
const then = result[4] as
| FromClause | JoinClause
| WhereClause | GroupIntoClause
| OrderByClause | SelectClause
return { type, identifier, iterable, then } as FromClause
})(stream)
}
export const join_into_clause = (stream: TokenStream): [Result<JoinIntoClause>, TokenStream] => {
const iterable = any([array_expression, member_or_call_expression, identifier, parameter])
const oprand = any([member_or_call_expression, identifier])
const select = seq([op_join, identifier, op_in, iterable, op_on, oprand, op_equals, oprand, op_into, identifier, then])
return map(select, result => {
const type = 'JoinIntoClause'
const identifier = result[1] as Identifier
const iterable = result[3] as ArrayExpression | MemberExpression | CallExpression | Identifier | External
const left = result[5] as Identifier | MemberExpression
const right = result[7] as Identifier | MemberExpression
const into = result[9] as Identifier
const then = result[10] as Then
return { type, identifier, iterable, left, right, into, then } as JoinIntoClause
})(stream)
}
export const join_clause = (stream: TokenStream): [Result<JoinClause>, TokenStream] => {
const iterable = any([array_expression, member_or_call_expression, identifier, parameter])
const oprand = any([member_or_call_expression, identifier])
const select = seq([op_join, identifier, op_in, iterable, op_on, oprand, op_equals, oprand, then])
return map(select, result => {
const type = 'JoinClause'
const identifier = result[1] as Identifier
const iterable = result[3] as ArrayExpression | MemberExpression | CallExpression | Identifier | External
const left = result[5] as Identifier | MemberExpression
const right = result[7] as Identifier | MemberExpression
const then = result[8] as Then
return { type, identifier, iterable, left, right, then } as JoinClause
})(stream)
}
export const const_clause = (stream: TokenStream): [Result<ConstClause>, TokenStream] => {
const select = seq([op_const, identifier, op_equal_sign, expression, then])
return map(select, result => {
const type = 'ConstClause'
const identifier = result[1] as Identifier
const expression = result[3] as Expression
const then = result[4] as Then
return { type, identifier, expression, then } as ConstClause
})(stream)
}
export const where_clause = (stream: TokenStream): [Result<WhereClause>, TokenStream] => {
const select = seq([op_where, expression, then])
return map(select, result => {
const type = 'WhereClause'
const expression = result[1] as Expression
const then = result[2] as Then
return { type, expression, then } as WhereClause
})(stream)
}
export const orderby_clause_argument = (stream: TokenStream): [Result<OrderByClauseArgument>, TokenStream] => {
const direction = any([op_ascending, op_descending])
const select = any([
seq([any([member_or_call_expression, identifier]), direction]),
seq([any([member_or_call_expression, identifier])])
])
return map(select, result => {
if (result.length === 2) {
const identifier = result[0] as Identifier
const token = result[1] as Token
const direction = token.value
return { identifier, direction } as OrderByClauseArgument
}
const identifier = result[0] as Identifier
const direction = 'ascending'
return { identifier, direction } as OrderByClauseArgument
})(stream)
}
export const orderby_clause = (stream: TokenStream): [Result<OrderByClause>, TokenStream] => {
const args = delimited(orderby_clause_argument, op_comma)
const select = seq([op_orderby, args, then])
return map(select, result => {
const type = 'OrderByClause'
const args = result[1] as OrderByClauseArgument[]
const then = result[2] as Then
return { type, arguments: args, then } as OrderByClause
})(stream)
}
export const group_into_clause = (stream: TokenStream): [Result<GroupIntoClause>, TokenStream] => {
const select = seq([op_group, identifier, op_by, expression, op_into, identifier, then])
return map(select, result => {
const type = 'GroupIntoClause'
const identifier = result[1] as Identifier
const by = result[3] as MemberExpression | Identifier
const into = result[5] as Identifier
const then = result[6] as Then
return { type, identifier, by, into, then } as GroupIntoClause
})(stream)
}
export const groupby_clause = (stream: TokenStream): [Result<GroupByClause>, TokenStream] => {
const select = seq([op_group, identifier, op_by, expression])
return map(select, result => {
const type = 'GroupByClause'
const identifier = result[1] as Identifier
const by = result[3] as Expression
return { type, identifier, by } as GroupByClause
})(stream)
}
export const select_clause = (stream: TokenStream): [Result<SelectClause>, TokenStream] => {
const select = seq([op_select, expression])
return map(select, result => {
const type = 'SelectClause'
const expression = result[1] as Expression
return { type, expression } as SelectClause
})(stream)
}
export const query_expression = (stream: TokenStream): [Result<QueryExpression>, TokenStream] => {
return map(from_clause, result => {
const type = 'QueryExpression'
const from = result as FromClause
return { type, from } as QueryExpression
})(stream)
}
export const parse = query_expression | the_stack |
module TDev.RT {
//? A 2D matrix of numbers
//@ stem("m") enumerable serializable
export class Matrix
extends RTValue
{
private data: number[] = [];
private rowCount: number = 0;
private columnCount: number = 0;
//public exportJson(ctx: JsonExportCtx): any {
// return ctx.encodeObjectNode(this, ["data", "rowCount", "columnCount"], [this.data.slice(0), this.rowCount, this.columnCount]);
//}
static mk(rowCount : number, columnCount : number) : Matrix
{
if (rowCount < 0 || isNaN(rowCount))
return null;
if (columnCount < 0 || isNaN(columnCount))
return null;
var irow = Math.floor(rowCount);
if (irow < 0)
return null;
var icolumn = Math.floor(columnCount);
if (icolumn < 0)
return null;
if (irow * icolumn < 0)
return null;
var m = new Matrix();
m.rowCount = irow;
m.columnCount = icolumn;
m.data = <number[]>new Array(irow * icolumn);
m.clear(0);
return m;
}
private index(i: number, j: number): number {
return this.columnCount * Math.floor(i) + Math.floor(j);
}
public toString(): string {
var r = ["["];
for (var i = 0; i < this.rowCount; i++)
{
if (i > 0)
r.push("\n");
for (var j = 0; j < this.columnCount; j++)
{
if (j > 0)
r.push(", ");
r.push( this.data[this.index(i, j)].toString() );
}
}
r.push("]");
return r.join("");
}
public get_enumerator() { return this.data.slice(0); }
//? Gets the total number of elements
//@ readsMutable
public count(): number { return this.rowCount * this.columnCount; }
//? Gets the number of rows
//@ readsMutable
public row_count(): number { return this.rowCount; }
//? Gets the number of columns
//@ readsMutable
public column_count(): number { return this.columnCount; }
//? Displays the value of the array on the wall
public post_to_wall(s: IStackFrame): void {
super.post_to_wall(s);
}
public getViewCore(s: IStackFrame, b: BoxBase): HTMLElement {
var d = div("item");
for (var i = 0; i < this.rowCount; i++) {
var r = i == 0 ? "[" : "";
for (var j = 0; j < this.columnCount; j++) {
if (j > 0)
r += ", ";
r += this.data[this.index(i, j)];
}
if (i == this.rowCount - 1)
r += "]";
d.appendChild(div(null, r))
}
return d;
}
//? Copies the content from ``other`` starting at position ``row`` and ``column``
//@ writesMutable
public copy_from(row: number, column: number, other: Matrix) {
row = Math.floor(row);
column = Math.floor(column);
for (var i = 0; i < other.rowCount; ++i) {
for (var j = 0; j < other.columnCount; ++j) {
this.data[this.index(row + i, column + j)] = other.data[other.index(i, j)];
}
}
}
//? Gets the value at a given index. Elements are ordered line by line starting top left.
//@ readsMutable
public at(index:number) : number { return this.data[Math.floor(index)]; }
//? Sets the value at a given index. Elements are ordered line by line starting top left.
//@ writesMutable
public set_at(index: number, value: number): void {
var _index = Math.floor(index);
if (0 <= _index && index < this.data.length)
this.data[_index] = value;
}
//? Gets the value at a given location. Returns invalid if outside of the array dimensions
//@ readsMutable
public item(row: number, column: number): number {
return this.at(this.index(row, column));
}
//? Sets the value at a particular position. The matrix will be expanded if the position falls outside the boundaries.
//@ writesMutable
public set_item(row: number, column: number, value: number): void {
this.set_at(this.index(row, column), value);
}
//? Creates a deep copy of the matrix.
//@ readsMutable
public clone(): Matrix {
var m = new Matrix();
m.rowCount = this.rowCount;
m.columnCount = this.columnCount;
m.data = this.data.slice(0);
return m;
}
//? Computes the minimum of the values
//@ readsMutable
public min(): number {
if (this.data.length == 0) return undefined;
var r = this.data[0];
for (var i = 1; i < this.data.length; ++i)
r = this.data[i] < r ? this.data[i] : r;
return r;
}
//? Computes the maximum of the values
//@ readsMutable
public max(): number
{
if (this.data.length == 0) return undefined;
var r = this.data[0];
for (var i = 1; i < this.data.length; ++i)
r = this.data[i] > r ? this.data[i] : r;
return r;
}
//? Returns a copy of the matrix scaled by factor.
//@ readsMutable
public scale(factor: number): Matrix {
var m = Matrix.mk(this.rowCount, this.columnCount);
for (var i = 0; i < this.data.length;++i)
m.data[i] = this.data[i] * factor;
return m;
}
//? Returns the matrix negated.
//@ readsMutable
public negate(): Matrix {
var m = Matrix.mk(this.rowCount, this.columnCount);
for (var i = 0; i < this.data.length;++i)
m.data[i] = -this.data[i];
return m;
}
//? Returns the transposed matrix.
//@ readsMutable
public transpose(): Matrix {
var m = Matrix.mk(this.columnCount, this.rowCount);
for (var i = 0; i < this.rowCount;++i)
for (var j = 0; j < this.columnCount; ++j)
m.data[m.index(j, i)] = this.data[this.index(i, j)];
return m;
}
//? Returns a matrix resulting from adding this matrix to b. The size of both matrices must match.
//@ readsMutable
public add(b: Matrix): Matrix {
if (this.rowCount != b.rowCount || this.columnCount != b.columnCount) {
Time.log("matrix add error: incompatible matrix sizes");
return undefined;
}
var m = Matrix.mk(this.rowCount, this.columnCount);
for (var i = 0; i < this.data.length;++i)
m.data[i] = this.data[i] + b.data[i];
return m;
}
//? Returns a matrix resulting from subtracting b from this matrix. The size of both matrices must match.
//@ readsMutable
public subtract(b: Matrix): Matrix {
if (this.rowCount != b.rowCount || this.columnCount != b.columnCount) {
Time.log("matrix subtract error: incompatible matrix sizes");
return undefined;
}
var m = Matrix.mk(this.rowCount, this.columnCount);
for (var i = 0; i < this.data.length; ++i)
m.data[i] = this.data[i] - b.data[i];
return m;
}
//? Returns a matrix resulting from multiply each element in the matrices. The size of both matrices must match.
//@ readsMutable
public multiply(b: Matrix): Matrix {
if (this.columnCount != b.rowCount) {
Time.log("matrix multiply error: incompatible matrix sizes");
return undefined;
}
var r = Matrix.mk(this.rowCount, b.columnCount);
var m = this.rowCount;
var n = this.columnCount;
var p = b.columnCount;
for (var i = 0; i < m; i++)
for (var j = 0; j < n; j++)
for (var k = 0; k < p; k++)
r.data[r.index(i,k)] +=
this.data[this.index(i,j)] * b.data[b.index(j,k)];
return r;
}
//? Gets the string representation of the matrix
//@ readsMutable
public to_string(): string {
return this.toString();
}
//? Gets a random element. Returns invalid if the matrix is empty.
//@ tandre
//@ readsMutable
public random(): number {
return this.data.length == 0 ? undefined : this.at(Math_.random(this.data.length));
}
//? Sets all the element of the matrix to the value.
//@ writesMutable
public clear(value: number): void {
for (var i = 0; i < this.data.length;++i)
this.data[i] = value;
}
public debuggerDisplay(clickHandler: () => any) {
var container: HTMLElement = div(null).withClick(clickHandler);
var tableVar: HTMLElement;
var tableDataCell: HTMLElement;
var tableRow: HTMLElement;
tableVar = document.createElement("table").withClick(clickHandler);
for(var i = 0; i < this.rowCount; ++i) {
tableRow = createElement("tr");
for(var j = 0; j < this.columnCount; ++j) {
tableDataCell = document.createElement("td").withClick(clickHandler);
tableDataCell.innerText = this.data[this.index(i, j)].toString();
tableDataCell.style.padding = "0.5em";
tableRow.appendChild(tableDataCell);
}
tableVar.appendChild(tableRow);
}
container.appendChild(tableVar);
return container;
}
}
} | the_stack |
import {
useState,
useRef,
InputHTMLAttributes,
ChangeEvent,
ClipboardEvent,
DragEvent,
Fragment,
} from 'react';
import { css } from '@emotion/react';
import { Delete, Plus } from '@sumup/icons';
import { ClickEvent } from '../../types/events';
import styled, { StyleProps } from '../../styles/styled';
import { uniqueId } from '../../util/id';
import { focusOutline, hideVisually } from '../../styles/style-mixins';
import Label from '../Label';
import IconButton, { IconButtonProps } from '../IconButton';
import Spinner from '../Spinner';
import ValidationHint from '../ValidationHint';
type Size = 'giga' | 'yotta';
export interface ImageInputProps
extends Omit<InputHTMLAttributes<HTMLInputElement>, 'size' | 'onChange'> {
/**
* A clear and concise description of the ImageInput's purpose.
*/
label: string;
/**
* The visual component to render as an image input. It should accept an src
* prop to render the image.
*/
component: ({ src, alt }: { src?: string; alt: string }) => JSX.Element;
/**
* A callback function to call when the user has selected an image.
*/
onChange: (event: File) => void | Promise<void>;
/**
* A callback function to call when the input is cleared.
*/
onClear: (event: ClickEvent) => void | Promise<void>;
/**
* An accessible label for the "clear" icon button.
*/
clearButtonLabel: string;
/**
* An accessible label to communicate the input's loading state.
*/
loadingLabel: string;
/**
* The source URL of an existing Avatar to be displayed in the ImageInput.
*/
src?: string;
/**
* A unique identifier for the input element. If not defined, a generated id
* is used.
*/
id?: string;
/**
* Triggers error styles on the component. Important for accessibility.
*/
invalid?: boolean;
/**
* An information or error message, displayed below the input.
*/
validationHint?: string;
/**
* Changes the size of the button that controls the input. Defaults to "yotta".
*/
size?: Size;
}
const InputWrapper = styled.div`
display: inline-block;
position: relative;
text-align: center;
`;
const HiddenInput = styled.input(
({ theme }) => css`
${hideVisually()};
&:focus + label > *:last-child {
${focusOutline(theme)};
}
&:focus:not(:focus-visible) + label > *:last-child {
box-shadow: none;
}
`,
);
type StyledLabelProps = {
isLoading: boolean;
isDragging: boolean;
invalid: boolean;
};
const baseLabelStyles = ({ theme }: StyleProps) => css`
cursor: pointer;
&::before {
content: '';
position: absolute;
top: 0;
left: 0%;
width: 100%;
height: 100%;
border-radius: 12px;
pointer-events: none;
background-color: ${theme.colors.black};
opacity: 0;
transition: opacity ${theme.transitions.default};
}
> *:last-child {
transition: box-shadow ${theme.transitions.default};
}
@supports (-webkit-filter: brightness(1)) or (filter: brightness(1)) {
transition: filter ${theme.transitions.default};
&::before {
content: none;
}
}
`;
const invalidLabelStyles = ({
theme,
invalid,
}: StyledLabelProps & StyleProps) =>
invalid &&
css`
> *:last-child {
box-shadow: 0 0 0 2px ${theme.colors.alert};
}
&:hover > *:last-child {
box-shadow: 0 0 0 2px ${theme.colors.r700};
}
`;
const loadingLabelStyles = ({ isLoading }: StyledLabelProps) => {
if (isLoading) {
return css`
&::before {
opacity: 0.4;
}
@supports (-webkit-filter: brightness(1)) or (filter: brightness(1)) {
filter: brightness(0.6);
}
`;
}
return css`
&:hover::before {
opacity: 0.1;
}
&:active::before {
opacity: 0.2;
}
@supports (-webkit-filter: brightness(1)) or (filter: brightness(1)) {
&:hover {
filter: brightness(0.9);
}
&:active {
filter: brightness(0.8);
}
}
`;
};
const draggingLabelStyles = ({
theme,
isDragging,
}: StyledLabelProps & StyleProps) =>
isDragging &&
css`
*:last-child {
${focusOutline(theme)};
}
&::before {
opacity: 0.1;
}
@supports (-webkit-filter: brightness(1)) or (filter: brightness(1)) {
filter: brightness(0.9);
}
`;
const addButtonStyles = ({ theme }: StyleProps) => css`
&:hover {
& > button {
background-color: ${theme.colors.p700};
border-color: ${theme.colors.p700};
}
}
&:active {
& > button {
background-color: ${theme.colors.p900};
border-color: ${theme.colors.p900};
}
}
`;
const StyledLabel = styled(Label)<StyledLabelProps>(
baseLabelStyles,
invalidLabelStyles,
loadingLabelStyles,
draggingLabelStyles,
addButtonStyles,
);
const actionButtonBaseStyles = ({ theme }: StyleProps) => css`
position: absolute;
right: -${theme.spacings.bit};
bottom: -${theme.spacings.bit};
`;
const actionButtonSizeStyles = ({ buttonSize }: ActionButtonProps) => {
if (buttonSize === 'giga') {
return css`
padding: 5px;
svg {
width: 14px;
height: 14px;
}
`;
}
return null;
};
type ActionButtonProps = IconButtonProps & { buttonSize: Size };
const ActionButton = styled(IconButton)<ActionButtonProps>(
actionButtonBaseStyles,
actionButtonSizeStyles,
);
const AddButton = styled(ActionButton)`
pointer-events: none;
`;
type LoadingIconProps = { isLoading: boolean };
const spinnerBaseStyles = ({ theme }: LoadingIconProps & StyleProps) => css`
position: absolute;
width: ${theme.iconSizes.giga};
height: ${theme.iconSizes.giga};
top: calc(50% - 16px);
left: calc(50% - 16px);
opacity: 0;
visibility: hidden;
transition: opacity ${theme.transitions.default},
visibility ${theme.transitions.default};
color: ${theme.colors.white};
pointer-events: none;
`;
const spinnerLoadingStyles = ({ isLoading }: LoadingIconProps) =>
isLoading &&
css`
opacity: 1;
visibility: inherit;
`;
const LoadingIcon = styled(Spinner)<LoadingIconProps>(
spinnerBaseStyles,
spinnerLoadingStyles,
);
const LoadingLabel = styled.span(hideVisually);
/**
* The ImageInput component allows users to upload images.
*/
export const ImageInput = ({
label,
src,
alt,
size = 'yotta',
id: customId,
clearButtonLabel,
onChange,
onClear,
disabled,
validationHint,
invalid = false,
loadingLabel,
component: Component,
...props
}: ImageInputProps): JSX.Element => {
if (
process.env.NODE_ENV !== 'production' &&
process.env.NODE_ENV !== 'test' &&
(!label || !clearButtonLabel || !loadingLabel)
) {
throw new Error(
'The ImageInput component is missing a `label`, a `clearButtonLabel` and/or a `loadingLabel` prop. This is an accessibility requirement.',
);
}
const inputRef = useRef<HTMLInputElement>(null);
const id = customId || uniqueId('image-input_');
const [isLoading, setIsLoading] = useState<boolean>(false);
const [isDragging, setDragging] = useState<boolean>(false);
const [previewImage, setPreviewImage] = useState<string>('');
const handleChange = (files?: FileList | null) => {
const file = files && files[0];
if (!file) {
return;
}
setPreviewImage('');
setIsLoading(true);
setPreviewImage(URL.createObjectURL(file));
Promise.resolve(onChange(file))
.then(() => setIsLoading(false))
.catch(() => setIsLoading(false));
};
const handleInputChange = (event: ChangeEvent<HTMLInputElement>) =>
handleChange(event.target.files);
const clearInputElement = () => {
if (inputRef.current) {
inputRef.current.value = '';
}
};
const handleClear = (event: ClickEvent) => {
Promise.resolve(onClear(event))
.then(() => {
clearInputElement();
setPreviewImage('');
})
.catch(() => {
clearInputElement();
setPreviewImage('');
});
};
/**
* We clear the input DOM element on click so that the onChange event is
* re-triggered if the same image is uploaded again.
*/
const handleClick = () => {
clearInputElement();
};
const handlePaste = (event: ClipboardEvent) => {
const { files } = event.clipboardData;
handleChange(files);
if (inputRef.current && files) {
// An error is thrown when trying to assign anything but a FileList here.
// For security reasons, it's not possible to simulate a FileList object.
// That's why this code has to be disabled during testing.
if (process.env.NODE_ENV !== 'test') {
inputRef.current.files = files;
}
}
};
const handleDragging = (event: DragEvent) => {
event.preventDefault();
event.stopPropagation();
setDragging(true);
};
const handleDragLeave = (event: DragEvent) => {
event.preventDefault();
event.stopPropagation();
setDragging(false);
};
const handleDrop = (event: DragEvent) => {
handleDragLeave(event);
const files = event.dataTransfer && event.dataTransfer.files;
handleChange(files);
if (inputRef.current && files) {
// An error is thrown when trying to assign anything but a FileList here.
// For security reasons, it's not possible to simulate a FileList object.
// That's why this code has to be disabled during testing.
if (process.env.NODE_ENV !== 'test') {
inputRef.current.files = files;
}
}
};
return (
<Fragment>
<InputWrapper onPaste={handlePaste}>
<HiddenInput
ref={inputRef}
id={id}
type="file"
accept="image/*"
onChange={handleInputChange}
onClick={handleClick}
disabled={disabled || isLoading}
aria-invalid={invalid}
{...props}
/>
<StyledLabel
isLoading={isLoading}
isDragging={isDragging}
invalid={invalid}
htmlFor={id}
onDragEnter={handleDragging}
onDragOver={handleDragging}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
<span css={hideVisually()}>{label}</span>
<Component src={src || previewImage} alt={alt || ''} />
</StyledLabel>
{src ? (
<ActionButton
type="button"
size="kilo"
variant="primary"
destructive
label={clearButtonLabel}
onClick={handleClear}
disabled={isLoading}
buttonSize={size}
>
<Delete size="16" />
</ActionButton>
) : (
<AddButton
type="button"
size="kilo"
variant="primary"
aria-hidden="true"
tabIndex={-1}
label="-" // We need to pass a label here to prevent IconButton from throwing
disabled={isLoading}
buttonSize={size}
>
<Plus size="16" />
</AddButton>
)}
<LoadingIcon isLoading={isLoading}>
<LoadingLabel>{loadingLabel}</LoadingLabel>
</LoadingIcon>
</InputWrapper>
<ValidationHint validationHint={validationHint} invalid={invalid} />
</Fragment>
);
}; | the_stack |
import 'jest-extended';
import { DataEntity, debugLogger, times } from '@terascope/utils';
import { ESCachedStateStorage, ESStateStorageConfig } from '../src';
import {
ESBulkQuery,
ESMGetResponse,
ESGetResponse,
ESGetParams,
ESMGetParams,
} from '../src/elasticsearch-state-storage';
// TODO: this should search against elasticsearch
describe('elasticsearch-state-storage', () => {
const logger = debugLogger('elasticsearch-state-storage');
let client: TestClient;
let stateStorage: ESCachedStateStorage;
async function setup(overrides?: Partial<ESStateStorageConfig>) {
const config: ESStateStorageConfig = Object.assign({
index: 'some_index',
type: 'sometype',
concurrency: 3,
source_fields: [],
chunk_size: 7,
cache_size: 100000,
max_big_map_size: 9,
persist: false,
meta_key_field: '_key'
}, overrides);
client = new TestClient(config);
stateStorage = new ESCachedStateStorage(client as any, logger, config);
await stateStorage.initialize();
}
async function teardown() {
if (stateStorage) {
await stateStorage.shutdown();
// @ts-expect-error
stateStorage = undefined;
}
if (client) {
// @ts-expect-error
client = undefined;
}
}
describe('getIdentifier', () => {
afterEach(() => teardown());
it('should use _key meta field by default', async () => {
await setup();
const testDoc = DataEntity.make({ data: 'data1', _key: 'key_1' }, { _key: 'key_1', _meta_key2: 'meta_key_2' });
const identifier = stateStorage.getIdentifier(testDoc);
expect(identifier).toBe('key_1');
});
it('should use meta_key field to get key if set in config', async () => {
await setup({ meta_key_field: '_meta_key2' });
const testDoc = DataEntity.make({ data: 'data1', _key: 'key_1' }, { _key: 'key_1', _meta_key2: 'meta_key_2' });
const identifier = stateStorage.getIdentifier(testDoc);
expect(identifier).toBe('meta_key_2');
});
it('should override meta_key_field if option given', async () => {
await setup({ meta_key_field: '_meta_key2' });
const testDoc = DataEntity.make({ data: 'data1', _key: 'key_1' }, { _key: 'key_1', _meta_key2: 'meta_key_2' });
const identifier = stateStorage.getIdentifier(testDoc, '_key');
expect(identifier).toBe('key_1');
});
});
describe('when given invalid data', () => {
beforeEach(() => setup());
afterEach(() => teardown());
describe('->get', () => {
it('should not create get requests with undefined keys', async () => {
const testDocs = [DataEntity.make({ data: 'someValue' })];
await expect(stateStorage.get(testDocs[0])).rejects.toThrowError(/There is no field "_key" set in the metadata/);
});
});
});
describe('->get', () => {
describe('when the found in cache', () => {
const doc = makeTestDoc();
let result: DataEntity|undefined;
beforeAll(async () => {
await setup();
stateStorage.set(doc);
result = await stateStorage.get(doc);
});
afterAll(() => teardown());
it('should pull the same reference', async () => {
expect(result).not.toBeUndefined();
expect(result).toEqual(doc);
expect(result).toBe(doc);
});
});
describe('when the NOT found in cache but in es', () => {
const doc = makeTestDoc();
const esDoc = copyDataEntity(doc);
let result: DataEntity|undefined;
beforeAll(async () => {
await setup();
client.setGetResponse(client.createGetResponse(esDoc));
result = await stateStorage.get(doc);
});
afterAll(() => teardown());
it('should pull the es reference from the cache', async () => {
expect(result).not.toBeUndefined();
expect(result).toEqual(esDoc);
expect(result).not.toBe(doc);
expect(result).not.toEqual(doc);
});
});
describe('when the NOT found in cache and NOT in es', () => {
const doc = makeTestDoc();
const esDoc = copyDataEntity(doc);
let result: DataEntity|undefined;
beforeAll(async () => {
await setup();
client.setGetResponse(client.createGetResponse(esDoc, false));
result = await stateStorage.get(doc);
});
afterAll(() => teardown());
it('should return undefined', async () => {
expect(result).toBeUndefined();
});
});
describe('when using an unknown doc', () => {
const doc = makeTestDoc();
let result: DataEntity|undefined;
beforeAll(async () => {
await setup();
result = await stateStorage.get(doc);
});
afterAll(() => teardown());
it('should return undefined', async () => {
expect(result).toBeUndefined();
});
});
});
describe('->isKeyCached', () => {
beforeEach(() => setup());
afterEach(() => teardown());
describe('when the record is in the cache', () => {
const doc = makeTestDoc();
const key = doc.getKey();
beforeEach(() => {
stateStorage.set(doc);
});
it('should return true', async () => {
expect(stateStorage.isKeyCached(key)).toBeTrue();
});
});
describe('when the record is NOT in the cache', () => {
it('should return false', async () => {
expect(stateStorage.isKeyCached('uhoh')).toBeFalse();
});
});
});
describe('->isCached', () => {
const doc = makeTestDoc();
const key = doc.getKey();
beforeAll(async () => {
await setup();
stateStorage.set(doc);
});
afterAll(() => teardown());
describe('when the record is in the cache', () => {
it('should return true using the original doc', async () => {
expect(stateStorage.isCached(doc)).toBeTrue();
});
it('should return true after getting it from the cache', async () => {
const cached = stateStorage.getFromCacheByKey(key);
if (!cached) {
expect(cached).not.toBeNil();
return;
}
expect(stateStorage.isCached(cached)).toBeTrue();
});
});
describe('when the record is NOT in the cache', () => {
it('should return true using the original doc', async () => {
expect(stateStorage.isCached(doc)).toBeTrue();
});
it('should return true after getting it from the cache', async () => {
const cached = stateStorage.getFromCacheByKey(key);
if (!cached) {
expect(cached).not.toBeNil();
return;
}
expect(stateStorage.isCached(cached)).toBeTrue();
});
});
});
describe('->getFromCache', () => {
describe('when the record is found', () => {
const doc = makeTestDoc();
beforeAll(async () => {
await setup();
stateStorage.set(doc);
});
afterAll(() => teardown());
it('should return the same reference to the doc', () => {
const cached = stateStorage.getFromCache(doc);
expect(cached).toBe(doc);
expect(cached).toEqual(doc);
});
});
describe('when the record has been updated in the cache', () => {
const doc = makeTestDoc();
const newDoc = copyDataEntity(doc);
beforeAll(async () => {
await setup();
stateStorage.set(doc);
stateStorage.set(newDoc);
});
afterAll(() => teardown());
it('should return the new reference to the doc', () => {
const cached = stateStorage.getFromCache(doc);
expect(cached).toBe(newDoc);
});
});
describe('when the record is NOT found in es and the cache', () => {
const doc = makeTestDoc();
beforeAll(() => setup());
afterAll(() => teardown());
it('should return undefined', () => {
expect(stateStorage.getFromCache(doc)).toBeUndefined();
});
});
});
describe('->mset', () => {
describe('when presist is false', () => {
beforeEach(() => setup());
afterEach(() => teardown());
it('should save many docs to cache and retrieve', async () => {
const docArray = makeTestDocs();
await stateStorage.mset(docArray);
const saved = [];
for (const doc of docArray) {
const savedDoc = await stateStorage.get(doc);
saved.push(savedDoc);
expect(DataEntity.isDataEntity(savedDoc)).toEqual(true);
}
expect(saved).toEqual(docArray);
});
});
describe('when presist is true', () => {
beforeEach(() => setup({
persist: true
}));
afterEach(() => teardown());
it('should make an es bulk request with correct key value', async () => {
const docArray = makeTestDocs();
await stateStorage.mset(docArray);
expect(client._bulkRequest).toBeArrayOfSize(6);
expect(client._bulkRequest[0].index._id).toBe('key-0');
expect(client._bulkRequest[1]).toEqual(docArray[0]);
expect(client._bulkRequest[2].index._id).toBe('key-1');
expect(client._bulkRequest[3]).toEqual(docArray[1]);
expect(client._bulkRequest[4].index._id).toBe('key-2');
expect(client._bulkRequest[5]).toEqual(docArray[2]);
});
});
describe('when presist is true and meta_key_field is specified', () => {
const otherDocArray = makeTestDocs(10);
beforeEach(() => setup({
persist: true,
meta_key_field: 'otherField',
chunk_size: 100,
}));
afterEach(() => teardown());
it('should use meta_key_field for mget query', async () => {
// mget response docs _key will be the otherfield
const mgetResponse = otherDocArray.map((doc) => {
const other = doc.getMetadata('otherField');
doc.setMetadata('_key', other);
return doc;
});
// create es mget response
const mget = client.createMGetResponse(mgetResponse.slice(0, 4));
const notFound = client.createMGetResponse(mgetResponse.slice(4), false);
notFound.docs.forEach((item) => mget.docs.push(item));
client.setMGetResponse(mget);
await stateStorage.mset(otherDocArray.slice(4, 6));
const result = await stateStorage.mget(otherDocArray);
expect(Object.keys(result).length).toBe(6);
expect(result['other-0']).toEqual({ data: 'data-0' });
expect(result['other-1']).toEqual({ data: 'data-1' });
expect(result['other-2']).toEqual({ data: 'data-2' });
});
it('should use returned docs _key for mset', async () => {
await stateStorage.mset(otherDocArray);
expect(client._bulkRequest).toBeArrayOfSize(20);
expect(client._bulkRequest[0].index._id).toBe('other-0');
expect(client._bulkRequest[1]).toEqual(otherDocArray[0]);
expect(client._bulkRequest[2].index._id).toBe('other-1');
expect(client._bulkRequest[3]).toEqual(otherDocArray[1]);
expect(client._bulkRequest[4].index._id).toBe('other-2');
expect(client._bulkRequest[5]).toEqual(otherDocArray[2]);
});
});
});
describe('->mget', () => {
beforeEach(() => setup());
afterEach(() => teardown());
it('should return object with all docs in cache and in es request', async () => {
const docArray = makeTestDocs(100);
// add some duplicates to the incoming docs
const dupArray = docArray.concat(docArray.slice(0, 20));
const docObj = docsToObject(docArray);
stateStorage.mset(docArray.slice(0, 30));
// create bulk response
client.setMGetResponse(client.createMGetResponse(docArray.slice(30, 50)));
// state response
const stateResponse = await stateStorage.mget(dupArray);
const keys = Object.keys(stateResponse);
expect(keys).toBeArrayOfSize(50);
keys.forEach((id: string) => {
expect(stateResponse[id]).toEqual(docObj[id]);
expect(DataEntity.isDataEntity(stateResponse[id])).toEqual(true);
const metaId = stateResponse[id].getKey();
expect(metaId).toEqual(id);
});
});
it('should not evict docs in current slice', async () => {
setup({ cache_size: 15 });
const docArray = makeTestDocs(20);
const firstSlice = docArray.slice(0, 10);
const secondSlice = docArray.slice(9);
client.setMGetResponse(client.createMGetResponse(firstSlice));
const firstResult = await stateStorage.mget(firstSlice);
expect(firstResult['key-9']).toBeDefined();
expect(Object.keys(firstResult)).toBeArrayOfSize(10);
expect(stateStorage.isKeyCached('key-9')).toBeTrue();
// create bulk response
client.setMGetResponse(client.createMGetResponse(secondSlice));
// state response
const secondResult = await stateStorage.mget(secondSlice);
const keys = Object.keys(secondResult);
expect(stateStorage.isKeyCached('key-9')).toBeTrue();
expect(secondResult['key-9']).toBeDefined();
expect(keys).toBeArrayOfSize(11);
});
});
describe('-> mget when testing a large data set', () => {
beforeEach(() => setup());
afterEach(() => teardown());
it('should return all the found and cached docs', async () => {
const docArray = makeTestDocs(5000);
const docObj = docsToObject(docArray);
// found by es
const mgetDocs = client.createMGetResponse(docArray.slice(0, 2000), true);
// not found by es
const notFoundDocs = client.createMGetResponse(docArray.slice(2000, 3000), false);
notFoundDocs.docs.forEach((item) => mgetDocs.docs.push(item));
// some docs already saved in cache
await stateStorage.mset(docArray.slice(3000, 5000));
// check that docs are in cache
expect(stateStorage.count()).toBe(2000);
// check on a doc
const getCheck = await stateStorage.get(docObj['key-3483']);
expect(getCheck).toEqual(docObj['key-3483']);
client.setMGetResponse(mgetDocs);
// retrieve all the docs
const mgetResult = await stateStorage.mget(docArray);
// should not be any unfound docs
expect(Object.keys(mgetResult).length).toBe(4000);
// check a found es mget doc
expect(mgetResult['key-1283']).toEqual(docObj['key-1283']);
// check a found cached doc
expect(mgetResult['key-4483']).toEqual(docObj['key-4483']);
// check an unfound doc
expect(mgetResult['key-2381']).toBeUndefined();
// add a larger timeout
}, 25 * 1000);
});
});
function makeTestDocs(records = 3): DataEntity[] {
return times(records, (n) => DataEntity.make({
data: `data-${n}`
}, {
_key: `key-${n}`,
otherField: `other-${n}`
}));
}
function makeTestDoc() {
return makeTestDocs()[0];
}
function docsToObject(docs: DataEntity[]): { [key: string]: DataEntity } {
const obj: { [key: string]: DataEntity } = {};
for (const doc of docs) {
const key = doc.getKey();
obj[key] = doc;
}
return obj;
}
function copyDataEntity(doc: DataEntity): DataEntity {
const key = doc.getKey();
const updated = Object.assign({}, doc, { copy: `copy-${key}` });
return DataEntity.make(updated, doc.getMetadata());
}
interface BulkRequest {
body: ESBulkQuery[];
}
class TestClient {
private _getResponse!: ESGetResponse;
private _mgetResponse!: ESMGetResponse;
_bulkRequest!: ESBulkQuery[];
private _config: ESStateStorageConfig;
constructor(config: ESStateStorageConfig) {
this._config = config;
}
createGetResponse(doc: DataEntity, found = true): ESGetResponse {
return this.createMGetResponse([doc], found).docs[0];
}
createMGetResponse(dataArray: DataEntity[], found = true): ESMGetResponse {
const docs = dataArray.map((item) => {
const id = item.getKey();
if (!id) throw new Error('Missing _key on test record');
if (typeof id !== 'string') throw new Error('Invalid _key on test record');
const response: ESGetResponse = {
_index: this._config.index,
_type: this._config.type,
_version: 1,
_id: id,
found,
};
if (found) {
// convert to reg obj to simulate ES response
response._source = Object.assign({}, item);
} else {
// @ts-expect-error
response._type = null;
delete (response as any)._version;
}
return response;
});
return {
docs,
};
}
setGetResponse(response: ESGetResponse) {
this._getResponse = response;
}
setMGetResponse(response: ESMGetResponse) {
this._mgetResponse = response;
}
async get(params: ESGetParams) {
if (params.index !== this._config.index) {
throw new Error(`Invalid index ${params.index} on fake get`);
}
if (params.type !== this._config.type) {
throw new Error(`Invalid type ${params.type} on fake get`);
}
if (!params.id || typeof params.id !== 'string') {
throw new Error('Invalid id to get');
}
return this._getResponse;
}
async mget(params: ESMGetParams) {
const ids = params.body && params.body.ids;
const invalidMsg = 'Invalid test data for mget';
if (!ids || !Array.isArray(ids)) {
throw new Error(`${invalidMsg}, expected ids to be an array`);
}
if (params.index !== this._config.index) {
throw new Error(`${invalidMsg}, expected type in request ${params.index}`);
}
if (params.type !== this._config.type) {
throw new Error(`${invalidMsg}, expected type in request ${params.type}`);
}
if (!this._mgetResponse || !Array.isArray(this._mgetResponse.docs)) {
throw new Error(`${invalidMsg}, expected response.docs to be an array`);
}
if (ids.length > this._mgetResponse.docs.length) {
const responseIds = this._mgetResponse.docs.map((result) => result._id);
throw new Error(`${invalidMsg}, expected ${JSON.stringify(responseIds, null, 2)} === ${JSON.stringify(ids, null, 2)}`);
}
for (const doc of this._mgetResponse.docs) {
if (doc._index !== this._config.index) {
throw new Error(`${invalidMsg}, expected index on record ${JSON.stringify(doc, null, 2)}`);
}
if (doc.found && doc._type !== this._config.type) {
throw new Error(`${invalidMsg}, expected type on record ${JSON.stringify(doc, null, 2)}`);
}
}
return this._mgetResponse;
}
async bulk(request: BulkRequest) {
this._bulkRequest = request.body;
return request;
}
} | the_stack |
import { expect } from 'chai';
import { backtest } from '../../lib/backtest';
import { DataFrame, IDataFrame } from 'data-forge';
import { IBar } from '../../lib/bar';
import { IStrategy, EnterPositionFn, IEntryRuleArgs, ExitPositionFn, IExitRuleArgs, TradeDirection } from '../../lib/strategy';
import * as moment from 'dayjs';
describe("backtest", () => {
function round(value: number) {
return Math.round(value * 100) / 100;
}
function makeDate(dateStr: string, fmt?: string): Date {
return moment(dateStr, fmt || "YYYY/MM/DD").toDate();
}
function mockBar(): IBarDef {
return {
time: "2018/10/20",
close: 2,
};
}
interface IBarDef {
time: string;
open?: number;
high?: number;
low?: number;
close: number;
volume?: number;
}
function makeBar(bar: IBarDef): IBar {
return {
time: makeDate(bar.time),
open: bar.open !== undefined ? bar.open : bar.close,
high: bar.high !== undefined ? bar.high : bar.close,
low: bar.low !== undefined ? bar.low : bar.close,
close: bar.close,
volume: bar.volume !== undefined ? bar.volume : 1,
};
}
function makeDataSeries(bars: IBarDef[]): IDataFrame<number, IBar> {
return new DataFrame<number, IBar>(bars.map(makeBar));
}
const mockEntry = () => {};
const mockExit = () => {};
function mockStrategy(): IStrategy {
return {
entryRule: mockEntry,
exitRule: mockExit,
};
}
function unconditionalLongEntry(enterPosition: EnterPositionFn, args: IEntryRuleArgs<IBar, {}>) {
enterPosition({ direction: TradeDirection.Long }); // Unconditionally enter position at market price.
};
function unconditionalLongExit(exitPosition: ExitPositionFn, args: IExitRuleArgs<IBar, {}>) {
exitPosition(); // Unconditionally exit position at market price.
};
const strategyWithUnconditionalEntry: IStrategy = {
entryRule: unconditionalLongEntry,
exitRule: mockExit,
};
const longStrategyWithUnconditionalEntryAndExit: IStrategy = {
entryRule: unconditionalLongEntry,
exitRule: unconditionalLongExit,
};
const simpleInputSeries = makeDataSeries([
{ time: "2018/10/20", close: 1 },
{ time: "2018/10/21", close: 2 },
{ time: "2018/10/22", close: 3 },
]);
const longerDataSeries = makeDataSeries([
{ time: "2018/10/20", close: 1 },
{ time: "2018/10/21", close: 2 },
{ time: "2018/10/22", close: 4 },
{ time: "2018/10/23", close: 5 },
{ time: "2018/10/24", close: 6 },
]);
it("generates no trades when no entry is ever taken", () => {
const trades = backtest(mockStrategy(), makeDataSeries([mockBar()]));
expect(trades.length).to.eql(0);
});
it("must pass in 1 or more bars", () => {
expect(() => backtest(mockStrategy(), new DataFrame<number, IBar>())).to.throw();
});
it('unconditional entry rule with no exit creates single trade', () => {
const trades = backtest(strategyWithUnconditionalEntry, simpleInputSeries);
expect(trades.length).to.eql(1);
});
it('enters position at open on day after signal', () => {
const inputSeries = makeDataSeries([
{ time: "2018/10/20", open: 1, close: 2 },
{ time: "2018/10/21", open: 3, close: 4 }, // Enter position at open on this day.
{ time: "2018/10/22", open: 5, close: 6 },
]);
const trades = backtest(strategyWithUnconditionalEntry, inputSeries);
const singleTrade = trades[0];
expect(singleTrade.entryPrice).to.eql(3);
});
it('enters position at open on day after signal', () => {
const inputSeries = makeDataSeries([
{ time: "2018/10/20", open: 1, close: 2 },
{ time: "2018/10/21", open: 3, close: 4 }, // Enter position at open on this day.
{ time: "2018/10/22", open: 5, close: 6 },
]);
const trades = backtest(strategyWithUnconditionalEntry, inputSeries);
const singleTrade = trades[0];
expect(singleTrade.entryPrice).to.eql(3);
});
it('unconditional entry rule creates single trade that is finalized at end of trading period', () => {
const trades = backtest(strategyWithUnconditionalEntry, simpleInputSeries);
expect(trades.length).to.eql(1);
const singleTrade = trades[0];
expect(singleTrade.exitTime).to.eql(makeDate("2018/10/22"));
expect(singleTrade.exitReason).to.eql("finalize");
});
it('open position is finalized on the last day of the trading period', () => {
const trades = backtest(strategyWithUnconditionalEntry, simpleInputSeries);
const singleTrade = trades[0];
expect(singleTrade.exitTime).to.eql(makeDate("2018/10/22"));
});
it('open position is finalized at end of trading period at the closing price', () => {
const inputSeries = makeDataSeries([
{ time: "2018/10/20", open: 1, close: 2 },
{ time: "2018/10/21", open: 3, close: 4 }, // Enter position at open on this day.
{ time: "2018/10/22", open: 5, close: 6 },
]);
const trades = backtest(strategyWithUnconditionalEntry, inputSeries);
const singleTrade = trades[0];
expect(singleTrade.exitPrice).to.eql(6);
});
it("conditional entry can be triggered within the trading period", () => {
const strategy: IStrategy = {
entryRule: (enterPosition, args) => {
if (args.bar.close > 3) {
enterPosition(); // Conditional enter when instrument closes above 3.
}
},
exitRule: mockExit,
};
const inputSeries = makeDataSeries([
{ time: "2018/10/20", close: 1 },
{ time: "2018/10/21", close: 2 },
{ time: "2018/10/22", close: 4 }, // Entry signal.
{ time: "2018/10/23", close: 5 }, // Entry day.
{ time: "2018/10/24", close: 6 },
]);
const trades = backtest(strategy, inputSeries);
expect(trades.length).to.eql(1);
const singleTrade = trades[0];
expect(singleTrade.entryTime).to.eql(makeDate("2018/10/23"));
});
it("conditional entry triggers entry at opening price of next bar", () => {
const strategy: IStrategy = {
entryRule: (enterPosition, args) => {
if (args.bar.close > 5) {
enterPosition(); // Conditional enter when instrument closes above 3.
}
},
exitRule: mockExit,
};
const inputSeries = makeDataSeries([
{ time: "2018/10/20", open: 1, close: 2 },
{ time: "2018/10/21", open: 3, close: 4 },
{ time: "2018/10/22", open: 5, close: 6 }, // Entry signal day.
{ time: "2018/10/23", open: 7, close: 8 }, // Entry day.
{ time: "2018/10/24", open: 9, close: 10 },
]);
const trades = backtest(strategy, inputSeries);
const singleTrade = trades[0];
expect(singleTrade.entryPrice).to.eql(7);
});
it("conditional entry is not triggered when condition is not met", () => {
const strategy: IStrategy = {
entryRule: (enterPosition, args) => {
if (args.bar.close > 10) {
enterPosition(); // Conditional enter when instrument closes above 3.
}
},
exitRule: mockExit,
};
const trades = backtest(strategy, longerDataSeries);
expect(trades.length).to.eql(0);
});
it("can conditionally exit before end of trading period", () => {
const strategy: IStrategy = {
entryRule: unconditionalLongEntry,
exitRule: (exitPosition, args) => {
if (args.bar.close > 3) {
exitPosition(); // Exit at next open.
}
},
};
const inputSeries = makeDataSeries([
{ time: "2018/10/20", close: 1 },
{ time: "2018/10/21", close: 2 }, // Entry day.
{ time: "2018/10/22", close: 4 }, // Exit signal.
{ time: "2018/10/23", close: 5 }, // Exit day.
{ time: "2018/10/24", close: 6 },
]);
const trades = backtest(strategy, inputSeries);
expect(trades.length).to.eql(1);
const singleTrade = trades[0];
expect(singleTrade.exitTime).to.eql(makeDate("2018/10/23"));
expect(singleTrade.exitReason).to.eql("exit-rule");
});
it("exits position with opening price of next bar", () => {
const strategy: IStrategy = {
entryRule: unconditionalLongEntry,
exitRule: (exitPosition, args) => {
if (args.bar.close > 5) {
exitPosition(); // Exit at next open.
}
},
};
const inputSeries = makeDataSeries([
{ time: "2018/10/20", open: 1, close: 2 },
{ time: "2018/10/21", open: 3, close: 4 }, // Entry
{ time: "2018/10/22", open: 5, close: 6 }, // Exits signal day.
{ time: "2018/10/23", open: 7, close: 8 }, // Exit day.
{ time: "2018/10/24", open: 9, close: 10 },
]);
const trades = backtest(strategy, inputSeries);
const singleTrade = trades[0];
expect(singleTrade.exitPrice).to.eql(7);
});
it("profit is computed for conditionally exited position", () => {
const strategy: IStrategy = {
entryRule: unconditionalLongEntry,
exitRule: (exitPosition, args) => {
if (args.bar.close > 3) {
exitPosition(); // Exit at next open.
}
},
};
const inputData = makeDataSeries([
{ time: "2018/10/20", close: 1 },
{ time: "2018/10/21", close: 5}, // Unconditionally enter here.
{ time: "2018/10/22", close: 6 }, // Exit signal.
{ time: "2018/10/23", close: 10 }, // Exit.
{ time: "2018/10/24", close: 100 }, // Last bar.
]);
const trades = backtest(strategy, inputData);
expect(trades.length).to.eql(1);
const singleTrade = trades[0];
expect(singleTrade.exitTime).to.eql(makeDate("2018/10/23"));
expect(singleTrade.profit).to.eql(5);
expect(singleTrade.profitPct).to.eql(100);
expect(singleTrade.growth).to.eql(2);
});
it("can exit based on intra-trade profit", () => {
const strategy: IStrategy = {
entryRule: unconditionalLongEntry,
exitRule: (exitPosition, args) => {
if (args.position.profitPct <= -50) {
exitPosition(); // Exit at 50% loss
}
},
};
const inputData = makeDataSeries([
{ time: "2018/10/20", close: 100 },
{ time: "2018/10/21", close: 100 }, // Entry day.
{ time: "2018/10/22", close: 20 }, // Big loss, exit signal.
{ time: "2018/10/23", close: 10 }, // Exit.
{ time: "2018/10/24", close: 1 },
]);
const trades = backtest(strategy, inputData);
expect(trades.length).to.eql(1);
const singleTrade = trades[0];
expect(singleTrade.exitTime).to.eql(makeDate("2018/10/23"));
expect(singleTrade.exitPrice).to.eql(10);
});
it("can exit position after max holding period", () => {
const strategy: IStrategy = {
entryRule: unconditionalLongEntry,
exitRule: (exitPosition, args) => {
if (args.position.holdingPeriod >= 3) {
exitPosition(); // Exit after holding for 3 days.
}
},
};
const inputData = makeDataSeries([
{ time: "2018/10/20", close: 1 },
{ time: "2018/10/21", close: 2 }, // Entry day.
{ time: "2018/10/22", close: 3 }, // 1 day
{ time: "2018/10/23", close: 4 }, // 2 days
{ time: "2018/10/24", close: 5 }, // 3 days
{ time: "2018/10/25", close: 6 }, // Exit day (after 3 days).
{ time: "2018/10/26", close: 7 },
]);
const trades = backtest(strategy, inputData);
expect(trades.length).to.eql(1);
const singleTrade = trades[0];
expect(singleTrade.exitTime).to.eql(makeDate("2018/10/25"));
expect(singleTrade.exitPrice).to.eql(6);
});
it("can execute multiple trades", () => {
const strategy: IStrategy = {
entryRule: (enterPosition, args) => {
if ((args.bar.close - args.bar.open) > 0) {
enterPosition(); // Enter on up day.
}
},
exitRule: (exitPosition, args) => {
if (args.position.profitPct > 1.5) {
exitPosition(); // Exit on small profit
}
},
};
const inputSeries = makeDataSeries([
{ time: "2018/10/20", open: 1, close: 1 }, // Flat, no signal.
{ time: "2018/10/21", open: 2, close: 3 }, // Up day, entry signal.
{ time: "2018/10/22", open: 4, close: 4 }, // Flat, in position.
{ time: "2018/10/23", open: 5, close: 6 }, // Good profit, exit signal
{ time: "2018/10/24", open: 9, close: 10 }, // Exit day.
{ time: "2018/10/25", open: 1, close: 1 }, // Flat, no signal.
{ time: "2018/10/26", open: 2, close: 3 }, // Up day, entry signal.
{ time: "2018/10/27", open: 4, close: 4 }, // Flat, in position.
{ time: "2018/10/28", open: 5, close: 6 }, // Good profit, exit signal
{ time: "2018/10/29", open: 9, close: 10 }, // Exit day.
{ time: "2018/10/30", open: 11, close: 11 }, // Last bar.
]);
const trades = backtest(strategy, inputSeries);
expect(trades.length).to.eql(2);
});
interface CustomBar extends IBar {
goLong: number; // Custom indicator, indicates 'buy now'.
}
it("can use custom bar type and enter/exit on computed indicator", () => {
const strategy: IStrategy<CustomBar> = {
entryRule: (enterPosition, args) => {
if (args.bar.goLong > 0) {
enterPosition(); // Enter on custom indicator.
}
},
exitRule: (exitPosition, args) => {
if (args.bar.goLong < 1) {
exitPosition(); // Exit on custom indicator.
}
},
};
const bars: CustomBar[] = [
{ time: makeDate("2018/10/20"), open: 1, high: 2, low: 1, close: 2, volume: 1, goLong: 0 },
{ time: makeDate("2018/10/21"), open: 3, high: 4, low: 3, close: 4, volume: 1, goLong: 1 }, // Entry signal.
{ time: makeDate("2018/10/22"), open: 5, high: 6, low: 5, close: 6, volume: 1, goLong: 1 }, // Entry day.
{ time: makeDate("2018/10/23"), open: 7, high: 8, low: 7, close: 8, volume: 1, goLong: 0 }, // Exit signal.
{ time: makeDate("2018/10/24"), open: 9, high: 10, low: 8, close: 10, volume: 1, goLong: 0 }, // Exit day.
{ time: makeDate("2018/10/25"), open: 11, high: 12, low: 11, close: 12, volume: 1, goLong: 0 }, // Last bar.
];
const inputSeries = new DataFrame<number, CustomBar>(bars);
const trades = backtest(strategy, inputSeries);
expect(trades.length).to.eql(1);
const singleTrade = trades[0];
expect(singleTrade.entryTime).to.eql(makeDate("2018/10/22"));
expect(singleTrade.entryPrice).to.eql(5);
expect(singleTrade.exitTime).to.eql(makeDate("2018/10/24"));
expect(singleTrade.exitPrice).to.eql(9);
});
it("example of caching a custom indicator before doing the backtest", () => {
const strategy: IStrategy<CustomBar> = {
entryRule: (enterPosition, args) => {
if (args.bar.goLong > 0) {
enterPosition(); // Enter on custom indicator.
}
},
exitRule: (exitPosition, args) => {
if (args.bar.goLong < 1) {
exitPosition(); // Exit on custom indicator.
}
},
};
const inputSeries = makeDataSeries([
{ time: "2018/10/20", open: 1, close: 1 }, // Flat, no signal.
{ time: "2018/10/21", open: 2, close: 3 }, // Up day, entry signal.
{ time: "2018/10/22", open: 4, close: 4 }, // Flat, in position.
{ time: "2018/10/23", open: 5, close: 6 }, // Good profit, exit signal
{ time: "2018/10/24", open: 9, close: 10 }, // Exit day.
{ time: "2018/10/25", open: 1, close: 1 }, // Flat, no signal.
{ time: "2018/10/26", open: 2, close: 3 }, // Up day, entry signal.
{ time: "2018/10/27", open: 4, close: 4 }, // Flat, in position.
{ time: "2018/10/28", open: 5, close: 6 }, // Good profit, exit signal
{ time: "2018/10/29", open: 9, close: 10 }, // Exit day.
{ time: "2018/10/30", open: 11, close: 11 }, // Last bar.
]);
const augumentedInputSeries = inputSeries
.generateSeries<CustomBar>(bar => {
let goLong = 0;
if ((bar.close - bar.open) > 0) {
goLong = 1; // Entry triggered by an up day.
}
return { goLong }; // Added new series to dataframe.
});
const trades = backtest(strategy, augumentedInputSeries);
expect(trades.length).to.eql(2);
});
it("passes through exception in entry rule", () => {
const badStrategy: IStrategy = {
entryRule: () => {
throw new Error("Bad rule!");
},
exitRule: () => {},
};
expect(() => backtest(badStrategy, simpleInputSeries)).to.throw();
});
it("passes through exception in exit rule", () => {
const badStrategy: IStrategy = {
entryRule: unconditionalLongEntry,
exitRule: () => {
throw new Error("Bad rule!");
},
};
expect(() => backtest(badStrategy, simpleInputSeries)).to.throw();
});
it("can set lookback period and use data series in entry rule", () => {
let lookbackPeriodChecked = false;
const strategy: IStrategy = {
lookbackPeriod: 2,
entryRule: (enterPosition, args) => {
lookbackPeriodChecked = true;
expect(args.lookback.count()).to.eql(2);
},
exitRule: () => {},
};
backtest(strategy, longerDataSeries);
expect(lookbackPeriodChecked).to.eql(true);
});
it("can set lookback period and use data series in exit rule", () => {
let lookbackPeriodChecked = false;
const strategy: IStrategy = {
lookbackPeriod: 2,
entryRule: unconditionalLongEntry,
exitRule: (exitPosition, args) => {
lookbackPeriodChecked = true;
expect(args.lookback.count()).to.eql(2);
},
};
backtest(strategy, longerDataSeries);
expect(lookbackPeriodChecked).to.eql(true);
});
it("exception is thrown when there is less data than the lookback period", () => {
const strategy: IStrategy = {
lookbackPeriod: 30,
entryRule: mockEntry,
exitRule: mockExit,
};
expect(() => backtest(strategy, simpleInputSeries)).to.throw();
});
it("can record trailing stop loss", () => {
const strategy: IStrategy = {
entryRule: unconditionalLongEntry,
trailingStopLoss: args => args.bar.close * (50/100)
};
const inputSeries = makeDataSeries([
{ time: "2018/10/20", close: 100 },
{ time: "2018/10/21", close: 200 },
{ time: "2018/10/22", close: 300 },
{ time: "2018/10/23", close: 200 },
{ time: "2018/10/24", close: 500 },
{ time: "2018/10/25", close: 400 },
{ time: "2018/10/26", close: 800 },
]);
const trades = backtest(strategy, inputSeries, { recordStopPrice: true });
expect(trades.length).to.eql(1);
const singleTrade = trades[0];
expect(singleTrade.stopPriceSeries!).to.eql([
{
time: makeDate("2018/10/21"),
value: 100,
},
{
time: makeDate("2018/10/22"),
value: 150,
},
{
time: makeDate("2018/10/23"),
value: 150,
},
{
time: makeDate("2018/10/24"),
value: 250,
},
{
time: makeDate("2018/10/25"),
value: 250,
},
{
time: makeDate("2018/10/26"),
value: 400,
},
]);
});
}); | the_stack |
import {
App,
MarkdownPostProcessorContext,
Plugin,
PluginSettingTab,
Setting,
FileSystemAdapter,
MarkdownRenderer,
Notice,
WorkspaceLeaf,
FileView,
TFile
} from 'obsidian';
import { spawn, exec, ChildProcess } from 'child_process';
import { v4 as uuid } from 'uuid';
import { statSync, writeFileSync, readFileSync, rm } from 'fs';
import { HttpClient } from 'typed-rest-client/HttpClient';
import { tmpdir } from 'os';
// https://stackoverflow.com/a/47614491/1150961.
function setInnerHTML(elm: Element, html: string) {
elm.innerHTML = html;
Array.from(elm.querySelectorAll("script")).forEach( oldScript => {
const newScript = document.createElement("script");
Array.from(oldScript.attributes)
.forEach( attr => newScript.setAttribute(attr.name, attr.value) );
newScript.appendChild(document.createTextNode(oldScript.innerHTML));
oldScript.parentNode.replaceChild(newScript, oldScript);
});
}
interface JupyterPluginSettings {
pythonInterpreter: string;
setupScript: string;
}
const DEFAULT_SETTINGS: JupyterPluginSettings = {
pythonInterpreter: 'python',
setupScript: '',
}
class JupterPreview extends FileView {
interpreter: string;
constructor(leaf: WorkspaceLeaf, interpreter: string) {
super(leaf);
// Show a placeholder before we've converted the notebook.
this.contentEl.innerHTML = 'Converting notebook...';
this.interpreter = interpreter;
}
onLoadFile(file: TFile): Promise<void> {
// Get the base path of the vault.
let adapter = file.vault.adapter;
if (!(adapter instanceof FileSystemAdapter)) {
this.contentEl.innerHTML = 'Could not determine notebook path.';
return null;
}
// Convert the file by writing it to a temporary location. Piping unfortunately leads to
// problems for long lines due to buffer overflows.
let basePath = adapter.getBasePath();
let filename = `${basePath}/${file.path}`;
let htmlPath = `${tmpdir()}/${uuid()}.html`;
let args = ['-m', 'nbconvert', `--output=${htmlPath}`, '--to=html', filename];
let child = spawn(this.interpreter, args);
// Process the output and delete the temporary file.
child.on('close', (code: number) => {
if (code) {
this.contentEl.innerHTML = 'Failed to convert notebook to HTML.';
} else {
setInnerHTML(this.contentEl, readFileSync(htmlPath).toString());
}
rm(htmlPath, () => null);
})
return null;
}
getViewType(): string {
return 'ipynb';
}
canAcceptExtension(extension: string): boolean {
return extension === 'ipynb';
}
}
class JupyterClient {
process: ChildProcess;
promises: Map<string, any>;
stdoutParts: string[];
interpreter: string;
processStdOut(data: any) {
this.stdoutParts.push(data.toString());
if (this.stdoutParts.last().endsWith('\n')) {
let response = JSON.parse(this.stdoutParts.join(''));
console.log('received response', response);
this.stdoutParts = [];
let promise = this.promises.get(response.id);
if (promise === undefined) {
console.error(`received response for unrecognised promise: ${response.id}`);
return;
}
promise(response.body);
}
}
processStdErr(data: any) {
console.log(data.toString());
}
constructor (interpreter: string, args?: string[], options?: any) {
this.interpreter = interpreter;
this.process = spawn(interpreter, args, options);
this.process.stdout.on('data', this.processStdOut.bind(this));
this.process.stderr.on('data', this.processStdErr.bind(this));
this.process.on('error', console.log);
this.promises = new Map();
this.stdoutParts = [];
}
async request(body: any): Promise<any> {
// Generate a random identifier.
let id = uuid();
// Send the request (\n terminated to make sure it gets picked up by the python process).
let data = JSON.stringify({id: id, body: body});
this.process.stdin.write(data + '\n');
// Create a resolvable promise and store it against the id.
let resolve;
let reject;
let promise = new Promise((resolve_, reject_) => {
resolve = resolve_;
reject = reject_;
})
this.promises.set(id, resolve);
return promise;
}
stop() {
this.process.stdin.end();
}
}
export default class JupyterPlugin extends Plugin {
settings: JupyterPluginSettings;
clients: Map<string, JupyterClient>;
async postprocessor(src: string, el: HTMLElement, ctx: MarkdownPostProcessorContext) {
// Render the code using the default renderer for python.
await MarkdownRenderer.renderMarkdown('```python\n' + src + '```', el, '',
this.app.workspace.activeLeaf.view);
// Needed for positioning of the button and hiding Jupyter prompts.
el.classList.add('obsidian-jupyter');
// Add a button to run the code.
let button = el.querySelector('pre').createEl('button', {
type: 'button',
text: 'Run',
cls: 'copy-code-button',
});
button.setAttribute('style', `right: 32pt`);
button.addEventListener('click', () => {
button.innerText = 'Running...';
this.getJupyterClient(ctx).request({
command: 'execute',
source: `${this.settings.setupScript}\n${src}`,
}).then(response => {
// Find the div to paste the output into or create it if necessary.
let output = el.querySelector('div.obsidian-jupyter-output');
if (output == null) {
output = el.createEl('div');
output.classList.add('obsidian-jupyter-output');
}
// Paste the output and reset the button.
setInnerHTML(output, response);
button.innerText = 'Run';
});
});
}
getJupyterClient(ctx: MarkdownPostProcessorContext): JupyterClient {
let client = this.clients.get(ctx.docId);
// Construct the interpeter path.
let cache = this.app.metadataCache.getCache(ctx.sourcePath);
let frontmatter: any = (cache ? cache.frontmatter : {}) || {};
let interpreter = (frontmatter['obsidian-jupyter'] || {})['interpreter'] || this.settings.pythonInterpreter;
// If we have a client, check that the interpreter path is right and stop it if not.
if (client && client.interpreter != interpreter) {
console.log(`interpreter path (${client.interpreter}) for the client for doc ` +
`${ctx.docId} does not match the desired path (${interpreter})`);
client.stop();
client = undefined;
}
// Create a new interpreter if required.
if (client === undefined) {
let options = {cwd: this.getBasePath()};
let path = this.getRelativeScriptPath();
client = new JupyterClient(interpreter, [path, ctx.docId], options);
this.clients.set(ctx.docId, client);
console.log(`created new client for doc ${ctx.docId} using interpreter ${interpreter}`);
}
return client;
}
createJupyterPreview(leaf: WorkspaceLeaf) {
return new JupterPreview(leaf, this.settings.pythonInterpreter);
}
async onload() {
console.log('loading jupyter plugin');
this.clients = new Map();
await this.loadSettings();
await this.downloadPythonScript();
this.addSettingTab(new JupyterSettingTab(this.app, this));
this.registerMarkdownCodeBlockProcessor('jupyter', this.postprocessor.bind(this));
this.registerView("ipynb", this.createJupyterPreview.bind(this));
this.registerExtensions(["ipynb"], "ipynb");
}
async downloadPythonScript() {
let path = this.getAbsoluteScriptPath();
try {
let stats = statSync(path);
if (!stats.isFile()) {
throw new Error('python script is missing');
}
console.log(`python script exists at ${path}`);
} catch {
console.log('downloading missing python script...');
let client = new HttpClient('obsidian-jupyter');
let url = `https://github.com/tillahoffmann/obsidian-jupyter/releases/download/${this.manifest.version}/obsidian-jupyter.py`;
let response = await client.get(url);
if (response.message.statusCode != 200) {
throw new Error(`could not download missing python script: ${response.message.statusMessage}`);
}
let content = await response.readBody();
writeFileSync(path, content);
console.log('obtained missing python script');
}
}
getRelativeScriptPath(): string {
return `${this.app.vault.configDir}/plugins/obsidian-jupyter/obsidian-jupyter.py`;
}
getAbsoluteScriptPath(): string {
return `${this.getBasePath()}/${this.getRelativeScriptPath()}`;
}
getBasePath(): string {
if (this.app.vault.adapter instanceof FileSystemAdapter) {
return (this.app.vault.adapter as FileSystemAdapter).getBasePath();
}
throw new Error('cannot determine base path');
}
onunload() {
console.log('unloading jupyter plugin');
this.clients.forEach((client, docId) => {
console.log(`stopping client for doc ${docId}...`);
client.stop();
});
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
}
class JupyterSettingTab extends PluginSettingTab {
plugin: JupyterPlugin;
constructor(app: App, plugin: JupyterPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
let { containerEl } = this;
containerEl.empty();
new Setting(containerEl)
.setName('Python interpreter')
.setDesc('Path to your python interpreter, e.g. `/usr/bin/python`.')
.setClass('wideSettingsElement')
.addText(text => text
.setValue(this.plugin.settings.pythonInterpreter)
.onChange(async (value) => {
this.plugin.settings.pythonInterpreter = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Python setup script')
.setDesc('Script that is run prior to every execution of a python code block.')
.setClass('setupScriptTextArea')
.setClass('wideSettingsElement')
.addTextArea(text => text
.setValue(this.plugin.settings.setupScript)
.onChange(async (value) => {
this.plugin.settings.setupScript = value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName('Test python environment')
.setDesc('Run a script to test the setup of your python environment (view developer console for details).')
.addButton(button => {
button.setButtonText('Run test');
button.onClick(evt => {
let client = this.plugin.getJupyterClient({
docId: 'test-document',
sourcePath: null,
frontmatter: null,
addChild: null,
getSectionInfo: null,
});
client.request({
command: 'execute',
source: '1 + 1',
}).then(response => {
console.log('Received response', response);
new Notice('Test successful, view developer console for details.');
}
).catch(error => {
console.error(error);
new Notice('Test failed, view developer console for details.');
}).finally(() => {
client.stop();
this.plugin.clients.delete('test-document');
});
});
});
new Setting(containerEl)
.setName('Install python dependencies')
.setDesc('This will modify your environment-use at your own risk.')
.addButton(button => {
button.setButtonText('Install dependencies');
button.onClick(evt => {
let interpreter = this.plugin.settings.pythonInterpreter;
let command = `${interpreter} -u -m pip install --upgrade --upgrade-strategy eager jupyter`;
new Notice('Installing dependencies; this may take some time...');
exec(command, (error, stdout, stderr) => {
if (error) {
console.error(`failed to install dependencies: {error}`);
new Notice('Failed to install dependencies, view developer console for details.');
}
console.log(`install stdout: ${stdout}`);
console.log(`install stderr: ${stdout}`);
new Notice('Installed dependencies, view developer console for details.');
});
});
});
}
} | the_stack |
import chalk from "chalk"
import fs from "fs"
import path from "path"
const LambdaSuffix = "$$lambda"
export function generateTsDef(context: CompilationUnitContext, ifs: InterfaceStat, typeRoot: string): boolean {
fs.mkdirSync(typeRoot, { recursive: true })
const references: string[] = []
const topNamespaces: Record<string, boolean> = {}
for (const c of context.classOrInterface()) {
let filename = ""
const frontBuffer: string[] = []
const endBuffer: string[] = []
const lambdaBuffer = ""
if (c.classDeclaration()) {
const classModifier = c.classDeclaration().classModifier()
const type = c.classDeclaration().type(0)
const extend = c.classDeclaration().type(1)
const implement = c.classDeclaration().typeList()
const classBody = c.classDeclaration().classBody()
filename = qualifiedName(type) + ".d.ts"
topNamespaces[type.packageName().Identifier(0).getText()] = true
// declare namespaces
const nsDeclaration = declareNamespaces(type)
frontBuffer.push(nsDeclaration[0])
endBuffer.push(nsDeclaration[1])
// class header
const modifier = classModifier.some(it => it.getText() === "abstract") ? "abstract " : ""
frontBuffer.push(modifier + "class " + header(type, extend && [extend], implement?.type()) + " {")
endBuffer.push("}\n")
// generate members
for (const member of classBody.classMember()) {
if (member.constructorDeclaration()) {
frontBuffer.push(" " + declareConstructor(member.constructorDeclaration(), ifs))
} else if (member.fieldDeclaration()) {
frontBuffer.push(" " + declareField(member.fieldDeclaration()))
} else if (member.methodDeclaration()) {
frontBuffer.push(" " + declareMethod(member.methodDeclaration(), ifs, true))
}
}
} else if (c.interfaceDeclaration()) {
const type = c.interfaceDeclaration().type()
const extend = c.interfaceDeclaration().typeList()
const interfaceBody = c.interfaceDeclaration().interfaceBody()
filename = qualifiedName(type) + ".d.ts"
topNamespaces[type.packageName().Identifier(0).getText()] = true
// declare namespaces
const nsDeclaration = declareNamespaces(type)
frontBuffer.push(nsDeclaration[0])
endBuffer.push(nsDeclaration[1])
// generate lambda type
if (isLambda(ifs, type)) {
if (interfaceBody.interfaceMember()?.some(it => it.methodDeclaration())) {
const method = interfaceBody.interfaceMember().filter(it => it.methodDeclaration())[0].methodDeclaration()
frontBuffer.push(
"interface " + type.Identifier().getText() + LambdaSuffix + typeArgumentsToString(type.typeArguments()) +
" {\n(" + methodArgumentsToString(method.methodArguments(), ifs) + ")" +
": " + methodArgumentToString(method.type(), ifs) + "\n}\n"
)
} else {
extend.type().filter(it => isLambda(ifs, it)).forEach(it => {
frontBuffer.push(
"type " + type.Identifier().getText() + LambdaSuffix + typeArgumentsToString(type.typeArguments()) +
" = " + qualifiedName(it, true) + LambdaSuffix + typeArgumentsToString(it.typeArguments()) + "\n"
)
})
}
}
// interface header
frontBuffer.push("interface " + header(type, extend?.type()) + " {")
endBuffer.push("}\n")
// generate members
for (const member of interfaceBody.interfaceMember()) {
if (member.fieldDeclaration()) {
frontBuffer.push(" " + declareField(member.fieldDeclaration()))
} else if (member.methodDeclaration()) {
frontBuffer.push(" " + declareMethod(member.methodDeclaration(), ifs))
}
}
} else {
console.error("Cannot find class or interface declaration")
continue
}
if (filename) {
const content = [...frontBuffer, ...endBuffer.reverse()].join("\n")
fs.writeFileSync(path.join(typeRoot, filename), content + lambdaBuffer)
process.stdout.clearLine(0)
process.stdout.cursorTo(0)
process.stdout.write(`Generated lib/@types/${filename}`)
references.push(filename)
}
}
process.stdout.clearLine(0)
process.stdout.cursorTo(0)
fs.writeFileSync(
path.join(typeRoot, "index.d.ts"),
references.map(it => `/// <reference path="${it}" />`).sort().join("\n")
)
console.log(chalk.green("Generated " + path.join(typeRoot, "index.d.ts")))
fs.writeFileSync(
path.join(typeRoot, "namespace.json"),
JSON.stringify(topNamespaces, null, 2)
)
console.log(chalk.green("Generated " + path.join(typeRoot, "namespace.json")))
return true
}
export function declareConstructor(constructor: ConstructorDeclarationContext, ifs: InterfaceStat): string {
let result = ""
constructor.modifier()?.forEach(it => result += convertMemberModifier(it.getText()) + " ")
result += "constructor"
result += "(" + methodArgumentsToString(constructor.methodArguments(), ifs) + ")"
return result
}
export function declareField(field: FieldDeclarationContext): string {
if (field.Identifier().getText() === "constructor") return ""
let result = ""
field.modifier()?.forEach(it => result += convertMemberModifier(it.getText(), true) + " ")
result += field.Identifier().getText()
result += ": " + typeToString(field.type())
return result
}
export function declareMethod(method: MethodDeclarationContext, ifs: InterfaceStat, isClass = false): string {
let result = ""
if (isClass) {
method.modifier()?.forEach(it => result += convertMemberModifier(it.getText()) + " ")
}
result += method.Identifier().getText()
result += typeArgumentsToString(method.typeArguments())
result += "(" + methodArgumentsToString(method.methodArguments(), ifs) + ")"
result += ": " + typeToString(method.type(), true)
return result
}
function methodArgumentToString(type: TypeContext, ifs: InterfaceStat): string {
if (isLambda(ifs, type)) {
return [
typeToString(type),
qualifiedName(type, true) + LambdaSuffix + typeArgumentsToString(type.typeArguments())
].join(" | ")
} else {
return typeAlias(qualifiedName(type, true)).map(it =>
it + typeArgumentsToString(type.typeArguments())
).join(" | ")
}
}
function methodArgumentsToString(methodArgs: MethodArgumentsContext, ifs: InterfaceStat): string {
const result: string[] = []
for (const type of (methodArgs.typeList()?.type() || [])) {
result.push("arg" + result.length + ": " + methodArgumentToString(type, ifs))
}
if (methodArgs.varargs()) {
result.push("...vargs: (" + methodArgumentToString(methodArgs.varargs().type(), ifs) + ")[]")
}
return result.join(", ")
}
export function header(type: TypeContext, extend?: TypeContext[], implement?: TypeContext[]): string {
let result = type.Identifier().getText() + typeArgumentsToString(type.typeArguments())
if (extend && extend.length) {
result += " extends " + extend.map(it => typeToString(it)).join(", ")
}
if (implement && implement.length) {
result += " implements " + implement.map(it => typeToString(it)).join(", ")
}
return result
}
export function typeArgumentsToString(typeArgs: TypeArgumentsContext): string {
if (!typeArgs) {
return ""
} else if (typeArgs.typeArgument().length) {
const args = typeArgs.typeArgument().map(it => typeArgumentToString(it))
return "<" + args.join(",") + ">" + (typeArgs.arrayBrackets()?.map(it => it.getText()).join("") || "")
} else {
return typeArgs.getText()
}
}
function typeArgumentToString(typeArg: TypeArgumentContext): string {
if (typeArg.getChild(1)?.getText() === "extends") {
if (typeArg.Identifier()) {
return typeArg.Identifier().getText() + " extends " +
typeArg.type().map(it => typeToString(it)).join(" & ")
} else {
return typeArg.type().map(it => typeToString(it)).join(" & ")
}
} else if (typeArg.getChild(1)?.getText() === "super") {
return "unknown"
} else if (typeArg.type(0)) {
return typeToString(typeArg.type(0))
} else {
return "unknown"
}
}
export function typeToString(type: TypeContext, alias = false): string {
if (type.subType()) {
return "unknown"
} else if (alias) {
return typeAlias(qualifiedName(type, true))[0] + typeArgumentsToString(type.typeArguments())
} else {
return qualifiedName(type, true) + typeArgumentsToString(type.typeArguments())
}
}
export function declareNamespaces(type: TypeContext): [string, string] {
const result: [string, string] = ["", ""]
for (const id of type.packageName().Identifier()) {
const ns = convertNamespace(id.getText())
result[0] += `namespace ${ns} {\n`
result[1] += "}\n"
}
return result[0] ? ["declare " + result[0], result[1]] : result
}
function typeAlias(type: string): string[] {
switch (type) {
case "boolean": return ["boolean", "java.lang.Boolean"]
case "byte": return ["number", "java.lang.Byte"]
case "char": return ["string", "java.lang.Character"]
case "double": return ["number", "java.lang.Double"]
case "float": return ["number", "java.lang.Float"]
case "int": return ["number", "java.lang.Integer"]
case "long": return ["number", "java.lang.Long"]
case "short": return ["number", "java.lang.Short"]
case "java.lang.Boolean": return ["boolean", "java.lang.Boolean"]
case "java.lang.Byte": return ["number", "java.lang.Byte"]
case "java.lang.CharSequence": return ["string", "java.lang.CharSequence"]
case "java.lang.Character": return ["string", "java.lang.Character"]
case "java.lang.Double": return ["number", "java.lang.Double"]
case "java.lang.Float": return ["number", "java.lang.Float"]
case "java.lang.Integer": return ["number", "java.lang.Integer"]
case "java.lang.Long": return ["number", "java.lang.Long"]
case "java.lang.Object": return ["java.lang.Object", "any"]
case "java.lang.Short": return ["number", "java.lang.Short"]
case "java.lang.String": return ["java.lang.String", "string"]
default: return [type]
}
}
// Convert member modifier
export function convertMemberModifier(modifier: string, isField = false): string {
if (modifier === "abstract") return modifier
if (modifier === "final" && isField) return "readonly"
if (modifier === "private") return modifier
if (modifier === "protected") return modifier
if (modifier === "public") return modifier
if (modifier === "static") return modifier
return ""
}
// Append $ to namespace if it is a typescript keyword
export function convertNamespace(namespace: string): string {
const invalid = ["debugger", "enum", "export", "function", "in", "is", "var"]
return invalid.indexOf(namespace) < 0 ? namespace : (namespace + "$")
}
export function qualifiedName(type: TypeContext, safe = false): string {
if (safe) {
const packages = type.packageName()?.Identifier().map(it => convertNamespace(it.getText())) || []
return [...packages, type.Identifier().getText()].join(".")
} else {
return (type.packageName()?.getText().concat(".") || "") + type.Identifier().getText()
}
}
// Return if an interface can be represented with a lambda expression
export function isLambda(stat: InterfaceStat, type: TypeContext): boolean {
let count = 0
const bfs = [qualifiedName(type)]
if (bfs[0] === "java.util.function.Consumer") return true
for (let i = 0; i < bfs.length; i++) {
const current = bfs[i]
if (stat[current]) {
count += stat[current][0]
stat[current].slice(1).forEach(it => {
if (bfs.indexOf(it) < 0) bfs.push(it)
})
}
}
return count === 1
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.